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

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

	class UserRemarks
	{
		var $imageID; //unique image ID for database
		var $script;
		var $tabulka; //name of MySQL table to be used
		var $adminMode;
		var $action;

		function UserRemarks($imageID, $script)
		{
			$bad_chars = "!@#$%^&*()+<>?{}|[]\:,.-= "; //translate non-allowed characters to '_'

			//replace blanks with %20 to ensure valid URL
			$this->script = str_replace(" ", "%20", $script);	//name of slide image web page file

			//ensure that table name has only allowable characters
			$this->tabulka = strtolower(strtr(DB_TABLE_NAME, $bad_chars, str_repeat("_", strlen($bad_chars))));

			$this->imageID = addslashes($imageID);

			$this->action = (IsSet($_REQUEST["action"])) ? $_REQUEST["action"] : "1";     // 1 = nothing, just list remarks
			$this->action = (IsSet($_REQUEST["delete"])) ? "3" : $this->action;  // 3 = delete this remark
			$this->action = (IsSet($_REQUEST["delete-all"])) ? "4" : $this->action;  // 4 = delete all remarks for this photo

			if( IsSet($_REQUEST["edit"]) )
				$this->adminMode = true;

			if( IsSet($_REQUEST['exit']) )
      		{
				$this->adminMode = false;
				$this->action = "6"; // 6 = force display remarks
			}
		} // end of function (method) UserRemarks

		function executeAction()
		{
			if( $this->action==2 ) // add remark
			{
				$remarkEntry = validateEntry();
				$this->adminMode = ($remarkEntry->name==ADMIN_USER && $remarkEntry->msg==ADMIN_PASSWD) ? true : false;

				if( ($remarkEntry->valid==true) AND ($this->adminMode==false) )		//skip adding remark if in adminMode
					addPhotoRemark($this->tabulka, $this->imageID, $remarkEntry);
			} //end of 'add remark'

			if( $this->action==5 ) // update one remark
			{
				$remarkEntry = validateEntry();

				if( $remarkEntry->valid==true )
					updatePhotoRemark($this->tabulka, $remarkEntry);

				$this->adminMode = true;
			} 	//end 'update current remark'

			if( $this->action==3 ) // delete one remark
			{
				deletePhotoRemark($this->tabulka);
				$this->adminMode = true;
			}

			if( $this->action==4 ) // delete all remarks for this image
			{
				deleteAllPhotoRemarks($this->tabulka, $this->imageID);
				$this->adminMode = true;
			}

			////// $action=666 or 100 cannot be accessed via album interface--see functions for usage
			//if( $this->action==666 ) // delete all remarks from this album
			//	deleteAllRemarks($this->tabulka);

			//if( $this->action==100 ) // show all remarks for this album
			//	showAllAlbumRemarks($this->tabulka);

			showAllPhotoRemarks($this->script, $this->adminMode, $this->tabulka, $this->imageID);

			//if( $this->action!=1 )
			//	forceDisplayRemarkSection();
		}

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

		function forceDisplayRemarksIfNecessary()
		{
			if( $this->action!=1 )
			{
				//forceDisplayRemarkSection();
				echo("showRemarks();");
				echo("bringRemarksToTop();");
			}
		}
	} //end of class UserRemarks

	function showAllPhotoRemarks($script, $admin, $table, $id)	//displays the remarks
	{
		$numOfRows = fetchRemarksCount($table, $id);

		if( $admin==true ) // administration console
		{
			echo("\n\t<form class='remarksadmin' action='".$script."' method='post'>");
			echo("\n\t\t<span class='remarksadminheader'>".MSG_ADMIN_CONSOLE.":</span>");
			echo("\n\t\t<input type='Hidden' name='id' value='".$id."'/>");
			echo("\n\t\t<input type='submit' value='".MSG_DELETE_ALL_REMARKS."' name='delete-all'/>&nbsp");
			echo("\n\t\t<input type='submit' value='".MSG_EXIT_ADMIN_MODE."' name='exit'/>");
			echo("\n\t</form>");
		}

		//display remark
		if( $numOfRows>0 ) //if there is data in the table for this image
		{
			$sql = mysql_query("select * from ".$table." where imageID='".$id."'"." order by date DESC");
			if( mysql_errno()!=0 )
				echo( reportError("Select in showAllPhotoRemarks()", mysql_errno(), mysql_error()) );

			while( $row=mysql_fetch_array($sql))
			{
				$msg = str_replace("\n","<br/>",$row["msg"]);
				$name = $row["name"];

				//restore quotes, etc., if needed
				if( !get_magic_quotes_gpc() )
				{
					$name = stripslashes($name);
					$msg = stripslashes($msg);
				}

				echo("\n<div class='remarkbox'>");
				if( $admin==true )
					showForm($script, $admin, $name, $msg, $row["id"]);	//show input form
				else
					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

			mysql_free_result($sql);
		}

		if( $admin==false ) //exhibit Add Remark form
			showForm($script, $admin, "", "", "0");
	}

	function showForm($script, $admin, $name, $msg, $id) //displays the remarks input form
	{
		$action = $admin ? "5" : "2";

		echo( "\n\t<form class='remarksinput' action='".$script."' method='post'>" );
		echo( "\n\t\t<input type='Hidden' name='action' value='".$action."'/>" );
		echo( "\n\t\t<input type='Hidden' name='id' value='".$id."'/>" );
		echo( "\n\t\t<b>".MSG_REMARK_AUTHOR."</b><br/><input name='name' type='text' value='".$name."' size='30'/>" );
		echo( "\n\t\t<br/><b>".MSG_REMARK_CONTENT."</b><br/><textarea rows='5' cols='60' wrap='60' name='msg' style='width: 100%; margin-bottom: 5px;'>".$msg."</textarea>" );
		if( $action=="2" ) //'add' button
			echo( "\n\t\t<br/><input type='submit' value='".MSG_ADD_REMARK."' name='go'/>" );
		else // 'edit' & 'delete' buttons
		{
			echo( "\n\t\t<br/><input type='submit' value='".MSG_UPDATE_REMARK."' name='go'/>&nbsp" );
			echo( "\n\t\t<input type='submit' value='".MSG_DELETE_REMARK."' name='delete'/>" );
		}
		echo( "\n\t</form>" );
		return $form;
	}

	function fetchRemarksCount($table, $id)
	{
		$query = "select count(*) from ".$table." where imageID='".$id."'";
		$sql = mysql_query($query);
		$numOfRows = 0;

		if( mysql_errno()==1146 ) // if table doesn't exists, then create one
		{
			mysql_query("create table ".$table." (id int not null AUTO_INCREMENT, imageID char(200), date datetime not null default '0000-00-00 00:00:00', name char(100), msg text, ip1 char(100), ip2 char(100), refer char(255), primary key (id))");
			if( mysql_errno()!=0 )
				echo( reportError("Create Table", mysql_errno(), mysql_error()) );
			$sql = mysql_query($query);
			if( mysql_errno()!=0 )
				echo( reportError("Fetch after create table", mysql_errno(), mysql_error()) );
		}
		else
		{
			$sql = mysql_query("select * from ".$table." where imageID='".$id."'");
			if( mysql_errno()!=0 )
				echo( reportError("Select in fetchRemarksCount()", mysql_errno(), mysql_error()) );

			$numOfRows = mysql_num_rows($sql);
		}
		mysql_free_result($sql);
		return $numOfRows;
	}

	function validateEntry()
	{
		//check to see if either name or msg is empty & display warning message if so		
		$name = (IsSet($_REQUEST["name"]))?$_REQUEST["name"]:"";
		$msg = (IsSet($_REQUEST["msg"]))?$_REQUEST["msg"]:"";

		$valid = true;
		if( (strlen($name)<1) || (strlen($msg)<1) )
		{
			echo("<div class='errorbox'><span class='errormessage'>".MSG_EMPTY_AUTHOR_OR_REMARK."</span></div>");
			$valid = false;
		}

		//escape quotes and slashes if necessary
		if( !get_magic_quotes_gpc() )
		{
			$name = addslashes($name);
			$msg = addslashes($msg);
		}

		$name = strip_tags($name); //strip off html tags but permit foreign chars
		$allowable_tags = "<b></b><em></em><strong></strong><i></i>"; //permit bold and italics
		$msg = strip_tags($msg, $allowable_tags); //strip off html tags but permit foreign chars

		return new Remark($name,$msg,$valid);
	}

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

	function sendNotification($table_name, $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 addPhotoRemark($table, $imageID, $remarkEntry)
	{
		$query = "insert into ".$table." (imageID, name, date, msg, ip1, ip2, refer) VALUES('$imageID','$remarkEntry->name', NOW(), '$remarkEntry->msg', '".gethostbyaddr($_SERVER["REMOTE_ADDR"])."',";
		if( !empty($_SERVER['HTTP_X_FORWARDED_FOR']) )
			$query .= "'" . gethostbyaddr($_SERVER['HTTP_X_FORWARDED_FOR']) . "'";
		else
			$query .= " NULL";
		$query .= ",'".addslashes($_SERVER["HTTP_REFERER"])."')";
		mysql_query($query);
		if( mysql_errno()!=0 )
			echo( reportError("Add Remark", mysql_errno(), mysql_error()) );
		else
		{
			if( NOTIFY ) // send notification email if enabled
				sendNotification($table, $imageID, $remarkEntry->name, $remarkEntry->msg);
		}
	}

	function updatePhotoRemark($table, $remarkEntry)
	{
		mysql_query("update ".$table." SET name= '".$remarkEntry->name."' , msg= '".$remarkEntry->msg."' where id = '".$_REQUEST["id"]."'");
		if( mysql_errno()!=0 )
			echo( reportError("Update Remark", mysql_errno(), mysql_error()) );
	}

	function deletePhotoRemark($table)
	{
		mysql_query("delete from ".$table." where id = '".$_REQUEST["id"]."'");

		if( mysql_errno()==1146 )
			echo("<div class='remarkstatusbox'>".MSG_NOTHING_TO_DELETE."</div>");
		else
		{
			if( mysql_errno()!=0 )
				echo( reportError("Delete remark for photo", mysql_errno(), mysql_error()) );
			else
				echo("<div class='remarkstatusbox'>".MSG_PHOTO_REMARK_DELETED."</div>");
		}
	}

	function deleteAllPhotoRemarks($table, $imageID)
	{
		mysql_query("delete from ".$table." where imageID = '".addslashes($imageID)."'");

		if( mysql_errno()==1146 )
			echo("<div class='remarkstatusbox'>".MSG_NOTHING_TO_DELETE."</div>");
		else
		{
			if( mysql_errno()!=0 )
				echo( reportError("Delete all remarks for photo", mysql_errno(), mysql_error()) );
			else
				echo("<div class='remarkstatusbox'>".MSG_PHOTO_REMARKS_DELETED."</div>");
		}
	}

	//////////
	// super admin features not availble through GUI--browse to special URL only
	//////////

	/**
	 * deletes ALL remarks from this album
	 *
	 * Example:
	 * http://www.server.com/picture1234.php?action=666&password=myDbPassword
	 *
	 * NOTE: database password required
	 */
	function deleteAllRemarks($table)
	{
		$password = (IsSet($_REQUEST["password"]))?$_REQUEST["password"]:"";
		$x=!strcmp(DB_PASSWORD, $password);
		if( !$x )
			echo("<div class='remarkstatusbox'>".MSG_INVALID_PASSWORD."</div>");
		else
		{
			mysql_query("drop table ".$table);
			if( mysql_errno()==1051 )
				echo("<div class='remarkstatusbox'>".MSG_NOTHING_TO_DELETE."</div>");
			else
			{
				if( mysql_errno()!=0 )
					echo( reportError("Drop Table", mysql_errno(), mysql_error()) );
				else
					echo("<div class='remarkstatusbox'>".MSG_ALL_REMARKS_DELETED."</div>");
			}
		}
	}

	/**
	 * Shows all remarks for pix in this album
	 *
	 * Example:
	 * http://www.server.com/picture1234.php?action=100&password=myDbPassword
	 *
	 * NOTE: database password required
	 */
	function showAllAlbumRemarks($table_name)
	{
		$result = mysql_query("select * from ".$table_name);
		if( mysql_errno()!=0 )
			echo( reportError("Dump table", mysql_errno(), mysql_error() ) );
		$table .= "<table border='1'>\n\n";
		$noFields = mysql_num_fields($result);
		$table .= "<tr>\n";
		for( $i = 0; $i<$noFields; $i++ )
		{
			$field = mysql_field_name($result, $i);
			$table .= "\t<th>$field</th>\n";
		}
		while( $r = mysql_fetch_row($result) )
		{
			$table .= "<tr>\n";
			foreach ($r as $col)
			{
				$table .= "\t<td>$col</td>\n";
			}
			$table .= "</tr>\n";
		}
		$table .= "</table>\n\n";
		echo $table;
	}

	function reportError($errloc, $errno, $errmsg)
	{
    	$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>";
		return $msg;
	}

	include "connect.php";

	/////// open connection to the database
	$connect = mysql_connect(DB_URL, DB_USERNAME, DB_PASSWORD) or die("Cannot connect to database: ".mysql_error());
	mysql_select_db(DB_NAME,$connect) or die("Cannot select database: ".mysql_error());
?>
