<?php 
ini_set("display_errors","1");
ini_set("display_startup_errors","1");
set_magic_quotes_runtime(0);

include("include/dbcommon.php");
include("include/##@TABLE.strShortTableName##_variables.php");




##if @BUILDER.bCreateLoginPage##
//	check if logged in
if(!@$_SESSION["UserID"] || !CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Search"))
{ 
	$_SESSION["MyURL"]=$_SERVER["SCRIPT_NAME"]."?".$_SERVER["QUERY_STRING"];
	header("Location: login.php?message=expired"); 
	return;
}
##endif##

include('include/xtempl.php');
$xt = new Xtempl();

$filename="";	
$message="";
$key=array();
$next=array();
$prev=array();
$all=postvalue("all");
$pdf=postvalue("pdf");
$mypage=1;

$id=1;


//	Before Process event
if(function_exists("BeforeProcessView"))
	BeforeProcessView($conn);

$strWhereClause="";
if(!$all)
{
	$keys=array();
##foreach @TABLE.arrKeyFields as @k##
	$keys["##@k s##"]=postvalue("editid##@index##");
##endfor##

//	get current values and show edit controls

	$strWhereClause = KeyWhere($keys);

##if @TABLE.nSecOptions!=ADVSECURITY_ALL && @BUILDER.nLoginMethod==SECURITY_TABLE && @BUILDER.bCreateLoginPage##
//	select only owned records
	$strWhereClause=whereAdd($strWhereClause,SecuritySQL("Search"));
##endif##

	$strSQL=gSQLWhere($strWhereClause);
}
else
{
	if ($_SESSION[$strTableName."_SelectedSQL"]!="" && @$_REQUEST["records"]=="") 
	{
		$strSQL = $_SESSION[$strTableName."_SelectedSQL"];
		$strWhereClause=@$_SESSION[$strTableName."_SelectedWhere"];
	}
	else
	{
		$strWhereClause=@$_SESSION[$strTableName."_where"];
##if @TABLE.nSecOptions==ADVSECURITY_VIEW_OWN  && @BUILDER.nLoginMethod==SECURITY_TABLE && @BUILDER.bCreateLoginPage##
		if($strWhereClause=="")
			$strWhereClause = whereAdd($strWhereClause,SecuritySQL("Search"));
##endif##
		$strSQL=gSQLWhere($strWhereClause);
	}
	$strOrderBy=$_SESSION[$strTableName."_order"];
	if(!$strOrderBy)
		$strOrderBy=$gstrOrderBy;
	$strSQL.=" ".trim($strOrderBy);
//	order by
	$strOrderBy=$_SESSION[$strTableName."_order"];
	if(!$strOrderBy)
		$strOrderBy=$gstrOrderBy;
	$strSQL.=" ".trim($strOrderBy);
		$numrows=gSQLRowCount($strWhereClause,##@TABLE.bGroupBy##);
}

$strSQLbak = $strSQL;
if(function_exists("BeforeQueryView"))
	BeforeQueryView($strSQL,$strWhereClause);
if($strSQLbak == $strSQL)
	$strSQL=gSQLWhere($strWhereClause);

if(!$all)
{
	LogInfo($strSQL);
	$rs=db_query($strSQL,$conn);
}
else
{
//	 Pagination:

	$nPageSize=0;
	if(@$_REQUEST["records"]=="page" && $numrows)
	{
		$mypage=(integer)@$_SESSION[$strTableName."_pagenumber"];
		$nPageSize=(integer)@$_SESSION[$strTableName."_pagesize"];
		if($numrows<=($mypage-1)*$nPageSize)
			$mypage=ceil($numrows/$nPageSize);
		if(!$nPageSize)
			$nPageSize=$gPageSize;
		if(!$mypage)
			$mypage=1;

##if @BUILDER.nDatabaseType==nDATABASE_MySQL##
		$strSQL.=" limit ".(($mypage-1)*$nPageSize).",".$nPageSize;
##elseif @BUILDER.nDatabaseType==nDATABASE_MSSQLServer##
		$strSQL = AddTop($strSQL, $mypage*$nPageSize);
##elseif @BUILDER.nDatabaseType==nDATABASE_Access##
		$strSQL = AddTop($strSQL, $mypage*$nPageSize);
##elseif @BUILDER.nDatabaseType==nDATABASE_Oracle##
		$strSQL = AddRowNumber($strSQL, $mypage*$nPageSize);
##elseif @BUILDER.nDatabaseType==nDATABASE_PostgreSQL##
		$maxrecs=$nPageSize;
		$strSQL.=" limit ".$nPageSize." offset ".(($mypage-1)*$nPageSize);
##endif##
	}
##if @BUILDER.nDatabaseType==nDATABASE_MySQL##
	$rs=db_query($strSQL,$conn);
##elseif @BUILDER.nDatabaseType==nDATABASE_MSSQLServer##
	$rs=db_query($strSQL,$conn);
	db_pageseek($rs,$nPageSize,$mypage);
##elseif @BUILDER.nDatabaseType==nDATABASE_Access##
	$rs=db_query_direct($strSQL,$conn,$numrows);
	db_pageseek($rs,$nPageSize,$mypage);
##elseif @BUILDER.nDatabaseType==nDATABASE_Oracle##
	$rs=db_query_direct($strSQL,$conn,$numrows);
	db_pageseek($rs,$nPageSize,$mypage);
##elseif @BUILDER.nDatabaseType==nDATABASE_PostgreSQL##
	$rs=db_query($strSQL,$conn);
##else##
	$rs=db_query($strSQL,$conn);
##endif##
}

$data=db_fetch_array($rs);

$out="";
$first=true;

$templatefile="";

while($data)
{



##foreach @TABLE.arrKeyFields as @k##
	##if Field(@k).strViewFormat==FORMAT_HTML || Field(@k).strViewFormat==FORMAT_FILE_IMAGE || Field(@k).strViewFormat==FORMAT_FILE || Field(@k).strViewFormat==FORMAT_HYPERLINK || Field(@k).strViewFormat==FORMAT_EMAILHYPERLINK || Field(@k).strViewFormat==FORMAT_CHECKBOX##
$xt->assign("show_key##@index##", htmlspecialchars($data["##@k s##"]));
	##else##
$xt->assign("show_key##@index##", htmlspecialchars(GetData($data,"##@k s##", "##Field(@k).strViewFormat##")));
	##endif##
##endfor##

$keylink="";
##foreach @TABLE.arrKeyFields as @k##
$keylink.="&key##@index##=".htmlspecialchars(rawurlencode(@$data["##@k s##"]));
##endfor##

##foreach Fields as @f filter @f.bViewPage order @f.nViewPageOrder##
////////////////////////////////////////////
//	##@f.strName## - ##@f.strViewFormat##
	$value="";
	##if @f.strViewFormat==FORMAT_DATABASE_IMAGE##
		##if @f.bShowThumbnail && !@f.bOriginalView##
		$value.="<a";
		##if @f.bUseiBox##
			$value .= " rel='ibox'";
		##else##
			$value .= " target=_blank";
		##endif##
		$value.=" href=\"##@TABLE.strShortTableName s##_imager.php?field=##@f.strName uhs##".$keylink."\">";
		$value.= "<img border=0";
		$value.=" src=\"##@TABLE.strShortTableName s##_imager.php?field=##@f.strThumbnail uhs##&alt=##@f.strName uhs##".$keylink."\">";
		$value.= "</a>";
		##else##
		$value = "<img";
		##if @f.ListFormatObj.nImageWidth && !@f.bOriginalView##
		$value.=" width=##@f.ListFormatObj.nImageWidth##";
		##endif##
		##if @f.ListFormatObj.nImageHeight && !@f.bOriginalView##
		$value.=" height=##@f.ListFormatObj.nImageHeight##";
		##endif##
		$value.=" border=0";
		$value.=" src=\"##@TABLE.strShortTableName s##_imager.php?field=##@f.strName uhs##".$keylink."\">";
	##endif##
	##elseif @f.strViewFormat==FORMAT_FILE_IMAGE##
	if(CheckImageExtension($data["##@f.strName s##"])) 
	{
	##if @f.bShowThumbnail && !@f.bOriginalView##
			 	// show thumbnail
		$thumbname="##@f.strThumbnail s##".$data["##@f.strName s##"];
		if(substr("##@f.strhlPrefix s##",0,7)!="http://" && !myfile_exists(GetUploadFolder("##@f.strName s##").$thumbname))
			$thumbname=$data["##@f.strName s##"];
		$value="<a";
		##if @f.bUseiBox##
			$value .= " rel='ibox'";
		##else##
			$value .= " target=_blank";
		##endif##
		$value.=" href=\"".htmlspecialchars(AddLinkPrefix("##@f.strName s##",$data["##@f.strName s##"]))."\">";
		$value.="<img";
		if($thumbname==$data["##@f.strName s##"])
		{
			##if @f.ListFormatObj.nImageWidth##
			$value.=" width=##@f.ListFormatObj.nImageWidth##";
			##endif##
			##if @f.ListFormatObj.nImageHeight##
			$value.=" height=##@f.ListFormatObj.nImageHeight##";
			##endif##
		}
		$value.=" border=0";
		$value.=" src=\"".htmlspecialchars(AddLinkPrefix("##@f.strName s##",$thumbname))."\"></a>";
	##else##
		$value="<img";
		##if @f.ListFormatObj.nImageWidth && !@f.bOriginalView##
		$value.=" width=##@f.ListFormatObj.nImageWidth##";
		##endif##
		##if @f.ListFormatObj.nImageHeight && !@f.bOriginalView##
		$value.=" height=##@f.ListFormatObj.nImageHeight##";
		##endif##
		$value.=" border=0";
		$value.=" src=\"".htmlspecialchars(AddLinkPrefix("##@f.strName s##",$data["##@f.strName s##"]))."\">";
	##endif##
	}
	##elseif @f.strViewFormat==FORMAT_DATABASE_FILE##
		##if @f.ListFormatObj.strFilename##
	$filename=$data["##@f.ListFormatObj.strFilename s##"];
	if(!$filename)
		$filename="file.bin";
		##else##
	$filename="file.bin";
		##endif##
	if(strlen($data["##@f.strName s##"]))
	{
		$value="<a href=\"##@TABLE.strShortTableName##_getfile.php?filename=".rawurlencode($filename)."&field=##@f.strName uhs##".$keylink."\">";
		$value.=htmlspecialchars($filename);
		$value.="</a>";
	}
	##elseif (@f.strEditFormat==EDIT_FORMAT_LOOKUP_WIZARD || @f.strEditFormat==EDIT_FORMAT_RADIO) && pLookupObj.nLookupType == LT_LOOKUPTABLE##
	$value=DisplayLookupWizard("##@f.strName s##",$data["##@f.strName s##"],$data,$keylink,MODE_VIEW);
			
	##elseif NeedEncode(@f)##
	$value = ProcessLargeText(GetData($data,"##@f.strName s##", "##@f.strViewFormat##"),"","",MODE_VIEW);
	##else##
	$value = GetData($data,"##@f.strName s##", "##@f.strViewFormat##");
	##endif##
	$xt->assign("##@f.strName g##_value",$value);
	$xt->assign("##@f.strName g##_fieldblock",true);
##endfor##

$body=array();
$body["begin"]="";
##if Fields[bViewPage && bUseiBox && bShowThumbnail].len##
if(!$pdf)
{
	$body["begin"].="<script type='text/javascript' src='include/ibox.js'></script>
	<link rel='stylesheet' href='include/ibox.css' type='text/css' media='screen'/>";
}
##endif##
##if @BUILDER.bViewPDF##
if(!$pdf)
{
	$body["begin"].="<script type=\"text/javascript\" src=\"include/jquery.js\"></script>";
	$body["begin"].="<script>".
	"\nvar TEXT_PDF_BUILD1='".jsreplace(##message PDF_BUILD1##)."';".
	"\nvar TEXT_PDF_BUILD2='".jsreplace(##message PDF_BUILD2##)."';".
	"</script>";
}

$pagename = $_SERVER["REQUEST_URI"];
if(!$pagename)
{
	$pagename=basename(__file__);
	$params="";
	foreach($_GET as $k=>$v)
	{
		if(strlen($params))
			$params.="&";
		$params.=rawurlencode($k)."=".rawurlencode($v);
	}
	if(strlen($params))
		$pagename.="?".$params;
}
if(strpos($pagename,"?")===false)
	$pagename.="?pdf=1";
else
	$pagename.="&pdf=1";

if(!$pdf)
$body["end"]="<script type=\"text/javascript\" src=\"include/pdf.js\"></script>".
"<script>".
"var page = \"".$pagename."\";".
"</script>".
"<iframe name=\"pdf\" class=pdf style=\"position:absolute;left:-1000px;\">".
"</iframe>";

if(!$pdf)
{
	$xt->assign_section("pdf_block","<div id=progress>","</div>");
	if(!$all)
		$xt->assign("pdflink_block",true);
	$xt->assign("pdfview_attrs","onclick=\"RunPDF(); return false; this.style.display='none';\"");
}
##endif##

$xt->assignbyref("body",$body);
$xt->assign("style_block",true);
$xt->assign("stylefiles_block",true);

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Next Prev button
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////    
##if @TABLE.moveNext##
if(!@$_SESSION[$strTableName."_noNextPrev"])
{
	$where_next=$where_prev="";
	$order_next=$order_prev="";
	$arrFieldForSort=array();
	$arrHowFieldSort=array();
	$where=$_SESSION[$strTableName."_where"];
	##foreach @TABLE.arrKeyFields as @k##
		if(GetFieldIndex("##@k s##"))
			$key[]=GetFieldIndex("##@k s##");
	##endfor##
//if session mass sorting empty, then create it as a sheet
	if(@$_SESSION[$strTableName."_arrFieldForSort"] && @$_SESSION[$strTableName."_arrHowFieldSort"])
	{
		$arrFieldForSort=$_SESSION[$strTableName."_arrFieldForSort"];
		$arrHowFieldSort=$_SESSION[$strTableName."_arrHowFieldSort"];
		$lenArr=count($arrFieldForSort);
	}
	else
	{
		if(count($g_orderindexes))
		{
			for($i=0;$i<count($g_orderindexes);$i++)
			{
				$arrFieldForSort[]=$g_orderindexes[$i][0];
				$arrHowFieldSort[]=$g_orderindexes[$i][1];
			}
		}
		elseif($gstrOrderBy!='')
			$_SESSION[$strTableName."_noNextPrev"] = 1;
		if(count($key))
		{
			for($i=0;$i<count($key);$i++)
			{
				$idsearch=array_search($key[$i],$arrFieldForSort);
				if($idsearch===false)
				{
					$arrFieldForSort[]=$key[$i];
					$arrHowFieldSort[]="ASC";
				}
			}
		}
		$_SESSION[$strTableName."_arrFieldForSort"]=$arrFieldForSort;
		$_SESSION[$strTableName."_arrHowFieldSort"]=$arrHowFieldSort;
		$lenArr=count($arrFieldForSort);
	}
//if session order by empty, then create a line order		
	if(@$_SESSION[$strTableName."_order"]) 
		$order_next=$_SESSION[$strTableName."_order"];
	elseif($lenArr>0)
	{
		for($i=0;$i<$lenArr;$i++)
			$order_next .=(GetFieldByIndex($arrFieldForSort[$i]) ? ($order_next!="" ? ", " : " ORDER BY ").$arrFieldForSort[$i]." ".$arrHowFieldSort[$i] : "");
	}
//create a line where and order for the two queries
	if($lenArr>0 and count($key) and !$_SESSION[$strTableName."_noNextPrev"])
	{
		if($where)
			$where .=" and ";
		$scob="";
		$flag=0;
		for($i=0;$i<$lenArr;$i++)
		{
			$fieldName=GetFieldByIndex($arrFieldForSort[$i]);
			if($fieldName)
			{
				$order_prev .=($order_prev!="" ? ", " : " ORDER BY ").$arrFieldForSort[$i].($arrHowFieldSort[$i]=="ASC" ? " DESC" : " ASC");
				$dbg=GetFullFieldName($fieldName);
				if(!is_null($data[$fieldName]))
				{
					$mdv=make_db_value($fieldName,$data[$fieldName]);
					$ga=($arrHowFieldSort[$i]=="ASC" ? ">" : "<");
					$gd=($arrHowFieldSort[$i]=="ASC" ? "<" : ">");
					$gasc=$dbg.$ga.$mdv;
					$gdesc=$dbg.$gd.$mdv;
					$gravn=($i!=$lenArr-1 ? $dbg."=".$mdv : "");
					$ganull=($ga=="<" ? " or ".$dbg." IS NULL" : "");
					$gdnull=($gd=="<" ? " or ".$dbg." IS NULL" : "");
				}
				else{
						$gasc=($arrHowFieldSort[$i]=="ASC" ? $dbg." IS NOT NULL" : "");
						$gdesc=($arrHowFieldSort[$i]=="ASC" ? "" : $dbg." IS NOT NULL");
						$gravn=($i!=$lenArr-1 ? $dbg." IS NULL" : "");
						$ganull=$gdnull="";
					}
				$where_next .=($where_next!="" ? " and (" : " (").($gasc=="" && $gravn=="" ? " 1=0 " : ($gasc!="" ? $gasc.$ganull : "").($gasc!="" && $gravn!="" ? " or " : "").$gravn." ");
				$where_prev .=($where_prev!="" ? " and (" : " (").($gdesc=="" && $gravn=="" ? " 1=0 " : ($gdesc!="" ? $gdesc.$gdnull : "").($gdesc!="" && $gravn!="" ? " or " : "").$gravn." ");
				$scob .=")";
			}
			else $flag=1;
		}
		$where_next =$where_next.$scob;
		$where_prev =$where_prev.$scob;
		$where_next=whereAdd($where_next,SecuritySQL("Search"));
		$where_prev=whereAdd($where_prev,SecuritySQL("Search"));
		if($flag==1)
		{
			$order_next="";
			for($i=0;$i<$lenArr;$i++)
				$order_next .=(GetFieldByIndex($arrFieldForSort[$i]) ? ($order_next!="" ? ", " : " ORDER BY ").$arrFieldForSort[$i]." ".$arrHowFieldSort[$i] : "");
		}
/*		
		$select_list="";
		foreach($keys as $k=>$v)
		{
			if(strlen($select_list))
				$select_list.=",";
			$select_list.=GetFullFieldName($k);
		}
		$select_list = "SELECT ".$select_list." ";
*/
		$sql_next=gSQLWhere($where.$where_next).$order_next;
		$sql_prev=gSQLWhere($where.$where_prev).$order_prev;
//		$sql_next = gSQLWhere_int($select_list,$gsqlFrom,$gsqlWhereExpr,$gsqlTail,$where.$where_next).$order_next;
//		$sql_prev = gSQLWhere_int($select_list,$gsqlFrom,$gsqlWhereExpr,$gsqlTail,$where.$where_prev).$order_prev;
		if($where_next!="" and $order_next!="" and $where_prev!="" and $order_prev!="")
		{
		##if @BUILDER.nDatabaseType==nDATABASE_MySQL || @BUILDER.nDatabaseType==nDATABASE_PostgreSQL##
			$sql_next.=" limit 1";
			$sql_prev.=" limit 1";
		##elseif @BUILDER.nDatabaseType==nDATABASE_MSSQLServer || @BUILDER.nDatabaseType==nDATABASE_Access##
			$sql_next=AddTop($sql_next, 1);
			$sql_prev=AddTop($sql_prev, 1);
		##elseif @BUILDER.nDatabaseType==nDATABASE_Oracle##
			$sql_next=AddRowNumber($sql_next, 1);
			$sql_prev=AddRowNumber($sql_prev, 1);
		##endif##	
		
			$res_next=db_query($sql_next,$conn);		
			if($row_next=db_fetch_array($res_next))
			{
		##foreach @TABLE.arrKeyFields as @k##
				$next[##@index##]=$row_next["##@k s##"];
		##endfor##
			}
			
			$res_prev=db_query($sql_prev,$conn);	
			if($row_prev=db_fetch_array($res_prev))
			{
		##foreach @TABLE.arrKeyFields as @k##
				$prev[##@index##]=$row_prev["##@k s##"];
		##endfor##
			}
		}	
	}
}	
##endif##
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	  
if(!$pdf && !$all)
{
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
##if @TABLE.moveNext##
    $nextlink=$prevlink="";
	if(count($next))
    {
		$xt->assign("next_button",true);
	 ##foreach @TABLE.arrKeyFields as @k##
	 ##if !@first##
		$nextlink .="&";
	 ##endif##
		$nextlink .="editid##@index##=".htmlspecialchars(rawurlencode($next[##@index##]));
	 ##endfor##
		$xt->assign("nextbutton_attrs","onclick=\"window.location.href='##@TABLE.strShortTableName##_view.##@ext##?".$nextlink."'\"");
	}
	else 
		$xt->assign("next_button",false);	
	if(count($prev))
	{
		$xt->assign("prev_button",true);
	##foreach @TABLE.arrKeyFields as @k##
	##if !@first##
		$prevlink .="&";
	##endif##
		$prevlink .="editid##@index##=".htmlspecialchars(rawurlencode($prev[##@index##]));
	 ##endfor##
		$xt->assign("prevbutton_attrs","onclick=\"window.location.href='##@TABLE.strShortTableName##_view.##@ext##?".$prevlink."'\"");
	}
    else 
		$xt->assign("prev_button",false);
##endif##
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	$xt->assign("back_button",true);
	$xt->assign("backbutton_attrs","onclick=\"window.location.href='##@TABLE.strShortTableName##_list.##@ext##?a=return'\"");
}

$oldtemplatefile=$templatefile;
$templatefile = "##@TABLE.strShortTableName##_view.htm";
if(!$all)
{
	if(function_exists("BeforeShowView"))
		BeforeShowView($xt,$templatefile,$data);
	if(!$pdf)
		$xt->display($templatefile);
##if @BUILDER.bViewPDF##
	if($pdf)
	{
		$xt->load_template($templatefile);
		$page = $xt->fetch_loaded();
		$pagewidth = postvalue("width")*1.05;
		$landscape=false;
		include("plugins/page2pdf.php");
	}
##endif##
	break;
}
##if @BUILDER.bViewPDF##
if($all)
{
	$head="<span name=page>";
	if(function_exists("BeforeShowView"))
		BeforeShowView($xt,$templatefile,$data);
	if($oldtemplatefile!=$templatefile)
		$xt->load_template($templatefile);

	$xt->assign("id",$id);
	$page="";
	if($id==1)
	{
		$head = $head;
		$head = "<html><head>".$xt->fetch_loaded("stylefiles_block")."</head><body>".$head;
	}
	$page .= $xt->fetch_loaded("style_block");
	$page .= $xt->fetch_loaded("body");
	$data=db_fetch_array($rs);
	$foot="</span>";
	if($data)
	{
		if(!$pdf)
			$foot.="<div style=\"page-break-after: always\">&nbsp;</div>";
		else
			$foot.="<div style=\"page-break-after: always\">&nbsp;</div>";
	}
	else
		$foot.="</body></html>";
	$page=$head.$page.$foot;
	$id++;

	if(!$pdf)
	{
		echo $page;
	}
	else
	{
		$out.=$page;
	}
}
##endif##		

}

##if @BUILDER.bViewPDF##
if($all)
{
	if(!$pdf)
		echo "<script>RunPDF();</script>";
	else
	{
		$page=$out;
		$pagewidth = postvalue("width")*1.05;
		$landscape=false;
		include("plugins/page2pdf.php");
	}
}
##endif##		

?>
