Location: PHPKode > projects > PSlash > pslash-0.70/html/mainfile.php
<?

###############################################################################
# Copyright (C) 2000  Derek Leung
#
# This program 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.
#
# You may modify your copy or copies of this Program or any portion of it,
# but you must cause the modified files to carry prominent notices stating 
# that you changed the files and the date of any change.  And you are required 
# to keep a copy of this License along with this Program.
#
# You are not required to accept this License, since you have not signed it. 
# However, nothing else grants you permission to modify or distribute this 
# Program or its derivative works. These actions are prohibited by law if 
# you do not accept this License. Therefore, by modifying or distributing 
# this Program (or any work based on this Program), you indicate your 
# acceptance of this License to do so, and all its terms and conditions 
# for copying, distributing or modifying this Program or works based on it.
#
# This program 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.  
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# See the GNU General Public License for more details.
# http://www.opensource.org/licenses/gpl-license.html
###############################################################################

$root_path = "/home/groups/p/ps/pslash/htdocs";

# No edit below this line
###############################################################################################################

require("$root_path/config.php");

// kick out anyone trying to access this file directly
if (preg_match("/mainfile.php/i", $PHP_SELF)) {
	echo "$config[psVersion] -- You can not access this file directly!";
	exit;
}

// connect to DB, we only do connect DB at this file for easier maintainence.  
// Every file that need access to DB need to include this file.
dbconnect();
Mainfile_initialize();



###############################################################################################################
function Mainfile_initialize() {

global $config, $myTopic;

	// decide which language we should use
	$tmpArray = getCookie($config[setting_cookie_name]);

	if ($tmpArray[language] != "") {
	$myLang = $tmpArray[language];
	} else {
	$myLang = $config[language];
	}
	$mesgPath = $config[root_path]. "/languages/messages." . $myLang . ".php"; 
	require($mesgPath);


	// if no topic is choosen, we pick the default theme
	$topics=getTopics();
	if (!in_array($myTopic,$topics)) {
		$myTopic = $config[def_theme];
	}

	unset($myLang,$mesgPath,$topics);

	require("$config[root_path]/themes/$myTopic/theme.php"); // only include theme in this file for easier maintainece
	require("$config[root_path]/themes/$myTopic/header.php"); // only include header in this file for easier maintainece
	require("$config[root_path]/themes/$myTopic/footer.php"); // only include footer in this file for easier maintainece



	######################################
	#check ban user
	#####################################

	$userArray = getCookie($config[user_cookie_name]);
	$result = mysql_query("select ban from ps_users where uid=$userArray[userid]");
	if ($result) {  
		list($ban) = mysql_fetch_array($result);
		mysql_free_result($result);
	}

	if ($ban == "true") {
		cleanCookie($config[user_cookie_name]);
		cleanCookie($config[setting_cookie_name]);

		if ($config[use_w3b] == true) {

			// logout wwwthreads
			setcookie("w3t_myname","","","/",$config[CookieURL]);
			setcookie("w3t_mypass","","","/",$config[CookieURL]);
			setcookie("w3t_language","","","/",$config[CookieURL]);
		}

		// using phpBB?  Logout
		if ($config[use_phpBB] == true) {
			$db_uname = fixquotes($userArray[username]);
			$result = mysql_query("select uid from ps_users where uname = '$db_uname'");
			list($uid) = mysql_fetch_row($result);
			include("$config[phpBB_path]/extention.inc");
			include("$config[phpBB_path]/config.php");
			include("$config[phpBB_path]/functions.php");
			include("$config[phpBB_path]/auth.php");

			if ($user_logged_in) {
				end_user_session($uid, $db);
				setcookie($cookiename,'','',$cookiepath,$cookiedomain,$cookiesecure);
				setcookie("LastVisit",'','',$cookiepath,$cookiedomain,$cookiesecure);
				setcookie("LastVisitTemp",'','',$cookiepath,$cookiedomain,$cookiesecure);
			}
		}

		errorPage("You have been BANNED!  Bye!",$myTopic);
	}
	unset($ban,$result,$userArray);
}


function getCookie($cookiename) { 

// funciton to get cookies

	$tmpstring = "global \$$cookiename;"; 
	
	eval($tmpstring); 
	unset($tmpstring); 

	if (isset(${$cookiename})) {
		
		$tmparray=unserialize(${$cookiename}); 
	} else { 
		
		$tmparray = array(); 
	} 
	return $tmparray; 
} 
    
function getCharset($str) {

// find the charset
global $config;

	switch ($str) {
		// set charset, add more charset here.. visit http://www.iana.org/assignments/character-sets for more info
		case "english"		:	$myCharset = "iso-8859-1"; break;  // english
		case "big5"			:	$myCharset = "big5"; break;
		case "chinese"		:	$myCharset = "gb2312"; break;
		case "japaneseJIS"	:	$myCharset = "Shift_JIS"; break;
		case "japaneseEUC"	:	$myCharset = "EUC-JP"; break;
		//default				:	$myCharset = "iso-8859-1"; break; // default english
		default				:	$myCharset = "big5"; break; // default 
	}
	return $myCharset;
}

function getPhpBBLang($str) {

// Since every message board using different name to describe a language, this function is to find the language string in phpBB format
global $config;

	switch ($str) {
		
		case "big5"			:	$myLang = "big5_chinese"; break;
		case "bulgarian"	:	$myLang = "bulgarian"; break;
		case "chinese"		:	$myLang = "english"; break; // not available for phpBB
		case "danish"		:	$myLang = "danish"; break;
		case "english"		:	$myLang = "english"; break;  
		case "french"		:	$myLang = "french"; break;
		case "german"		:	$myLang = "german"; break;
		case "hugarian"		:	$myLang = "english"; break; // not available for phpBB
		case "italian"		:	$myLang = "italian"; break;
		case "japanese"		:	$myLang = "english"; break; // not available for phpBB
		case "korean"		:	$myLang = "korean"; break;
		case "mexican_spanish"		:	$myLang = "mexican_spanish"; break;
		case "nederlands"	:	$myLang = "nederlands"; break;
		case "norwegian"		:	$myLang = "english"; break; // not available for phpBB
		case "polish"		:	$myLang = "english"; break; // not available for phpBB
		case "portuguese"	:	$myLang = "portuguese"; break;
		case "portuguese_brazil"		:	$myLang = "portuguese_brazil"; break;
		case "romanian"		:	$myLang = "english"; break; // not available for phpBB
		case "russian"		:	$myLang = "russian"; break;
		case "spanish"		:	$myLang = "spanish"; break;
		case "swedish"		:	$myLang = "swedish"; break;
		default				:	$myLang = "english"; break; // default 
	}
	return $myLang;
}

function getWWWThreadsLang($str) {

// Since every message board using different name to describe a language, this function is to find the language string in wwwthreads format
global $config;

	switch ($str) {
		
		case "big5"			:	$myLang = "big5"; break;
		case "bulgarian"	:	$myLang = "english"; break; // not available for wwwthreads
		case "chinese"		:	$myLang = "chinese"; break; 
		case "danish"		:	$myLang = "danish"; break;
		case "english"		:	$myLang = "english"; break;  
		case "french"		:	$myLang = "french"; break;
		case "german"		:	$myLang = "german"; break;
		case "hugarian"		:	$myLang = "hugarian"; break;
		case "italian"		:	$myLang = "italian"; break;
		case "japanese"		:	$myLang = "english"; break; // not available for wwwthreads
		case "korean"		:	$myLang = "english"; break; // not available for wwwthreads
		case "mexican_spanish"		:	$myLang = "spanish"; break;
		case "nederlands"	:	$myLang = "english"; break; // not available for wwwthreads
		case "norwegian"		:	$myLang = "norwegian"; break;
		case "polish"		:	$myLang = "polish"; break;
		case "portuguese"	:	$myLang = "portuguese"; break;
		case "portuguese_brazil"		:	$myLang = "portuguese"; break;
		case "romanian"		:	$myLang = "romanian"; break;
		case "russian"		:	$myLang = "russian"; break;
		case "spanish"		:	$myLang = "spanish"; break;
		case "swedish"		:	$myLang = "english"; break; // not available for wwwthreads
		default				:	$myLang = "english"; break; // default 
	}
	return $myLang;
}



  
function Main_Menu_Box() {

// The main menu box to display

	global $myTopic, $config;

	$userArray = getCookie($config[user_cookie_name]);
	$tmpArray = getCookie($config[setting_cookie_name]);
	if ($tmpArray[language] != "") {
		$myLang = $tmpArray[language];
	} else {
		$myLang = $config[language];
	}

?>
<TABLE cellSpacing=0 cellPadding=5 width=150 align=center border=0 class=leftbox>
	<TBODY>
		<tr><td class=leftboxtop><b>Main Menu</b></td></tr>
		<TR>
			<TD class=leftbox>
				<a href="<?=$config[root_url]?>"><?=translate("Home")?></a><br>  
				<a href="<?="$config[root_url]/index.php?myTopic=$myTopic"?>"><?=translate("Topic Home")?></a><br>  
				<a href="<?=$config[root_url]?>/submit.php"><?=translate("Submit News")?></a><br>
				<a href="<?=$config[root_url]?>/modules/visitors2/"><?=translate("Site Stats")?></a><br>
				<a href="<?=$config[root_url]."/faq/faq.".$myLang.".php"?>"><?=translate("FAQ")?></a><br>
				<a href="<?=$config[root_url]?>/search.php"><?=translate("Search the site")?></a><br> 
				<a href="<?=$config[root_url]?>/memberslist.php"><?=translate("Member List")?></a><br> 
				<? if (sizeof($userArray) <= 0) { ?>
					<a href="<?=$config[root_url]?>/user.php"><?=translate("New User")?></a><br> 
				<? } ?>
				<a href="<?=$config[root_url]?>/user.php"><?=translate("User Area")?></a><br> 
				<? if ($userArray[status] == "Admin" || $userArray[status] == "Moderator") { ?>
					<a href="<?=$config[root_url]?>/admin.php"><?=translate("Admin Area")?></a><br> 
				<? } ?>
			</TD>
		</TR>
	</TBODY>
</TABLE>


<?
	unset($userArray);
}


function browser_Box() {
// The browser box to display

?>
<TABLE cellSpacing=0 cellPadding=5 width=150 align=center border=0 class=leftbox>
	<TBODY>
		<tr><td class=leftboxtop><b>We support</b></td></tr>
		<TR>
			<TD class=leftbox align=center>
				<a href="http://www.microsoft.com/windows/ie/default.htm"><img border="0" src="<?=$config[theme_relative_path]?>/imgs/ie.gif"></a><br>Internet explorer 5<br>(Recommend)<br><br>
				<a href="http://home.netscape.com/download/index.html"><img border="0" src="<?=$config[theme_relative_path]?>/imgs/netscape.gif"></a><br>Netscape 6<br>
				
			</TD>
		</TR>
	</TBODY>
</TABLE>


<?
	
}

function powerby_box() {

// function to display system is powered by
	global $config;

?>
	<TABLE cellSpacing=0 cellPadding=5 width=150 align=center border=0 class=leftbox>
		<TBODY>
			<tr><td class=leftboxtop><center><b><?=$config[sitename]?><br>Powered by</b></center></td></tr>
			<TR>
				<TD align=middle class=leftbox>
					<a href="http://www.<?=$config[os]?>.org"><img border="0" src="<?=$config[img_relative_path]?>/<?=$config[os]?>.png" width="88" height="31"></a><br>
					<a href="http://www.apache.org"><img border="0" src="<?=$config[img_relative_path]?>/apache.png" width="88" height="31"></a><br>
					<a href="http://www.php.net"><img border="0" src="<?=$config[img_relative_path]?>/php.png" width="88" height="31"></a><br>
					<a href="http://www.mysql.com"><img border="0" src="<?=$config[img_relative_path]?>/mysql.png" width="90" height="32"></a><br>
					<a href="http://www.zend.com"><img border="0" src="<?=$config[img_relative_path]?>/zend.png" width="88" height="31"></a>
				</TD>
			</TR>
		</TBODY>
	</TABLE>
<?
}

function Language_resol_box($header_resol) {

// The language and resolution box to display
	global $myTopic,$config;

	$userArray = getCookie($config[user_cookie_name]);
	$settingArray = getCookie($config[setting_cookie_name]);
	if (sizeof($userArray) <=0) {
		
	?>
	<TABLE cellSpacing=0 cellPadding=5 width=150 align=center border=0 class=leftbox>
		<TBody>
			<tr><td class=leftboxtop><b><?= translate("Language & Resolution");?></b></td></tr>
			<tr>
				<td class=leftbox>
					<form action="language.php" method="post">
						<select name="lang"><option value="english" <? if ($settingArray[language]=="english") { echo "selected";}?>>English
							<option value="big5" <? if ($settingArray[language]=="big5") { echo "selected";}?>>Big5 Chinese
						</select>
				</td>
			</tr>
			<tr>
				<td class=leftbox>
						<select name="resolution">
							<option value="800x600" <? if ($header_resol == "760") echo "selected";?> >800x600
							<option value="1024x768" <? if ($header_resol == "984") echo "selected";?> >1024x768
							<option value="1280x1024" <? if ($header_resol == "1240") echo "selected";?> >1280x1024
						</select><br>
						<input type="submit" value="<?php echo translate("Update"); ?>">
						<input type="hidden" name="myTopic" value="<?=$myTopic?>">		
					</form>
				</td>
			</tr>
		</tbody>
	</table>
	
	<?
	}
	unset ($userArray,$settingArray);
}

function Login_Box() {

// The login box to display
	global $config;

	$userArray = getCookie($config[user_cookie_name]);

	if (sizeof($userArray) <=0) {
		 ?>
		 <TABLE cellSpacing=0 cellPadding=5 width=150 align=center border=0 class=leftbox>
			<TBody>
				<tr>
					<td class=leftboxtop><b><?= translate("User Login")?></b></td>
				</tr>
				<tr>
					<td class=leftbox>
						<form action="<?=$config[root_url]?>/user.php" method="post">
							<?=translate("Username")?>:<br> <input type=text name=uname size=12><br>
							<?=translate("Password")?>:<br> <input type=password name=pass size=12><br>
							<input type="submit" name="op" value="<?php echo translate("login"); ?>">
							<input type="hidden" name="op" value="login">
						</form>
					</td>
				</tr>
			</tbody>
		</table>
		<br>

		<?
		 } else {

		 ?>
		 <TABLE cellSpacing=0 cellPadding=5 width=150 align=center border=0 class=leftbox>
			<TBody>
				<tr>
					<td class=leftboxtop><b><?= translate("User Logout")?></b></td>
				</tr>
				<tr>
					<td class=leftbox>
						<form action="<?=$config[root_url]?>/user.php" method="post">
							<input type="submit" value="<?php echo translate("Logout"); ?>">
							<input type="hidden" name="op" value="logout">
						</form>
					</td>
				</tr>
			</tbody>
		</table>
		<br>


	<? }
	unset($userArray);

}

function dynamic_box() {

// the box to display all the category and its' articles.
	global $myTopic,$config;
	
	if ($config[root_relative_path] == "/") {
		$rootPath = "";
	} else {
		$rootPath = $config[root_relative_path];
	}

	$result = mysql_query("select a.aid, a.aName, a.link, a.url, a.cid, c.cName, c.cid from ps_article a, ps_category c where a.cid = c.cid and c.topic = '$myTopic' and a.topic= '$myTopic' order by c.listOrder, a.listOrder");

	$first = true;
	if ($result) {
		while (list($head_aaid, $head_aaName, $head_alink, $head_aurl, $head_acid,$head_ccName, $head_ccid) = mysql_fetch_row($result)) {
			if ($prevName != $head_ccName) {
				if ($first == true) {
					$first =false;
				} else {
					echo "</td></tr></tbody></table><br>";
				}
				echo "<TABLE cellSpacing=0 cellPadding=5 width=150 align=center border=0 class=leftbox>";
				echo "<TBody><td class=leftboxtop><b>$head_ccName</b></td></tr><tr><td class=leftbox>";
				$prevName = $head_ccName;
			}
			if ($head_alink == "on") {
				echo "<li><a href=\"".$head_aurl."\">".$head_aaName."</a><br>";
			} else{
				echo "<li><a href=\"$rootPath"."/editorial.php?aid=".$head_aaid."&myTopic=$myTopic\">".$head_aaName."</a><br>";
			}
		}
		echo "</td></tr></tbody></table><br>";
	}
	
	if ($result) {
		mysql_free_result($result);
	}
	
	unset ($head_aaid, $head_aaName, $head_alink, $head_aurl, $head_acid,$head_ccName, $head_ccid,$result,$rootPath, $first,$prevName);
}



function getOnlineUsers() {

// gather info about who is online and what they are doing at the moment
	global $config;

	$ip = getenv("REMOTE_ADDR");
	$userArray = getCookie($config[user_cookie_name]);

	$result = mysql_query("delete from ps_onlineUsers where NOW() - accessTime > 1000"); // delete any entry longer than 10 minutes 
	if (sizeof($userArray) > 0) {
		$isMember = fixquotes($userArray[username]);
	} else {
		$isMember = "ANON-".$ip;
	}
	
	// get what the user is doing
	$What = getenv ("SCRIPT_NAME");
    //$script[0] = "";
    //preg_match ("/(.*)\/(.*).php/",$What,$script);
    //$What     = $script[2] . ".php";

	mysql_query("replace into ps_onlineUsers (ipAddr,username, accessTime,action) values ('$ip','$isMember',now(),'$What')");
	$result = mysql_query("select ipAddr,username  from ps_onlineUsers where NOW() - accessTime < 1000");  // 1000 = 10 minutes

	// do the counting how many member and how many anonymous online
	$nonMemberCount = 0;
	$memberCount = 0;
	while (list($ip,$isMember) = mysql_fetch_row($result)) {
		if ($isMember == "ANON-" . $ip) {
			$nonMemberCount++;
		} else {
			$memberCount++;
		}
	}

	$onlineTitle = translate("Who's Online");
	if ($config[root_relative_path] == "/") {
		$rootPath = "";
	} else {
		$rootPath = $config[root_relative_path];
	}
	$temp = "There are currently %s member(s), and %s guest(s) that are active in last 10 minutes.<br><br> Click <a href=\"%s/online.php\">here</a> to see what they are doing.";
	if (sizeof($userArray) > 0) {
		$temp2 .= "You now login as<br><b>%s</b>";
		$onlineContent = "<center>".sprintf(translate($temp),$memberCount, $nonMemberCount,$rootPath)."<br><br>".sprintf(translate($temp2),$userArray[username])."</center><br>";
	} else {
		$onlineContent = "<center>".sprintf(translate($temp),$memberCount, $nonMemberCount,$rootPath)."</center><br>";
	}
	
	

	echo "<TABLE cellSpacing=0 cellPadding=5 width=150 align=center border=0 class=leftbox>";
	echo "<TBody><td class=leftboxtop><b>$onlineTitle</b></td></tr><tr><td class=leftbox>";
	echo "$onlineContent";
	echo "</td></tr></tbody></table><br>";
	unset($ip,$userArray,$result,$isMember,$What,$nonMemberCount,$memberCount,$onlineTitle,$rootPath,$onlineContent);
}


function showTopicLinks($topics) {

// Show all topics with links
	global $config;

	echo "<center>[&nbsp;";
	if (sizeof($topics)>0) {
		echo " <a href=\"index.php?myTopic=$config[def_theme]\">".Translate($config[def_theme])."</a> ";
	}

	for ($i=0; $i < sizeof($topics)-1; $i++) {
		echo " | ";
		if ($topics[$i] != $config[def_theme]) {
			echo "<a href=\" index.php?myTopic=".$topics[$i]."\">".$topics[$i]."</a>";
		}
	}
	if ($topics[$i] != $config[def_theme]) {
		echo "<a href=\" index.php?myTopic=".$topics[$i]."\">".$topics[$i]."</a>";
	}
	echo "&nbsp;]</center><br>\n";
	unset($topics,$i);

}

function getTopicRights($uid="") {

// to get users topic right, return list of topics
	global $config;

	$userArray= getCookie($config[user_cookie_name]);
	if ($uid =="") {
		$uid = $userArray[userid];
	} 
		
	$result = mysql_query("select topicRights from ps_users where uid=$uid");
	list($rights) = mysql_fetch_row($result);
	if ($result) {
		mysql_free_result($result);
	}
	$i=0;
	$rightArray = array();
	$result = mysql_query("select topic from ps_topics where tid in ($rights)");
	if ($result) {
		while (list($topic) = mysql_fetch_row($result)) {
			//echo "$topic<br>";
			$rightArray[$i] = $topic;
			$i++;
		}
	
		mysql_free_result($result);
	}
	
	unset($userArray,$uid,$rights,$i,$topic,$result);
	return $rightArray;

}

function getTopicRights2($uid="") {

// to get users topic right and only return a list of topics that are viewable on main page	
	global $config;

	$userArray= getCookie($config[user_cookie_name]);
	if ($uid =="") {
		$uid = $userArray[userid];
	} 

	$rightArray = array();	
	$result = mysql_query("select topicRights from ps_users where uid=$uid");
	list($rights) = mysql_fetch_row($result);
	if ($result) {
		mysql_free_result($result);
	}

	$i=0;
	
	$result = mysql_query("select topic from ps_topics where tid in ($rights) and displayTopic='true'");
	while (list($topic) = mysql_fetch_row($result)) {
		
		$rightArray[$i] = $topic;
		$i++;
	}
	if ($result) {
		mysql_free_result($result);
	}

	unset($userArray,$uid,$rights,$i,$topic,$result);
	return $rightArray;

}

function alpha($sortby,$filepath,$separator) { 

//Creates the list of letters and makes them a link.
// for example, please read memberslist.php
   
        $alphabet = array ("All", "A","B","C","D","E","F","G","H","I","J","K","L","M",
                            "N","O","P","Q","R","S","T","U","V","W","X","Y","Z","Other");
        $num = count($alphabet) - 1;
        echo "<center>[ "; // start of HTML
        $counter = 0;
        while (list(, $ltr) = each($alphabet)) {
            echo "<A HREF=\"$filepath".$separator."letter=$ltr&sortby=$sortby\">$ltr</a>";
            if ( $counter == round($num/2) ) {
                echo " ]\n<br>\n[ "; 
            } elseif ( $counter != $num ) {
                echo "&nbsp;|&nbsp;\n";
            }
            $counter++;
        }
        echo " ]\n</center>\n<br>\n";  // end of HTML
}

function SortLinks($sortby,$filepath,$letter,$separator,$arg) {  

global $config;
// a generic function to makes order by links..
// this function need $sortby, $filepath, $letter , $separator and $arg for input
// $separator is either ? or & 
// $arg is an array contain a list of associate array, the associate array consisit of $key[method] and $key[name]
// $key[method] <-- the method for sorting
// $key[name] <- the name of the method
// for example, please read memberslist.php
        
		if ($config[root_relative_path] == "/") {
			$rootPath = "";
		} else {
			$rootPath = $config[root_relative_path];
		}

        echo "\n<center>\n"; // Start of HTML
        echo translate("Sort by: ")." [ ";
		
		$i=0;
		foreach ($arg as $key) {
			
			$i++;
			if ($sortby == $key[method] OR !$sortby) {
				echo "<A HREF=\"$filepath".$separator."letter=$letter&sortby=$key[method]&orderby=ASC\"><img border=0 src=\"$rootPath/imgs/up.gif\"></a><b>".sprintf(translate("%s"),$key[name])."</b><A HREF=\"$filepath".$separator."letter=$letter&sortby=$key[method]&orderby=DESC\"><img border=0 src=\"$rootPath/imgs/down.gif\"></a>&nbsp;";
			} else {
				echo "<A HREF=\"$filepath".$separator."letter=$letter&sortby=$key[method]&orderby=ASC\"><img border=0 src=\"$rootPath/imgs/up.gif\"></a>".sprintf(translate("%s"),$key[name])."<A HREF=\"$filepath".$separator."letter=$letter&sortby=$key[method]&orderby=DESC\"><img border=0 src=\"$rootPath/imgs/down.gif\"></a>&nbsp;";
				
			}
			if (sizeof($arg) > $i) {
				echo "|\n&nbsp;";
			}
		}
        echo " ]\n</center>\n"; // end of HTML
}

function numberLink($arg) {
// a generic function to make a number list at the bottom, you will need function alpha() and SortLinks() to work with this function

// we need the following input
//$input[num_rows_per_order] <- number of rows without LIMIT clause
//$input[pagesize] = <- how many rows we want to display per page
//$input[num_rows] <- number of rows with all the WHERE clause and LIMIT, ORDER clause
//$input[page] <- the current page
//$input[item] <- what items are we dealing with right now?
//$input[letter] <- the current letter
//$input[sortby] <- the sort by method
//$input[orderby] <- the order to sort, either ASC or DESC
//$input[filepath] <- the file path to the file
//$input[separator] <- separator either ? or &
// for example, please read memberslist.php

	echo "<table width='100%' cellspacing='0' cellpadding='0' cols='3'><tr>";
                
	if ( $arg[num_rows_per_order] > $arg[pagesize] ) { 
		$total_pages = ceil($arg[num_rows_per_order] / $arg[pagesize]); // How many pages are we dealing with here ??
		$prev_page = $arg[page] - 1;
				
		// show previous page link
		if ( $prev_page > 0 ) {
			echo "<td align='left' width='33%'><a href='$arg[filepath]".$arg[separator]."letter=$arg[letter]&sortby=$arg[sortby]&orderby=$arg[orderby]&page=$prev_page'>";
			echo "<font style=\"font-size: 0.7em;\">&lt;".translate("previous page")."</font></a></td>";
		} else { 
			echo "<td width='33%'>&nbsp;</td>\n"; 
		}
			
		// show how many users found
		echo "<td align='center' width='33%'>";
		echo "<font style=\"font-size: 0.7em;\">$arg[num_rows_per_order] $arg[item] found ($total_pages pages, $arg[num_rows] $arg[item] shown).</font>";
		echo "</td>";

		// show next page link
		$next_page = $arg[page] + 1;
		if ( $next_page <= $total_pages ) {
			echo "<td align='right' width='33%'><a href='$arg[filepath]".$arg[separator]."letter=$arg[letter]&sortby=$arg[sortby]&orderby=$arg[orderby]&page=$next_page'>";
			echo "<font style=\"font-size: 0.7em;\">".translate("next page")."&gt;</font></a></td>";
		} else {
			echo "<td width='33%'>&nbsp;</td></tr>\n"; 
		}
	
		/* Added a numbered page list, only shows up to 50 pages. */        
		echo "<tr><td colspan=\"3\" align=\"center\">";
		echo " <font style=\"font-size: 0.7em;\">[ </font>";
					
		for($n=1; $n < $total_pages; $n++) {
			 
			if ($arg[page] != $n) {
				echo "<a href='$arg[filepath]".$arg[separator]."letter=$arg[letter]&sortby=$arg[sortby]&orderby=$arg[orderby]&page=$n'>";
				echo "<font style=\"font-size: 0.7em;\">$n</font></a>";
			} else {
				echo "<font style=\"font-size: 0.7em;\">$n</font>";
			}
					   
			if($n >= 50) {  // if more than 50 pages are required, break it at 50.
				$break = true; 
				break;
			} else {  // guess not.
				echo "<font style=\"font-size: 0.7em;\"> | </font>"; 
			}
		}
					
		if(!isset($break)) { // are we sopposed to break ?
			echo "<a href='$arg[filepath]".$arg[separator]."letter=$arg[letter]&sortby=$arg[sortby]&orderby=$arg[orderby]&page=$total_pages'>";
			echo "<font style=\"font-size: 0.7em;\">$n</font></a>";
		}
		echo " <font style=\"font-size: 0.7em;\">]</font> ";
		echo "</td></tr>";

		/* This is where it ends */
	}else{  // or we dont have any users..
		echo "<td class=\"sidebox\" align='center'>";
		echo "<font style=\"font-size: 0.7em;\">$arg[num_rows_per_order] $arg[item] found.</font>";
		echo "</td></tr>";     
	}
			
	echo "</table>\n";
}

function errorMsg($str) {

// a formated error message, if possible , use errorPage().

echo "<center><b><font color=\"red\" size=\"+1\">" . translate($str) . "</font></b></center>";
echo "<br>";


}

function errorPage($str,$myTopic) {

// generic error page
	global $config;

	ps_header("");
	echo "<br><br><br><br><br><br>";
	echo "<center><b><font color=\"red\" size=\"+1\">" . translate($str) . "</font></b></center>";
	echo "<br><br><br><br><br><br>";
	ps_footer("");
	exit;

}


function auto_link($str) {

// My implementation for linking all urls and email.  Only use 2 preg_replace.  FAST!

	$str2 = preg_replace("/(?<!<a href=\")(?<!\")(?<!\">)((http|https|ftp):\/\/[\w#<>?=&.\/-]+)/","<a href=\"\\1\">\\1</a>",$str);
	$str2 = preg_replace("/((?<!<a href=\"mailto:)(?<!\">)(?<=(>|\s))[\w_-]+@[\w_.-]+[\w]+)/","<a href=\"mailto:\\1\">\\1</a>",$str2);
	return $str2;
}


function dbconnect() {

// connects to MySQL

	global $config;

	//require ("$config[root_path]/db_settings.php");
	mysql_pconnect($config[dbhost], $config[dbuname], $config[dbpass]);
	@mysql_select_db($config[dbname]) or die ("Unable to select database");
}



function putCookie($cookiename, $varname, $data, $send="") { 

// function to store cookie, use serialize() to bypass the limit of using 20 cookies per domain. 
// And make it easier to add new cookie later.

	global $config;
	//keep this array always static so that when we get out of this function, it still keep the variable.
	static $tmpArray; 
	
	$tmpArray[$varname] = $data;
		
	if ($send != "") {
		$tmpstring = serialize($tmpArray); 
		setcookie($cookiename, $tmpstring, time()+$config[cookieTTL], $config[cookie_path], $config[CookieURL]); // now we clean the static array after we send the cookie	
		unset($tmpstring); 
		$tmpArray = "";
		unset($tmpArray);
	}
}	

function cleanCookie($cookiename) { 

// function to clean cookies

	global $config;
	setcookie($cookiename, "", "", $config[cookie_path],$config[CookieURL]); 
	
} 



function FixQuotes ($str = "", $type="") {

// replaces quote with double apostrophe in string for insertion into database if it use sybase DB, else use slashes.

	global $config;

	if ($type == "") {
		$type = $config[dbType];
	}

	if ($type == "mysql") {	
		// no further processing
	}
	
	if ($type == "sybase") {
		ini_set("magic_quotes_sybase",1);
	}

	$str = addslashes($str);
	return $str;
	//$str = ereg_replace("'","''",$str);
	//$str = preg_replace("/\\\/","\\\\",$str);
	//$str = preg_replace("/\\0/","\\\0",$str);	
	//return $str;
}

/*********************************************************/
/* text filter                                           */
/*********************************************************/

function delQuotes($string){ 

  # no recursive function to add quote to an HTML tag if needed
  # and delete duplicate spaces between attribs.

  $tmp="";    # string buffer
  $result=""; # result string
  $i=0;
  $attrib=-1; # Are us in an HTML attrib ?   -1: no attrib   0: name of the attrib   1: value of the atrib
  $quote=0;   # Is a string quote delimited opened ? 0=no, 1=yes
  $len = strlen($string);

  while ($i<$len) {
    switch($string[$i]) { # What car is it in the buffer ?
      case "\"": #"       # a quote. 
        if ($quote==0) {
	  $quote=1;
	} else {
	  $quote=0;
	  if (($attrib>0) && ($tmp != "")) { $result .= "=\"$tmp\""; }
	  $tmp="";
	  $attrib=-1;
	}
      break;
      case "=":           # an equal - attrib delimiter
        if ($quote==0) {  # Is it found in a string ?
	  $attrib=1;
	  if ($tmp!="") $result.=" $tmp";
	  $tmp="";
	} else $tmp .= '=';
      break;
      case " ":           # a blank ?
        if ($attrib>0) {  # add it to the string, if one opened.
	  $tmp .= $string[$i];
	}
      break;
      default:            # Other
        if ($attrib<0)    # If we weren't in an attrib, set attrib to 0
          $attrib=0;
	$tmp .= $string[$i];
      break;
    }
    $i++;
  }
  if (($quote!=0) && ($tmp != "")) {
    if ($attrib==1) $result .= "="; 
                          # If it is the value of an atrib, add the '='
    $result .= "\"$tmp\"";# Add quote if needed 
  }

  unset($tmp,$i,$attrib,$quote,$len,$string);
  return $result;
}

function check_words($Message) {

// removes "bad" words according to configuration in config.php
	global $config;
	
	//my fix for check words, this method works with language other than English.
	
	$text = preg_replace($config[CensorList], $config[CensorReplace],$Message);
	return $text;
	exit;
/*
	The following code from phpslash, but it doesnt work on language other than English...so I use mine instead
	if ($config[CensorMode] != 0) {
		if (is_array($config[CensorList])) {
			
			$Replacement = $config[CensorReplace];

			if ($config[CensorMode] == 1) { # Exact match
				$RegExPrefix   = '([^[:alpha:]]|^)';
				$RegExSuffix   = '([^[:alpha:]]|$)';
			} elseif ($config[CensorMode] == 2) {    # Word beginning
				$RegExPrefix   = '([^[:alpha:]]|^)';
				$RegExSuffix   = '[[:alpha:]]*([^[:alpha:]]|$)';
			} elseif ($config[CensorMode] == 3) {    # Word fragment
				$RegExPrefix   = '([^[:alpha:]]*)[[:alpha:]]*';
				$RegExSuffix   = '[[:alpha:]]*([^[:alpha:]]*)';
			}
			$censorList = $config[CensorList];
			
			for ($i = 0; $i < count($censorList) && $RegExPrefix != ''; $i++) {
				$Message = eregi_replace($RegExPrefix.$censorList[$i].$RegExSuffix,"\\1$Replacement\\2",$Message);
				
			}
			
		}
	}

	return ($Message);
*/
}


function myNl2br($str) {

// make new line to <br>

   $str = str_replace("\r","",$str);
   $str = str_replace("\n","<br>",$str);
   return $str;
}


function check_html ($str, $strip="") {

// strips "bad" HTML tags from a string according to configuration in config.php
	global $config;

	$AllowableHTML = $config[AllowableHTML];
	if ($strip == "nohtml")
		$AllowableHTML=array('');
	

	$str = eregi_replace("<[[:space:]]*([^>]*)[[:space:]]*>",'<\\1>', $str);
               // Delete all spaces from html tags .
	$tmp = "";
	while (ereg("<(/?[[:alpha:]]*)[[:space:]]*([^>]*)>",$str,$reg)) {
		$i = strpos($str,$reg[0]);
		$l = strlen($reg[0]);
		if ($reg[1][0] == "/") $tag = strtolower(substr($reg[1],1));
		else $tag = strtolower($reg[1]);  
		if ($a = $AllowableHTML[$tag])
			if ($reg[1][0] == "/") $tag = "</$tag>";
			elseif (($a == 1) || ($reg[2] == "")) $tag = "<$tag>";
			else {
			  # Place here the double quote fix function.
			  $attrb_list=delQuotes($reg[2]);
			  $tag = "<$tag" . $attrb_list . ">";
			} # Attribs in tag allowed
		else $tag = "";

		$tmp .= (substr($str,0,$i) . $tag);
		$str = (substr($str,$i+$l));


	}
	$str = $tmp . $str ;
	unset ($tmp,$reg,$a,$attrib_list,$tag,$i,$AllowableHTML,$strip);
	return $str;
	
}



/*********************************************************/
/* formatting stories                                    */
/*********************************************************/

function formatTimestamp($time) {

// this is a replacement for mysql date_format function, display in long format
	global $config;	

	ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $datetime);
	$datetime = strftime($config[dateString], mktime($datetime[4],$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
	return($datetime);
}


function formatShortTimestamp($time) {

// this is a replacement for the mysql date_format function, display in short format
	global $config;

	ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $datetime);
	$datetime = strftime($config[shortDateString], mktime($datetime[4],$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
	return($datetime);
}



function top10() {

//  10 lastest article in last 2 weeks across all topics 
	global $myTopic,$config;

	$boxstuff = "";
	$boxTitle = translate("10 Lastest News");
	
	$querystr = "select sid, title, counter, time, topic from ps_stories where (TO_DAYS(NOW()) - TO_DAYS(time)) <= 14 order by time desc limit 10";
	$topiclist = getTopics();
	$result = mysql_query( $querystr );
	if (mysql_num_rows($result) > 0) {
		while(list($sid, $title, $counter, $time, $topic) = mysql_fetch_row($result)) {
			$title = check_words($title);
			if (!in_array($topic,$topiclist)) {
				$topic2 = $config[def_theme];
			} else {
				$topic2 = $topic;
			}
			$boxstuff .= "<li><a href=\"index.php?myTopic=$topic2\">[$topic]</a> <a href=\"article.php?sid=$sid&myTopic=$topic2\">$title</a><font color=#ff6600 size=1> ($counter hits)</font></li>";
		}
		
		mysql_free_result($result);
		themesidebox($boxTitle, $boxstuff);
	}

	unset($boxstuff,$boxTitle,$querystr,$topiclist,$title,$topic2,$result);
}

function oldNews() {

// Display old news box
	global $myTopic,$config;

	$boxstuff = "";
	$boxTitle = translate("older news");
	
	$tmpArray = getCookie($config[setting_cookie_name]);
	if ($tmpArray[storynum] != "") {
		$storynum = $tmpArray[storynum];
	} else {
		$storynum = $config[limitnews];
	}
	
	$sql = "select sid, title from ps_stories ";
	if ($myTopic != $config[def_theme]) {
		$sql.="WHERE topic = '".$myTopic."' ";
	} else {
		#get a list of topic that do not have its own topic page, they all fall into the Default topic.
		$rs = mysql_query("select topic from ps_topics where displayTopic='false'");
		$i=0;
		while (list($key) = mysql_fetch_row($rs) ) {
			$noDisplayTopic[$i] = "'" . $key . "'";
			$i++;
		}
		if (sizeof($noDisplayTopic) >0) {
			$displayStr = implode(",",$noDisplayTopic);
		} else {
			$displayStr = "''";
		}
		$sql.="WHERE topic = '".$myTopic."' or topic in ($displayStr) ";

	}
	$sql .= "order by time desc limit $storynum,$config[older_story_num]";
	
	$result = mysql_query( $sql );
	
	if (mysql_num_rows($result) > 0) {
		while(list($sid, $title) = mysql_fetch_row($result)) {
			$title = check_words($title);
			$boxstuff .= "<li><a href=\"article.php?sid=$sid&myTopic=$myTopic\">$title</a></li>";
			
		}
		mysql_free_result($result);
		themesidebox($boxTitle, $boxstuff);
	}

	unset($boxstuff,$boxTitle,$tmpArray,$storynum,$querystr,$result,$sql);
}




/********************************/
/******* poll functions *********/
/********************************/

function pollMain($pollID,$url="") {

// displays a poll but dependent on pollNewest() and pollBooth.php.  if $url is set, we will forward to whatever $url specify
	global $config,$myTopic;
	
	if(!isset($pollID))
		$pollID = 0;
	
	$boxContent = "";
	$result = mysql_query("SELECT pollTitle, voters FROM ps_poll_desc WHERE pollID=$pollID");
	$boxContent = '';
	if (mysql_num_rows($result) > 0) {
		list($pollTitle, $voters) = mysql_fetch_row($result);
		mysql_free_result($result);
		// make the form
		$boxContent .= "<form action=\"pollBooth.php\" method=\"post\">";
		$boxContent .= "<input type=\"hidden\" name=\"pollID\" value=\"".$pollID."\">";
		$boxContent .= "<input type=\"hidden\" name=\"forwarder\" value=\"".$url."\">"; 
		$boxContent .= "<input type=\"hidden\" name=\"myTopic\" value=\"".$myTopic."\">";
		$boxContent .= "<input type=\"hidden\" name=\"op\" value=\"voteNow\">";
		$boxTitle = translate("Poll");
		$boxContent .= "<b>$pollTitle</b><br>";

		// grap all the options for the poll
		for($i = 1; $i <= $config[maxOptions]; $i++) {
			$result = mysql_query("SELECT pollID, optionText, optionCount, voteID FROM ps_poll_data WHERE (pollID=$pollID) AND (voteID=$i)");
			$object = mysql_fetch_object($result);
			if(is_object($object)) {
				mysql_free_result($result);
				$optionText = $object->optionText;
				if($optionText != "") {
					$boxContent .= "<input type=\"radio\" name=\"voteID\" value=\"".$i."\"> $optionText <br>";
				}
			}
		}
		$boxContent .= "<font size=2><input type=\"submit\" value=\"".translate("Vote")."\"><br>";
		$boxContent .= "[<a href=\"pollBooth.php?op=results&pollID=$pollID&myTopic=$myTopic\">". translate("Poll Results"). "</a> | <a href=\"pollBooth.php?myTopic=$myTopic\">". translate("Old Polls") . "</a>]<br>";
		$boxContent .= translate ("Votes").": <b>$voters</b>";
		$boxContent .= "</font></form>";
	} else {
		// no poll
		$boxTitle = translate("No poll");
		$boxContent = translate("There is no poll currently set!")."<br>";
	}
	// display the poll
	themesidebox($boxTitle, $boxContent);
	unset($boxTitle,$boxContent,$result,$pollTitle,$voters,$i,$object,$optionText);
}


function pollLatest($myTopic) {

// grabs latest poll info
	
	$result = mysql_query("SELECT MAX(pollID) FROM ps_poll_desc where topic='$myTopic'");
	list($pollID) = mysql_fetch_row($result);
	if ($result) {
		mysql_free_result($result);
	}
	return $pollID;
	
	
}


function pollNewest($myTopic) {

// grabs latest poll info and display it.

	$pollID = pollLatest($myTopic);
	pollMain($pollID);
}

//---------------------------------------------------------
// fucntions to pasrse RDF file
/*
rssparse.php3
 *
 *      Copyright (C) 2000 Jeremey Barrett
 *      hide@address.com
 *      http://nwow.org
 *
 *      Version 0.4
 *
 *      This library is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU Lesser General Public License as published by
 *      the Free Software Foundation; either version 2.1 of the License, or
 *      (at your option) any later version.
 *      
 *      This library 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 Lesser General Public License for more details.
 *      
 *      You should have received a copy of the GNU Lesser General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 *
 *      rssparse.php3 is a small PHP script for parsing RDF/RSS XML data. It has been
 *      tested with a number of popular web news and information sites such as 
 *      slashdot.org, lwn.net, and freshmeat.net. This is not meant to be exhaustive 
 *      but merely to provide the basic necessities. It will grow in capabilities 
 *      with time, I'm sure.
 *
 *      This is code I wrote for Nerds WithOut Wires, http://nwow.org.
 *		Code is modified by Derek Leung (hide@address.com) on 5/10/2001
*/
function _rssparse_start_elem ($parser, $elem, $attrs) {

  global $_rss;

  if ($elem == "CHANNEL") {
    $_rss->depth++;
    $_rss->state[$_rss->depth] = "channel";
    $_rss->tmptitle[$_rss->depth] = "";
    $_rss->tmplink[$_rss->depth] = "";
    $_rss->tmpdesc[$_rss->depth] = "";
  }
  else if ($elem == "IMAGE") {
    $_rss->depth++;
    $_rss->state[$_rss->depth] = "image";
    $_rss->tmptitle[$_rss->depth] = "";
    $_rss->tmplink[$_rss->depth] = "";
    $_rss->tmpdesc[$_rss->depth] = "";
    $_rss->tmpurl[$_rss->depth] = "";
  }
  else if ($elem == "ITEM") {
    $_rss->depth++;
    $_rss->state[$_rss->depth] = "item";
    $_rss->tmptitle[$_rss->depth] = "";
    $_rss->tmplink[$_rss->depth] = "";
    $_rss->tmpdesc[$_rss->depth] = "";
  }
  else if ($elem == "TITLE") {
    $_rss->depth++;
    $_rss->state[$_rss->depth] = "title";
  }
  else if ($elem == "LINK") {
    $_rss->depth++;
    $_rss->state[$_rss->depth] = "link";
  }
  else if ($elem == "DESCRIPTION") {
    $_rss->depth++;
    $_rss->state[$_rss->depth] = "desc";
  }
  else if ($elem == "URL") {
    $_rss->depth++;
    $_rss->state[$_rss->depth] = "url";
  }
}
  
function _rssparse_end_elem ($parser, $elem) {
  global $_rss;

  if ($elem == "CHANNEL") {
    $_rss->set_channel($_rss->tmptitle[$_rss->depth], $_rss->tmplink[$_rss->depth], $_rss->tmpdesc[$_rss->depth]);
    $_rss->depth--;
  }
  else if ($elem == "IMAGE") {
    $_rss->set_image($_rss->tmptitle[$_rss->depth], $_rss->tmplink[$_rss->depth], $_rss->tmpdesc[$_rss->depth], $_rss->tmpurl[$_rss->depth]);
    $_rss->depth--;
  }
  else if ($elem == "ITEM") {
    $_rss->add_item($_rss->tmptitle[$_rss->depth], $_rss->tmplink[$_rss->depth], $_rss->tmpdesc[$_rss->depth]);
    $_rss->depth--;
  }
  else if ($elem == "TITLE") {
    $_rss->depth--;
  }
  else if ($elem == "LINK") {
    $_rss->depth--;
  }
  else if ($elem == "DESCRIPTION") {
    $_rss->depth--;
  }
  else if ($elem == "URL") {
    $_rss->depth--;
  }
}
  
function _rssparse_elem_data ($parser, $data) {
  global $_rss;

  if ($_rss->state[$_rss->depth] == "title") {
    $_rss->tmptitle[($_rss->depth - 1)] .= $data;
  }
  else if ($_rss->state[$_rss->depth] == "link") {
    $_rss->tmplink[($_rss->depth - 1)] .= $data;
  }
  else if ($_rss->state[$_rss->depth] == "desc") {
    $_rss->tmpdesc[($_rss->depth - 1)] .= $data;
  }
  else if ($_rss->state[$_rss->depth] == "url") {
    $_rss->tmpurl[($_rss->depth - 1)] .= $data;
  }
}

class rssparser {
  var $title;
  var $link;
  var $desc;
  var $items = array();
  var $nitems;
  var $image = array();
  var $state = array();
  var $tmptitle = array();
  var $tmplink = array();
  var $tmpdesc = array();
  var $tmpurl = array();
  var $depth;

  function rssparser() {
    $this->nitems = 0;
    $this->depth = 0;
  }

  function set_channel($in_title, $in_link, $in_desc) {
    $this->title = $in_title;
    $this->link = $in_link;
    $this->desc = $in_desc;
  }

  function set_image($in_title, $in_link, $in_desc, $in_url) {
    $this->image["title"] = $in_title;
    $this->image["link"] = $in_link;
    $this->image["desc"] = $in_desc;
    $this->image["url"] = $in_url;
  }

  function add_item($in_title, $in_link, $in_desc) {
	$in_title = str_replace("!-and-!","&",$in_title); // fix for parser can read "&" char
	$in_link = str_replace("!-and-!","&",$in_link); // fix for parser can read "&" char
    $this->items[$this->nitems]["title"] = $in_title;
    $this->items[$this->nitems]["link"] = $in_link;
    $this->items[$this->nitems]["desc"] = $in_desc;
    $this->nitems++;
  }

  function parse($fp) {

    $xml_parser = xml_parser_create();
    
    xml_set_element_handler($xml_parser, "_rssparse_start_elem", "_rssparse_end_elem");
    xml_set_character_data_handler($xml_parser, "_rssparse_elem_data");
    
    while ($data = fread($fp, 4096)) {
	  $data = str_replace("&","!-and-!",$data); // fix for parser can read "&" char

      if (!xml_parse($xml_parser, $data, feof($fp))) {
		
		return 1;
      }
    }
    
    xml_parser_free($xml_parser);
    
    return 0;
  }
}

function rssparse ($fp) {
  global $_rss;

  $_rss = new rssparser();

  if ($_rss->parse($fp)) {
    return 0;
  }
  
  return $_rss;
}

//---------------------------------------------------------
/*
class parse_rdf {
	// this parse class is more reliable, but it takes way too much cpu time due to a lot of regex use..so I commment it out for now
	function parse_rdf($dateiname) {
		
		$rdf_source = @file($dateiname);
		
		if (0 == count($rdf_source) ) {
			echo "<h1>Sorry, can't fetch url $dateiname.</h1>";
		} else if (1 == count($rdf_source) ) {
			echo "Error! no HTTP1.1";
			$this->title= "Sorry, can't fetch url $dateiname. Got ".$rdf_source[0];
		} else {
			
			for ($i=0; $i<count($rdf_source); $i++) {
				$rdf_source[$i] = eregi_replace( "\"", "\\\"", $rdf_source[$i] );
				$rdf_source[$i] = eregi_replace( "[\n\r\t]", "", $rdf_source[$i] );
				$rdf_block = $rdf_block.$rdf_source[$i];
				$regex = "/\<.*([\w]+)\s\w+=\"(.+)\".?\>/iU";
				if (preg_match($regex,$rdf_source[$i],$parts)) {
					$execute='$this->'.$parts[1]."=\"".$parts[2]."\";";
					eval($execute);
				}
			}
			$rdf_block = ereg_replace("[\n\r]","",$rdf_block);
			$this->expand($rdf_block);
		}
	}

	function parse($rdf_block) {
 		$regex = "/\<([^c][^\/\>:]+)\>(.*)\<\/\\1\>/iU";
		if (preg_match_all($regex,$rdf_block,$parts)) {
			return $parts;
		}
	}
	
	function reformat($textblock) {
		$textblock=ereg_replace("<","&lt;",$textblock);
		$textblock=ereg_replace(">","&gt;",$textblock);
		$textblock=ereg_replace("'","\'",$textblock);
		return $textblock;
	}       
	
	function expand($rdf_block) {
		$data = $this->parse($rdf_block);
		$rdf_names = $data[1];
		$rdf_data  = $data[2];
		for ($i=0; $i<count($rdf_names); $i++) {
			$this->tempobject = $this->subtemp.$rdf_names[$i];
			if (preg_match("/[<>]/",$rdf_data[$i])) { 
				$this->subtemp=$this->tempobject."_";
				$this->expand($rdf_data[$i]); 
			} else {
				$execute='$this->'.$this->tempobject;
				if ($this->subtemp=="item_") { $execute .= "[]"; }
					$execute .= " = '".$this->reformat($rdf_data[$i])."';";
					eval($execute);
			}
 		}
 		$this->subtemp="";
	}
        
	function show_image($border="1") {
 		$image_to_show  = "<a href=\"$this->image_link\">";
 		$image_to_show .= "<img border=\"$border\" src=\"$this->image_url\"";
		$image_to_show .= " alt=\"$this->image_title\"";
		if ($this->image_width and $this->image_height) {
			$image_to_show .=" width=\"$this->image_width\" height=\"$this->image_height\"";
		}
		$image_to_show .= "></a>";
		return $image_to_show;
	}
	
	function show_textinput() {
		if ($this->textinput_title) {
			print "<form action=\"$this->textinput_link\" method=\"get\">\n<table border=0>\n";
			print "<tr><td><b>$this->textinput_description</b></td></tr>\n";
			print "<tr><td><input type=\"text\" name=\"".$this->textinput_name."\">";
			print "<input type=submit value=\"$this->textinput_title\"></td></tr>\n";
			print "</table>\n";
			print "</form>\n";
		}
	}
}

*/

function getTopicsDisabled() { 

        # get topics the user don't wan't to appear.
        # (list of topics disabled by user in homepage parameters)
	
	global $config;
	$c_user = getCookie($config[setting_cookie_name]);
	$cTopics = array();
	$cTopics = explode(" ",$c_user[topics]);
	
	# build the topics list
	$result = mysql_query("select topic, tid, required from ps_topics");
	$my_topics = array();
	$i=0;
	if($result > 0) {
		while(list($topic,$tid,$required) = mysql_fetch_row($result)) {
			if (in_array($tid,$cTopics) && ($required!='Y')) { 
				$my_topics[] = $topic; 
			}
			# If topic is mandatory, can't add it to the list of
			# disabled topics...
		}
		mysql_free_result($result);
	}

	unset($c_user,$cTopics,$result,$i,$topic,$tid,$required);
	return $my_topics;
}

function getTopics() { 

	# Get all the topics from the DB and hide whatever topics
    # that the user disable.
	
	$my_topics=getTopicsDisabled();

	# delete user disabled topics from list
	$result = mysql_query("select topic from ps_topics where displayTopic='true' order by topic");
	$topics=array();
 	if($result > 0) {
		while(list($topic) = mysql_fetch_row($result)) {
		  if (!in_array($topic,$my_topics)) { 
			$topics[] = $topic; 
	
		   }
		  # Add topic to the list if not in disabled list.
	 	}
		mysql_free_result($result);
	}

	unset($my_topics,$result,$topic);
	return $topics;
	
}


function getAllTopics() { 

	# Get all the topics from the DB 

	$result = mysql_query("select topic from ps_topics order by topic");
	$topics=array();
 	if($result > 0) {
		while(list($topic) = mysql_fetch_row($result)) {
			$topics[] = $topic; 
	 	}
		mysql_free_result($result);
	}

	unset($result,$topic);
	return $topics;
}


function getTopicsWithNoSection() {

// get all the topics that do not have their own section
	$rs = mysql_query("select topic from ps_topics where displayTopic='false'");
	$i=0;
	while (list($key) = mysql_fetch_row($rs) ) {
		$noDisplayTopic[$i] = "'" . $key . "'";
		$i++;
	}
	if (sizeof($noDisplayTopic) >0) {
		$displayStr = implode(",",$noDisplayTopic);
	} else {
		$displayStr = "''";
	}
	return $displayStr;

}

function getAvailTopics($uid="") {

	# this function check for the admin right, and return back the topics according to admin level
	global $config;

	$userArray = getCookie($config[user_cookie_name]);

	// Find the right according to each user
	if ($uid == "") {
		$uid = $userArray[userid];
	}
	$result = mysql_query("select topicRights from ps_users where uid=$uid");
	if ($result) {
		list($topicRights) = mysql_fetch_row($result);
		mysql_free_result($result);
	}
	$i=0;
	$topics = array();
	if ($topicRights != "") {
		$topicArray = explode(",",$topicRights);
		while (list($key,$val) = each ($topicArray)) {
			$result = mysql_query("select topic from ps_topics where tid=$val");
			$tempTopic = mysql_fetch_row($result);
			if ($tempTopic != "") {
				list($topics[$key]) = $tempTopic;
			}
			$i++;
		}

		mysql_free_result($result);
	}
	
	// find the moderate level according to topic
	if ($userArray[status] != "Admin") {
                $result = mysql_query("select topic from ps_topics where moderate<>3");
    } else {
                $result = mysql_query("select topic from ps_topics");
    }
	if (mysql_num_rows($result) > 0) {
		while ($temp = mysql_fetch_array($result)) {
			if (!in_array($temp[topic],$topics)) {
				$topics[$i++] = $temp[topic];
			}
		}
		mysql_free_result($result);
	}
	
	
	unset($userArray,$uid,$result,$topicRights,$i,$topicArray, $key,$temp);
	sort($topics);
	return $topics;

}

function getAdminRights($uid="") {

// Get the admin priviledge for specific user
	global $config;

	$userArray= getCookie($config[user_cookie_name]);
	if ($uid =="") {
		$uid = $userArray[userid];
	} 
	$result = mysql_query("select rights from ps_users where uid=$uid");
	list($rights) = mysql_fetch_array($result);
	mysql_free_result($result);
	$rightArray = explode(",",$rights);

	unset($uid,$userArray,$rights,$result);
	return $rightArray;
}

function emailValid_Partial($Addr, $Level, $Timeout = 15000) { 

// check if email address is valid, take less time, but not as accurate at level 3.  Level 5 might drop out some valid email address from time to time
// credit to hide@address.com (Darguz)
//  Valid Top-Level Domains 
    $gTLDs = "com:net:org:edu:gov:mil:int:arpa:"; 
    $CCs   = "ad:ae:af:ag:ai:al:am:an:ao:aq:ar:as:at:au:aw:az:ba:bb:bd:be:bf:". 
             "bg:bh:bi:bj:bm:bn:bo:br:bs:bt:bv:bw:by:bz:ca:cc:cf:cd:cg:ch:ci:". 
             "ck:cl:cm:cn:co:cr:cs:cu:cv:cx:cy:cz:de:dj:dk:dm:do:dz:ec:ee:eg:". 
             "eh:er:es:et:fi:fj:fk:fm:fo:fr:fx:ga:gb:gd:ge:gf:gh:gi:gl:gm:gn:". 
             "gp:gq:gr:gs:gt:gu:gw:gy:hk:hm:hn:hr:ht:hu:id:ie:il:in:io:iq:ir:". 
             "is:it:jm:jo:jp:ke:kg:kh:ki:km:kn:kp:kr:kw:ky:kz:la:lb:lc:li:lk:". 
             "lr:ls:lt:lu:lv:ly:ma:mc:md:mg:mh:mk:ml:mm:mn:mo:mp:mq:mr:ms:mt:". 
             "mu:mv:mw:mx:my:mz:na:nc:ne:nf:ng:ni:nl:no:np:nr:nt:nu:nz:om:pa:". 
             "pe:pf:pg:ph:pk:pl:pm:pn:pr:pt:pw:py:qa:re:ro:ru:rw:sa:sb:sc:sd:". 
             "se:sg:sh:si:sj:sk:sl:sm:sn:so:sr:st:su:sv:sy:sz:tc:td:tf:tg:th:". 
             "tj:tk:tm:tn:to:tp:tr:tt:tv:tw:tz:ua:ug:uk:um:us:uy:uz:va:vc:ve:". 
             "vg:vi:vn:vu:wf:ws:ye:yt:yu:za:zm:zr:zw:"; 

//  The countries can have their own 'TLDs', e.g. mydomain.com.au 
    $cTLDs = "com:net:org:edu:gov:mil:co:ne:or:ed:go:mi:"; 

    $fail = 0; 

//  Shift the address to lowercase to simplify checking 
    $Addr = strtolower($Addr); 

//  Split the Address into user and domain parts 
    $UD = explode("@", $Addr); 
    if (sizeof($UD) != 2 || !$UD[0]) $fail = 1; 

//  Split the domain part into its Levels 
    $Levels = explode(".", $UD[1]); $sLevels = sizeof($Levels); 
    if ($sLevels < 2) $fail = 1; 

//  Get the TLD, strip off trailing ] } ) > and check the length 
    $tld = $Levels[$sLevels-1]; 
    $tld = ereg_replace("[>)}]$|]$", "", $tld); 
    if (strlen($tld) < 2 || strlen($tld) > 3 && $tld != "arpa") $fail = 1; 

    $Level--; 

//  If the string after the last dot isn't in the generic TLDs or country codes, it's invalid. 
    if ($Level && !$fail) { 
    $Level--; 
    if (!ereg($tld.":", $gTLDs) && !ereg($tld.":", $CCs)) $fail = 2; 
    } 

//  If it's a country code, check for a country TLD; add on the domain name. 
    if ($Level && !$fail) { 
    $cd = $sLevels - 2; $domain = $Levels[$cd].".".$tld; 
    if (ereg($Levels[$cd].":", $cTLDs)) { $cd--; $domain = $Levels[$cd].".".$domain; } 
    } 

//  See if there's an MX record for the domain 
    if ($Level && !$fail) { 
    $Level--; 
    if (!getmxrr($domain, $mxhosts, $weight)) $fail = 3; 
    } 

//  Attempt to connect to port 25 on an MX host 
    if ($Level && !$fail) { 
    $Level--; 
    while (!$sh && list($nul, $mxhost) = each($mxhosts)) 
      $sh = fsockopen($mxhost, 25); 
    if (!$sh) $fail = 4; 
    } 

//  See if anyone answers 
    if ($Level && !$fail) { 
    $Level--; 
    set_socket_blocking($sh, false); 
    $out = ""; $t = 0; 
    while ($t++ < $Timeout && !$out) 
      $out = fgets($sh, 256); 
    if (!ereg("^220", $out)) $fail = 5; 
    } 

    if ($sh) fclose($sh); 

	unset($gTLDs,$CCs,$cTLDs,$Addr,$UD,$Levels,$sLevels,$tld);
	unset($cd,$domain,$mxhosts,$weight,$nul,$mxhost,$sh,$out,$t);
    return $fail; 
  } //MailVal


function emailValid_Full($Email,$Debug=false)  {
	
// check if email address is valid, take more time, but more accurate.
// credit to hide@address.com
    global $HTTP_HOST;  

    $Return =array();   
    // Variable for return.  
    // $Return[0] : [true|false]  
    // $Return[1] : Processing result save.  

    if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $Email)) {  
        $Return[0]=false;  
        $Return[1]="${Email} is E-Mail form that is not right.";  
        if ($Debug) echo "Error : {$Email} is E-Mail form that is not right.<br>";          
        return $Return;  
    }  
    else if ($Debug) echo "Confirmation : {$Email} is E-Mail form that is not right.<br>";  

    // E-Mail @ by 2 by standard divide. if it is $Email this "hide@address.com"..  
    // $Username : lsm  
    // $Domain : ebeecomm.com  
    // list function reference : http://www.php.net/manual/en/function.list.php  
    // split function reference : http://www.php.net/manual/en/function.split.php  
    list ( $Username, $Domain ) = split ("@",$Email);  

    // That MX(mail exchanger) record exists in domain check .  
    // checkdnsrr function reference : http://www.php.net/manual/en/function.checkdnsrr.php  
    if ( checkdnsrr ( $Domain, "MX" ) )  {  
        if($Debug) echo "Confirmation : MX record about {$Domain} exists.<br>";  
        // If MX record exists, save MX record address.  
        // getmxrr function reference : http://www.php.net/manual/en/function.getmxrr.php  
        if ( getmxrr ($Domain, $MXHost))  {  
      if($Debug) {  
                echo "Confirmation : Is confirming address by MX LOOKUP.<br>";  
              for ( $i = 0,$j = 1; $i < count ( $MXHost ); $i++,$j++ ) {  
            echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Result($j) - $MXHost[$i]<BR>";   
        }  
            }  
        }  
        // Getmxrr function does to store MX record address about $Domain in arrangement form to $MXHost.  
        // $ConnectAddress socket connection address.  
        $ConnectAddress = $MXHost[0];  
    }  
    else {  
        // If there is no MX record simply @ to next time address socket connection do .  
        $ConnectAddress = $Domain;          
        if ($Debug) echo "Confirmation : MX record about {$Domain} does not exist.<br>";  
    }  

    // fsockopen function reference : http://www.php.net/manual/en/function.fsockopen.php  
    $Connect = fsockopen ( $ConnectAddress, 25 );  

    // Success in socket connection  
    if ($Connect)    
    {  
        if ($Debug) echo "Connection succeeded to {$ConnectAddress} SMTP.<br>";  
        // Judgment is that service is preparing though begin by 220 getting string after connection .  
        // fgets function reference : http://www.php.net/manual/en/function.fgets.php  
        if ( ereg ( "^220", $Out = fgets ( $Connect, 1024 ) ) ) {  
              
            // Inform client's reaching to server who connect.  
            fputs ( $Connect, "HELO $HTTP_HOST\r\n" );  
                if ($Debug) echo "Run : HELO $HTTP_HOST<br>";  
            $Out = fgets ( $Connect, 1024 ); // Receive server's answering cord.  

            // Inform sender's address to server.  
            fputs ( $Connect, "MAIL FROM: <{$Email}>\r\n" );  
                if ($Debug) echo "Run : MAIL FROM: &lt;{$Email}&gt;<br>";  
            $From = fgets ( $Connect, 1024 ); // Receive server's answering cord.  

            // Inform listener's address to server.  
            fputs ( $Connect, "RCPT TO: <{$Email}>\r\n" );  
                if ($Debug) echo "Run : RCPT TO: &lt;{$Email}&gt;<br>";  
            $To = fgets ( $Connect, 1024 ); // Receive server's answering cord.  

            // Finish connection.  
            fputs ( $Connect, "QUIT\r\n");  
                if ($Debug) echo "Run : QUIT<br>";  

            fclose($Connect);  

                // Server's answering cord about MAIL and TO command checks.  
                // Server about listener's address reacts to 550 codes if there does not exist   
                // checking that mailbox is in own E-Mail account.  
                if ( !ereg ( "^250", $From ) || !ereg ( "^250", $To )) {  
                    $Return[0]=false;  
                    $Return[1]="${Email} is address done not admit in E-Mail server.";  
                    if ($Debug) echo "{$Email} is address done not admit in E-Mail server.<br>";  
                    return $Return;  
                }  
        }  
    }  
    // Failure in socket connection  
    else {  
        $Return[0]=false;  
        $Return[1]="Can not connect E-Mail server ({$ConnectAddress}).";  
        if ($Debug) echo "Can not connect E-Mail server ({$ConnectAddress}).<br>";  
        return $Return;  
    }  
    $Return[0]=true;  
    $Return[1]="{$Email} is E-Mail address that there is no any problem.";  
    return $Return;  
}  

function makeRDF($title,$link,$linkArray,$descArray,$filename) {

// make a rdf format file and save on a file
	global $config;
	$count = sizeof($linkArray);
	

	$content = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><rdf:RDF\nxmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\nxmlns=\"http://my.netscape.com/rdf/simple/0.9/\">\n";

	$content .= "\t<channel>\n";
	$content .= "\t\t<title>$title</title>\n";
	$content .= "\t\t<link>$link</link>\n";
	$content .= "\t\t<description>$title</description>\n";
	$content .= "\t</channel>\n\n";

	for ($i=0 ; $i<$count; $i++) {

		$content .= "\t<item>\n";
		$content .= "\t\t<title>$descArray[$i]</title>\n";
		$content .= "\t\t<link>$linkArray[$i]</link>\n";
		$content .= "\t</item>\n\n";
	}

	$content .= "</rdf:RDF>";
	$myFile = $config[rdf_path]."/".$filename;

	$fp = fopen($myFile,"w");
	if (flock($fp,2)) {
		fwrite($fp,$content);
	}
	flock($fp,3);
	fclose($fp);
	unset($content,$count,$i,$myFile,$fp);
}


function grapHeadLines($url, $bid) {
// grap headlines base on the refresh time.  If it is time to grap a fresh copy, we grap a fresh copy, eles we just return the cache

	global $config;

	// find the host name and path
	if (preg_match("/^(http|ftp|https):\/\/?([^\/]+)(\/[^\n]+)/i",$url, $matches)) {
		$isURL = true;
	} else {
		$isURL = false;
	}
	$host = $matches[2];
	$path = $matches[3];

	
	// not a URL, it is a physical path, we grap the file from physical path and return it
	if ($isURL == false) {
		$fp = fopen("$url", "r");
		$rdf = rssparse($fp);
		fclose($fp);
		return $rdf;
	}

	
	// check the time if we use the cache or grap a fresh copy
	$result = mysql_query("select refresh, ts, now() from ps_blocks where id = $bid");
	list($refresh,$ts, $now) = mysql_fetch_row($result);
	$test  = strtotime($now) - strtotime($ts);
	$test = $test / 60;

	// not the time to grap a fresh copy yet, we return the cache
	if ($test < $refresh) {
		$rdfFile = "rdfCache" . $bid . ".rdf";
		$fp = fopen("$config[rdf_path]/$rdfFile", "r");
		$rdf = rssparse($fp);
		fclose($fp);
		return $rdf;
	}	

	if ($host != "") {
		/*
		// the following code is for virtual hosting site, I keep it here just in case you came into a site that is a virtual hosting site.
		// but this is very slow compare to the normal method
		$fp = fsockopen($host,80); 
		fputs($fp,"GET $path HTTP/1.1\r\n"); 
		fputs($fp,"Host: $host\r\n\r\n"); 
		*/
		
		// save it to file
		$rdfFile = "rdfCache" . $bid . ".rdf";
		$fp2 = fopen("$config[rdf_path]/$rdfFile", "w");
		$fp = fopen("$url","r");
		$start = false;
		while(!feof($fp)){ 
			$buffer = fgets($fp,1024); 
			if (preg_match("/rdf/i",$buffer)) {
				$start = true;
			}
			if ($start == true) {
				fputs($fp2,$buffer);

			}
		} 
		fclose($fp); 
		fclose($fp2);

		// read back the cache file and return it later
		$fp = fopen("$config[rdf_path]/$rdfFile", "r");
		$rdf = rssparse($fp);
		fclose($fp);

		// we now update the timestamp in database
		mysql_query("update ps_blocks set ts = NOW() where id = $bid");
		if (mysql_error()) {
			$mesg = "Error! ". mysql_error();
		} 

		return $rdf;
	}

	// not finding anything, return false
	return false;
}


function getblocks($myTopic) {
// grabs side boxes from database and display

	
	$result = @mysql_query("select id,title, content, type, url from ps_blocks where topic='$myTopic' order by listOrder ");
	if (mysql_num_rows($result) > 0 ) {
		while(list($bid, $title, $content, $type, $url) = mysql_fetch_array($result)) {
			// Handle dynamic/static blocks
			if ($type == "D") {
				// Dynamic block. Pass to the appropriate theme display function.
				themedynamicsidebox($title, $url,$bid);
			} else  {
				// Static block. Clean out any PHP specific start/end block.
				$content = str_replace("<?","",$content);
				$content = str_replace("?>","",$content);
				themesidebox(auto_link($title), auto_link($content));
			}
		}
		mysql_free_result($result);
	}
	unset($title,$content,$type,$url,$bid);
}

// No code after this line to avoid cookie error.
?>
Return current item: PSlash