<?php
// ------------------------------------------------------------------------- //
//                XOOPS - PHP Content Management System                      //
//                       <http://www.xoops.org/>                             //
// ------------------------------------------------------------------------- //
//  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.                                      //
//                                                                           //
//  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.  See the            //
//  GNU General Public License for more details.                             //
//                                                                           //
//  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 //
// ------------------------------------------------------------------------- //
	// ################## Various functions from here ################

	function xoops_header($closehead=true) {
		global $xoopsConfig, $xoopsTheme;
		$myts =& MyTextSanitizer::getInstance();
		if ( !headers_sent() ) {
			if ( $xoopsConfig['gzip_compression'] ) {
                		if (extension_loaded("zlib") ) {
                        		if ( function_exists('version_compare') ) { // PHP 4.10+ has version_compare
                                		if ( version_compare("4.0.5", phpversion(),'le') ) {
                                        		ob_start("ob_gzhandler");
                               	 		} else {
                                        		ob_start();
                                		}
                        		} elseif ( preg_match("/[4-9]\.[0-9]\.[5-9].*/", phpversion()) )  {                     
                                		ob_start("ob_gzhandler");
                        		} else {
                                		ob_start();
                        		}
                		} else {
                        		ob_start();
                		}
        		} else {
                		ob_start();
        		}
			header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        		header("Cache-Control: no-store, no-cache, must-revalidate");
        		header("Cache-Control: post-check=0, pre-check=0", false);
        		header("Pragma: no-cache");
		}
		$meta = getMeta();
		$meta = $myts->makeTareaData4InsideQuotes($meta);
    		echo "<html>\n";
    		echo "<head>\n";
		echo "<meta http-equiv='Content-Type' content='text/html; charset="._CHARSET."' />\n";
		echo "<meta name='author' content='".$xoopsConfig['sitename']."' />\n";
		echo "<meta name='copyright' content='Copyright (c) 2002 by ".$xoopsConfig['sitename']."' />\n";
		echo "<meta name='keywords' content='".$meta."' />\n";
		echo "<meta name='description' content='".$xoopsConfig['slogan']."' />\n";
		echo "<meta name='generator' content='".XOOPS_VERSION."' />\n\n";
		echo "<title>".$xoopsConfig['sitename']."</title>\n";
		include(XOOPS_ROOT_PATH."/include/xoopsjs.php");
		$themecss = getcss(getTheme());
		echo "<link rel='stylesheet' type='text/css' media='all' href='".XOOPS_URL."/xoops.css' />\n";
		if ( $themecss ) {
			echo "<style type='text/css' media='all'><!-- @import url($themecss); --></style>\n\n";
		}
		if ( $closehead ) {
			echo "</head><body>";
		}
	}

	function xoops_footer(){
		echo "</body></html>";
		ob_end_flush();
	}

	/*
	 * Function to display formatted times in user timezone
	 */
	function formatTimestamp($time, $format="l", $timeoffset="") {
		global $xoopsConfig, $xoopsUser;
		if ( $timeoffset == "" ) {
			if ( $xoopsUser ) {
				$timeoffset = $xoopsUser->getVar("timezone_offset");
			} else {
				$timeoffset = $xoopsConfig['default_TZ'];
			}
		}
		$usertimestamp = $time + ($timeoffset - $xoopsConfig['server_TZ'])*3600;
		if ( $format == "s" ) {
			$datestring = _SHORTDATESTRING;
		} elseif ( $format == "m" ) {
			$datestring = _MEDIUMDATESTRING;
		} elseif ( $format == "l" ) {
			$datestring = _DATESTRING;
		} elseif ( $format == "mysql" ) {
			$datestring = "Y-m-d H:i:s";
		} elseif ( $format != "" ) {
			$datestring = $format;
		} else {
			$datestring = _DATESTRING;
		}
        	$datetime = date($datestring, $usertimestamp);
        	$datetime = ucfirst($datetime);
        	return $datetime;
	}

	/*
	 * Function to calculate server timestamp from user entered time (timestamp)
	 */
	function userTimeToServerTime($timestamp, $userTZ=NULL){
		global $xoopsConfig;
		if ( !isset($userTZ) ) {
			$userTZ = $xoopsConfig['default_TZ'];
		}
		$offset = $userTZ - $xoopsConfig['server_TZ'];
		$timestamp = $timestamp - ($offset * 3600);
		return $timestamp;
	}


	/*
	 * Functions to display dhtml loading image box
	 */
	function OpenWaitBox() {
		global $xoopsConfig;
		if ($xoopsConfig['display_loading_img']==1) {
			echo "<div id='waitDiv' style='position:absolute;left:40%;top:50%;visibility:hidden;text-align: center;'><table cellpadding='6' border='2' class='bg2'><tr><td align='center'><b><big>" ._FETCHING."</big></b><br /><img src='".XOOPS_URL."/images/await.gif' alt='' /><br />" ._PLEASEWAIT."</td></tr></table></div><script type='text/javascript'> <!-- 
	var DHTML = (document.getElementById || document.all || document.layers);
function ap_getObj(name) { if (document.getElementById) { return document.getElementById(name).style; } else if (document.all) { return document.all[name].style;
} else if (document.layers) { return document.layers[name]; } } function ap_showWaitMessage(div,flag)  { if (!DHTML) return; var x = ap_getObj(div); x.visibility = (flag) ? 'visible':'hidden'
if(! document.getElementById) if(document.layers) x.left=280/2; return true; } ap_showWaitMessage('waitDiv', 1); 
 //--> </script>";
		}
	}

	function CloseWaitBox()  {
		global $xoopsConfig;
		if ($xoopsConfig['display_loading_img']==1){
			echo "<script type='text/javascript'> <!-- 
  			ap_showWaitMessage('waitDiv', 0);
 			//--></script><br />";
		}	
	}

	function makePass() {
		$makepass="";
		$syllables = array("er","in","tia","wol","fe","pre","vet","jo","nes","al","len","son","cha","ir","ler","bo","ok","tio","nar","sim","ple","bla","ten","toe","cho","co","lat","spe","ak","er","po","co","lor","pen","cil","li","ght","wh","at","the","he","ck","is","mam","bo","no","fi","ve","any","way","pol","iti","cs","ra","dio","sou","rce","sea","rch","pa","per","com","bo","sp","eak","st","fi","rst","gr","oup","boy","ea","gle","tr","ail","bi","ble","brb","pri","dee","kay","en","be","se");
		srand((double)microtime()*1000000);
		for ($count=1;$count<=4;$count++) {
			if (rand()%10 == 1) {
				$makepass .= sprintf("%0.0f",(rand()%50)+1);
			} else {
				$makepass .= sprintf("%s",$syllables[rand()%62]);
			}
		}
		return $makepass;
	}

	function checkIp($ip){
		global $xoopsBadIps;
		if ( !empty($xoopsBadIps) ) {
			foreach ($xoopsBadIps as $xbi) {
				if ( !empty($xbi) && preg_match("/".$xbi."/", $ip)) {
					return false;
				}
			}
		}
		return true;
	}

	function checkEmail($email){
		if (!$email || !eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+([\.][a-z0-9-]+)+$",$email)){
			return false;
		}
		return true;
	}

	function formatURL($url){
		if (($url != "") && (!(eregi('(^http[s]*:[/]+)(.*)', $url)))){
			$url = "http://" . $url;
		}
		return $url;
	}

	/*
	* Prints allowed html tags on this site
	*/
	function get_allowed_html(){
		global $xoopsConfig;
		$allowed = str_replace(">","> ",$xoopsConfig['allowed_html']);
		return htmlspecialchars($allowed);
	}


	/*
	* Just a simple wrap to php mail() function
	*/
	function xoops_mail($to, $subject, $message, $headers=""){
		global $xoopsConfig;
		if ( $headers == "" ) {
			$headers = "From: ".$xoopsConfig['sitename']." <".$xoopsConfig['adminmail'].">\n";
			$headers .= "X-Mailer: PHP/".phpversion()."\n";
		}
		mail($to, $subject, $message, $headers);
	}

	/*
	 * Function to display banners in all pages
	 */
	function showbanner() {
		global $xoopsDB, $xoopsConfig, $REMOTE_ADDR;
			$bresult = $xoopsDB->query("SELECT COUNT(*) FROM ".$xoopsDB->prefix("banner")."");
    		list ($numrows) = $xoopsDB->fetchRow($bresult);
    		if ( $numrows > 1 ) {
			$numrows = $numrows-1;
			mt_srand((double)microtime()*1000000);
			$bannum = mt_rand(0, $numrows);
    		} else {
			$bannum = 0;
    		}
    		if ( $numrows > 0 ) {
			$bresult = $xoopsDB->query("SELECT * FROM ".$xoopsDB->prefix("banner")."",1,$bannum);
    			list ($bid, $cid, $imptotal, $impmade, $clicks, $imageurl, $clickurl, $date) = $xoopsDB->fetchRow($bresult);
    			if ( $xoopsConfig['my_ip']==$REMOTE_ADDR ) {
				// EMPTY
			} else {
				$xoopsDB->queryF("UPDATE ".$xoopsDB->prefix("banner")." SET impmade=impmade+1 WHERE bid=$bid");
    			}
			/* Check if this impression is the last one and print the banner */
			if ( $imptotal == $impmade ) {
				$newid = $xoopsDB->genId($xoopsDB->prefix("bannerfinish")."_bid_seq");
	    			$xoopsDB->queryF("INSERT INTO ".$xoopsDB->prefix("bannerfinish")." (bid, cid, impressions, clicks, datestart, dateend) VALUES ($newid, $cid, $impmade, $clicks, $date, ".time().")");
	    			$xoopsDB->queryF("DELETE FROM ".$xoopsDB->prefix("banner")." WHERE bid=".$bid."");
			}
    			echo "<div><a href='".XOOPS_URL."/banners.php?op=click&amp;bid=$bid' target='_blank'><img src='$imageurl' alt='' /></a></div>";
		}
	}


	/*
	 * Function to redirect a user to certain pages
	 */
	function redirect_header($url, $time=4, $message=""){
		global $xoopsConfig;
		echo "<html><head>\n";
		echo "<meta http-equiv='Content-Type' content='text/html; charset="._CHARSET."' />\n";
		echo "<meta http-equiv='Refresh' content='$time; url=$url' />\n";
		echo "<style>
		body {	
			margin:50px 0px; padding:0px;
			text-align:center;
		}
		#Content {
			width:70%;
			margin:0px auto;
			text-align:center;
			padding:15px;
			border:1px dashed #333;
			background-color:#eee;
		}
		</style>";
		echo "</head><body><div id='content'>\n";
		if ( $message!="" ) {
			echo "<h4>".$message."</h4>\n";
		} else {
			echo "<h4>"._TAKINGBACK."</h4>\n";
		}
		echo "<br /><b>\n";
		printf(_IFNOTRELOAD,$url);
		echo "</b>\n";
		echo "</div>\n";
		echo "</body></html>";
	}


	/*
	 * Function to get meta tag keywords
	 */
	function getMeta(){
		global $xoopsDB;
		$sql = "SELECT meta FROM ".$xoopsDB->prefix("metafooter")." WHERE (1=1)";
		$result = $xoopsDB->query($sql);
		list($meta) = $xoopsDB->fetchRow($result);
		return $meta;
	}

	/*
	 * Function to get footer
	 */
	function getFooter(){
		global $xoopsDB;
		$sql = "SELECT footer FROM ".$xoopsDB->prefix("metafooter")." WHERE (1=1)";
		$result = $xoopsDB->query($sql);
		list($footer) = $xoopsDB->fetchRow($result);
		return $footer;
	}

	/*
	 * Function to get a user selected theme file
	 */
	function getTheme($theme=""){
		global $xoopsConfig, $xoopsDB, $xoopsUser;
		$themedir = XOOPS_ROOT_PATH."/themes";
		if ( !isset($theme) || trim($theme) == "" ) {
			if ( $xoopsUser ) {
				$theme = $xoopsUser->getVar("theme");
				if ( isset($theme) && $theme != "" ) {
					if ( file_exists($themedir."/".$theme."/theme.php") ) {
						return $theme;
					}
				} else {
					return $xoopsConfig['default_theme'];
				}
			} else {
				return $xoopsConfig['default_theme'];
			}
		} else {
			$theme = trim($theme);
			if ( file_exists($themedir/$theme/theme.php) ) {
				return $theme;
			}
		}
		return $xoopsConfig['default_theme'];
	}

	/*
	 * Function to get css file for a certain theme
	 */
	function getcss($whatdir) {
		global $xoopsConfig, $HTTP_USER_AGENT;
		if(ereg('MSIE',$HTTP_USER_AGENT) && !ereg('Opera',$HTTP_USER_AGENT)){
			$str_css = "style.css";
		}else{
			$str_css = "styleNN.css";
		}
		$themedir = XOOPS_ROOT_PATH."/themes";
		$filepath = "$themedir/$whatdir/style/$str_css";
		$default = "$themedir/$whatdir/style/style.css";
		if ( file_exists($filepath) ) {
		//need to change to absolute path for inclusion from modules
			$whatcss = XOOPS_URL."/themes/$whatdir/style/$str_css";
		} elseif ( file_exists($default) ) {
			$whatcss = XOOPS_URL."/themes/$whatdir/style/style.css";
		} else {
			$whatcss = "";
		}
		return $whatcss;
	}

	/*
	 * Function to display a message encouraging users
	 * to use web standards browser
	 */
	function waspInfo() {
		return "<p class='ahem'><small>This site will look MUCH better in a browser that supports <a title='The Web Standards Project&apos;s BROWSER UPGRADE initiative.' href='http://www.webstandards.org/upgrade/'>web standards</a>, but its content is accessible to any browser or Internet device.</small></p>";
	}

	function avatarExists($uid){
		global $xoopsConfig;
		// recommend not to change this
		$allowed_ext = array("gif", "jpeg", "jpg", "png");
		foreach($allowed_ext as $ext){
			if ( file_exists(XOOPS_ROOT_PATH."/images/avatar/users/".$uid.".".$ext ) ) {
				return "users/".$uid.".".$ext;
			}
		}
		return false;
	}

	function &getMailer(){
		if ( class_exists("XoopsMailerLocal") ) {
			return new XoopsMailerLocal();
		} else {
			return new XoopsMailer();
		}
	}



	// #################### Block functions from here ##################

	/*
	 * Purpose : Builds the blocks on both sides
	 * Input   : $side = On wich side should the block are displayed?
	 *             0, l, left : On the left side
	 *             1, r, right: On the right side
	 *             other:   Only on one side (
	 *                          Call from theme.php makes all blocks on the left side
	 *                          and from theme.php for the right site)
	 */
	function make_sidebar($side) {
		global $xoopsUser;
		$xoopsblock = new XoopsBlock();
		$arr = array();
		if ( $side == "left" ) {
			$side = XOOPS_SIDEBLOCK_LEFT;
		} elseif ( $side == "right" ) {
			$side = XOOPS_SIDEBLOCK_RIGHT;
		} else {
			$side = XOOPS_SIDEBLOCK_BOTH;
		}
		if ( $xoopsUser ) {
			$arr = $xoopsblock->getAllBlocksByGroup($xoopsUser->groups(), true, $side, XOOPS_BLOCK_VISIBLE);
		} else {
			$arr = $xoopsblock->getAllBlocksByGroup(XoopsGroup::getByType("Anonymous"), true, $side, XOOPS_BLOCK_VISIBLE);
		}
		foreach ( $arr as $myblock ) {
			$block = array();
			$block = $myblock->buildBlock();
			if($block){
				if ( $side == XOOPS_SIDEBLOCK_LEFT ) {
                        		themesidebox($block['title'],$block['content']);
                        	} elseif( $side == XOOPS_SIDEBLOCK_RIGHT && function_exists("themesidebox_right") ) {
                        		themesidebox_right($block['title'],$block['content']);
                        	} else {
					themesidebox($block['title'],$block['content']);
				}
			}
			unset($myblock);
			unset($block);
		}
	}

	/*
	 * Function to display center block
	 */
	function make_cblock() {
		global $xoopsUser;
		$xoopsblock = new XoopsBlock();
		$cc_block = $cl_block = $cr_block = "";
		$arr = array();
		if ( $xoopsUser ) {
			$arr = $xoopsblock->getAllBlocksByGroup($xoopsUser->groups(), true, XOOPS_CENTERBLOCK_ALL, XOOPS_BLOCK_VISIBLE);
		} else {
			$arr = $xoopsblock->getAllBlocksByGroup(XoopsGroup::getByType("Anonymous"), true, XOOPS_CENTERBLOCK_ALL, XOOPS_BLOCK_VISIBLE);
		}
		if ( count($arr) > 0 ){
			foreach ( $arr as $myblock ) {
				$block = array();
				$block = $myblock->buildBlock();
				if ( $block ) {
					if ( XOOPS_CENTERBLOCK_CENTER == $myblock->getVar("side") ) {
						if ( $block['title'] != "" ) {
							$cc_block .= "<tr valign='top'><td colspan='2'><b>".$block['title']."</b><hr />".$block['content']."<br /><br /></td></tr>\n";
						} else {
							$cc_block .= "<tr><td colspan='2'>".$block['content']."<br /><br /></td></tr>\n";
						}
					} elseif ( XOOPS_CENTERBLOCK_LEFT == $myblock->getVar("side") ) {
						if ( $block['title'] != "" ) {
							$cl_block .= "<p><b>".$block['title']."</b><hr />".$block['content']."</p>\n";
						} else {
							$cl_block .= "<p>".$block['content']."</p>\n";
						}
					} else {
						if ( $block['title'] != "" ) {
							$cr_block .= "<p><b>".$block['title']."</b><hr />".$block['content']."</p>\n";
						} else {
							$cr_block .= "<p>".$block['content']."</p>\n";
						}
					}
				}
				unset($myblock);
				unset($block);
			}
			OpenTable();
			echo "<table width=\"100%\">".$cc_block."<tr valign='top'><td width='50%'>".$cl_block."</td><td width='50%'>".$cr_block."</td></tr></table>\n";
			CloseTable();
		}
	}



	function openThread($width="100%"){
		echo "<table border='0' cellpadding='0' cellspacing='0' align='center' valign='top' width='$width'><tr><td class='bg2'><table border='0' cellpadding='4' cellspacing='1' width='100%'><tr class='bg3' align='left'><td width='20%'>". _POSTER ."</td><td>". _THREAD ."</td></tr>";
	}


	function showThread($color_number, $subject_image, $subject, $text, $post_date, $ip_image, $reply_image, $edit_image, $delete_image, $username="", $rank_title="", $rank_image="", $avatar_image="", $reg_date="", $posts="", $user_from="", $online_image="", $profile_image="", $pm_image="", $email_image="", $www_image="", $icq_image="", $aim_image="", $yim_image="", $msnm_image="") {
		global $xoopsConfig;
		if ( $color_number == 1 ) {
			$bg = 'bg1';
		} else {
			$bg = 'bg3';
		}
		echo "<tr class='$bg' align='left'><td valign='top' style='word-space: nowrap;'><b>$username</b><br />$rank_title<br />$rank_image<br />$avatar_image<br /><br /><span style='font-size:smaller;'>$reg_date<br />$posts<br />$user_from<br /><br />$online_image</span></td>";
	echo "<td valign='top'><table width='100%' border='0'><tr><td valign='top'>$subject_image&nbsp;<span style='font-size:smaller;'><b>$subject</b><span style='font-size:smaller;'></td><td align='right'>".$ip_image."".$reply_image."".$edit_image."".$delete_image."</td></tr>";
	echo "<tr><td colspan='2'><p>$text</p></td></tr></table></td></tr>";
	echo "<tr class='$bg' align='left'><td valign='middle' style='word-space: nowrap;'><img src='".XOOPS_URL."/images/icons/posticon.gif' alt='' /><span style='font-size:smaller;'>&nbsp;$post_date</span></td><td valign='middle'>".$profile_image."".$pm_image."".$email_image."".$www_image."".$icq_image."".$aim_image."".$yim_image."".$msnm_image."</td></tr>";
	}
	
	function closeThread(){
		echo "</table></td></tr></table>";
	}


	function ss_timing_start ($name = 'default') {
		global $ss_timing_start_times;
		$ss_timing_start_times[$name] = explode(' ', microtime());
	}

	function ss_timing_stop ($name = 'default') {
		global $ss_timing_stop_times;
		$ss_timing_stop_times[$name] = explode(' ', microtime());
	}

	function ss_timing_current ($name = 'default') {
		global $ss_timing_start_times, $ss_timing_stop_times;
		if (!isset($ss_timing_start_times[$name])) {
			return 0;
		}
		if (!isset($ss_timing_stop_times[$name])) {
			$stop_time = explode(' ', microtime());
		} else {
			$stop_time = $ss_timing_stop_times[$name];
		}
		// do the big numbers first so the small ones aren't lost
		$current = $stop_time[1] - $ss_timing_start_times[$name][1];
		$current += $stop_time[0] - $ss_timing_start_times[$name][0];
		return $current;
	}


?>