<?php
ini_set("display_errors","1");
ini_set("display_startup_errors","1");
header("Expires: Thu, 01 Jan 1970 00:00:01 GMT"); 
set_magic_quotes_runtime(0);

include("oldinclude/dbcommon.php");
include("oldinclude/##@TABLE.strShortTableName s##_variables.php");
##if @BUILDER.arrLanguages.len>1##
include("oldinclude/languages.php");
##endif##

##if @BUILDER.bCreateLoginPage##
if(!@$_SESSION["UserID"])
{ 
	$_SESSION["MyURL"]=$_SERVER["SCRIPT_NAME"]."?".$_SERVER["QUERY_STRING"];
	header("Location: login.php?message=expired"); 
	return;
}
if(!CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Export"))
{
	echo "<p>".##message NO_PERMISSIONS##."<a href=\"login.php\">".##message BACK_TO_LOGIN##."</a></p>";
	return;
}
##endif##

$all=postvalue("all");

include('oldlibs/Smarty.class.php');
$smarty = new Smarty();

$conn=db_connect();

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

$strWhereClause="";

if (@$_REQUEST["a"]!="") 
{
	
	$sWhere = "1=0";	
	
//	process selection
	$selected_recs=array();
	if (@$_REQUEST["mdelete"])
	{
		foreach(@$_REQUEST["mdelete"] as $ind)
		{
			$keys=array();
	##foreach @TABLE.arrKeyFields as @k##
			$keys["##@k s##"]=refine($_REQUEST["mdelete##@index##"][$ind-1]);
	##endfor##
			$selected_recs[]=$keys;
		}
	}
	elseif(@$_REQUEST["selection"])
	{
		foreach(@$_REQUEST["selection"] as $keyblock)
		{
			$arr=split("&",refine($keyblock));
			if(count($arr)<##@TABLE.arrKeyFields.len##)
				continue;
			$keys=array();
	##foreach @TABLE.arrKeyFields as @k##
			$keys["##@k s##"]=urldecode($arr[##eval @index-1##]);
	##endfor##
			$selected_recs[]=$keys;
		}
	}

	foreach($selected_recs as $keys)
	{
		$sWhere = $sWhere . " or ";
		$sWhere.=KeyWhere($keys);
	}
//	$strSQL = AddWhere($gstrSQL,$sWhere);
##if @TABLE.nSecOptions==ADVSECURITY_VIEW_OWN  && @BUILDER.nLoginMethod==SECURITY_TABLE && @BUILDER.bCreateLoginPage##
	$sWhere=whereAdd($sWhere,SecuritySQL("Search"));
##endif##
	$strSQL = gSQLWhere($sWhere);
	$strWhereClause=$sWhere;
}
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);
}
if(postvalue("pdf"))
	$strWhereClause = @$_SESSION[$strTableName."_pdfwhere"];

$_SESSION[$strTableName."_pdfwhere"] = $strWhereClause;


$strOrderBy=$_SESSION[$strTableName."_order"];
if(!$strOrderBy)
	$strOrderBy=$gstrOrderBy;
$strSQL.=" ".trim($strOrderBy);

$strSQLbak = $strSQL;
if(function_exists("BeforeQueryPrint"))
	BeforeQueryPrint($strSQL,$strWhereClause,$strOrderBy);

//	Rebuild SQL if needed
if($strSQL!=$strSQLbak)
{
//	changed $strSQL - old style	
	$numrows=GetRowCount($strSQL);
}
else
{
	$strSQL = gSQLWhere($strWhereClause);
	$strSQL.=" ".trim($strOrderBy);
	$numrows=gSQLRowCount($strWhereClause,##@TABLE.bGroupBy##);
}
LogInfo($strSQL);

$mypage=(integer)$_SESSION[$strTableName."_pagenumber"];
if(!$mypage)
	$mypage=1;

//	page size
$PageSize=(integer)$_SESSION[$strTableName."_pagesize"];
if(!$PageSize)
	$PageSize=$gPageSize;

$recno=1;
$records=0;	
$pageindex=1;

if(!$all)
{	
if($numrows)
{
	$maxRecords = $numrows;
	$maxpages=ceil($maxRecords/$PageSize);
	if($mypage > $maxpages)
		$mypage = $maxpages;
	if($mypage<1) 
		$mypage=1;
	$maxrecs=$PageSize;
##if @BUILDER.nDatabaseType==DATABASE_MySQL##
	$strSQL.=" limit ".(($mypage-1)*$PageSize).",".$PageSize;
}
$rs=db_query($strSQL,$conn);
##elseif @BUILDER.nDatabaseType==DATABASE_MSSQLServer##
	$strSQL = AddTop($strSQL, $mypage*$PageSize);
}
$rs=db_query($strSQL,$conn);
db_pageseek($rs,$PageSize,$mypage);
##elseif @BUILDER.nDatabaseType==DATABASE_Access##
	$strSQL = AddTop($strSQL, $mypage*$PageSize);
}
$rs=db_query_direct($strSQL,$conn,$numrows);
db_pageseek($rs,$PageSize,$mypage);
##elseif @BUILDER.nDatabaseType==DATABASE_Oracle##
	$strSQL = AddRowNumber($strSQL, $mypage*$PageSize);
}
$rs=db_query_direct($strSQL,$conn,$numrows);
db_pageseek($rs,$PageSize,$mypage);
##elseif @BUILDER.nDatabaseType==DATABASE_PostgreSQL##
	$maxrecs=$PageSize;
	$strSQL.=" limit ".$PageSize." offset ".(($mypage-1)*$PageSize);
}
$rs=db_query($strSQL,$conn);
##endif##


//	hide colunm headers if needed
$recordsonpage=$numrows-($mypage-1)*$PageSize;
if($recordsonpage>$PageSize)
	$recordsonpage=$PageSize;
##repeat @TABLE.nRecordsPerRowPrint @i##
	if($recordsonpage>=##@i##)
		$smarty->assign("column##@i##show",true);
	else
		$smarty->assign("column##@i##show",false);
##endrepeat##

}
else
{
	$rs=db_query($strSQL,$conn);
	$recordsonpage = $numrows;
##repeat @TABLE.nRecordsPerRowPrint @i##
	if($recordsonpage>=##@i##)
		$smarty->assign("column##@i##show",true);
	else
		$smarty->assign("column##@i##show",false);
##endrepeat##
}


##foreach Fields as @f filter @f.strTotalsType && @f.bPrinterPage## 
##if @first##
	$totals=array();
##endif##
	$totals["##@f.strName s##"]=0;
##endfor## 	

//	fill $rowinfo array
	$pages = array();
	$rowinfo = array();

	while($data=db_fetch_array($rs))
	{
		if(function_exists("BeforeProcessRowPrint"))
		{
			if(!BeforeProcessRowPrint($data))
				continue;
		}
		break;
	}

	while($data && ($all || $recno<=$PageSize))
	{
		$row=array();
		for($col=1;$data && ($all || $recno<=$PageSize) && $col<=##@TABLE.nRecordsPerRowPrint##;$col++)
		{

##foreach Fields as @f filter @f.strTotalsType && @f.bPrinterPage## 
			##if @f.strTotalsType=="COUNT"##
				$totals["##@f.strName s##"]+= ($data["##@f.strName s##"]!="");
			##else##
				$totals["##@f.strName s##"]+=($data["##@f.strName s##"]+0);
			##endif##
##endfor## 
			$recno++;
			$records++;
			$keylink="";
##foreach @TABLE.arrKeyFields as @k##
			$keylink.="&key##@index##=".htmlspecialchars(rawurlencode(@$data["##@k s##"]));
##endfor##

##foreach Fields as @f filter @f.bPrinterPage order @f.nPrinterPageOrder##

//	##@f.strName## - ##@f.strViewFormat##
			$value="";
	##if @f.strViewFormat==FORMAT_DATABASE_IMAGE##
		##if @f.bShowThumbnail##
				$value.="<a target=_blank 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##
				$value.=" width=##@f.ListFormatObj.nImageWidth##";
			##endif##
			##if @f.ListFormatObj.nImageHeight##
				$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##
			 	// show thumbnail
				$thumbname="##@f.strThumbnail s##".$data["##@f.strName s##"];
				if(substr("##@f.strhlPrefix s##",0,7)!="http://" && !file_exists(GetUploadFolder("##@f.strName s##").$thumbname))
					$thumbname=$data["##@f.strName s##"];
				$value="<a target=_blank 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##
				$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##",$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##
/*	
			if(strlen($data["##@f.strName s##"]))
			{
				$strdata = make_db_value("##@f.strName s##",$data["##@f.strName s##"]);
				$LookupSQL="SELECT ";
			##if @f.EditFormatObj.pLookupObj.bCustomDisplay##
				$LookupSQL.="##@f.strDisplayField s##";
			##else## 
				$LookupSQL.="##@f.strDisplayField ws##";
			##endif##
				$LookupSQL.=" FROM ##@f.EditFormatObj.pLookupObj.strTable ts## WHERE ##@f.strLinkField ws## = " . $strdata;
			##if EditFormatObj.pLookupObj.strWhere##
				$LookupSQL.=" and (".##EditFormatObj.pLookupObj.strWhere##.")"; 
			##endif##
				LogInfo($LookupSQL);
				$rsLookup = db_query($LookupSQL,$conn);
				$lookupvalue=$data["##@f.strName s##"];
				if($lookuprow=db_fetch_numarray($rsLookup))
					$lookupvalue=$lookuprow[0];
				##if NeedEncode(@f)##
					$value=ProcessLargeText(GetDataInt($lookupvalue,$data,"##@f.strName s##", "##@f.strViewFormat s##"),"field=##@f.strName uhs##".$keylink,"",MODE_PRINT);
				##else##
					$value=GetDataInt($lookupvalue,$data,"##@f.strName s##", "##@f.strViewFormat s##");
				##endif##				

			}
			else
				$value="";
*/				
			$value=DisplayLookupWizard("##@f.strName s##",$data["##@f.strName s##"],$data,$keylink,MODE_PRINT);
	##elseif NeedEncode(@f)##
			$value = ProcessLargeText(GetData($data,"##@f.strName s##", "##@f.strViewFormat##"),"field=##@f.strName uhs##".$keylink,"",MODE_PRINT);
	##else##
			$value = GetData($data,"##@f.strName s##", "##@f.strViewFormat##");
	##endif##
			$row[$col."##@f.strName g##_value"]=$value;
##endfor##
			$row[$col."show"]=true;
			if(function_exists("BeforeMoveNextPrint"))
				BeforeMoveNextPrint($data,$row,$col);
			while($data=db_fetch_array($rs))
			{
				if(function_exists("BeforeProcessRowPrint"))
				{
					if(!BeforeProcessRowPrint($data))
						continue;
				}
				break;
			}
		}
		$rowinfo[]=$row;
		if($all && $records>=##@TABLE.m_nReportLinesPerPage##)
		{
			$page=array("rowinfo" =>$rowinfo);
			$page["idx"]=$pageindex;
			$pageindex++;
			$pages[] = $page;
			$records=0;
			$rowinfo=array();
		}
	}
	if($all && count($rowinfo))
	{
		$page=array("rowinfo" =>$rowinfo);
		$page["idx"]=$pageindex;
		$pages[] = $page;
	}
	if(!$all)
		$smarty->assign_by_ref("rowinfo",$rowinfo);
	else
	{
		if(count($pages))
		{
			$pages[count($pages)-1]["showtotals"]=true;
			$pages[count($pages)-1]["last"]=true;
		}
		$smarty->assign_by_ref("pages",$pages);
	}

##foreach Fields as @f filter @f.strTotalsType && @f.bPrinterPage## 
##if @first##
//	show totals
##endif##
$smarty->assign("showtotal_##@f.strName g##", GetTotals("##@f.strName s##",$totals["##@f.strName s##"],"##@f.strTotalsType##",$recno-1,"##@f.strViewFormat##"));
##endfor##

	
##foreach @TABLE.arrMasterTables as @m filter @m.bDisplayInfo##
##if @first##
//	display master table info
$mastertable=$_SESSION[$strTableName."_mastertable"];
$masterkeys=array();
$smarty->assign("showmasterfile","empty.htm");
##endif##
if($mastertable=="##@m.strMasterTable s##")
{
//	include proper masterprint.php code
	include("oldinclude/##@BUILDER.Tables[strDataSourceTable==@m.strMasterTable].strShortTableName##_masterprint.php");
	##foreach @m.arrDetailKeys as @mk##
	$masterkeys[]=@$_SESSION[$strTableName."_masterkey##@index##"];
	##endfor##
	DisplayMasterTableInfo("##@TABLE.strDataSourceTable s##", $masterkeys);
	$smarty->assign("showmasterfile","##@BUILDER.Tables[strDataSourceTable==@m.strMasterTable].strShortTableName##_masterprint.htm");
}
##endfor##

$strSQL=$_SESSION[$strTableName."_sql"];


$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";
$smarty->assign("pageurl",$pagename);
if(postvalue("pdf"))
	$smarty->assign("pdf",true);

if(!$all)
	$templatefile = "##@TABLE.strShortTableName##_print.htm";
else
	$templatefile = "##@TABLE.strShortTableName##_print_all.htm";
	
if(function_exists("BeforeShowPrint"))
	BeforeShowPrint($smarty,$templatefile);

if(!postvalue("pdf"))
	$smarty->display($templatefile);
else
{
	$page = $smarty->fetch($templatefile);
	$pagewidth=postvalue("width")*1.05;
	$pageheight=postvalue("height")*1.05;
	$landscape=false;
	if(postvalue("all"))
	{
		if($pagewidth>$pageheight)
		{
			$landscape=true;
			if($pagewidth/$pageheight<297/210)
				$pagewidth = 297/210*$pageheight;
		}
		else
		{
			if($pagewidth/$pageheight<210/297)
				$pagewidth = 210/297*$pageheight;
		}
	}
	include("plugins/page2pdf.php");
}

