<?php

	include "connect.php";
	switch (DB_TYPE) //load database_specific functions
	{
		case "mysql":
			include "db_mysql.php";
			break;
		case "postgresql":
			include "db_postgresql.php";
			break;
	}

    connectToDatabase(); 

	class Remark
	{
		var $name;
		var $msg;
		var $valid;

		function Remark($name, $msg, $valid)
		{
			$this->name = $name;
			$this->msg = $msg;
			$this->valid = $valid;
		}
	}

	class UserRemarks
	{
		var $imageID;   //unique image ID for database
		var $script;    //page to reload when form data sent
		var $respath;   //path to BPP 'res' folder
		var $table;     //name of database table
		var $adminMode; //switch for admin mode
		var $option;    //action to be taken
		var $code = ''; //CAPTCHA code
		
		function UserRemarks($imageID, $script, $respath)
		{
			$this->script=setScript($script);
			$this->respath = $respath;
			$this->code=createRandomValue();
			$this->table = getTableName();

			if( $imageID!=NULL )
				$this->setImageId($imageID);

			$this->option = "1";   													// 1 = nothing, just list remarks
			$this->option = (IsSet($_POST["go"]))          ? "2" : $this->option;   // 2 = add new remark
			$this->option = (IsSet($_POST["savechanges"])) ? "3" : $this->option;   // 3 = save changes 
			
			if (IsSet($_POST['filter']) ) //remarks filter drop down menu set
					$this->adminMode = true;
				
			if( IsSet($_POST['exitadmin']) ) //exit admin mode button clicked
				$this->adminMode = false;
		}

		function executeAction() 
		{
			switch ($this->option)
			{
				case 1: //just display remarks
					if ($this->adminMode)
						adminMode($this->script,$this->imageID,$this->table);
					else
						showAllPhotoRemarks($this->table,$this->imageID,$this->script,$this->respath,$this->code);	
					break;
				case 2: //add remark
					$valid=true;
					if ($_POST["author"]==ADMIN_USER)
					{
						if ($_POST["remark"] != ADMIN_PASSWD)
						{ //display error if password incorrect
							echo("<div class='errorbox'><span class='errormessage'>".MSG_INVALID_LOGIN."</span></div>");
							$valid=false;
						}
						else //username and password valid
						{
							if (USE_CAPTCHA)
							$valid= validateCAPTCHA()  ? true : false;
						}
						if ($valid)
						{
							$this->adminMode = true;
							adminMode($this->script,$this->imageID,$this->table);
						}
						else
							showAllPhotoRemarks($this->table,$this->imageID,$this->script,$this->respath,$this->code);	
					}
					
					else //name not ADMIN USER
					{
						$remarkEntry = validateEntry();
						if ($remarkEntry->valid)
							addPhotoRemark($this->table, $this->imageID, $remarkEntry);	
						showAllPhotoRemarks($this->table,$this->imageID,$this->script,$this->respath,$this->code);	
					}	
					break;			
				case 3: // save changes	
					saveChanges($this->table,$this->script);	
					$this->adminMode = true;
					adminMode($this->script,$this->imageID,$this->table);	
					break;			
				}
		}
		
		function displayRemarksIfNotEmpty()  
		{			
			if(fetchRemarksCount($this->table, $this->imageID, 0)>0 )
				echo("showRemarks();"); //call javascript to show remarks section
		}

		function forceDisplayRemarksIfNecessary()  
		{
			if ( ($this->adminMode) OR ($this->option==2) )
			{
				echo("showRemarks();");
				echo("bringRemarksToTop();");
			}
		}

		function setImageId($imageID) 
		{
//			$this->imageID = addslashes($imageID);
			$this->imageID = $imageID;
		}

		function showRemarksCount()  
		{
			echo(fetchRemarksCount($this->table, $this->imageID, 0) );
		}

	} //end of class UserRemarks

	function addPhotoRemark($table, $imageID, $remarkEntry)
	{
		$remarkEntry->name = quote_smart($remarkEntry->name); //escape necessary characters
		$remarkEntry->msg  = quote_smart($remarkEntry->msg);
		$imageID = quote_smart($imageID);
		$query = "insert into $table (imageID, name, date, msg, ip1, approved, refer) VALUES($imageID,$remarkEntry->name, NOW(), $remarkEntry->msg, '".gethostbyaddr($_SERVER["REMOTE_ADDR"])."',";
		if (USE_MODERATION)
			$query .= "'N'" ;
		else
			$query .= "'Y'";
		$query .= ",'".addslashes($_SERVER["HTTP_REFERER"])."')";
		$error = doQuery($query,"Add Remark",$sql);
		if (!$error) 
		{
			if (USE_MODERATION) 
				echo("<div class='remarkstatusbox'>".MSG_MODERATION."</div>");	
			if (NOTIFY) // send notification email if enabled
				sendNotification($imageID, $remarkEntry->name, $remarkEntry->msg);
		}
				
		unset($_POST['author']); //empty variables so add remarks form is empty
		unset($_POST['remark']);
	}

	function adminMode($script,$imageID,$table)
	{
		$return_array=setupFilter($imageID,$table);
		$filter=$return_array[0];
		$selectquery=$return_array[1];
		$countquery=$return_array[2];

		$error = doQuery($countquery,"count in adminmode",$sql);
		$row = fetchArray($sql);
		$numTotalRemarks= $row[0];
		freeResult($sql);

		displayAdminConsole($filter,$numTotalRemarks,$script);	
		if ($numTotalRemarks!=0)
		{   		
			$error = doQuery($selectquery,"select all in adminmode",$sql);
				
			while($row=fetchArray($sql))
			{
				$id = $row["id"];
				$imageID = str_replace("/","/\n",$row["imageID"]);
				$date = $row["date"];
				$name = $row["name"];
				$msg = $row["msg"];
				$ip1 = $row["ip1"];
				$approved = $row["approved"];
				$deleted = "N";
				displayMainFormSegment($id,$imageID,$date,$name,$msg,$ip1,$approved,$deleted);
			} //end while	
		echo( "\n\t</form>" );
		freeResult($sql);
		}	
	}

	function checkForGDLibrary()
	{
		//if CAPTCHA enabled, check for GD support
		if (USE_CAPTCHA)
		{
			if (!function_exists("imagecreate"))
			{
				$msg = "\n<div class='errorbox'>";
				$msg .= "\n\t<span class='errormessage'>The CAPTCHA feature requires that the PHP engine have the GD library installed.<br/>";
				$msg .= "\n\t\tThis webserver does not appear to support the CAPTCHA feature.<br/>";
				$msg .= "\n\t\tPlease regenerate this album after unselecting the CAPTCHA feature.";
				$msg .= "\n\t</span>";
				$msg .= "\n</div>";
				echo ($msg);
			}
		}
	}

	function cleanEntries($name,$msg)
	{
		//filter most html tags in entries and close unbalanced allowed tags
		//create allowable opening html tags array		
		$open_tag[1]="<b>";		 //permit bold and italics
		$open_tag[2]="<em>";	
		$open_tag[3]="<strong>";		
		$open_tag[4]="<i>";
		
		$allowable_tags=""; //initialize and build allowable html tags string
		foreach ($open_tag as $tag) {$allowable_tags=$allowable_tags.$tag."</".substr($tag,1);}

		$name = strip_tags($name); //strip off all html tags but permit foreign chars	
		$msg = strip_tags($msg, $allowable_tags); //strip off unallowed html tags but permit foreign chars
		
		//check for unbalanced open tags..close tags if needed (do not worry about order)		
		foreach ($open_tag as $tag)
		{
			$pos1=strpos($msg,$tag); $t1=!($pos1===false);//$t1 is true if open tag exists
			$pos2=strpos($msg,"</".substr($tag,1)); $t2=!($pos2===false);//$t2 is true if close tag exists
			if ($t1 && !$t2) $msg=$msg."</".substr($tag,1); //create close tag if needed
		}
		$nameMsg[0]=$name;
		$nameMsg[1]=$msg;
		return $nameMsg;
	}

  	function createRandomValue() //create random characters for CAPTCHA code
  	{
   		$rand_value = '';

    	while (strlen($rand_value) < CAPTCHA_DIGITS) 
		{
			$char = chr(mt_rand(0,255));

      		if (eregi('^[a-kmnp-z2-9]$', $char)) $rand_value .= $char; //make sure char is valid (no 0,O,1,l)
    	}

    	return $rand_value;
  	}	

	function displayAdminConsole($filter,$numTotalRemarks,$script)
	{
		echo( "\n<form name='adminmode' class='remarksinput' action='$script' method='post' onsubmit='return validateAdminmode(\"".MSG_EMPTY_AUTHOR_OR_REMARK."\")'>" );

		//display administrator console
		echo("\n\t<div class='remarksadmin'>");
		echo("\n\t  <table width='100%'>");
		echo("\n\t    <tr>");
		echo("\n\t\t<td width='70%'><span class='remarksadminheader'>".MSG_ADMIN_CONSOLE.":</span></td>");
		if ($numTotalRemarks!=0)
			echo("\n\t\t<td width='30%'><input type='checkbox' value='N' name='deleteAll' onClick='checkAllBoxes(this.form,\"delete[\",\"deleteAll\")' />&nbsp; <span style='vertical-align:top;'<b>&nbsp;".MSG_DELETE_ALL_REMARKS."</b></span></td>");
		else
			echo("\n\t\t<td width='30%'>&nbsp;</td>");
		echo("\n\t    </tr>");

		echo("\n\t    <tr>");
		echo("\n\t\t<td><b>".MSG_ADMIN_FILTER."</b>");
		echo("\n\t\t  <select name='filter' size=1 class='remarksadmindropdown' onChange='document.adminmode.submit()'>");
		echo($filter[1]);
		echo($filter[2]);
		echo($filter[3]);
		echo($filter[4]);			
		echo("\n\t\t  </select></td>");
		if (USE_MODERATION && $numTotalRemarks!=0)
			echo("\n\t\t<td><input type='checkbox' value='N' name='approveAll' onClick='checkAllBoxes(this.form,\"approved[\",\"approveAll\")' />&nbsp; <span style='vertical-align:top;'<b>&nbsp;".MSG_APPROVE_ALL_REMARKS."</b></span></td>");
		else
			echo("\n\t\t<td>&nbsp;</td>");
		echo("\n\t    </tr>");

		echo("\n\t  </table>");

		echo("\n\t    </br></br>");			

		echo("\n\t\t<input type='submit' value='".MSG_EXIT_ADMIN_MODE."' name='exitadmin' class='remarksadminbuttons' />");
		if ($numTotalRemarks != 0)
			echo("\n\t\t<input type='submit' value='".MSG_SAVE_CHANGES."' name='savechanges' class='remarksadminbuttons' />");
		echo("\n\t</div>");
	}

	function displayMainFormSegment($id,$imageID,$date,$name,$msg,$ip1,$approved,$deleted)
	{
		echo("\n\t<div class='remarkbox'>");

		echo( "\n\t  <input type='Hidden' name='id[$id]' value='$id'/>" );
		echo( "\n\t    <table width='100%'>");	
		echo( "\n\t\t<tr>");
		echo( "\n\t\t  <td width='70%'><b>".MSG_DATE_TIME."</b></td>");
		echo( "\n\t\t  <td width='30%'>&nbsp;</td>");
		echo( "\n\t\t</tr>");
		echo( "\n\t\t<tr>");
		echo( "\n\t\t  <td><input type='text' name='date[$id]' value='".fetchDate($date)."'readonly style='background:#e3e3e5;' /></td>");
		if ($deleted !="N")
			echo("\n\t\t  <td><input type='checkbox' name='delete[$id]' value='Y' checked><span style='vertical-align:top;'<b>&nbsp;".MSG_DELETE_REMARK_THIS_PAGE."</b></span></td>");
		else
			echo("\n\t\t  <td><input type='checkbox' name='delete[$id]' value='N'><span style='vertical-align:top;'<b>&nbsp;".MSG_DELETE_REMARK_THIS_PAGE."</b></span></td>");

		echo( "\n\t\t</tr>");

		echo( "\n\t\t<tr>");
		echo( "\n\t\t  <td><b>".MSG_REMARK_AUTHOR."</b></td>");
		echo( "\n\t\t  <td>&nbsp;</td>");
		echo( "\n\t\t</tr>");

		echo( "\n\t\t<tr>");
		echo( "\n\t\t  <td><input name='name[$id]' type='text' value='".htmlentities($name, ENT_QUOTES)."'  size='30' /></td>");
		if (USE_MODERATION)
		{					
			if ($approved !="N")
				echo("\n\t\t  <td><input type='checkbox' name='approved[$id]' value='Y' checked><span style='vertical-align:top;'<b>&nbsp;".MSG_REMARK_APPROVED."</b></span></td>");
			else
				echo("\n\t\t  <td><input type='checkbox' name='approved[$id]' value='N'><span style='vertical-align:top;'<b>&nbsp;".MSG_REMARK_APPROVED."</b></span></td>");
		}
		else
			echo("\n\t\t  <td>&nbsp;</td>");
		echo( "\n\t\t</tr>");

		echo( "\n\t\t<tr>");
		echo( "\n\t\t  <td><b>".MSG_REMARK_CONTENT."</b></td>");
		echo( "\n\t\t  <td width='50%'><b>".MSG_IMAGE_ID."</b></td>");	
		echo( "\n\t\t</tr>");

		echo( "\n\t\t<tr>");
		echo("\n\t\t  <td><textarea rows='5' cols='30' wrap='30' name='msg[$id]' style='width: 90%; margin-bottom: 5px;'>".htmlentities($msg,ENT_QUOTES)."</textarea></td>" );																	
		echo( "\n\t\t  <td><textarea name='imageID[$id]' rows='5' cols='20' wrap='20' readonly style='background:#e3e3e5;' />$imageID</textarea></td>");
		echo( "\n\t\t</tr>");
		echo( "\n\t    </table>");
				
		echo("\n\t</div>");
	}

	function encryptDecrypt($strMessage) 
	{ 
		//Function : encrypt/decrypt a string message v.1.0  without a known key 
		//Author   : Aitor Solozabal Merino (spain) 
		//Email    : aitor-3@euskalnet.net 
		//Date     : 01-04-2005 

    	$lenStrMessage=strlen($strMessage); 
    	$strEncryptedMessage=""; 
    	FOR ($position = 0;$position<$lenStrMessage;$position++)
		{ 
        	$strEncryptedMessage .= chr((ord(substr($strMessage, $position, 1))) ^ ((255+(($lenStrMessage +$position)+1)) % 255)); 
    	} 
    	return $strEncryptedMessage; 
	}

	function fetchDate($date)
	{
		return( date(DATEFMT, strtotime($date)).DATE_SUFFIX );
	}

	function fetchRemarksCount($table, $id, $selection)
	{
		switch ($selection)
		{
			case 1: //all remarks
				$query="select count(*) from $table where (imageID=\"$id\" )";
				break;
			case 2: //unapproved remarks
				$query="select count(*) from $table where (imageID=\"$id\" AND approved =\"N\" )";
				break;
			default: //approved remarks
				$query="select count(*) from $table where (imageID=\"$id\" AND (approved =\"Y\" OR approved is null) )";
				break;
		}

		$error = doQuery($query,"Select in fetchRemarksCount()",$sql);
		$row = fetchArray($sql);
		$numOfRows= $row[0];
		freeResult($sql);
		return $numOfRows;
	}

	function getTableName()
	{
		$bad_chars = "!@#$%^&*()+<>?{}|[]\:,.-= "; //translate non-allowed characters to '_'
		return strtolower(strtr(DB_TABLE_NAME, $bad_chars, str_repeat("_", strlen($bad_chars))));
	}

	function reportError($errloc, $errno, $errmsg)
	{
		if ($errno != 0) 
		{
	    	$msg = "\n<div class='errorbox'>";
			$msg .= "\n\t<span class='errormessage'>A database error has occurred!!</span>";
			$msg .= "\n\t<span class='errormessage'>Please report the following error details to site administrators:</span>";
			$msg .= "\n\t<ul>";
			$msg .= "\n\t\t<li>Error location: $errloc</li>";
			$msg .= "\n\t\t<li>Error no.: $errno</li>";
			$msg .= "\n\t\t<li>Error message: $errmsg</li>";
			$msg .= "\n\t</ul>";
			$msg .= "\n</div>";
			echo ($msg);
			return true;
		}
		else 
			return false;
	}

	function saveChanges($table,$script)
	{
		$nameArray=$_POST['name'];
		$msgArray=$_POST['msg'];
		$approvedArray=isSET($_POST['approved']) ? $_POST['approved'] : array();
		$deleteArray=isSET($_POST['delete']) ? $_POST['delete'] : array();
		$dateArray=$_POST['date'];
		$imageIdArray=$_POST['imageID'];
		$idArray=$_POST['id'];

		$keyArray=array_keys($nameArray);

		foreach ($keyArray as $key) //step through keys
		{
			$query="select * from $table where id=$key";
			$error = doQuery($query,"Select in Save Changes",$sql);

			$row = fetchArray($sql);

			$id = $row["id"];
			$imageID = $row["imageID"];
			$date = $row["date"];
			$name = $row["name"];
			$msg = $row['msg'];
			$ip1 = $row["ip1"];
			$approved = $row["approved"];

			if(IsSet($deleteArray[$key])) //remark marked for deletion
			{
				$query="delete from $table where id = '$id'";
				$error = doQuery($query,"Delete remark for photo",$sql);
			}

			if(IsSet($nameArray[$key]))
				$name=$nameArray[$key];
			if(IsSet($msgArray[$key]))
				$msg=$msgArray[$key];
			
			$approved = (IsSet($approvedArray[$key])) ? "Y" : "N";
			//if moderation disabled, remarks is approved	
			if (!USE_MODERATION) $approved="Y";
		
			//clean up $name,$msg
			$nameMsg=cleanEntries($name,$msg);
			$name=$nameMsg[0];
			$msg=$nameMsg[1];

			//update entry				
			$query="update $table SET name= '$name' , msg= '$msg' , approved= '$approved' where id = '$id'";
			$error = doQuery($query,"Update in Save Changes",$sql);
	
		}//end foreach ($keyArray as $key)

		echo("<div class='remarkstatusbox'>".MSG_CHANGES_SAVED."</div>");	
		echo( "\n</form>" );
	}


	function sendNotification($imageID, $name, $msg)
	{
		$notification_msg = "\n".NOTIFY_PHOTO_ID.": ".$imageID."\n".NOTIFY_AUTHOR.": ".$name."\n".NOTIFY_MSG.":\n"."\n".$msg;
		$x = mail(NOTIFY_TO, NOTIFY_SUB, $notification_msg, "From: ".NOTIFY_FROM);
	}

	function setupFilter($imageID,$table)
	{
		//remarks filter dropdown menu
		$filter[1]="\n\t\t\t<option value='".MSG_ALL_REMARKS_THIS_PAGE."'>".MSG_ALL_REMARKS_THIS_PAGE." </option>";
		$filter[2]="\n\t\t\t<option value='".MSG_ALL_REMARKS_THIS_ALBUM."'>".MSG_ALL_REMARKS_THIS_ALBUM."</option>";
		if (USE_MODERATION)
		{
			$filter[3]="\n\t\t\t<option value='".MSG_ALL_UNAPPROVED_REMARKS_THIS_PAGE."'>".MSG_ALL_UNAPPROVED_REMARKS_THIS_PAGE."</option>";
			$filter[4]="\n\t\t\t<option value='".MSG_ALL_UNAPPROVED_REMARKS_THIS_ALBUM."'>".MSG_ALL_UNAPPROVED_REMARKS_THIS_ALBUM."</option>";
		}
		//locate album name
		$albumName=substr($imageID,0,strpos($imageID,'/'));
		$whereSubclause="LEFT(imageID,instr(imageID,\"/\")-1)";

		$selectedFilter = IsSet($_POST['filter']) ? $_POST['filter'] : MSG_ALL_REMARKS_THIS_PAGE;
		switch ($selectedFilter) //set 'selected' option
		{
			case MSG_ALL_REMARKS_THIS_PAGE:
				$countquery="select count(*) from $table where (imageID=\"$imageID\" )";
				$selectquery="select * from $table where (imageID=\"$imageID\" ) order by date DESC";
				$filter[1] = str_replace("option","option selected",$filter[1]);
				break;
			case MSG_ALL_REMARKS_THIS_ALBUM:
				$countquery="select count(*) from $table where $whereSubclause=\"$albumName\"";
				$selectquery="select * from $table where $whereSubclause=\"$albumName\" order by date DESC";
				$filter[2] = str_replace("option","option selected",$filter[2]);
				break;
			case MSG_ALL_UNAPPROVED_REMARKS_THIS_PAGE:
				$countquery="select count(*) from $table where (imageID=\"$imageID\" AND approved =\"N\" )";
				$selectquery="select * from $table where (imageID=\"$imageID\" AND approved =\"N\" ) order by date DESC";
				$filter[3] = str_replace("option","option selected",$filter[3]);
				break;
			case MSG_ALL_UNAPPROVED_REMARKS_THIS_ALBUM:
				$countquery="select count(*) from $table where (approved =\"N\" AND $whereSubclause=\"$albumName\")";
				$selectquery="select * from $table where (approved =\"N\" AND $whereSubclause=\"$albumName\") order by date DESC";
				$filter[4] = str_replace("option","option selected",$filter[4]);
				break;
		}

		$returnArray=array(0=>$filter,1=>$selectquery,2=>$countquery);
		return $returnArray;
	}

	function setScript($script)
	{
		//replace blanks with %20 and apostrophe with %27 to ensure valid URL
		$temp = str_replace(" ", "%20", $script);
		return ( str_replace("'", "%27", $temp) );
	}

	function showAllPhotoRemarks($table,$imageID,$script,$respath,$code)	//displays the remarks
	{
        checkForGDLibrary();

		$numTotalRemarks = fetchRemarksCount($table, $imageID, 1);
		$numApprovedRemarks = fetchRemarksCount($table, $imageID, 0);
		$numOfRows = $numApprovedRemarks; //default to displaying only approved remarks

		if (USE_MODERATION) //display # of unapproved remarks
		{
			$numUnapprovedRemarks = fetchRemarksCount($table, $imageID, 2);
			if ($numUnapprovedRemarks > 0)
				echo("<div class='remarkstatusbox'>".$numUnapprovedRemarks."&nbsp;".MSG_AWAITING_APPROVAL."</div>");
		}

		//display remark
			
		if( $numOfRows>0 ) //if there is data in the table for this image
		{
			$query="select * from $table where (imageID=\"$imageID\" AND (approved =\"Y\" OR approved is null) ) order by date DESC";
			$error = doQuery($query,"Select in showAllPhotoRemarks()",$sql);

			while( $row=fetchArray($sql))
			{
				$msg = str_replace("\n","<br/>",$row["msg"]);
				$name = $row["name"];
				$approved = ($row["approved"] == "N") ? false : true;

				echo("\n<div class='remarkbox'>");
				echo("\n\t<div class='remarkblock'>$msg</div>");									
				echo("\n\t<div class='remarksource'>".MSG_POSTED_BY." <b>".$name."</b> ".MSG_POSTED_AT." ".fetchDate($row["date"])."</div>");
				echo("\n</div>");
			} //end while

			freeResult($sql);
		}
			
		$author = (IsSet($_POST["author"])) ? $_POST["author"]: "";
		$remark = (IsSet($_POST["remark"]))  ? $_POST["remark"]:  "";

		// $author & $remark are non-empty only when an entry error occurs
	
		echo( "\n\t<form name='addRemark' class='remarksinput' action='$script' method='post' onsubmit='return validateAddRemark(\"".MSG_EMPTY_AUTHOR_OR_REMARK."\")'>" );
		echo( "\n\t\t<b>".MSG_REMARK_AUTHOR."</b><br/><input name='author' type='text' value='".htmlentities($author, ENT_QUOTES)."'  size='30'/>" );
		echo( "\n\t\t<br/><b>".MSG_REMARK_CONTENT."</b><br/><textarea rows='5' cols='60' wrap='60' name='remark' style='width: 100%; margin-bottom: 5px;'>".htmlentities($remark,ENT_QUOTES)."</textarea>" );

		echo( "\n\t\t<br/><input type='submit' value='".MSG_ADD_REMARK."' name='go'/>" ); //'add' button
		if (USE_CAPTCHA) // display CAPTCHA string
		{	
			$encryptedCode=encryptDecrypt($code);
			echo( "\n\t\t&nbsp;&nbsp;".MSG_CAPTCHA_1);
			echo( "\n\t\t <img src=".$respath."/php/captcha.php?cpt=".urlencode($encryptedCode)." style='vertical-align: bottom;'>");
			echo( "\n\t\t<input type='Hidden' name='cpt' value=".urlencode($encryptedCode)." />" );
			echo( "\n\t\t".MSG_CAPTCHA_2."<input type='text' value='' size='8' name='cpct'/>");						
		}
			
		echo( "\n\t</form>" );
	}

	function validateCAPTCHA()
	{
		$captcha_response = (IsSet($_POST["cpct"])) ? $_POST["cpct"] : "";
		$code = (IsSET($_POST["cpt"])) ? $_POST["cpt"] : "";
		$valid=true;

		if ($captcha_response == "")
		{
			echo("<div class='errorbox'><span class='errormessage'>".MSG_CAPTCHA_EMPTY."</span></div>");
			$valid = false;
		}
		elseif ($captcha_response != encryptDecrypt(urldecode($code)))
		{
			echo("<div class='errorbox'><span class='errormessage'>".MSG_CAPTCHA_ERROR."</span></div>");
			unset($_POST["cpt"]); unset($_POST["cpct"]);
			$valid = false;
		}
		return $valid;
	}

	function validateEntry()
	{
		$name = (IsSet($_POST["author"])) ? $_POST["author"]: "";
		$msg = (IsSet($_POST["remark"]))   ? $_POST["remark"]:  "";	
		$valid = true;
		if (USE_CAPTCHA)
			$valid= (validateCAPTCHA() ) ? true: false; //if CAPTCHA valid, don't change value of $valid
		$nameMsg=cleanEntries($name,$msg);
		$name=$nameMsg[0];
		$msg=$nameMsg[1];
		return new Remark($name,$msg,$valid);
	}

?>
