<?php
include "../includes/session.php";
include "../includes/config.php";
include "../includes/function.php";
if (get_magic_quotes_gpc()) {
    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE); 
} 

$rootserver = $_SESSION["session_rootserver"];
$secureserver=$_SESSION["session_secureserver"];
$size_per_user=0; 	// passed by reference to size checking function 
$allowed_space=0;	// passed by reference to size checking function
$basicLocation=fetchBasicLocation(1);	//	this function fetches the location of the install folder 
$temperory_location=$basicLocation . "/workarea/tempsites";
$real_location=$basicLocation . "/workarea/sites";


//User selects publish page which will take him to the payment page which will be a secure page. 
//The secure page may not have access to the session state of the normal page if the secure url
//is a shared one, hence we are passing the userid(uid), tempsiteid(tid), templateType(type), styleSheet(style) 
if($_POST["pubpage"] == "publishpage") {	
	header("location:$secureserver/publishpage.php?uid=" . $_SESSION["session_userid"] . "&tid=" . $_SESSION['session_currenttempsiteid'] . "&type=advanced&style=" . $_SESSION["session_style"] . "&");
	exit;
}


$script_string="<script> ";
	//Functions used in various sections

		//function createPage($pageName,$templateId,$pageType,$editing) returns pageurl {} used to create a page in work area
		//$pageName 	==> name of the page created
		//$templateId 	==>	Id of the template 
		//$tmpSiteId	==>	Id of the temperory site the file has to be copied to
		//$pageType		==>	'1' indicates index.htm, '2' indicates a sub.htm.
		//$editing		==>	'true' indicates we are editing a published site(workarea/sites/siteid), 
		//					'false' indicates this site has not yet published (workarea/tempsites/tempsiteid)
		//$firstTime 	==>	'true' indicates page is being created for the first time so copy images
		//					'false' indicates page is being created for the nth time so do not copy images
		//process		==>	We copy a page from the templates/$templateId/[index.htm/sub.htm] based on the $pageType
		//					to the workarea/[sites/tempsites]/[siteId/tempsiteId].  If the $pageType is 1 then we 
		//					copy index.htm, else we copy sub.htm. If the $editing == true then we copy the page to 
		//					sites/siteid also.	if $firstTime == true then we copy the templates/$templateId/watermarkimages files to
		//					workarea/[sites/tempsites]/[siteId/tempsiteId]/images,  templates/$templateId/style.css to 	
		//					workarea/[sites/tempsites]/[siteId/tempsiteId]/style.css. we give the permissions to 777.
		//					if $gbflag == true then we replace <body> tag with the guestbook code. 
		function createPage($pageName,$templateid,$tmpsiteid,$pageType,$editing,$firstTime=false,$gbflag=false) {
			//physical location of the template will be /templates/template_id/
			//2 pages will be present 'index.htm' and 'sub.htm'
			//a folder called 'images' and 'watermarkimages' will be present in this folder.
			$workLocation = "";
			$pageToCopy = "";
			if($pageType == 1) {
				$pageToCopy = "index.htm";
			}
			else {
				$pageToCopy = "sub.htm";
			}
			//if $editing == true then set copy location to workarea/sites/siteid, copy the page to sites/siteid also.
			//else copy location to workarea/tempsites/tempsiteid
			if($editing == true) {
				$workLocation = "../workarea/sites/$tmpsiteid";
			   @copy("../".$_SESSION["session_template_dir"]."/$templateid/$pageToCopy","../sites/$tmpsiteid/$pageName");
			   @chmod("../sites/$tmpsiteid/$pageName",0777);
			}
			else {
				$workLocation = "../workarea/tempsites/$tmpsiteid";
			}
			//If the page is created for the first time copy watermarkimages to images folder in workarea, and style.css to workarea. 			
			if($firstTime == true)	{
				copydirr("../".$_SESSION["session_template_dir"]."/".$templateid."/watermarkimages",$workLocation . "/images",0777,false);
 			    @copy("../".$_SESSION["session_template_dir"]."/$templateid/style.css",$workLocation . "/style.css");
			    @chmod($workLocation . "/style.css",0777);
		    }
		    @copy("../".$_SESSION["session_template_dir"]."/$templateid/$pageToCopy",$workLocation . "/$pageName");
   		    @chmod($workLocation . "/$pageName",0777);
			//If the page being created is a guestbook replace <body> tag with guestbook code(php) 
			if($gbflag == true) {
				$search_string = "<body>";
				 $replace_string='<body><span id=guestbook_span><?php
                          $filename = \'gb.txt\';
                          // make sure the file exists and is writable first.
                          if (is_writable($filename)) {
                              if (!$handle = fopen($filename, \'a+\')) {
                                   $message.= "Cannot open file ($filename)";
                                   exit;
                              }
                                  If($_GET["act"]=="post"){
                                          $message= "";
                                          $content = addslashes($_POST["name"])."`|^".$_POST["email"]."`|^".$_POST["matter"]."`|^".date("Y-m-d")."~`|\n";
                                          if (fwrite($handle, $content) === FALSE) {
                                                  $message.= "Cannot write to file ($filename)";
                                                  exit;
                                          }

                                          $message.= "Thank you. Your Guest book entry added";
                                          fseek($handle, 0);

                                  }
                              //read file content to make display
                                  $displaycontents.="<table align=center width=70%><tr><td align=center><font face=verdana size=2><b>Current GuestBook Entries<br>&nbsp;</b></font></td></tr>";

                                  if(filesize($filename)>0){

                                                  $readcontents = @fread($handle, filesize($filename));
                                                  $entryarray=explode("~`|\n",$readcontents);


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

                                                          $valuearray=explode("`|^",$entryarray[$i]);
                                                          $displaycontents.="<tr><td align=left bgcolor=#dddddd><font face=verdana size=2>Posted &nbsp;by &nbsp;".stripslashes($valuearray[0])."( ".$valuearray[1]." ) &nbsp;on&nbsp; ".$valuearray[3]."</font></td></tr>";
                                                          $displaycontents.="<tr><td align=left valign=top><font face=verdana size=2><br>".$valuearray[2]."</font></td></tr>";
                                                          $displaycontents.="<tr><td align=left valign=top>&nbsp;</td></tr>";


                                                  }


                                  }else{

                                                  $displaycontents.="<tr><td align=center valign=top><font face=verdana size=2>Sorry! Guest book is empty.</font></td></tr>";

                                  }
                                  $displaycontents.="</table>";
                                  fclose($handle);


                          } else {

                              $message.= "The file $filename is not writable.Please provide write permission to it";

                          }




                          ?>
                          <script>
                          function checkMail(email)
                          {
                                  var str1=email;
                                  var arr=str1.split(\'@\');
                                  var eFlag=true;
                                  if(arr.length != 2)
                                  {
                                          eFlag = false;
                                  }
                                  else if(arr[0].length <= 0 || arr[0].indexOf(\' \') != -1 || arr[0].indexOf("\'") != -1 || arr[0].indexOf(\'"\') != -1 || arr[1].indexOf(\'.\') == -1)
                                  {
                                                  eFlag = false;
                                  }
                                  else
                                  {
                                          var dot=arr[1].split(\'.\');
                                          if(dot.length < 2)
                                          {
                                                  eFlag = false;
                                          }
                                          else
                                          {
                                                  if(dot[0].length <= 0 || dot[0].indexOf(\' \') != -1 || dot[0].indexOf(\'"\') != -1 || dot[0].indexOf("\'") != -1)
                                                  {
                                                          eFlag = false;
                                                  }

                                                  for(i=1;i < dot.length;i++)
                                                  {
                                                          if(dot[i].length <= 0 || dot[i].indexOf(\' \') != -1 || dot[i].indexOf(\'"\') != -1 || dot[i].indexOf("\'") != -1 || dot[i].length > 4)
                                                          {
                                                                  eFlag = false;
                                                          }
                                                  }
                                          }
                                  }
                                          return eFlag;
                          }
                          function validate(){

                                          if(document.gbForm.name.value=="" ){

                                                  alert("Please enter your name");
                                                  document.gbForm.name.focus();

                                          }else if (document.gbForm.email.value==""){

                                                  alert("Please enter your email");
                                                  document.gbForm.email.focus();

                                          }else if(checkMail(document.gbForm.email.value)==false){

                                               alert(\'Invalid mail format\');
                                               document.gbForm.email.focus();
                                               return false;

                                      }else if (document.gbForm.matter.value==""){

                                                  alert("Please enter your matter");
                                                  document.gbForm.matter.focus();

                                          }else{

                                                  document.gbForm.submit();
                                          }

                          }
                          </script>
                          <?php
                          echo $displaycontents;
                          ?>
                          <table width="100%"  border="0" align="center">
                            <tr>
                              <td>&nbsp;</td>
                            </tr>
                            <tr>
                              <td align="center"><form name="gbForm" method="post" action="<?php $_SERVER[\'PHP_SELF\']; ?>?act=post">
                                <fieldset style="width:400px;">
                                    <table width="100%"  border="0">
                                  <tr align="center">
                                    <td colspan="3"><br>
                                      <strong><font face=verdana size=2>Add your guestbook entry</font> </strong><br>&nbsp;</td>
                                    </tr>
                                                    <tr>
                                    <td width="100%" align="center" colspan=3><font face=verdana size=1 color=red><?php echo $message; ?></font></td>
                                  </tr>
                                  <tr>
                                    <td width="45%" align="right"><font face=verdana size=2>Your Name</font></td>
                                    <td width="3%">&nbsp;</td>
                                    <td width="52%" align="left" valign="top"><input name="name" type="text" id="name"></td>
                                  </tr>
                                  <tr>
                                    <td>&nbsp;</td>
                                    <td>&nbsp;</td>
                                    <td>&nbsp;</td>
                                  </tr>
                                  <tr>
                                    <td align="right"><font face=verdana size=2>Your Email Address</font></td>
                                    <td>&nbsp;</td>
                                    <td align="left" valign="top"><input name="email" type="text" id="email"></td>
                                  </tr>
                                  <tr>
                                    <td>&nbsp;</td>
                                    <td>&nbsp;</td>
                                    <td>&nbsp;</td>
                                  </tr>
                                  <tr>
                                    <td align="right"><font face=verdana size=2>Guest Book Matter</font></td>
                                    <td>&nbsp;</td>
                                    <td align="left" valign="top">            <textarea name="matter" id="matter"></textarea></td>
                                  </tr>
                                  <tr>
                                    <td>&nbsp;</td>
                                    <td>&nbsp;</td>
                                    <td>&nbsp;</td>
                                  </tr>
                                  <tr align="center">
                                    <td colspan="3"><input type="button" value="Sign Guest Book" onclick=validate();></td>
                                    </tr>
                                </table>
                                    </fieldset>
                              </form></td>
                            </tr>
                          </table></span>';
				file_replace($search_string, $replace_string, $workLocation . "/$pageName");
				if(!is_file($workLocation . "/gb.txt")) {
					fwrite(fopen($workLocation . "/gb.txt","w"),".");
					@chmod($workLocation . "/gb.txt",0777);
				}
			}
		    return $workLocation . "/$pageName";
		}
	
		
		//function SaveFile($fileToSave)
		//$fileToSave ==>	the full path of the file to be saved
		//It saves the data that comes in the form Post EditorHTM,EditorHTM2,EditorHTM3,EditorHTM4,
		//EditorHTM5 variables to the location specified in $fileToSave.   
		function SaveFile($fileToSave,$search_string) {
			$fp = fopen($fileToSave,"w");
			fwrite($fp,$_POST["EditorHTM"]);	
			fwrite($fp,$_POST["EditorHTM2"]);	
			fwrite($fp,$_POST["EditorHTM3"]);	
			fwrite($fp,$_POST["EditorHTM4"]);	
			fwrite($fp,$_POST["EditorHTM5"]);	
			fclose($fp);
			//replace temporary location src so that relative paths will be "./" instead of "temporarylocation/"  for images and other
			//objects with src and similar tags
			file_replace ($search_string, ".", $fileToSave);
		}
		
		//file_replace ($search, $replace, $filename) returns true/false
		//$search	==>	The string that is to replaced from the file
		//$replace	==>	The string to replace with(normally "./")
		//$filename	==>	The name of the file that is to be operated upon
		//We call this function normally to replace the editor generated absolute path in the files that represents the 
		//temporary location of edition of files with relative "./" 
		function file_replace ($search, $replace, $filename) {
		   if (file_exists($filename)) {
			   $cnt = file_get_contents($filename);
				   $cnt = eregi_replace($search,$replace,$cnt);
				   fwrite(fopen($filename,"w"),$cnt);  //here file_put_contents() cannot be used since it is available only on php5 
			   		return true;
		   }
		   return false;
	   }
		
		//function to save changes to resource file
		//function SaveResource($resource_location,$var_deletedimages,$var_newimages)
		//$resource_location ==>	the location of the resource.txt file that has to be modified
		//$var_deletedimages ==>	'|' character seperated image file names that has to be deleted from the resource file
		//$var_newimages 	 ==>	'|' character seperated image file names that has to be added to the resource file	
		//the resource file is read into an array using file($resourcelocation)
		//for each name in $deletedimages we delete a name from the populated array and then finally overwrite the new array into resource.txt
		//Then the contents in the $newimages is written to resourcelocation 
		$resource_save_flag = false;
		function SaveResource($resource_location,$var_deletedimages,$var_newimages,$userid) {
			//resource flag is being used for correctly manipulating the resource file.
			//For each save operation the user initiates the 'checkid' parameter is sent which contains the session_checkid + 1
			//ie. if the session_checkid >= checkid(posted) then that means the page is submitted as part of a refresh operation 
			// and the resource.txt file operation has been already performed.  Hence we return back to the calling location without 
			//modifying the resource.txt file
			//else we set the session_checkid as checkid(posted) and resource_flag is set to true, and resource.txt file is modified.   
			global $resource_save_flag;
			if($resource_save_flag == false) {
				if($_SESSION["session_checkid"] >= $_POST["checkid"]) {
					return;
				}
				else {
					$_SESSION["session_checkid"]=$_POST["checkid"];
					$resource_save_flag = true;
				}
			}
			
			if(is_file($resource_location)) {
			$content_arr = file($resource_location);
			if(strlen($var_deletedimages) > 0) {	// IF Delete images > 0
				$deleted_arr = explode('|',$var_deletedimages);
				$deleted_count = count($deleted_arr);
				for($i=0;$i < $deleted_count;$i++) {	// FOR LOOP - I
						$temp_string=$deleted_arr[$i];
						switch(substr($temp_string,0,2)) {
							case "ug":
									$temp_string = "../usergallery/$userid/images/" . $temp_string;
									break;
							case "sg":
									$temp_string = "../systemgallery/" . $temp_string;
									break;
							case "sl":
									$temp_string = "../samplelogos/" . $temp_string;
									break;
							case "fl":
									$temp_string = "../usergallery/$userid/flash/" . $temp_string;
									break;
							default:
									continue;											
						}
					$temp_count = 0;	
					foreach($content_arr as $lines) {	// FOR LOOP - II
						if(strcmp($temp_string,rtrim($lines,"\n")) == 0) {
							$content_arr[$temp_count] = "";
							break;
						}
						$temp_count++;
					}		// END FOR LOOP - II	
				}			// END FOR LOOP - I
			}		// END IF Delete images > 0
			}
			$fwriter=fopen($resource_location,"w");
			if(count($content_arr) > 0) {
				foreach($content_arr as $lines) {	// FOR LOOP 
					if($lines != "") {
						fputs($fwriter,$lines);
					}
				}
			}
			if(strlen($var_newimages) > 0) {	// IF New images > 0
				$new_arr = explode('|',$var_newimages);
				$new_count = count($new_arr);
				for($i=0;$i < $new_count;$i++) {	// FOR LOOP - I
					$temp_string=$new_arr[$i];
					switch(substr($temp_string,0,2)) {
						case "ug":
								$temp_string = "../usergallery/$userid/images/" . $temp_string . "\n";
								break;
						case "sg":
								$temp_string = "../systemgallery/" . $temp_string . "\n";
								break;
						case "sl":
								$temp_string = "../samplelogos/" . $temp_string . "\n";
								break;
						case "fl":
									$temp_string = "../usergallery/$userid/flash/" . $temp_string . "\n";
									break;		
						default:
								continue;											
					}
					fputs($fwriter,$temp_string);
				}
			}	// END IF New images > 0
			fclose($fwriter);
		}
		
		
		//function removePage($pageName,$templateid,$tmpsiteid,$pageType,$editing) {
		//$pageName		==>	name of the page to be deleted
		//$tmpsiteid	==>	temp site id
		//$editing		==>	'true' indicates we are removing a page while editing a published site, hence use 'sites' folder
		//					'false' indicates  we are removing a page while creating a new site, hence use 'tempsites' folder
		function removePage($pageName,$tmpsiteid,$editing) {
			$workLocation = "";
			//if $editing == true then we delete the page sites/$tmpsiteid/$pageName 
			//along with the workarea/tempsites/$tmpsiteid/$pageName
			if($editing == true) {
				$workLocation = "../workarea/sites/$tmpsiteid/$pageName";
				if(is_file("../sites/$tmpsiteid/$pageName")) {
	    	       @unlink("../sites/$tmpsiteid/$pageName");
				}
			}
			else {
				$workLocation = "../workarea/tempsites/$tmpsiteid/$pageName";
			}
			if (is_file($workLocation)) {
    	       @unlink($workLocation);
	       }
		}		
		
		//function setupEditSite($tmpsiteid,$templateid,&$var_guestbook) returns presentPage 
		//$tmpsiteid		==>	id of the site(published/temporary)
		//$templateid		==>	id of the template
		//&$var_guestbook	==>	 $var_guestbook	is passed as reference to which we assign "yes" if the returned page is a guestbook   
		//The folders workarea/sites/$tmpsiteid, workarea/sites/$tmpsiteid/images, workarea/sites/$tmpsiteid/flash is created
		//Images inside templates/templateId/images is copied to  workarea/sites/$tmpsiteid/images
		//Files inside sites/$tmpsiteid is copied to workarea/sites/$tmpsiteid
		//resource.txt in the  workarea/sites/$tmpsiteid is read and images,flash objects are copied to the respective folders.
		function setupEditSite($tmpsiteid,$templateid,&$var_guestbook) {
			$pageToCopy = "";
			$workLocation = "../workarea/sites/$tmpsiteid";
			//folders are created for setting up the work location
			if(!is_dir($workLocation)){
				@mkdir($workLocation,0777);
				@chmod($workLocation,0777); 
			}				
			if(!is_dir($workLocation . "/images")){
				@mkdir($workLocation . "/images",0777);
				@chmod($workLocation . "/images",0777);
				
				@mkdir($workLocation . "/flash",0777);
				@chmod($workLocation . "/flash",0777);
			}				
			//images for template are copied to work location
			copydirr("../".$_SESSION["session_template_dir"]."/".$templateid."/images",$workLocation . "/images",0777,false);
			//files of the created site including resource.txt is copied to work location
			copydirr("../sites/".$tmpsiteid,$workLocation,0777,false);
			//resource.txt is read and images of user gallery/system gallery that has been referred to from the created site
			//is copied to work location/images along with the flash objects to work location/flash.
			if(is_file($workLocation . "/resource.txt")) {
				$content_arr = file($workLocation . "/resource.txt");
				foreach($content_arr as $lines) {
					$file_name = rtrim($lines,"\n");
					$base_file_name = basename($file_name);
					switch(substr($base_file_name,0,2))
					{
						case "ug":
								$location = "/images/" . $base_file_name;
								break;
						case "sg":		
								$location = "/images/" . $base_file_name;
								break;
						case "sl":		
								$location = "/images/" . $base_file_name;
								break;
						case "fl":		
								$location = "/flash/" . $base_file_name;
								break;
						default:		
								$location = "/images/" . $base_file_name;
					}
					@copy($file_name, $workLocation . $location);
					@chmod($workLocation . $location,0777);
				}
			}
			$var_presentpage="";
			$sql = "Select * from tbl_site_pages where nsite_id='" . $tmpsiteid . "'";
			$result = mysql_query($sql) or die(mysql_error());
			if(mysql_num_rows($result) > 0)  {
				$row = mysql_fetch_array($result);
				$var_presentpage=$row["vpage_name"];	
				$var_guestbook=($row["vpage_type"] == "guestbook")?"yes":"";
			}
			return $var_presentpage;
		}
		
		//function isValidRequest($tmpsiteid,$templateid,$userid,$var_type) return true/false
		//$tmpsiteid	==>	temp site id
		//$templateid	==>	template id
		//$userid		==>	user id
		//$var_type		==>	if temporary then "new" else "edit"
		//$init_flag	==>	init flag default to false
		//checks if the tenpsiteid,templateid, userid  matches in the database
		function isValidRequest($tmpsiteid,$templateid,$userid,$var_type,$init_flag=false) {
			if($init_flag == true) {
				$var_insert_field="";
			}
			else {
				$var_insert_field=" AND ntemplate_id='" . addslashes($templateid) . "' ";
			}
			if($var_type == "new") {
				$sql = "Select ntempsite_id from tbl_tempsite_mast where ntempsite_id='" . addslashes($tmpsiteid) . "' 
				" . $var_insert_field . " AND nuser_id='" . addslashes($userid) . "'";
			}	
			else {
				$sql = "Select nsite_id from tbl_site_mast where nsite_id='" . addslashes($tmpsiteid) . "' 
				" . $var_insert_field . " AND nuser_id='" . addslashes($userid) . "'";
			}
			$result = mysql_query($sql) or die(mysql_error());
			if(mysql_num_rows($result) > 0) {
				return true;
			}
			else {
				return false;
			}
		}
		
		//isValidGuestbookEntry($var_gb,$var_type,$tmpsiteid) returns true/false
		//$var_gb		==>	"yes" indicates has to be checked before saying true.
		//$var_type		==>	 Temporary then "new" else "edit" 	
		//$tmpsiteid	==>	 Temp site id	
		// returns true if the guestbook entry for the site is valid, else, returns false.
		function isValidGuestbookEntry($var_gb,$var_type,$tmpsiteid) {
			if($var_gb != "yes") {
				return true;
			}
			if($var_type == "new") {
				$sql = "Select * from tbl_tempsite_pages where ntempsite_id='$tmpsiteid' AND vpage_type='guestbook'";
			}
			else {
				$sql = "Select * from tbl_site_pages where nsite_id='$tmpsiteid' AND vpage_type='guestbook'";
			}
			if(mysql_num_rows(mysql_query($sql)) > 0) {
				return false;
			}
			return true;
		}
	//End functions
	
	//possible values for actiontype 	==>	(editsite,init,save,saveandcreate,saveandexit,edit,saveandedit,newpage,delete,saveas)
	//When this page gets loaded for the first time as request comes from template selection for a non-published site
		//Edit a site previously created 
		//If you are editing a temporary site type will be "new"
		//If you are editing a published site type will be "edit" 
		if($_GET["actiontype"] == "editsite") {	//edit the site previously created 
			//we check for the size factor(validateSizePerUser) and request validity(isValidRequest)
			//On passing both the tests, session_currenttempsiteid, session_currenttemplateid and session_templatetype is set
			//If the type = "new" (temporary site)
			//	 	tbl_tempsite_pages is checked to see if it contains any pages for the site
			//			if no then 
			//					an index.htm page is copied to the work location from the template section , a row is added to 
			//					tbl_tempsite_pages for index.htm, 
			//			else 
			//					a page is randomly selected and var_presentpage and pageurl is set accordingly   
			//			end if
			//Else
			//		we call setupeditsite function that copies files from the sites folder, read the resource.txt file and copies files
			//		and return the persent page, then we construct the page url
			//End IF  
			//size checking, if exceeded limit, then alert the user, user taken to usermain
			if(!validateSizePerUser($_SESSION["session_userid"],$size_per_user,$allowed_space,"../")) {
				echo "<script> alert('Your space exceeded permitted limit." . 
				"(Space taken by you: " . human_read($size_per_user) . " " . 
				"Allowed space: " . human_read($allowed_space) . ") \\r\\n" . 
				"Delete unused images or any/all of the sites created by you to proceed further.'); location.href='../usermain.php'; </script>";
				exit();
			}
			//end size checking
			//If we are editing a temporary created site
			//'type' = new 
			if($_GET["type"] == "new") {		// edit a non published site

				$var_type=$_GET["type"];
				$var_actionin = $_GET["actiontype"];			//assigned to a hidden variable(actionin) 	
				$templateid=addslashes($_GET['templateid']);
				$_SESSION['session_currenttempsiteid'] = $_GET["tempsiteid"];
				$tmpsiteid=$_SESSION['session_currenttempsiteid'];
				$userid=$_SESSION["session_userid"];
 			    $_SESSION['session_currenttemplateid']=$templateid;
				
				if(!isValidRequest($tmpsiteid,$templateid,$userid,$var_type)) {
					echo("<script>alert('Invalid request! Please try again.'); location.href='../usermain.php';</script>");
					exit();
				}
				$_SESSION['session_templatetype'] = "advanced";
				$sql = "Select * from tbl_tempsite_pages where ntempsite_id='" . $_SESSION['session_currenttempsiteid'] . "'";	
				$result = mysql_query($sql) or die(mysql_error());
				if(mysql_num_rows($result) <= 0) {	//this 'if' part never gets executed
					$sql = "Insert into tbl_tempsite_pages(ntempsp_id,ntempsite_id,vpage_name,vpage_title,vpage_type,vtype) 
							Values('','" . $_SESSION['session_currenttempsiteid']  . "',
							'index.htm','','htm','advanced')";
					mysql_query($sql) or die(mysql_error());		
					$var_presentpage="index.htm";
					$var_pageurl=createPage("index.htm",$templateid,$tmpsiteid,1,false);
				}
				else {
					$row = mysql_fetch_array($result);
					$var_presentpage=$row["vpage_name"];
					$var_guestbook = ($row["vpage_type"] == "guestbook")?"yes":"";
					$var_pageurl="../workarea/tempsites/$tmpsiteid/$var_presentpage";
				}
			}	//end if $_GET["type"] == "new", if we are editing a published site 'type'=edit			
			elseif($_GET["type"] == "edit") {	//edit a published site
				$var_type=$_GET["type"];
				$var_actionin = $_GET["actiontype"];			//assigned to a hidden variable(actionin) 	
				$templateid=addslashes($_GET['templateid']);
				$_SESSION['session_currenttempsiteid'] = $_GET["tempsiteid"];
				$tmpsiteid=$_SESSION['session_currenttempsiteid'];
				$userid=$_SESSION["session_userid"];
 			    $_SESSION['session_currenttemplateid']=$templateid;
				
				if(!isValidRequest($tmpsiteid,$templateid,$userid,$var_type)) {
					echo("<script>alert('Invalid request! Please try again.'); location.href='../usermain.php';</script>");
					exit();
				}
				$var_guestbook="";
			 	$_SESSION['session_templatetype'] = "advanced";
				//setupeditsite function is called to copy the files from site folder, read resource.txt and copy files accordingly
				$var_presentpage=setupEditSite($tmpsiteid,$templateid,$var_guestbook);
				$var_pageurl="../workarea/sites/$tmpsiteid/$var_presentpage";
			}// end if $_GET["type"] == edit
		}
		elseif($_GET["actiontype"] == "init") {
			//actiontype == init  indicates a new temporary site being created for the first time
			//Check for the size factor(validateSizePerUser) and request validity(isValidRequest)
			//On passing both the tests,  session_currenttemplateid and session_templatetype is set
			//If type="new" then
			//			tbl_tempsite_mast updated to reflect current template id and type as advanced for the current tempsiteid
			//			tbl_tempsite_pages is checked for pages for the site.
			//			if no then a row is added to tbl_tempsite_pages for the tempsite_id
			//			we call createPage that copies the index.htm from template to work location
			//End if
			//we add index.htm as the default page. 
			//size checking
			if(!validateSizePerUser($_SESSION["session_userid"],$size_per_user,$allowed_space,"../")) {
				echo "<script> alert('Your space exceeded permitted limit." . 
				"(Space taken by you: " . human_read($size_per_user) . " " . 
				"Allowed space: " . human_read($allowed_space) . ") \\r\\n" . 
				"Delete unused images or any/all of the sites created by you to proceed further.'); location.href='../usermain.php'; </script>";
				exit();
			}
			//end size checking
			if($_GET["type"] == "new") {  //this page is called for a new site not yet published
				$var_type=$_GET["type"];
				$var_actionin = $_GET["actiontype"];			//assigned to a hidden variable(actionin) 	
				$templateid=addslashes($_GET['templateid']);
				$tmpsiteid=$_SESSION['session_currenttempsiteid'];
				$userid=$_SESSION["session_userid"];

				if(!isValidRequest($tmpsiteid,$templateid,$userid,$var_type,true)) {
					echo("<script>alert('Invalid request! Please try again.'); location.href='../usermain.php';</script>");
					exit();
				}
				  //session_templatetype & session_currenttemplateid set
				  $_SESSION['session_templatetype'] = "advanced";
				  $_SESSION['session_currenttemplateid']=$templateid;
				  
				  $qry="update tbl_tempsite_mast set ntemplate_id='".$_SESSION['session_currenttemplateid']."',vtype='advanced' where ntempsite_id='".$_SESSION['session_currenttempsiteid']."'";
				  mysql_query($qry);

				$sql = "Select * from tbl_tempsite_pages where ntempsite_id='" . $_SESSION['session_currenttempsiteid'] . "' AND vpage_name='index.htm'";	
				$result = mysql_query($sql) or die(mysql_error());
				if(mysql_num_rows($result) <= 0) {
					$sql = "Insert into tbl_tempsite_pages(ntempsp_id,ntempsite_id,vpage_name,vpage_title,vpage_type,vtype) 
							Values('','" . $_SESSION['session_currenttempsiteid']  . "',
							'index.htm','','homepage','advanced')";
					mysql_query($sql) or die(mysql_error());		
				}
  				$var_presentpage="index.htm";
				$var_pageurl=createPage("index.htm",$templateid,$tmpsiteid,1,false,true);
			}  //End If $_GET["type"] == "new"
		}		//End If $_GET["actiontype"] == "init"
		elseif($_POST["actiontype"] == "save" || $_POST["actiontype"] == "saveandcreate" || $_POST["actiontype"] == "saveandexit") {
			//saving a page, saving present page and creating a new one, saving present page and exiting 
			//While saving the page we check the type of operation ie. we are trying to save a page in a temporary site
			//or in a published site depending on the 'type'.  IF type == "new" then temporary ; IF type == "edit" then published;
			//The file content is posted back in 5 post parameters
			//IF type == "new" then
			//			worklocation is "workarea/tempsites/tempsiteid/"
			//		(i) save the file(to work location )that is posted back  by calling the function saveFile().(This function also 
			//		    replaces any references like http://sitename/foldername/......  to "./" by the help of $searchstring parameter) 	
			//		(ii) save the resource file(resource.txt) by calling the function saveResource().  	
			//Else
			//			worklocation is "workarea/sites/siteid/"
			//		(i) save the file(to work location )that is posted back  by calling the function saveFile().(This function also 
			//		replaces any references like http://sitename/foldername/......  to "./" by the help of $searchstring parameter)
			//		(ii) save the resource file(resource.txt) by calling the function saveResource().
			//		(iii) call saveFile() to save to the location sites/siteid.
			//		(iv)  call saveresource() to save the changes in sites/siteid/resource.txt
			//End If
			//IF actiontype == "saveandexit" then navigate back to usermain.php End IF
			//IF actiontype == "saveandcreate" then 
			//	IF the newPageToCreate is a guest book(var_gbnew == "yes") then
			//		check for guestbook addition validity by 
			//			(i)	checking if the current page was a guestbook(var_guestbook == "yes")
			//			(ii)checking database- see if there is already a guestbook entry for the siteid(isValidGuestbookEntry())
			//	End If
			//	If newPageToCreate is a guest book and doesnot pass validity checks then alert the user of the current error
			//	with the currentpage in the editable area.
			//	If size exceeded the permitted limit then alert the user of the size problem, with the current page in the editable area    					  	  		
			//	with the current page in the editable area.
			//	Check if the newpageName is present in the database for the siteid.
			//	If no then insert a row in the table tbl_tempsite_pages(temporary)/tbl_site_pages(published) or the page.
			//	call the function createPage() to copy index.htm/sub.htm based on user selection to work location.
			//	(if type == "edit" then a copy of the page is created in sites/siteid also which is done by createPage())  
			//	The presentpage and pageurl is set according to the value returned by createPage())
			//END IF	
			//	Check in tbl_tempsite_pages to see if there is a page with the 
			$bool_type = false;
			$var_actionin = $_POST["actiontype"];	
			$var_presentpage = $_POST["presentpage"];
			$var_pageurl=$_POST["pageurl"];
			$var_type = $_POST["type"];
			$var_deletedimages=$_POST["deletedimages"];
			$var_newimages=$_POST["newimages"];
			$var_guestbook = $_POST["guestbook"];
			$tmpsiteid=$_SESSION['session_currenttempsiteid']; // reconsider this statement since the session will be different in case of sites
			$userid=$_SESSION["session_userid"];
			
			//these 3 parameters will be passed only if "actiontype" = "saveandcreate" 
			$templateid=$_SESSION['session_currenttemplateid'];
			$var_pagetype=($_POST["pagetype"] == "index")?1:2;
			$var_editpage = $_POST["editpage"];
			$bool_guestbook = false;
			$var_gbnew="";
			if($_POST["gbnew"] == "yes") {
				$var_gbnew = $_POST["gbnew"];
				$bool_guestbook=true;
				$db_pagetype = "guestbook";
			}
			else {
				$db_pagetype = ($var_pagetype == 1)?"homepage":"subpage";
			}
	
			if(!isValidRequest($tmpsiteid,$templateid,$userid,$var_type)) {
					echo("<script>alert('Invalid request! Please try again.'); location.href='../usermain.php';</script>");
					exit();
			}	
				 
			if($var_type == "new") {
				$search_string=$temperory_location . "/$tmpsiteid";
				$fileToSave = "../workarea/tempsites/$tmpsiteid/$var_presentpage";
				$resource_location="../workarea/tempsites/$tmpsiteid/resource.txt";
				$sql_check = "Select * from tbl_tempsite_pages where ntempsite_id='" . $_SESSION['session_currenttempsiteid'] . "' AND vpage_name='" . addslashes($var_editpage) . "'";
				$sql_insert = "Insert into tbl_tempsite_pages(ntempsp_id,ntempsite_id,vpage_name,vpage_title,vpage_type,vtype) 
								Values('','" . $_SESSION['session_currenttempsiteid']  . "',
								'" . addslashes($var_editpage) . "','','" . $db_pagetype . "','advanced')";
			}
			elseif($var_type == "edit") {
				$bool_type = true;
				$search_string=$real_location . "/$tmpsiteid";
				$fileToSave = "../workarea/sites/$tmpsiteid/$var_presentpage";
				$resource_location="../workarea/sites/$tmpsiteid/resource.txt";
				$sql_check = "Select * from tbl_site_pages where nsite_id='" . $_SESSION['session_currenttempsiteid'] . "' AND vpage_name='" . addslashes($var_editpage) . "'";
				$sql_insert = "Insert into tbl_site_pages(nsp_id,nsite_id,vpage_name,vpage_title,vpage_type,vtype) 
								Values('','" . $_SESSION['session_currenttempsiteid']  . "',
								'" . addslashes($var_editpage) . "','','" . $db_pagetype . "','advanced')";
				//save to original site location
				SaveFile("../sites/$tmpsiteid/$var_presentpage",$search_string);
				SaveResource("../sites/$tmpsiteid/resource.txt",$var_deletedimages,$var_newimages,$userid);
			}
			SaveFile($fileToSave,$search_string);
			SaveResource($resource_location,$var_deletedimages,$var_newimages,$userid);
			if($_POST["actiontype"] == "saveandexit") {
				echo("<script>alert('Page Saved!'); location.href='../usermain.php'; </script>");
				exit();
			}
			$script_string .= " alert(\"Page Saved!\"); 
								global_saved = true; 
								 global_reload = true; ";
			
			// If user selected to create a new page
			if($_POST["actiontype"] == "saveandcreate") {	
				if($var_gbnew == "" || ($var_gbnew != $var_guestbook && isValidGuestbookEntry($var_gbnew,$var_type,$_SESSION['session_currenttempsiteid']))){
					if(validateSizePerUser($userid,$size_per_user,$allowed_space,"../")) {
						$result = mysql_query($sql_check) or die(mysql_error());
						$var_guestbook = $var_gbnew;
						if(mysql_num_rows($result) <= 0) {
							mysql_query($sql_insert) or die(mysql_error());		
						}
						$var_presentpage=$var_editpage;
						
						$var_pageurl=createPage($var_editpage,$templateid,$tmpsiteid,$var_pagetype,$bool_type,false,$bool_guestbook);
					}
					else {
						//size checking
						$script_string .= "alert('Cannot create new page. Your space exceeded permitted limit." . 
										"(Space taken by you: " . human_read($size_per_user) . " " . 
										"Allowed space: " . human_read($allowed_space) . ") \\r\\n" . 
										"Delete unused images or any/all of the sites created by you to proceed further.');";
						//end size checking
					}
				}	
				else {
					$script_string .= "alert('Cannot add two guestbook at a time.');";
				}
			}	
			//End If user selected to create a new page					 
		}
		elseif($_POST["actiontype"] == "edit" || $_POST["actiontype"] == "saveandedit") {
			//user changes page , may be selecting by saving and moving focus  
			//User changing the page, at times saving the current page and selecting another page to view
			//validity of request checked by calling isValidRequest(), if not valid navigated to usermain.php
			//user changing the page:
			//'editpage' will contain the id of the page the user selected to view/edit.
			//tbl_tempsite_pages is searched for the id, and name of the page is set to var_presentpage , 
			//and if the page selected to view is a guestbook we set var_guestbook is set to yes.
			//user saving the current page(actiontype == "saveandedit"):
			//IF type == "edit" then
			//	saveFile() is called to save the contents to sites/siteid/
			//	saveResource() is called to save the resource modifications to sites/siteid/resource.txt
			//	saveFile() is called to save the contents to workarea/sites/siteid/
			//	saveResource() is called to save the resource modifications to workarea/sites/siteid/resource.txt
			//Else
			//	saveFile() is called to save the contents to workarea/tempsites/tempsiteid/	 
			//	saveResource() is called to save the resource modifications to workarea/tempsites/tempsiteid/resource.txt 
			//END IF
			$bool_type = false;
			$var_actionin = $_POST["actiontype"];	
			$var_presentpage = $_POST["presentpage"];
			$var_pageurl=$_POST["pageurl"];
			$var_type = $_POST["type"];
			$var_deletedimages=$_POST["deletedimages"];
			$var_newimages=$_POST["newimages"];
			$tmpsiteid=$_SESSION['session_currenttempsiteid']; // reconsider this statement since the session will be different in case of sites
			$userid=$_SESSION["session_userid"];
			$templateid=$_SESSION['session_currenttemplateid'];
		
			$var_editpage=$_POST["editpage"];		// here editpage will contain the id of the page
			
			if(!isValidRequest($tmpsiteid,$templateid,$userid,$var_type)) {
					echo("<script>alert('Invalid request! Please try again.'); location.href='../usermain.php';</script>");
					exit();
			}

			if($var_type == "new") {
				//for save
				$search_string=$temperory_location . "/$tmpsiteid";
				$fileToSave = "../workarea/tempsites/$tmpsiteid/$var_presentpage";
				$resource_location="../workarea/tempsites/$tmpsiteid/resource.txt";

				$sql = "Select * from tbl_tempsite_pages where ntempsp_id='" . addslashes($var_editpage) . "'";
				$result = mysql_query($sql) or die(mysql_error());
				if(mysql_num_rows($result)) {
					$row = mysql_fetch_array($result);
					$var_presentpage = $row["vpage_name"];
					$var_guestbook = ($row["vpage_type"] == "guestbook")?"yes":"";
					$var_pageurl = "../workarea/tempsites/" . $row["ntempsite_id"] . "/$var_presentpage";	
				}
			}
			else {
				//for save
				$bool_type = true;
				$search_string=$real_location . "/$tmpsiteid";
				$fileToSave = "../workarea/sites/$tmpsiteid/$var_presentpage";
				$resource_location="../workarea/sites/$tmpsiteid/resource.txt"; 
				$fileRealLocation = "../sites/$tmpsiteid/$var_presentpage";
				
				$sql = "Select * from tbl_site_pages where nsp_id='" . addslashes($var_editpage) . "'";
				$result = mysql_query($sql) or die(mysql_error());
				if(mysql_num_rows($result)) {
					$row = mysql_fetch_array($result);
					$var_presentpage = $row["vpage_name"];
					$var_guestbook = ($row["vpage_type"] == "guestbook")?"yes":"";
					$var_pageurl = "../workarea/sites/" . $row["nsite_id"] . "/$var_presentpage";	
				}
			}
			if($_POST["actiontype"] == "saveandedit") {
				//for save
				if($var_type == "edit") {
					SaveFile($fileRealLocation,$search_string);
					SaveResource("../sites/$tmpsiteid/resource.txt",$var_deletedimages,$var_newimages,$userid);
				}
				SaveFile($fileToSave,$search_string);
				SaveResource($resource_location,$var_deletedimages,$var_newimages,$userid);
				$script_string .= " alert(\"Page Saved!\"); 
									global_saved = true; 
									 global_reload = true; ";
	
			}
		}
		elseif($_POST["actiontype"] == "newpage") {
			//USER CREATING A NEW PAGE
			//check if guestbookentry is proper for site isValidGuestbookEntry()
			//	if false then var_presentpage = currentpage,var_pageurl is set according to currentpage
			//size limit checked using validateSizePerUser() 
			//	if false then var_presentpage = currentpage,var_pageurl is set according to currentpage
			//checked for request validity
			//	if false user navigated to usermain
			//IF type == "new then
			//	(i)	  tbl_tempsite_pages checked for pagename in tempsiteid
			//	(ii)  if no identical pagename found then a row is inserted to tbl_tempsite_pages
			//	(iii) createpage() is called that copies index.htm/sub.htm based on user selection to workarea/tempsites/tempsiteid/pageName
			//	(iv)  var_presentpage and var_pageurl is set accordingly
			//ELSE
			//	(i)   tbl_site_pages checked for pagename in siteid
			//	(ii)  if no identical pagename found then a row is inserted to tbl_site_pages
			//	(iii) createpage() called that copies index.htm/sub.htm based on user selection to workarea/sites/siteid/pageName and sites/siteid/pagename	 
			//	(iv)  var_presentpage and var_pageurl is set accordingly
			//END IF
			$bool_type = false;
			$var_type=$_POST["type"];
			$var_actionin = $_POST["actiontype"];			//assigned to a hidden variable(actionin) 	
			$templateid=$_SESSION['session_currenttemplateid'];
			$var_pagetype=($_POST["pagetype"] == "index")?1:2;
			$tmpsiteid=$_SESSION['session_currenttempsiteid'];
			$userid=$_SESSION["session_userid"];
			$var_editpage = $_POST["editpage"];			// here editpage will contain the name of the page
			$var_guestbook=$_POST["guestbook"];
			$bool_guestbook = false;
			$db_pagetype = "";
			if($_POST["gbnew"] == "yes") {		//here guestbook will contain "yes" if user selected guestbook
				$bool_guestbook = true;
				$var_gbnew = $_POST["gbnew"];
				$db_pagetype = "guestbook";
			}		
			else {
				$db_pagetype = ($var_pagetype == 1)?"homepage":"subpage";
			}
		
			if(isValidGuestbookEntry($var_gbnew,$var_type,$_SESSION['session_currenttempsiteid'])) {
				if(validateSizePerUser($userid,$size_per_user,$allowed_space,"../")) {
					$var_guestbook=$var_gbnew;
					if(!isValidRequest($tmpsiteid,$templateid,$userid,$var_type)) {
							echo("<script>alert('Invalid request! Please try again.'); location.href='../usermain.php';</script>");
							exit();
					}
		
					if($var_type == "new") {  //this page is called for a new site not yet published
							$sql_check = "Select * from tbl_tempsite_pages where ntempsite_id='" . $_SESSION['session_currenttempsiteid'] . "' AND vpage_name='" . addslashes($var_editpage) . "'";	
							$sql_insert = "Insert into tbl_tempsite_pages(ntempsp_id,ntempsite_id,vpage_name,vpage_title,vpage_type,vtype) 
										Values('','" . $_SESSION['session_currenttempsiteid']  . "',
										'" . addslashes($var_editpage) . "','','" . $db_pagetype . "','advanced')";
					}
					else {
							$bool_type = true;
							$sql_check = "Select * from tbl_site_pages where nsite_id='" . $_SESSION['session_currenttempsiteid'] . "' AND vpage_name='" . addslashes($var_editpage) . "'";	
							$sql_insert = "Insert into tbl_site_pages(nsp_id,nsite_id,vpage_name,vpage_title,vpage_type,vtype) 
										Values('','" . $_SESSION['session_currenttempsiteid']  . "',
										'" . addslashes($var_editpage) . "','','" . $db_pagetype . "','advanced')";
					}
					$result = mysql_query($sql_check) or die(mysql_error());
					if(mysql_num_rows($result) <= 0) {
						mysql_query($sql_insert) or die(mysql_error());		
					}
					$var_presentpage=$var_editpage;
					
					$var_pageurl=createPage($var_editpage,$templateid,$tmpsiteid,$var_pagetype,$bool_type,false,$bool_guestbook);
				}
				else {
					$script_string .= "alert('Cannot create new page. Your space exceeded permitted limit." . 
										"(Space taken by you: " . human_read($size_per_user) . " " . 
										"Allowed space: " . human_read($allowed_space) . ") \\r\\n" . 
										"Delete unused images or any/all of the sites created by you to proceed further.');";
					$var_presentpage = $_POST["presentpage"];
					$var_pageurl=$_POST["pageurl"];
				}	
			}
			else {
				$script_string .= "alert('Cannot add two guestbooks.');";
				$var_presentpage = $_POST["presentpage"];
				$var_pageurl=$_POST["pageurl"];
			}
		}
		elseif($_POST["actiontype"] == "delete") {
				//USER DELETING A PAGE
				//checked for request validity using isValidRequest()
				//if false then user navigated to usermain.php
				//if type == "new" then
				//	(i)    work location is set as workarea/tempsites/tempsiteid/
				//	(ii)   delete page physically from work location by calling removePage()
				//			saveResource() called to make modifications on work location/resource.txt		
				//	(iii)  delete from tbl_tempsite_pages the currentpage
				//	(iv)   Run a select query on tbl_tempsite_pages for the current tempsiteid
				//	(v)	   get the first row and take the page name as var_presentpage, create var_pageurl, and var_guestbook set accordingly
				//	(vi)   if there is no row present in tbl_tempsite_pages , insert a row for index.htm to tbl_tempsite_pages,
				//			copy the templates/templateid/index.htm to worklocation
				//else
				//	(i)    work location is set as workarea/sites/siteid/
				//	(ii)   delete page physically from work location by calling removePage()
				//			  saveResource() called to make modifications on work location/resource.txt		
				//	       delete page physically from sites/siteid by calling removePage()
				//			saveResource() called to make modifications on sites/siteid/resource.txt		
				//	(iii)  delete from tbl_site_pages the currentpage
				//	(iv)   Run a select query on tbl_site_pages for the current siteid
				//	(v)	   get the first row and take the page name as var_presentpage, create var_pageurl, and var_guestbook set accordingly
				//	(vi)   if there is no row present in tbl_site_pages , insert a row for index.htm to tbl_site_pages,
				//			copy the templates/templateid/index.htm to worklocation, set var_presentpage, create var_pageurl.
				//END IF
				$bool_type = false;
				$var_type=$_POST["type"];
				$var_editpage=$_POST["editpage"];		// here editpage will contain the id of the page you are trying to delete 
				$var_actionin = $_POST["actiontype"];				//assigned to a hidden variable(actionin) 	
				$var_presentpage = $_POST["presentpage"];
				$var_deletedimages=$_POST["deletedimages"];
				$templateid=$_SESSION['session_currenttemplateid'];
				$tmpsiteid=$_SESSION['session_currenttempsiteid'];
				$userid=$_SESSION["session_userid"];

				if(!isValidRequest($tmpsiteid,$templateid,$userid,$var_type)) {
					echo("<script>alert('Invalid request! Please try again.'); location.href='../usermain.php';</script>");
					exit();
				}
				
				if($var_type == "new") {
					$resource_location="../workarea/tempsites/$tmpsiteid/";
					$sql_delete = "Delete from tbl_tempsite_pages where ntempsp_id='" . addslashes($var_editpage) . "'";
					$sql_check = "Select * from tbl_tempsite_pages where ntempsite_id='" . addslashes($tmpsiteid) . "'";
					$sql_insert = "Insert into tbl_tempsite_pages(ntempsp_id,ntempsite_id,vpage_name,vpage_title,vpage_type,vtype) 
								Values('','" . $_SESSION['session_currenttempsiteid']  . "',
								'index.htm','','homepage','advanced')";
					removePage($var_presentpage,$tmpsiteid,false);
				}
				elseif($var_type == "edit") {
					$bool_type = true;
					$sql_delete = "Delete from tbl_site_pages where nsp_id='" . addslashes($var_editpage) . "'";
					$sql_check = "Select * from tbl_site_pages where nsite_id='" . addslashes($tmpsiteid) . "'";
					$sql_insert = "Insert into tbl_site_pages(nsp_id,nsite_id,vpage_name,vpage_title,vpage_type,vtype) 
								Values('','" . $_SESSION['session_currenttempsiteid']  . "',
								'index.htm','','homepage','advanced')";
					$resource_location="../workarea/sites/$tmpsiteid/";
					removePage($var_presentpage,$tmpsiteid,true);
					SaveResource("../sites/$tmpsiteid/resource.txt",$var_deletedimages,"",$userid); 
				}
				
				//This call to SaveResource deletes the images that was there in the page from resource.txt
				SaveResource(($resource_location . "resource.txt"),$var_deletedimages,"",$userid); 

				mysql_query($sql_delete) or die(mysql_error());	
				
				$result=mysql_query($sql_check) or die(mysql_error());	
				if(mysql_num_rows($result) > 0) {
					$row = mysql_fetch_array($result);
					$var_presentpage = $row["vpage_name"];
					$var_guestbook = ($row["vpage_type"] == "guestbook")?"yes":"";
					$var_pageurl= $resource_location . $var_presentpage;
				}
				else {
						mysql_query($sql_insert) or die(mysql_error());		
						$var_presentpage="index.htm";
						$var_pageurl=createPage("index.htm",$templateid,$tmpsiteid,1,$bool_type);
				}
				$script_string .= " alert(\"Page Deleted!\");"; 
				
		}
		else if($_POST["actiontype"] == "saveas") {
			//SAVE AS SECTION
			//if guestbook == "yes" then same page shown saying 'cannot have two copies of guestbook'.
			//Checked for size limit using validateSizePerUser()
			//	if false then message shown saying 'cannot save page in new name....' and same page shown.
			//Checked for request validity using isValidRequest()
			//	if false then user navigated to usermain.php
			//IF type == "new" then
			//	set work location as workarea/tempsites/tempsiteid/
			//	check if newpageName exists in tbl_tempsite_pages
			//	if no then insert a row to tbl_tempsite_pages
			//	call saveFile() with the current page as the source and editpage as the destination in work location 
			//	call saveResource() to modify resource.txt file accordingly
			//	set the presentpage as the newPageName and build pageUrl.
			//ELSE
			//	set work location as workarea/sites/siteid/
			//	check if newpageName exists in tbl_site_pages
			//	if no then insert a row to tbl_site_pages
			//	call saveFile() with the current page as the source and editpage as the destination in work location 
			//	call saveResource() to modify resource.txt file accordingly
			//	call saveFile() with the current page as source and sites/siteid/newPageName as destination
			//	call saveResource() to modify sites/siteid/resource.txt file accordingly
			//	set the presentpage as the newPageName and build pageUrl.	
			//END IF		
			$bool_type = false;
			$var_actionin = $_POST["actiontype"];	
			$var_presentpage = $_POST["presentpage"];
			$var_pageurl=$_POST["pageurl"];
			$var_type = $_POST["type"];
			$var_deletedimages=$_POST["deletedimages"];
			$var_newimages=$_POST["newimages"];

			$tmpsiteid=$_SESSION['session_currenttempsiteid']; // reconsider this statement since the session will be different in case of sites
			$userid=$_SESSION["session_userid"];
			
			//these 3 parameters will be passed only if "actiontype" = "saveandcreate" 
			$templateid=$_SESSION['session_currenttemplateid'];
			//$var_pagetype=($_POST["pagetype"] == "index")?1:2;
			$var_editpage = $_POST["editpage"];
			if($_POST["guestbook"] == "yes") {
				$var_guestbook = $_POST["guestbook"];
				$script_string .= " alert(\"Cannot have two copies of the guestbook.!\");";
			}
			elseif(!validateSizePerUser($userid,$size_per_user,$allowed_space,"../")) {
				$script_string .= "alert('Cannot save page in new name. Your space exceeded permitted limit." . 
										"(Space taken by you: " . human_read($size_per_user) . " " . 
										"Allowed space: " . human_read($allowed_space) . ") \\r\\n" . 
										"Delete unused images or any/all of the sites created by you to proceed further.');";
			}
			else {	 
				if(!isValidRequest($tmpsiteid,$templateid,$userid,$var_type)) {
						echo("<script>alert('Invalid request! Please try again.'); location.href='../usermain.php';</script>");
						exit();
				}	 
				if($var_type == "new") {
					$search_string=$temperory_location . "/$tmpsiteid";
					$fileToSave = "../workarea/tempsites/$tmpsiteid/$var_editpage";
					$resource_location="../workarea/tempsites/$tmpsiteid/resource.txt";
	/*				$sql_check = "Select * from tbl_tempsite_pages where ntempsite_id='" . $_SESSION['session_currenttempsiteid'] . "' AND vpage_name='" . addslashes($var_editpage) . "'";
					$sql_insert = "Insert into tbl_tempsite_pages(ntempsp_id,ntempsite_id,vpage_name,vpage_title,vpage_type,vtype) 
									Values('','" . $_SESSION['session_currenttempsiteid']  . "',
									'" . addslashes($var_editpage) . "','','htm','advanced')";*/
					$sql_check = "Select * from tbl_tempsite_pages where ntempsite_id='" . $_SESSION['session_currenttempsiteid'] . "' AND vpage_name='";
					$sql_insert = "Insert into tbl_tempsite_pages(ntempsp_id,ntempsite_id,vpage_name,vpage_title,vpage_type,vtype) 
									Values('','" . $_SESSION['session_currenttempsiteid']  . "',
									'" . addslashes($var_editpage) . "','','";
					
				}
				elseif($var_type == "edit") {
				
					$bool_type = true;
					$search_string=$real_location . "/$tmpsiteid";
					$fileToSave = "../workarea/sites/$tmpsiteid/$var_editpage";
					$resource_location="../workarea/sites/$tmpsiteid/resource.txt";
	/*				$sql_check = "Select * from tbl_site_pages where nsite_id='" . $_SESSION['session_currenttempsiteid'] . "' AND vpage_name='" . addslashes($var_editpage) . "'";
					$sql_insert = "Insert into tbl_site_pages(nsp_id,nsite_id,vpage_name,vpage_title,vpage_type,vtype) 
									Values('','" . $_SESSION['session_currenttempsiteid']  . "',
									'" . addslashes($var_editpage) . "','','htm','advanced')";*/
					//save to original site location
					$sql_check = "Select * from tbl_site_pages where nsite_id='" . $_SESSION['session_currenttempsiteid'] . "' AND vpage_name='";
					$sql_insert = "Insert into tbl_site_pages(nsp_id,nsite_id,vpage_name,vpage_title,vpage_type,vtype) 
									Values('','" . $_SESSION['session_currenttempsiteid']  . "',
									'" . addslashes($var_editpage) . "','','";
	
					SaveFile("../sites/$tmpsiteid/$var_editpage",$search_string);
					SaveResource("../sites/$tmpsiteid/resource.txt",$var_deletedimages,$var_newimages,$userid);
				}
				SaveFile($fileToSave,$search_string);
				SaveResource($resource_location,$var_deletedimages,$var_newimages,$userid);
				
				$temp_ins_string="";
				$result = mysql_query($sql_check . addslashes($var_presentpage) . "'") or die(mysql_error() . 'one');
				if(mysql_num_rows($result) > 0) {
					$row = mysql_fetch_array($result);
					$temp_ins_string=$row["vpage_type"];
				}
				$result = mysql_query($sql_check . addslashes($var_editpage) . "'") or die(mysql_error() . 'two');
				if(mysql_num_rows($result) <= 0) {
					mysql_query($sql_insert . $temp_ins_string . "','advanced')") or die(mysql_error() . 'three');
				}
				$var_pageurl=$fileToSave;
				$var_presentpage=$var_editpage;
			}
		}
		$script_string .= "</script>";
	
//$show_body_on_load=true;
?>
<SCRIPT language=JavaScript src="js/formatbar.js"></script>
<script>
	try{
	document.body.onload=loading();
	}catch(e){}
</script>
<LINK href="style/editor.css" type=text/css rel=stylesheet>
<?php
	include "./userheader.php";
	echo($script_string);
?>
<table width="100%" cellpadding="0" cellspacing="0" class=background>
	<tr>
	  <td width="100%" align="center">
	  <table width="80%" cellpadding="0" cellspacing="0">
	  	<tr>
			<td width="100%" align="center" valign="top">
			<?php
			if($var_type == "new") {
				$sql = "Select ntempsp_id as 'nsp_id',vpage_name from tbl_tempsite_pages where 
				 ntempsite_id='" . $_SESSION['session_currenttempsiteid'] . "'";
				echo("<img src=\"../images/cstep7.gif\">");	
			}
			else {
			$sql = "Select nsp_id,vpage_name from tbl_site_pages where nsite_id='" . $_SESSION['session_currenttempsiteid'] . "'";
			}
			?>
	  <fieldset><legend class="maintext"><b>Current Page : </b><?php echo($var_presentpage); ?></legend>
	   <font class="maintext"> <br> 
	   Page List</font>
        <select name="cmbPages" onChange="javascript:editPage();" class="selectbox" style="width:200px; ">
          <?php
			
			$result = mysql_query($sql) or die(mysql_error());
			if(mysql_num_rows($result) > 0)	{
				while($row= mysql_fetch_array($result)) {
					echo("<OPTION VALUE=\"" . $row["nsp_id"] . "\"" . (($var_presentpage == $row["vpage_name"])?"Selected":"") . " >" . $row["vpage_name"] . "</OPTION>");
				}
			} 
			mysql_free_result($result);
		?>
        </select>
        &nbsp;
        <input type="button" name="EditButton"  value="View"  onClick="javascript:editPage();" style="display:none; ">
         &nbsp;&nbsp;&nbsp;&nbsp; 
      <input type="button" name="SavePage"  value="Save"  onClick="javascript:savePage(1);" style="width:70px; " class="editorbutton">
      <input type="button" name="RemovePage"  value="Delete"  onClick="javascript:removePage();" style="width:70px; "  class="editorbutton">
      <input type="button" name="AddPage"  value="Add Page" style="width:70px; "  onClick="javascript:addPage();"  class="editorbutton">
      <input name="Preview" type="button" id="Preview" value="Preview" style="width:70px; " onClick="javascript:previewSite(<?php echo("'" . (($var_type == "new")?"tempsites":"sites") . "','" . $_SESSION['session_currenttempsiteid'] . "','" . $var_presentpage . "'"); ?>);"  class="editorbutton">
	  <input name="Publish" type="button" id="Publish" value="Publish" onClick="javascript:publishSite();" class="editorbutton" style="width:70px; ">
		<br>&nbsp;
	  </fieldset>
		
		
		
		
		<form name="PageDetails" method="post" action="editor.php">
			<input type="hidden" name="checkid" id="checkid" value="<?php echo($_SESSION["session_checkid"]); ?>">
			<input type="hidden" name="actiontype" id="actiontype" value="">
			<input type="hidden" name="presentpage" id="presentpage" value="<?php echo($var_presentpage); ?>"> 
			<input type="hidden" name="editpage" id="editpage" value="">
			<input type="hidden" name="guestbook" id="guestbook" value="<?php echo($var_guestbook); ?>">
			<input type="hidden" name="gbnew" id="gbnew" value="">
			<input type="hidden" name="basiclocation" id="basiclocation" value="<?php echo($basicLocation); ?>">
			<input type="hidden" name="pagetype" id="pagetype" value="">
			<input type="hidden" name="pageurl" id="pageurl" value="<?php echo($var_pageurl); ?>">
			<input type="hidden" name="actionIn" id="actionIn" value="<?php echo($var_actionin); ?>">
			<input type="hidden" name="type" id="type" value="<?php echo($var_type); ?>">
			<INPUT type=hidden name="EditorHTM" id="EditorHTM" value=""> 
			<INPUT type=hidden name="EditorHTM2"  value="">
			 <INPUT type=hidden name="EditorHTM3"  value=""> 
			 <INPUT type=hidden name="EditorHTM4"  value=""> 
			 <INPUT type=hidden name="EditorHTM5"  value="">
			 <input type="hidden" name="deletedimages" id="deletedimages" value="">
			 <input type="hidden" name="newimages" id="newimages" value="">
		</form>
		<form name="publishPage" method="post" action="">
		<input type="hidden" name="pubpage" id="pubpage" value="">
		</form>

			</td>
		</tr>
	  </table>
		</td>
    </tr>
</table>

<DIV class=MainBody style="WIDTH: 100%; HEIGHT: 100%">
<!-- Insert top menu  -->
<SCRIPT language=JavaScript src="js/makemenu.js"></SCRIPT>
<SCRIPT language=JavaScript src="js/menu.js"></script>
<!-- Insert format bar  -->
 <TABLE cellSpacing=0 cellPadding=0 width="100%" border=0>
  <TBODY>
  <TR>
  <TD class=body height=22>
      <TABLE class=toolbar id=toolbar_full cellSpacing=0 cellPadding=0
      width="100%" align=left border=0>
      <TBODY>
      <TR>
      <TD class=body height=22>
       <?php
	   //Include the shortcut menu
	    include("includes/formatbar.inc");
       ?>
        </TD></TR>
        </TBODY>
        </TABLE>
   </TD></TR>
</TBODY></TABLE>
<DIV id=charMenu style="DISPLAY: none">
<TABLE 
style="BORDER-RIGHT: buttonshadow 2px solid; BORDER-TOP: buttonhighlight 1px solid; FONT-WEIGHT: bold; FONT-SIZE: 14px; BORDER-LEFT: buttonhighlight 1px solid; CURSOR: hand; BORDER-BOTTOM: buttonshadow 1px solid; FONT-FAMILY: Verdana" 
borderColor=#666666 cellSpacing=5 cellPadding=1 bgColor=buttonface border=1>
  <TBODY>
  <TR>
    <TD onclick=parent.insertChar(this) width=15>&#161;</TD>
    <TD onclick=parent.insertChar(this) width=15>&#191;</TD>
    <TD onclick=parent.insertChar(this) width=15>&#162;</TD>
    <TD onclick=parent.insertChar(this) width=15>&#163;</TD>
    <TD onclick=parent.insertChar(this) width=15>&#165;</TD></TR>
  <TR>
    <TD onclick=parent.insertChar(this) width=15>&#164;</TD>
    <TD onclick=parent.insertChar(this) width=15>&#167;</TD>
    <TD onclick=parent.insertChar(this) width=15>&#171;</TD>
    <TD onclick=parent.insertChar(this) width=15>&#187;</TD>
    <TD onclick=parent.insertChar(this) width=15>&#177;</TD></TR>
  <TR>
    <TD onclick=parent.insertChar(this) width=15>&#169;</TD>
    <TD onclick=parent.insertChar(this) width=15>&#174;</TD>
    <TD onclick=parent.insertChar(this) width=15>&#8482;</TD>
    <TD onclick=parent.insertChar(this) width=15>&#172;</TD>
    <TD onclick=parent.insertChar(this) width=15>&#175;</TD></TR>
  <TR>
    <TD onclick=parent.insertChar(this) width=15>&#176;</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>&#183;</TD>
    <TD onclick=parent.insertChar(this) width=15>&#8224;</TD>
    <TD onclick=parent.insertChar(this) width=15>&#8225;</TD></TR>
  <TR>
    <TD onclick=parent.insertChar(this) width=15>&#188;</TD>
    <TD onclick=parent.insertChar(this) width=15>&#189;</TD>
    <TD onclick=parent.insertChar(this) width=15>&#190;</TD></TR></TBODY></TABLE>
</DIV>
<SELECT id=sPageSwitch style="DISPLAY: none" unselectable="on"
            onchange=sGoTo(this.options[this.selectedIndex].value); ></SELECT>
<IFRAME id=foo contentEditable=true
style="BORDER-RIGHT: #000000 0px solid; PADDING-RIGHT: 0px; BORDER-TOP: #000000 0px solid; PADDING-LEFT: 0px; PADDING-BOTTOM: 0px; OVERFLOW: auto; BORDER-LEFT: #000000 0px solid; WIDTH: 100%; PADDING-TOP: 0px; BORDER-BOTTOM: #000000 0px solid; SCROLLBAR-BASE-COLOR: #dddddd; ; HEIGHT: expression(setHeight()); BACKGROUND-COLOR: white"
src="javascript:false;" onload="fooLoad();" onfocus="fooFocus();"></IFRAME>
</DIV>
<?php
include "./userfooter.php";
?>
<script>
function fooFocus() {
}	
 

</script>