<?php
/*
++++++++++++++++++++++++++++++++++++++++++++++++++++++
| LightNEasy Content Management System
| Copyright 2007 - 2008 Fernando Baptista
| http://Lightneasy.org
++++++++++++++++++++++++++++++++++++++++++++++++++++++
| common.php common functions module
| no database Version 2.2.1
++++++++++++++++++++++++++++++++++++++++++++++++++++++
| Released under the terms & conditions of v2 of the
| GNU General Public License. For details refer to
| the included gpl.txt file or visit http://gnu.org
++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/

function showrss() {
	$out="News feed: <a href=\"./LightNEasy/rss.php\"><img src=\"images/rss.png\" alt=\"RSS feed\" title=\"News RSS feed\" style=\"border: none; padding: none; margin: none;\"/></a>\n";
	return $out;
}

function lyteframe( $title, $link, $width=0, $height=0 ) {
	$out="<a rev=\"width: ";
	if($width)
		$out.= $width;
	else
		$out.= "640";
	$out.= "px; height: ";
	if($height)
		$out.= $height;
	else
		$out.= "380";
	$out.= "px; scrolling: no;\" title=\"".$title."\" rel=\"lyteframe\" href=\"".$link."\">".$title."</a>\n";
	return $out;
}

function iframe($url, $width) {
	$out="<div style=\"text-align: center; margin: 0; padding: 0;\">\n";
	$out.="<iframe id=\"the_iframe\"\n width=\"";
	if($width) $out.=$width;
	else $out.="100%";
	$out.="\"\n onLoad=\"calcHeight();\"\n src=\"".$url."\"\n scrolling=\"NO\"\n frameborder=\"0\"\n height=\"1\">\nAn iframe capable browser is\nrequired to view this web site\n</iframe>\n</div>\n";
	return $out;
}

function galery($gal="") {
	global $langmessage;
	$out.="<div class=\"LNE_gallery\">";
	if($gal!="") {
		$count=1;
		$out.="<h2 class=\"LNE_title\">".$gal."</h2>\n";
		$galeries[0]="galeries/".$gal;
	} else {
		if(isset($_POST['gal']))
			$gal=$_POST['gal'];
		$folder="galeries";
		$galeries = preg_find('/./' , $folder , PREG_FIND_DIRONLY | PREG_FIND_SORTBASENAME);
	}
	// how many galeries?
	if(count($galeries)>1) {
		$out.="\n<form method=\"post\" name=\"galery\" action=\"\"><fieldset style=\"border: 0;\">\n";
		$out.="<select onchange=\"document.galery.submit();\" name=\"gal\" class=\"LNE_select\">\n";
		foreach($galeries as $galery) {
			$out.='<option value="'.$galery.'"';
			if($gal==$galery) $out.=" selected";
			$out.=">".substr($galery,9)."&nbsp;</option>\n";
			if($gal=="") $gal=$galery;
		}
		$out.="</select>\n";
		$out.="<input type=\"hidden\" name=\"showgalery\" value=\"$langmessage[94]\" />\n";
		$out.="</fieldset></form>\n";
		$out.="<br />\n";
	} else {
		$gal=$galeries[0];
	}
	//$gal contains the galery folder
	$filez=preg_find('/./',$gal,PREG_FIND_SORTBASENAME);
	foreach($filez as $file) {
		$out.="<a href=\"".$file."\" rel=\"lytebox[".$gal."]\" title=\"".$file."\" >\n";
		$out.="<img src=\"LightNEasy/thumbsup.php?image=../".$file."&amp;width=100&amp;height=100\"  alt=\"".$file."\" class=\"LNE_gallery_img\" /></a>\n";
	}
	$out.="</div>\n";
	return $out;
}

// shows links or downloads
function show($cat,$type) {
	global $langmessage;
	//read link categories
	$aaa=trim(@file_get_contents("data/".$type."cat.dat"));
	unset($linkcat);
	unset($linkscat);
	$linkcat=explode("||",$aaa);
	$count1=0;
	$count=0;
	while($linkcat[$count] != "") {
		$aaa=explode("|",$linkcat[$count]);
		if($cat==$aaa[0] || $cat==0) {
			$linkscat[$count1]=$aaa;
			$count1++;
		}
		$count++;
	}
	//read links id,nome,link, descricao,cat
	$aaa=trim(@file_get_contents("data/".$type."s.dat"));
	unset($link);
	unset($links);
	$link=explode("||",$aaa);
	$count=0;
	$sel=0;
	while($link[$count] != "") {
		if($cat) {
			$aaa=explode("|",$link[$count]);
			if($aaa[4]==$cat) {
				$links[$sel]=$aaa;
				$sel++;
			}
		} else
			$links[$count]=explode("|",$link[$count]);
		$count++;
	}
	$count=0;
	if($type=="download") $GETarray=$_GET;
	$out.="<div id=\"LNE_show\">\n";
	while($linkscat[$count][0]!="") {
		$out.="<h3>".decode($linkscat[$count][2])."</h3>\n";
		$count1=0;
		$first=1;
		while($links[$count1][0]!="") {
			if($links[$count1][4]==$linkscat[$count][0]) {
				if($first) {
					$out.="<ul>\n";
					$first=0;
				}
				if($type=="link") {
					$out.="<li><a href=\"".$links[$count1][2]."\">".decode($links[$count1][1])."</a><div>".decode($links[$count1][3])."</div></li>\n";
				} else {
					$GETarray['dlid'] = $links[$count1][0];
					$out.="<li><a href=\"".$_SERVER['SCRIPT_NAME']."?".http_build_query($GETarray,'','&amp;')."\">".decode($links[$count1][1])."</a><div>".decode($links[$count1][3])."</div></li>\n";
				}
			}
			$count1++;
		}
		if(!$first) $out.="</ul>\n";
		$count++;
	}
	$out.="</div>\n";
	return $out;
}

function fullmenu($generat=0) {
	global $pagenum, $menu, $selected, $extension, $set;
	$count=0;
	$out="\n";
	while($menu[$count][0] != "") {
		if(strpos($menu[$count][3],"#") === false) {
		$out.='<li';
		if($menu[$count][2]!="0")
			$out.=" class=\"LNE_menu_doubleintend\"";
		elseif($menu[$count][1]!="0")
			$out.=" class=\"LNE_menu_intend\"";
		else
			$out.=" class=\"LNE_menu\"";
		$out.="><a ";
		if($menu[$count][4]==$selected['name'])
			$out.= 'class="selected" ';
		if(strpos($menu[$count][3],"*"))
			$out.='href="'.str_replace("*", "",$menu[$count][3]).'">';
		elseif($generat)
			$out.='href="'.$menu[$count][3].".".$set['extension'].'">';
		else
			$out.='href="'.$set['indexfile'].'?page='.$menu[$count][3].'">';
		$out.=$menu[$count][4]."</a></li>\n";
		}
		$count++;
	}
	return $out;
}

function shownews($post_integra=1,$post_cabecalho=9,$comenta=0,$categ=-1) {
	global $langmessage, $set, $fuso_s, $pagenum;
	$fuso_s = strval($set['timeoffset']) * 3600;
	if($_GET['id']!="") {
		if(!is_intval($_GET["id"])) die ($langmessage[98]);
		$noticia_numero = $_GET["id"];
	}
	$aa=explode("||",trim(@file_get_contents("data/news.dat")));
	$count=0;
	$lugar=-1;
	$cc=0;
	//read all news or only news=$categ, if set
	while($aa[$cc] != "") {
		$aaa=explode("|",trim($aa[$cc]));
		if($categ==-1 || (strval($aaa[7]) == strval($categ))) {
			$row_db[$count]=$aaa;
			if($noticia_numero!="" && $row_db[$count][0]==$noticia_numero)
				$lugar=$count;
			$count++;
		}
		$cc++;
	}
	$count--;
	$total=$count;
	if($lugar==-1)
		$noticia_numero=$row_db[$count][0];
	else {
	// place the selected news on top
		$n=$row_db[$lugar];
		for($i=$lugar; $i<$total; $i++) {
			$row_db[$i]=$row_db[$i+1];
		}
		$row_db[$total]=$n;
		$post_integra=1;
	}
	$row_cmt=readdata("comments");
	$first=true;
	$firstcomment=true;
	// display expanded news
	$out.="<div id=\"LNEnews\">\n";
	while($row_db[$count][0]!="" && $total-$count<$post_integra) {
		if(!$first) $out.="<hr /><br />";
		$out.=show_one_news($row_db[$count][3],$row_db[$count][5],$row_db[$count][4],$row_db[$count][1],$row_db[$count][2]);
		if($comenta) { // are comments set?
			// read comments
			$j=0;
			foreach($row_cmt as $aaa) {
				if($aaa[0]==$row_db[$count][0]) {
					$comments[$j]=$aaa;
					$j++;
				}
			}
			if($j) { // there are comments
				if($_GET['showcomments']) {
					$ff=true;
					$i=0;
					while($comments[$i][0]!="") {
						if($ff) {
							$out.="<div class=\"LNEnews_comments\">".$langmessage[143].":</div>";
							$ff=false;
						}
						$out.="<div class=\"LNEnews_comment\">\n";
						$out.="<span class=\"poster\">$langmessage[144]: </span>\n";
						$out.="<span class=\"author\">".decode($comments[$i][1])."</span>";
						if($comments[$i][2]!="-")
							$out.="<br /><span class=\"email\"><a href=\"mailto:".decode($comments[$i][2])."\">".decode($comments[$i][2])."</a></span>";
						$out.="<span class=\"text\">".decode($comments[$i][4])."</span>";
						$out.="<span class=\"time\">".$langmessage[112]." ".data_formatada($comments[$i][3] + $fuso_s)."</span>";
						$out.="</div>\n";
						$i++;
						unset($_GET['showcomments']);
					}
				} else
					$out.="<a href=\"".$_SERVER['SCRIPT_NAME']."?page=".$pagenum."&amp;id=".$noticia_numero."&amp;showcomments=1\">". $langmessage[143].": ".$j."</a><br />\n";
			}
			// display comments form
			if($firstcomment) {
				$out.="<br />".commentform($noticia_numero);
				$firstcomment=false;
			}
		}
		$first=false;
		$count--;
	}
	$first=true;
	$GETarray = $_GET;
	$total=$count;
	while($row_db[$count][0]!="" && $total-$count<$post_cabecalho) {
		if($first) {
			$first=false;
			$out.="<div style=\"text-align: center; font-size: 85%; font-weight: bold; \">$langmessage[113]</div>";
			$out.="<table border='0' align='center'><tr><td>$langmessage[12]</td><td>$langmessage[114]</td><td>$langmessage[16]</td></tr>";
		}
		$GETarray['id'] = $row_db[$count][0];
		$call = $_SERVER['SCRIPT_NAME'] . "?" . http_build_query($GETarray,'','&amp;');
		$out.="<tr><td><a href=\"".$call."\">".decode($row_db[$count][3])."</a></td><td>".strftime("%d/%m/%y - %I:%M %p", $row_db[$count][5] + $fuso_s)."</td><td>".$row_db[$count][1]."</td></tr>";
		$count--;
	}
	if(!$first) $out.="</table>";
	$out.=showrss();
	$out.="</div>\n";
	return $out;
}

function lastnews($cat=-1) {
	$aa=explode("||",trim(@file_get_contents("./data/news.dat")));
	$gotit=false;
	$count=0;
	while($aa[$count]!="") {
		$zzz=explode("|",trim($aa[$count]));
		$count++;
		if($cat==-1 || $cat==$zzz[7]) {
			$row_db=$zzz;
			$gotit=true;
		}
	}
	if($gotit) return show_one_news($row_db[3],$row_db[5],$row_db[4],$row_db[1],$row_db[2]);
	else return false;
}

function show_one_news($a,$b,$c,$d,$e) {
	global $langmessage, $fuso_s;
	$out ="<span class=\"LNEnews_title\" >".decode($a)."</span>\n";
	$out.="<span class=\"LNEnews_date\">$langmessage[112] ".data_formatada($b + $fuso_s)."</span>\n";
	$out.="<span class=\"LNEnews_text\">".stripslashes(decode($c))."</span>\n";
	$out.="<span class=\"LNEnews_author\">$langmessage[16]: ".decode($d)."</span>\n";
	if($e!="-") $out.="<span class=\"LNEnews_email\">$e</span>\n";
	$out.="<br />\n";
	return $out;
}

function senddownload() {
	global $langmessage;
	$path=sv('PHP_SELF');
	if(!is_intval($_GET['dlid'])) die ("#d Aha! Clever!");
	$aaa=trim(@file_get_contents("data/downloads.dat"));
	unset($download);
	$download=explode("||",$aaa);
	$count=0;
	while($download[$count] != "") {
		$aaa=explode("|",$download[$count]);
		if($aaa[0]==$_GET['dlid']) {
			$downloads=$aaa;
			break;
		}
		$count++;
	}
	unset($_GET['dlid']);
	if(strpos($downloads[2],"*")) $filename=str_replace("*", "",$downloads[2]);
	else $filename="downloads/".html_entity_decode($downloads[2]);
	if(file_exists($filename)) {
		$size = filesize($filename);
		$ext = explode (".",$filename);
		if ($ext[1]=="php" || $ext[1]=="html") die ($langmessage[108]);
		switch($ext[1]) {
		case "doc":
			header("Content-Type: application/msword");
			break;
		case "pdf":
			header("Content-Type: application/pdf");
			break;
		case "ppt":
			header("Content-Type: application/ms-powerpoint");
			break;
		case "xls":
			header("Content-Type: application/ms-excel");
			break;
		case "mp3":
			header("Content-Type: audio/mp3");
			break;
		case "avi":
			header("Content-Type: video/avi");
			break;
		case "mpg":
			header("Content-Type: video/mpeg");
			break;
		default:
			header("Content-Type: application/save");
		}
		header("Content-Length: $size");
		header("Content-Disposition: attachment; filename=$filename"); 
		header("Content-Transfer-Encoding: binary");
		$fp = fopen("$filename", "r");
		fpassthru($fp);
		fclose($fp);
	} else {
		$message=$langmessage[109];
	}
	return $message;
	header("Location: ".$path);
}

function sendmessage() {
	global $set, $langmessage;
	if(!is_intval(trim($_POST['secCode'])) || !is_intval($_SESSION['operation'])) die ("#9 - aha! Clever!");
	if($_POST['secCode'] != $_SESSION['operation']) {
		$message=$langmessage[139];
	} else {
		if(isset($_POST['text'])) {
			$message=$langmessage[26];
			if($_POST['text']!="" && $_POST['name']!="") {
				$text=htmlentities(stripslashes($_POST['text']));
				$name=htmlentities(stripslashes($_POST['name']));
				$email=htmlentities(stripslashes($_POST['email']));
				$header="From: ".$set['fromname']." ".$set['fromemail']."\r\n";
				$to=$set['toemail']."\r\n";
				if(!mail($to,$langmessage[27].$set['fromname'],$langmessage[27].$name." at ".$email.":\r\n".$text,$header)) $message=$langmessage[28];
   			} else $message=$langmessage[29];
		} else $message=$langmessage[29];
	}
	return $message;
}

function contact() {
	global $pagenum, $langmessage;
	$out="<div id=\"LNE_contact\">\n<form method=\"post\" action=\"\"><fieldset>\n<table>\n";
	$out.="<tr><td align=\"right\">$langmessage[30]:</td>\n";
	$out.="<td><input  type=\"text\" name=\"name\" value=\"\" /></td></tr>\n";
	$out.="<tr><td align=\"right\">$langmessage[31]:</td>\n";
	$out.="<td><input  type=\"text\" name=\"email\" value=\"\" /></td></tr>\n";
	$out.="<tr><td align=\"right\" valign=\"top\">$langmessage[32]:</td>\n";
	$out.="<td><textarea name=\"text\" rows=\"8\" style=\"width: 250px;\"></textarea></td></tr>\n";
	$out.="<tr><td align=\"right\"><b>$langmessage[99]:&nbsp;</b></td>\n";
	$out.="<td><input type=\"text\" name=\"secCode\" maxlength=\"6\" style=\"width:50px\">\n";
	$out.=" <b>&laquo;</b><img src=\"./LightNEasy/seccode.php\" width=\"71\" height=\"21\" align=\"absmiddle\"></td></tr>\n";
	$out.="<tr><td>&nbsp;<input  type=\"hidden\" name=\"page\" value=\"$pagenum\" /></td>\n<td>";
	$out.="<input type=\"hidden\" name=\"submit\" value=\"Send message\" />";
	$out.="<input type=\"submit\" name=\"aa\" value=\"$langmessage[33]\" />";
	$out.="</td></tr>\n</table></fieldset></form></div>\n";
	return $out;
}

function sendcomment() {
	global $editar, $langmessage;
	if(!is_intval(trim($_POST['newsid'])) || !is_intval(trim($_POST['secCode'])) || !is_intval($_SESSION['operation'])) die ("#1 - aha! Clever!");
	$editar=true;
	if($_POST['commentname']=="" || $_POST['commentmessage']=="")
		$message=$langmessage[101];
	else {
		if($_POST['secCode'] != $_SESSION['operation'])
			$message=$langmessage[139];
		else {
			$order = array("\r\n", "\n", "\r");
			$_POST['commentmessage'] = str_replace($order, "<br />", $_POST['commentmessage']);
			if($_POST['commentemail']=="") $_POST['commentemail']="-";
			if(!$fp=fopen("./data/comments.dat","a")) die ($langmessage[142]);
			fwrite($fp,$_POST['newsid']."|".encode($_POST['commentname'])."|".encode($_POST['commentemail'])."|".time()."|".encode(stripslashes($_POST['commentmessage']))."||");
			fclose($fp);
			$message=$langmessage[141];
			$editar=false;
		}
	}
	return $message;
}

function loginform() {
	global $langmessage, $LNEversion;
	$out='<div align="center"><form method="post" action=""><h2>LightNEasy '.$LNEversion.' '.$langmessage[120].'</h2>';
	$out.='<p>'.$langmessage[6].':&nbsp;<input  type="password" name="password" value="" />';
	$out.='<input type="hidden" name="submit" value="Login" />';
	$out.='<input type="submit" name="aa" value="'.$langmessage[120].'" /></p></form></div>';
	return $out;
}

function commentform($newsid) {
	global $langmessage,$editar;
	$out.="<form class=\"LNEcommentform\" action=\"\" method=\"post\"><fieldset style=\"border: none;\">\n";
	$out.="<table class=\"LNEcommenttable\" border=\"0\" cellspacing=\"0\" cellpadding=\"4\">\n";
	$out.="<tr><td colspan=\"2\" style=\"text-align: center;\"><h2>".$langmessage[137]."</h2></td></tr>\n";
	$out.="<tr><td align=\"right\"><b>$langmessage[30]:&nbsp;</b></td>\n";
	$out.="<td><input type=\"text\" name=\"commentname\" style=\"width:250px\" value=\"";
	if($editar) $out.=$_POST['commentname'];
	$out.="\"></td></tr>\n";
	$out.="<td align=\"right\"><b>$langmessage[31]:&nbsp;</b></td>\n";
	$out.="<td><input type=\"text\" name=\"commentemail\" style=\"width:250px\" value=\"";
	if($editar) $out.=$_POST['commentemail'];
	$out.="\"></td></tr>\n";
	$out.="<tr valign=top><td align=\"right\"><b>$langmessage[138]:&nbsp;</b></td>\n";
	$out.="<td><textarea name=\"commentmessage\" style=\"width:250px; height:80px\">";
	if($editar) $out.=$_POST['commentmessage'];
	$out.="</textarea></td>\n";
	$out.="</tr><tr><td align=\"right\"><b>$langmessage[99]:&nbsp;</b></td>\n";
	$out.="<td><input type=\"text\" name=\"secCode\" maxlength=\"6\" style=\"width:50px\">\n";
	$out.=" <b>&laquo;</b><img src=\"./LightNEasy/seccode.php\" width=\"71\" height=\"21\" align=\"absmiddle\"></td>\n";
	$out.="</tr><tr><td><input type=\"hidden\" name=\"submit\" value=\"sendcomment\" /><br />&nbsp;";
	$out.="<input type=\"hidden\" name=\"newsid\" value=\"$newsid\" /></td><td>";
	$out.="<input type=\"submit\" class=\"LNEcommentsubmit\"value=\"$langmessage[137]\" />\n</td></tr>\n</table>\n</fieldset></form><br />\n";
	return $out;
}

function youtube($url) {
	$out='<object width="425" height="355"><param name="movie" value="http://www.youtube.com/';
	$out.=$url;
	$out.='"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/';
	$out.=$url;
	$out.='" type="application/x-shockwave-flash" wmode="transparent" width="425" height="355"></embed></object>';
	return $out;
}

function googlev($url) {
	$out='<embed style="width:400px; height:326px;" id="VideoPlayback" type="application/x-shockwave-flash" src="http://video.google.com/googleplayer.swf?docId=';
	$out.=$url;
	$out.='" flashvars=""></embed>';
	return $out;
}

function mp3($url) {
	$out='<object type="application/x-shockwave-flash" data="js/dewplayer.swf?son=';
	$out.=$url;
	$out.='" width="200" height="20"> <param name="movie" value="js/dewplayer.swf?son=';
	$out.=$url;
	$out.='" /></object>';
	return $out;
}

function readmenu() {
	//Read menu
	global $menu, $pagenum,$selected;
	$aaa=trim(file_get_contents("data/menu.dat"));
	unset($mmenu);
	$mmenu=explode("||",$aaa);
	$count=0;
	foreach($mmenu as $mmmenu) {
		$menu[$count]=explode("|",trim($mmmenu));
		$menu[$count][4]=decode($menu[$count][4]);
		if($menu[$count][3]==$pagenum) {
			$selected['index']=$menu[$count][0];
			$selected['name']=$menu[$count][4];
		}
		$count++;
	}
	//Read page data
	$aaa=trim(file_get_contents("data/pages.dat"));
	$pag=array();
	$pag=explode("||",$aaa);
	$selected['descr']="-";
	$selected['templ']="-";
	foreach($pag as $ppag) {
		$page=array();
		$page=explode("|",trim($ppag));
		$count=0;
		while($menu[$count][0] !="") {
			if($menu[$count][3] == trim($page[0])) {
				$menu[$count][5] = $page[1];
				$menu[$count][6] = $page[2];
				if($menu[$count][4]==$selected['name']) {
					$selected['descr'] = $page[1];
					$selected['templ'] = $page[2];
					break;
				}
			}
			$count++;
		}
	}
}

function readdata($file){
	// read a data file, returns an array with the content
	$aa = explode("||",trim(@file_get_contents("data/".$file.".dat")));
	$count = 0;
	foreach($aa as $aaa) {
		$bb[$count] = explode("|",trim($aaa));
		$count++;
	}
	return $bb;
}

function readsetup() {
	global $set, $langmessage;
	require "data/config.php";
	$set['title']=decode($set['title']);
	$set['subtitle']=decode($set['subtitle']);
	$set['keywords']=decode($set['keywords']);
	$set['description']=decode($set['description']);
	$set['author']=decode($set['author']);
	$set['footer']=decode($set['footer']);
	$set['keywords']=decode($set['keywords']);
	$set['extension']="php";
	if($set['language']=="") $set['language']="en_US";
	if($set['langeditor']=="") $set['langeditor']="en";
	require "./languages/lang_".$set['language'].".php";
}

function is_intval($value) {
     return 1 === preg_match('/^[+-]?[0-9]+$/', $value);
}

function data_formatada($unix_time) {
	global $set;
	return strftime($set['dateformat'], $unix_time);
}

function encode($string) {
	return addslashes(utf8_encode(htmlentities($string)));
}

function decode($string) {
	return html_entity_decode(utf8_decode(stripslashes($string)));
}

function sv($s) {
	if (!isset($_SERVER)) {
		global $_SERVER;
		$_SERVER = $GLOBALS['HTTP_SERVER_VARS'];
	}
	if (isset($_SERVER[$s]))return $_SERVER[$s];
	else return'';
}

function compare($x,$y) {
	if($x[0] == $y[0]) return 0;
	elseif($x[0] < $y[0]) return -1;
	else return 1;
}

function sanitize($text) {
	// Convert problematic ascii characters to their true values
	$search = array("40","41","58","65","66","67","68","69","70",
		"71","72","73","74","75","76","77","78","79","80","81",
		"82","83","84","85","86","87","88","89","90","97","98",
		"99","100","101","102","103","104","105","106","107",
		"108","109","110","111","112","113","114","115","116",
		"117","118","119","120","121","122"
		);
	$replace = array("(",")",":","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","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"
		);
	$entities = count($search);
	for ($i=0;$i < $entities;$i++) $text = preg_replace("#(&\#)(0*".$search[$i]."+);*#si", $replace[$i], $text);
	// the following is based on code from bitflux (http://blog.bitflux.ch/wiki/)
	// Kill hexadecimal characters completely
	$text = preg_replace('#(&\#x)([0-9A-F]+);*#si', "", $text);
	// remove any attribute starting with "on" or xmlns
	$text = preg_replace('#(<[^>]+[\\"\'\s])(onmouseover|onmousedown|onmouseup|onmouseout|onmousemove|onclick|ondblclick|onload|xmlns)[^>]*>#iU', ">", $text);
	do {
		$oldtext = $text;
		preg_replace('#</*(applet|meta|xml|blink|link|style|script|embed|object|iframe|frame|frameset|ilayer|layer|bgsound|title|base)[^>]*>#i', "", $text);
	// remove javascript: and vbscript: protocol
	} while ($oldtext != $text);
	$text = preg_replace('#([a-z]*)=([\`\'\"]*)script:#iU', '$1=$2nojscript...', $text);
	$text = preg_replace('#([a-z]*)=([\`\'\"]*)javascript:#iU', '$1=$2nojavascript...', $text);
	$text = preg_replace('#([a-z]*)=([\'\"]*)vbscript:#iU', '$1=$2novbscript...', $text);
	$text = preg_replace('#(<[^>]+)style=([\`\'\"]*).*expression\([^>]*>#iU', "$1>", $text);
	$text = preg_replace('#(<[^>]+)style=([\`\'\"]*).*behaviour\([^>]*>#iU', "$1>", $text);
	return $text;
}

//replacement for PHP5 function http_build_query() if that function doesn't exist
//taken from the PHP online manual
if(!function_exists('http_build_query')) {
    function http_build_query($data,$prefix=null,$sep='',$key='') {
        $ret    = array();
            foreach((array)$data as $k => $v) {
                $k    = urlencode($k);
                if(is_int($k) && $prefix != null) {
                    $k    = $prefix.$k;
                };
                if(!empty($key)) {
                    $k    = $key."[".$k."]";
                };

                if(is_array($v) || is_object($v)) {
                    array_push($ret,http_build_query($v,"",$sep,$k));
                }
                else {
                    array_push($ret,$k."=".urlencode($v));
                };
            };

        if(empty($sep)) {
            $sep = ini_get("arg_separator.output");
        };

        return    implode($sep, $ret);
    };
};


/*
 * Find files in a directory matching a pattern
 *
 *
 * Paul Gregg <pgregg@pgregg.com>
 * 20 March 2004,  Updated 20 April 2004
 * Updated 18 April 2007 to add the ability to sort the result set
 * Updated 9 June 2007 to prevent multiple calls to sort during recursion
 * Version: 2.2
 * This function is backwards capatible with any code written for a
 * previous version of preg_find()
 *
 * Open Source Code:   If you use this code on your site for public
 * access (i.e. on the Internet) then you must attribute the author and
 * source web site: http://www.pgregg.com/projects/php/preg_find/preg_find.phps
 * Working examples: http://www.pgregg.com/projects/php/preg_find/
 *
 */

define('PREG_FIND_RECURSIVE', 1);
define('PREG_FIND_DIRMATCH', 2);
define('PREG_FIND_FULLPATH', 4);
define('PREG_FIND_NEGATE', 8);
define('PREG_FIND_DIRONLY', 16);
define('PREG_FIND_RETURNASSOC', 32);
define('PREG_FIND_SORTDESC', 64);
define('PREG_FIND_SORTKEYS', 128);
define('PREG_FIND_SORTBASENAME', 256);   # requires PREG_FIND_RETURNASSOC
define('PREG_FIND_SORTMODIFIED', 512);   # requires PREG_FIND_RETURNASSOC
define('PREG_FIND_SORTFILESIZE', 1024);  # requires PREG_FIND_RETURNASSOC
define('PREG_FIND_SORTDISKUSAGE', 2048); # requires PREG_FIND_RETURNASSOC

// PREG_FIND_RECURSIVE   - go into subdirectorys looking for more files
// PREG_FIND_DIRMATCH    - return directorys that match the pattern also
// PREG_FIND_DIRONLY     - return only directorys that match the pattern (no files)
// PREG_FIND_FULLPATH    - search for the pattern in the full path (dir+file)
// PREG_FIND_NEGATE      - return files that don't match the pattern
// PREG_FIND_RETURNASSOC - Instead of just returning a plain array of matches,
//                         return an associative array with file stats
//
// You can also request to have the results sorted based on various criteria
// By default if any sorting is done, it will be sorted in ascending order.
// You can reverse this via use of:
// PREG_FIND_SORTDESC    - Reverse order of sort
// PREG_FILE_SORTKEYS    - Sort on the keyvalues or non-assoc array results
// The following sorts *require* PREG_FIND_RETURNASSOC to be used as they are
// sorting on values stored in the constructed associative array
// PREG_FIND_SORTBASENAME - Sort the results in alphabetical order on filename
// PREG_FIND_SORTMODIFIED - Sort the results in last modified timestamp order
// PREG_FIND_SORTFILESIZE  - Sort the results based on filesize
// PREG_FILE_SORTDISKUSAGE - Sort based on the amount of disk space taken
// to use more than one simply seperate them with a | character

// Search for files matching $pattern in $start_dir.
// if args contains PREG_FIND_RECURSIVE then do a recursive search
// return value is an associative array, the key of which is the path/file
// and the value is the stat of the file.
Function preg_find($pattern, $start_dir='.', $args=NULL) {

  static $depth = -1;
  ++$depth;

  $files_matched = array();

  $fh = opendir($start_dir);

  while (($file = readdir($fh)) !== false) {
    if (strcmp($file, '.')==0 || strcmp($file, '..')==0) continue;
    $filepath = $start_dir . '/' . $file;
    if (preg_match($pattern,
                   ($args & PREG_FIND_FULLPATH) ? $filepath : $file)) {
      $doadd =    is_file($filepath)
               || (is_dir($filepath) && ($args & PREG_FIND_DIRMATCH))
               || (is_dir($filepath) && ($args & PREG_FIND_DIRONLY));
      if ($args & PREG_FIND_DIRONLY && $doadd && !is_dir($filepath)) $doadd = false;
      if ($args & PREG_FIND_NEGATE) $doadd = !$doadd;
      if ($doadd) {
        if ($args & PREG_FIND_RETURNASSOC) { // return more than just the filenames
          $fileres = array();
          if (function_exists('stat')) {
            $fileres['stat'] = stat($filepath);
            $fileres['du'] = $fileres['stat']['blocks'] * 512;
          }
          if (function_exists('fileowner')) $fileres['uid'] = fileowner($filepath);
          if (function_exists('filegroup')) $fileres['gid'] = filegroup($filepath);
          if (function_exists('filetype')) $fileres['filetype'] = filetype($filepath);
          if (function_exists('mime_content_type')) $fileres['mimetype'] = mime_content_type($filepath);
          if (function_exists('dirname')) $fileres['dirname'] = dirname($filepath);
          if (function_exists('basename')) $fileres['basename'] = basename($filepath);
          if (isset($fileres['uid']) && function_exists('posix_getpwuid')) $fileres['owner'] = posix_getpwuid ($fileres['uid']);
          $files_matched[$filepath] = $fileres;
        } else
          array_push($files_matched, $filepath);
      }
    }
    if ( is_dir($filepath) && ($args & PREG_FIND_RECURSIVE) ) {
      $files_matched = array_merge($files_matched,
                                   preg_find($pattern, $filepath, $args));
    }
  }

  closedir($fh); 

  // Before returning check if we need to sort the results.
  if (($depth==0) && ($args & (PREG_FIND_SORTKEYS|PREG_FIND_SORTBASENAME|PREG_FIND_SORTMODIFIED|PREG_FIND_SORTFILESIZE|PREG_FIND_SORTDISKUSAGE)) ) {
    $order = ($args & PREG_FIND_SORTDESC) ? 1 : -1;
    $sortby = '';
    if ($args & PREG_FIND_RETURNASSOC) {
      if ($args & PREG_FIND_SORTMODIFIED)  $sortby = "['stat']['mtime']";
      if ($args & PREG_FIND_SORTBASENAME)  $sortby = "['basename']";
      if ($args & PREG_FIND_SORTFILESIZE)  $sortby = "['stat']['size']";
      if ($args & PREG_FIND_SORTDISKUSAGE) $sortby = "['du']";
    }
    $filesort = create_function('$a,$b', "\$a1=\$a$sortby;\$b1=\$b$sortby; if (\$a1==\$b1) return 0; else return (\$a1<\$b1) ? $order : 0- $order;");
    uasort($files_matched, $filesort);
  }
  --$depth;
  return $files_matched;
}
?>