<?php 
@ini_set("display_errors","1");
@ini_set("display_startup_errors","1");
include("include/dbcommon.php");
include("classes/searchclause.php");
session_cache_limiter("none");

include("include/nucleos_presenciais_variables.php");

if(!isLogged())
{ 
	$_SESSION["MyURL"]=$_SERVER["SCRIPT_NAME"]."?".$_SERVER["QUERY_STRING"];
	header("Location: login.php?message=expired"); 
	return;
}
if(CheckPermissionsEvent($strTableName, 'P') && !CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Export"))
{
	echo "<p>"."Você não tem permissão para acessar esta tabela"."<a href=\"login.php\">"."Voltar à página de Login"."</a></p>";
	return;
}

$layout = new TLayout("export","BreezeAqua1","MobileAqua1");
$layout->blocks["top"] = array();
$layout->containers["export"] = array();

$layout->containers["export"][] = array("name"=>"exportheader","block"=>"","substyle"=>2);


$layout->containers["export"][] = array("name"=>"exprange_header","block"=>"rangeheader_block","substyle"=>3);


$layout->containers["export"][] = array("name"=>"exprange","block"=>"range_block","substyle"=>1);


$layout->containers["export"][] = array("name"=>"expoutput_header","block"=>"","substyle"=>3);


$layout->containers["export"][] = array("name"=>"expoutput","block"=>"","substyle"=>1);


$layout->containers["export"][] = array("name"=>"expbuttons","block"=>"","substyle"=>2);


$layout->skins["export"] = "fields";
$layout->blocks["top"][] = "export";$page_layouts["nucleos_presenciais_export"] = $layout;


// Modify query: remove blob fields from fieldlist.
// Blob fields on an export page are shown using imager.php (for example).
// They don't need to be selected from DB in export.php itself.
//$gQuery->ReplaceFieldsWithDummies(GetBinaryFieldsIndices());

$cipherer = new RunnerCipherer($strTableName);

$strWhereClause = "";
$strHavingClause = "";
$strSearchCriteria = "and";
$selected_recs = array();
$options = "1";

header("Expires: Thu, 01 Jan 1970 00:00:01 GMT"); 
include('include/xtempl.php');
include('classes/runnerpage.php');
$xt = new Xtempl();
$id = postvalue("id") != "" ? postvalue("id") : 1;

$phpVersion = (int)substr(phpversion(), 0, 1); 
if($phpVersion > 4)
{
	include("include/export_functions.php");
	$xt->assign("groupExcel", true);
}
else
	$xt->assign("excel", true);

//array of params for classes
$params = array("pageType" => PAGE_EXPORT, "id" => $id, "tName" => $strTableName);
$params["xt"] = &$xt;
if(!$eventObj->exists("ListGetRowCount") && !$eventObj->exists("ListQuery"))
	$params["needSearchClauseObj"] = false;
$pageObject = new RunnerPage($params);

//	Before Process event
if($eventObj->exists("BeforeProcessExport"))
	$eventObj->BeforeProcessExport($conn, $pageObject);

if (@$_REQUEST["a"]!="")
{
	$options = "";
	$sWhere = "1=0";	

//	process selection
	$selected_recs = array();
	if (@$_REQUEST["mdelete"])
	{
		foreach(@$_REQUEST["mdelete"] as $ind)
		{
			$keys=array();
			$keys["id"] = refine($_REQUEST["mdelete1"][mdeleteIndex($ind)]);
			$selected_recs[] = $keys;
		}
	}
	elseif(@$_REQUEST["selection"])
	{
		foreach(@$_REQUEST["selection"] as $keyblock)
		{
			$arr=explode("&",refine($keyblock));
			if(count($arr)<1)
				continue;
			$keys = array();
			$keys["id"] = urldecode($arr[0]);
			$selected_recs[] = $keys;
		}
	}

	foreach($selected_recs as $keys)
	{
		$sWhere = $sWhere . " or ";
		$sWhere.=KeyWhere($keys);
	}

	$sWhere = whereAdd($sWhere,SecuritySQL("Search"));

	$strSQL = $gQuery->gSQLWhere($sWhere);
	$strWhereClause=$sWhere;
	
	$_SESSION[$strTableName."_SelectedSQL"] = $strSQL;
	$_SESSION[$strTableName."_SelectedWhere"] = $sWhere;
	$_SESSION[$strTableName."_SelectedRecords"] = $selected_recs;
}

if ($_SESSION[$strTableName."_SelectedSQL"]!="" && @$_REQUEST["records"]=="") 
{
	$strSQL = $_SESSION[$strTableName."_SelectedSQL"];
	$strWhereClause = @$_SESSION[$strTableName."_SelectedWhere"];
	$selected_recs = $_SESSION[$strTableName."_SelectedRecords"];
}
else
{
	$strWhereClause = @$_SESSION[$strTableName."_where"];
	$strHavingClause = @$_SESSION[$strTableName."_having"];
	$strSearchCriteria = @$_SESSION[$strTableName."_criteria"];
	if($strWhereClause == "")
		$strWhereClause = whereAdd($strWhereClause,SecuritySQL("Search"));
	$strSQL = $gQuery->gSQLWhere($strWhereClause, $strHavingClause, $strSearchCriteria);
}

$mypage = 1;
if(@$_REQUEST["type"])
{
//	order by
	$strOrderBy = $_SESSION[$strTableName."_order"];
	if(!$strOrderBy)
		$strOrderBy = $gstrOrderBy;
	$strSQL.=" ".trim($strOrderBy);

	$strSQLbak = $strSQL;
	if($eventObj->exists("BeforeQueryExport"))
		$eventObj->BeforeQueryExport($strSQL,$strWhereClause,$strOrderBy, $pageObject);
//	Rebuild SQL if needed
	if($strSQL!=$strSQLbak)
	{
//	changed $strSQL - old style	
		$numrows=GetRowCount($strSQL);
	}
	else
	{
		$strSQL = $gQuery->gSQLWhere($strWhereClause, $strHavingClause, $strSearchCriteria);
		$strSQL.=" ".trim($strOrderBy);
		$rowcount=false;
		if($eventObj->exists("ListGetRowCount"))
		{
			$masterKeysReq=array();
			for($i = 0; $i < count($pageObject->detailKeysByM); $i ++)
				$masterKeysReq[] = $_SESSION[$strTableName."_masterkey".($i + 1)];
			$rowcount = $eventObj->ListGetRowCount($pageObject->searchClauseObj,$_SESSION[$strTableName."_mastertable"],$masterKeysReq,$selected_recs, $pageObject);
		}
		if($rowcount !== false)
			$numrows = $rowcount;
		else
			$numrows = $gQuery->gSQLRowCount($strWhereClause,$strHavingClause,$strSearchCriteria);
	}
	LogInfo($strSQL);

//	 Pagination:

	$nPageSize = 0;
	if(@$_REQUEST["records"]=="page" && $numrows)
	{
		$mypage = (integer)@$_SESSION[$strTableName."_pagenumber"];
		$nPageSize = (integer)@$_SESSION[$strTableName."_pagesize"];
		
		if(!$nPageSize)
			$nPageSize = $gSettings->getInitialPageSize();
				
		if($nPageSize<0)
			$nPageSize = 0;
			
		if($nPageSize>0)
		{
			if($numrows<=($mypage-1)*$nPageSize)
				$mypage = ceil($numrows/$nPageSize);
		
			if(!$mypage)
				$mypage = 1;
			
					$strSQL.=" limit ".(($mypage-1)*$nPageSize).",".$nPageSize;
		}
	}
	$listarray = false;
	if($eventObj->exists("ListQuery"))
	{
		$arrFieldForSort = array();
		$arrHowFieldSort = array();
		require_once getabspath('classes/orderclause.php');
		$fieldList = unserialize($_SESSION[$strTableName."_orderFieldsList"]);
		for($i = 0; $i < count($fieldList); $i++)
		{
			$arrFieldForSort[] = $fieldList[$i]->fieldIndex; 
			$arrHowFieldSort[] = $fieldList[$i]->orderDirection; 
		}
		$listarray = $eventObj->ListQuery($pageObject->searchClauseObj, $arrFieldForSort, $arrHowFieldSort,
			$_SESSION[$strTableName."_mastertable"], $masterKeysReq, $selected_recs, $nPageSize, $mypage, $pageObject);
	}
	if($listarray!==false)
		$rs = $listarray;
	elseif($nPageSize>0)
	{
					$rs = db_query($strSQL,$conn);
	}
	else
		$rs = db_query($strSQL,$conn);

	if(!ini_get("safe_mode"))
		set_time_limit(300);
	
	if(substr(@$_REQUEST["type"],0,5)=="excel")
	{
//	remove grouping
		$locale_info["LOCALE_SGROUPING"]="0";
		$locale_info["LOCALE_SMONGROUPING"]="0";
				if($phpVersion > 4)
			ExportToExcel($cipherer, $pageObject);
		else
			ExportToExcel_old($cipherer);
	}
	else if(@$_REQUEST["type"]=="word")
	{
		ExportToWord($cipherer);
	}
	else if(@$_REQUEST["type"]=="xml")
	{
		ExportToXML($cipherer);
	}
	else if(@$_REQUEST["type"]=="csv")
	{
		$locale_info["LOCALE_SGROUPING"]="0";
		$locale_info["LOCALE_SDECIMAL"]=".";
		$locale_info["LOCALE_SMONGROUPING"]="0";
		$locale_info["LOCALE_SMONDECIMALSEP"]=".";
		ExportToCSV($cipherer);
	}
	db_close($conn);
	return;
}

// add button events if exist
$pageObject->addButtonHandlers();

if($options)
{
	$xt->assign("rangeheader_block",true);
	$xt->assign("range_block",true);
}

$xt->assign("exportlink_attrs", 'id="saveButton'.$pageObject->id.'"');

$pageObject->body["begin"] .="<script type=\"text/javascript\" src=\"include/loadfirst.js\"></script>\r\n";
$pageObject->body["begin"] .= "<script type=\"text/javascript\" src=\"include/lang/".getLangFileName(mlang_getcurrentlang()).".js\"></script>";

$pageObject->fillSetCntrlMaps();
$pageObject->body['end'] .= '<script>';
$pageObject->body['end'] .= "window.controlsMap = ".my_json_encode($pageObject->controlsHTMLMap).";";
$pageObject->body['end'] .= "window.viewControlsMap = ".my_json_encode($pageObject->viewControlsHTMLMap).";";
$pageObject->body['end'] .= "window.settings = ".my_json_encode($pageObject->jsSettings).";";
$pageObject->body['end'] .= '</script>';
$pageObject->body["end"] .= "<script language=\"JavaScript\" src=\"include/runnerJS/RunnerAll.js\"></script>\r\n";
$pageObject->addCommonJs();

$pageObject->body["end"] .= "<script>".$pageObject->PrepareJS()."</script>";
$xt->assignbyref("body",$pageObject->body);

$xt->display("nucleos_presenciais_export.htm");

function ExportToExcel_old($cipherer)
{
	global $cCharset;
	header("Content-Type: application/vnd.ms-excel");
	header("Content-Disposition: attachment;Filename=nucleos_presenciais.xls");

	echo "<html>";
	echo "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\">";
	
	echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=".$cCharset."\">";
	echo "<body>";
	echo "<table border=1>";

	WriteTableData($cipherer);

	echo "</table>";
	echo "</body>";
	echo "</html>";
}

function ExportToWord($cipherer)
{
	global $cCharset;
	header("Content-Type: application/vnd.ms-word");
	header("Content-Disposition: attachment;Filename=nucleos_presenciais.doc");

	echo "<html>";
	echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=".$cCharset."\">";
	echo "<body>";
	echo "<table border=1>";

	WriteTableData($cipherer);

	echo "</table>";
	echo "</body>";
	echo "</html>";
}

function ExportToXML($cipherer)
{
	global $nPageSize,$rs,$strTableName,$conn,$eventObj, $pageObject;
	header("Content-Type: text/xml");
	header("Content-Disposition: attachment;Filename=nucleos_presenciais.xml");
	if($eventObj->exists("ListFetchArray"))
		$row = $eventObj->ListFetchArray($rs, $pageObject);
	else
		$row = $cipherer->DecryptFetchedArray($rs);	
	//if(!$row)
	//	return;
		
	global $cCharset;
	
	echo "<?xml version=\"1.0\" encoding=\"".$cCharset."\" standalone=\"yes\"?>\r\n";
	echo "<table>\r\n";
	$i = 0;
	$pageObject->viewControls->forExport = "xml";
	while((!$nPageSize || $i<$nPageSize) && $row)
	{
		$values = array();
			$values["nome"] = $pageObject->showDBValue("nome", $row);
			$values["nome_regional"] = $pageObject->showDBValue("nome_regional", $row);
			$values["login"] = $pageObject->showDBValue("login", $row);
			$values["endereco"] = $pageObject->showDBValue("endereco", $row);
			$values["cep"] = $pageObject->showDBValue("cep", $row);
			$values["estado"] = $pageObject->showDBValue("estado", $row);
			$values["cidade"] = $pageObject->showDBValue("cidade", $row);
			$values["tipo"] = $pageObject->showDBValue("tipo", $row);
			$values["data_inicio"] = $pageObject->showDBValue("data_inicio", $row);
			$values["observacao"] = $pageObject->showDBValue("observacao", $row);
			$values["prepara_para"] = $pageObject->showDBValue("prepara_para", $row);
			$values["funciona_em"] = $pageObject->showDBValue("funciona_em", $row);
			$values["ativo"] = $pageObject->showDBValue("ativo", $row);
			$values["motivo"] = $pageObject->showDBValue("motivo", $row);
			$values["responsavel"] = $pageObject->showDBValue("responsavel", $row);
			$values["site"] = $pageObject->showDBValue("site", $row);
			$values["email"] = $pageObject->showDBValue("email", $row);
			$values["telefone"] = $pageObject->showDBValue("telefone", $row);
			$values["celular"] = $pageObject->showDBValue("celular", $row);
			$values["operadora"] = $pageObject->showDBValue("operadora", $row);
			$values["meta_funcionamento"] = $pageObject->showDBValue("meta_funcionamento", $row);
			$values["meta_alunos"] = $pageObject->showDBValue("meta_alunos", $row);
			$values["limite_alunos_por_coordenador"] = $pageObject->showDBValue("limite_alunos_por_coordenador", $row);
			$values["min_presenca_coordenador"] = $pageObject->showDBValue("min_presenca_coordenador", $row);
			$values["min_presenca_professor"] = $pageObject->showDBValue("min_presenca_professor", $row);
			$values["data_ultimo_score"] = $pageObject->showDBValue("data_ultimo_score", $row);
			$values["min_presenca_aluno"] = $pageObject->showDBValue("min_presenca_aluno", $row);
			$values["ultimo_score"] = $pageObject->showDBValue("ultimo_score", $row);
			$values["min_atividades"] = $pageObject->showDBValue("min_atividades", $row);
		
		$eventRes = true;
		if ($eventObj->exists('BeforeOut'))
			$eventRes = $eventObj->BeforeOut($row, $values, $pageObject);
		
		if ($eventRes)
		{
			$i++;
			echo "<row>\r\n";
			foreach ($values as $fName => $val)
			{
				$field = htmlspecialchars(XMLNameEncode($fName));
				echo "<".$field.">";
				echo $values[$fName];
				echo "</".$field.">\r\n";
			}
			echo "</row>\r\n";
		}
		
		
		if($eventObj->exists("ListFetchArray"))
			$row = $eventObj->ListFetchArray($rs, $pageObject);
		else
			$row = $cipherer->DecryptFetchedArray($rs);
	}
	echo "</table>\r\n";
}

function ExportToCSV($cipherer)
{
	global $rs,$nPageSize,$strTableName,$conn,$eventObj, $pageObject;
	header("Content-Type: application/csv");
	header("Content-Disposition: attachment;Filename=nucleos_presenciais.csv");
	
	if($eventObj->exists("ListFetchArray"))
		$row = $eventObj->ListFetchArray($rs, $pageObject);
	else
		$row = $cipherer->DecryptFetchedArray($rs);

// write header
	$outstr = "";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"nome\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"nome_regional\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"login\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"endereco\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"cep\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"estado\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"cidade\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"tipo\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"data_inicio\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"observacao\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"prepara_para\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"funciona_em\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"ativo\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"motivo\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"responsavel\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"site\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"email\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"telefone\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"celular\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"operadora\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"meta_funcionamento\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"meta_alunos\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"limite_alunos_por_coordenador\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"min_presenca_coordenador\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"min_presenca_professor\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"data_ultimo_score\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"min_presenca_aluno\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"ultimo_score\"";
	if($outstr!="")
		$outstr.=",";
	$outstr.= "\"min_atividades\"";
	echo $outstr;
	echo "\r\n";

// write data rows
	$iNumberOfRows = 0;
	$pageObject->viewControls->forExport = "csv";
	while((!$nPageSize || $iNumberOfRows < $nPageSize) && $row)
	{
		$values = array();
			$values["nome"] = $pageObject->getViewControl("nome")->showDBValue($row, "");
			$values["nome_regional"] = $pageObject->getViewControl("nome_regional")->showDBValue($row, "");
			$values["login"] = $pageObject->getViewControl("login")->showDBValue($row, "");
			$values["endereco"] = $pageObject->getViewControl("endereco")->showDBValue($row, "");
			$values["cep"] = $pageObject->getViewControl("cep")->showDBValue($row, "");
			$values["estado"] = $pageObject->getViewControl("estado")->showDBValue($row, "");
			$values["cidade"] = $pageObject->getViewControl("cidade")->showDBValue($row, "");
			$values["tipo"] = $pageObject->getViewControl("tipo")->showDBValue($row, "");
			$values["data_inicio"] = $pageObject->getViewControl("data_inicio")->showDBValue($row, "");
			$values["observacao"] = $pageObject->getViewControl("observacao")->showDBValue($row, "");
			$values["prepara_para"] = $pageObject->getViewControl("prepara_para")->showDBValue($row, "");
			$values["funciona_em"] = $pageObject->getViewControl("funciona_em")->showDBValue($row, "");
			$values["ativo"] = $pageObject->getViewControl("ativo")->showDBValue($row, "");
			$values["motivo"] = $pageObject->getViewControl("motivo")->showDBValue($row, "");
			$values["responsavel"] = $pageObject->getViewControl("responsavel")->showDBValue($row, "");
			$values["site"] = $pageObject->getViewControl("site")->showDBValue($row, "");
			$values["email"] = $pageObject->getViewControl("email")->showDBValue($row, "");
			$values["telefone"] = $pageObject->getViewControl("telefone")->showDBValue($row, "");
			$values["celular"] = $pageObject->getViewControl("celular")->showDBValue($row, "");
			$values["operadora"] = $pageObject->getViewControl("operadora")->showDBValue($row, "");
			$values["meta_funcionamento"] = $pageObject->getViewControl("meta_funcionamento")->showDBValue($row, "");
			$values["meta_alunos"] = $pageObject->getViewControl("meta_alunos")->showDBValue($row, "");
			$values["limite_alunos_por_coordenador"] = $pageObject->getViewControl("limite_alunos_por_coordenador")->showDBValue($row, "");
			$values["min_presenca_coordenador"] = $pageObject->getViewControl("min_presenca_coordenador")->showDBValue($row, "");
			$values["min_presenca_professor"] = $pageObject->getViewControl("min_presenca_professor")->showDBValue($row, "");
			$values["data_ultimo_score"] = $pageObject->getViewControl("data_ultimo_score")->showDBValue($row, "");
			$values["min_presenca_aluno"] = $pageObject->getViewControl("min_presenca_aluno")->showDBValue($row, "");
			$values["ultimo_score"] = $pageObject->getViewControl("ultimo_score")->showDBValue($row, "");
			$values["min_atividades"] = $pageObject->getViewControl("min_atividades")->showDBValue($row, "");

		$eventRes = true;
		if ($eventObj->exists('BeforeOut'))
		{
			$eventRes = $eventObj->BeforeOut($row,$values, $pageObject);
		}
		if ($eventRes)
		{
			$outstr="";
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["nome"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["nome_regional"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["login"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["endereco"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["cep"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["estado"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["cidade"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["tipo"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["data_inicio"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["observacao"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["prepara_para"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["funciona_em"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["ativo"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["motivo"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["responsavel"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["site"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["email"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["telefone"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["celular"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["operadora"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["meta_funcionamento"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["meta_alunos"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["limite_alunos_por_coordenador"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["min_presenca_coordenador"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["min_presenca_professor"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["data_ultimo_score"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["min_presenca_aluno"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["ultimo_score"]).'"';
			if($outstr!="")
				$outstr.=",";
			$outstr.='"'.str_replace('"', '""', $values["min_atividades"]).'"';
			echo $outstr;
		}
		
		$iNumberOfRows++;
		if($eventObj->exists("ListFetchArray"))
			$row = $eventObj->ListFetchArray($rs, $pageObject);
		else
			$row = $cipherer->DecryptFetchedArray($rs);
			
		if(((!$nPageSize || $iNumberOfRows<$nPageSize) && $row) && $eventRes)
			echo "\r\n";
	}
}

function WriteTableData($cipherer)
{
	global $rs,$nPageSize,$strTableName,$conn,$eventObj, $pageObject;
	
	if($eventObj->exists("ListFetchArray"))
		$row = $eventObj->ListFetchArray($rs, $pageObject);
	else
		$row = $cipherer->DecryptFetchedArray($rs);
//	if(!$row)
//		return;
// write header
	echo "<tr>";
	if($_REQUEST["type"]=="excel")
	{
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Nome").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Nome Regional").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Login").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Endereco").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Cep").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Estado").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Cidade").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Tipo").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Data Inicio").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Observacao").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Prepara Para").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Funciona Em").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Ativo").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Motivo").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Responsavel").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Site").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Email").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Telefone").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Celular").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Operadora").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Meta Funcionamento").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Meta Alunos").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Limite Alunos Por Coordenador").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Min Presenca Coordenador").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Min Presenca Professor").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Data Ultimo Score").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Min Presenca Aluno").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Ultimo Score").'</td>';	
		echo '<td style="width: 100" x:str>'.PrepareForExcel("Min Atividades").'</td>';	
	}
	else
	{
		echo "<td>"."Nome"."</td>";
		echo "<td>"."Nome Regional"."</td>";
		echo "<td>"."Login"."</td>";
		echo "<td>"."Endereco"."</td>";
		echo "<td>"."Cep"."</td>";
		echo "<td>"."Estado"."</td>";
		echo "<td>"."Cidade"."</td>";
		echo "<td>"."Tipo"."</td>";
		echo "<td>"."Data Inicio"."</td>";
		echo "<td>"."Observacao"."</td>";
		echo "<td>"."Prepara Para"."</td>";
		echo "<td>"."Funciona Em"."</td>";
		echo "<td>"."Ativo"."</td>";
		echo "<td>"."Motivo"."</td>";
		echo "<td>"."Responsavel"."</td>";
		echo "<td>"."Site"."</td>";
		echo "<td>"."Email"."</td>";
		echo "<td>"."Telefone"."</td>";
		echo "<td>"."Celular"."</td>";
		echo "<td>"."Operadora"."</td>";
		echo "<td>"."Meta Funcionamento"."</td>";
		echo "<td>"."Meta Alunos"."</td>";
		echo "<td>"."Limite Alunos Por Coordenador"."</td>";
		echo "<td>"."Min Presenca Coordenador"."</td>";
		echo "<td>"."Min Presenca Professor"."</td>";
		echo "<td>"."Data Ultimo Score"."</td>";
		echo "<td>"."Min Presenca Aluno"."</td>";
		echo "<td>"."Ultimo Score"."</td>";
		echo "<td>"."Min Atividades"."</td>";
	}
	echo "</tr>";
	
// write data rows
	$iNumberOfRows = 0;
	$pageObject->viewControls->forExport = "export";
	while((!$nPageSize || $iNumberOfRows<$nPageSize) && $row)
	{
		countTotals($totals, $totalsFields, $row);
		
		$values = array();
	
					$values["nome"] = $pageObject->getViewControl("nome")->showDBValue($row, "");
					$values["nome_regional"] = $pageObject->getViewControl("nome_regional")->showDBValue($row, "");
					$values["login"] = $pageObject->getViewControl("login")->showDBValue($row, "");
					$values["endereco"] = $pageObject->getViewControl("endereco")->showDBValue($row, "");
					$values["cep"] = $pageObject->getViewControl("cep")->showDBValue($row, "");
					$values["estado"] = $pageObject->getViewControl("estado")->showDBValue($row, "");
					$values["cidade"] = $pageObject->getViewControl("cidade")->showDBValue($row, "");
					$values["tipo"] = $pageObject->getViewControl("tipo")->showDBValue($row, "");
					$values["data_inicio"] = $pageObject->getViewControl("data_inicio")->showDBValue($row, "");
					$values["observacao"] = $pageObject->getViewControl("observacao")->showDBValue($row, "");
					$values["prepara_para"] = $pageObject->getViewControl("prepara_para")->showDBValue($row, "");
					$values["funciona_em"] = $pageObject->getViewControl("funciona_em")->showDBValue($row, "");
					$values["ativo"] = $pageObject->getViewControl("ativo")->showDBValue($row, "");
					$values["motivo"] = $pageObject->getViewControl("motivo")->showDBValue($row, "");
					$values["responsavel"] = $pageObject->getViewControl("responsavel")->showDBValue($row, "");
					$values["site"] = $pageObject->getViewControl("site")->showDBValue($row, "");
					$values["email"] = $pageObject->getViewControl("email")->showDBValue($row, "");
					$values["telefone"] = $pageObject->getViewControl("telefone")->showDBValue($row, "");
					$values["celular"] = $pageObject->getViewControl("celular")->showDBValue($row, "");
					$values["operadora"] = $pageObject->getViewControl("operadora")->showDBValue($row, "");
					$values["meta_funcionamento"] = $pageObject->getViewControl("meta_funcionamento")->showDBValue($row, "");
					$values["meta_alunos"] = $pageObject->getViewControl("meta_alunos")->showDBValue($row, "");
					$values["limite_alunos_por_coordenador"] = $pageObject->getViewControl("limite_alunos_por_coordenador")->showDBValue($row, "");
					$values["min_presenca_coordenador"] = $pageObject->getViewControl("min_presenca_coordenador")->showDBValue($row, "");
					$values["min_presenca_professor"] = $pageObject->getViewControl("min_presenca_professor")->showDBValue($row, "");
					$values["data_ultimo_score"] = $pageObject->getViewControl("data_ultimo_score")->showDBValue($row, "");
					$values["min_presenca_aluno"] = $pageObject->getViewControl("min_presenca_aluno")->showDBValue($row, "");
					$values["ultimo_score"] = $pageObject->getViewControl("ultimo_score")->showDBValue($row, "");
					$values["min_atividades"] = $pageObject->getViewControl("min_atividades")->showDBValue($row, "");
		
		$eventRes = true;
		if ($eventObj->exists('BeforeOut'))
		{
			$eventRes = $eventObj->BeforeOut($row, $values, $pageObject);
		}
		if ($eventRes)
		{
			$iNumberOfRows++;
			echo "<tr>";
		
							if($_REQUEST["type"]=="excel")
					echo '<td x:str>';
				else
					echo '<td>';
			
									if($_REQUEST["type"]=="excel")
						echo PrepareForExcel($values["nome"]);
					else
						echo $values["nome"];
			echo '</td>';
							if($_REQUEST["type"]=="excel")
					echo '<td x:str>';
				else
					echo '<td>';
			
									if($_REQUEST["type"]=="excel")
						echo PrepareForExcel($values["nome_regional"]);
					else
						echo $values["nome_regional"];
			echo '</td>';
							if($_REQUEST["type"]=="excel")
					echo '<td x:str>';
				else
					echo '<td>';
			
									if($_REQUEST["type"]=="excel")
						echo PrepareForExcel($values["login"]);
					else
						echo $values["login"];
			echo '</td>';
							if($_REQUEST["type"]=="excel")
					echo '<td x:str>';
				else
					echo '<td>';
			
									if($_REQUEST["type"]=="excel")
						echo PrepareForExcel($values["endereco"]);
					else
						echo $values["endereco"];
			echo '</td>';
							if($_REQUEST["type"]=="excel")
					echo '<td x:str>';
				else
					echo '<td>';
			
									if($_REQUEST["type"]=="excel")
						echo PrepareForExcel($values["cep"]);
					else
						echo $values["cep"];
			echo '</td>';
							echo '<td>';
			
				
								if($_REQUEST["type"]=="excel")
					echo PrepareForExcel($values["estado"]);
				else
					echo $values["estado"];//echo htmlspecialchars($values["estado"]); commented for bug #6823
					
			echo '</td>';
							echo '<td>';
			
				
								if($_REQUEST["type"]=="excel")
					echo PrepareForExcel($values["cidade"]);
				else
					echo $values["cidade"];//echo htmlspecialchars($values["cidade"]); commented for bug #6823
					
			echo '</td>';
							echo '<td>';
			
				
								if($_REQUEST["type"]=="excel")
					echo PrepareForExcel($values["tipo"]);
				else
					echo $values["tipo"];//echo htmlspecialchars($values["tipo"]); commented for bug #6823
					
			echo '</td>';
							echo '<td>';
			
									if($_REQUEST["type"]=="excel")
						echo PrepareForExcel($values["data_inicio"]);
					else
						echo $values["data_inicio"];
			echo '</td>';
							if($_REQUEST["type"]=="excel")
					echo '<td x:str>';
				else
					echo '<td>';
			
									if($_REQUEST["type"]=="excel")
						echo PrepareForExcel($values["observacao"]);
					else
						echo $values["observacao"];
			echo '</td>';
							if($_REQUEST["type"]=="excel")
					echo '<td x:str>';
				else
					echo '<td>';
			
				
								if($_REQUEST["type"]=="excel")
					echo PrepareForExcel($values["prepara_para"]);
				else
					echo $values["prepara_para"];//echo htmlspecialchars($values["prepara_para"]); commented for bug #6823
					
			echo '</td>';
							if($_REQUEST["type"]=="excel")
					echo '<td x:str>';
				else
					echo '<td>';
			
				
								if($_REQUEST["type"]=="excel")
					echo PrepareForExcel($values["funciona_em"]);
				else
					echo $values["funciona_em"];//echo htmlspecialchars($values["funciona_em"]); commented for bug #6823
					
			echo '</td>';
							echo '<td>';
			
									echo $values["ativo"];
			echo '</td>';
							if($_REQUEST["type"]=="excel")
					echo '<td x:str>';
				else
					echo '<td>';
			
				
								if($_REQUEST["type"]=="excel")
					echo PrepareForExcel($values["motivo"]);
				else
					echo $values["motivo"];//echo htmlspecialchars($values["motivo"]); commented for bug #6823
					
			echo '</td>';
							if($_REQUEST["type"]=="excel")
					echo '<td x:str>';
				else
					echo '<td>';
			
									if($_REQUEST["type"]=="excel")
						echo PrepareForExcel($values["responsavel"]);
					else
						echo $values["responsavel"];
			echo '</td>';
							if($_REQUEST["type"]=="excel")
					echo '<td x:str>';
				else
					echo '<td>';
			
									if($_REQUEST["type"]=="excel")
						echo PrepareForExcel($values["site"]);
					else
						echo $values["site"];
			echo '</td>';
							if($_REQUEST["type"]=="excel")
					echo '<td x:str>';
				else
					echo '<td>';
			
									if($_REQUEST["type"]=="excel")
						echo PrepareForExcel($values["email"]);
					else
						echo $values["email"];
			echo '</td>';
							if($_REQUEST["type"]=="excel")
					echo '<td x:str>';
				else
					echo '<td>';
			
									if($_REQUEST["type"]=="excel")
						echo PrepareForExcel($values["telefone"]);
					else
						echo $values["telefone"];
			echo '</td>';
							if($_REQUEST["type"]=="excel")
					echo '<td x:str>';
				else
					echo '<td>';
			
									if($_REQUEST["type"]=="excel")
						echo PrepareForExcel($values["celular"]);
					else
						echo $values["celular"];
			echo '</td>';
							echo '<td>';
			
				
								if($_REQUEST["type"]=="excel")
					echo PrepareForExcel($values["operadora"]);
				else
					echo $values["operadora"];//echo htmlspecialchars($values["operadora"]); commented for bug #6823
					
			echo '</td>';
							echo '<td>';
			
									echo $values["meta_funcionamento"];
			echo '</td>';
							echo '<td>';
			
									echo $values["meta_alunos"];
			echo '</td>';
							echo '<td>';
			
									echo $values["limite_alunos_por_coordenador"];
			echo '</td>';
							echo '<td>';
			
									echo $values["min_presenca_coordenador"];
			echo '</td>';
							echo '<td>';
			
									echo $values["min_presenca_professor"];
			echo '</td>';
							echo '<td>';
			
									if($_REQUEST["type"]=="excel")
						echo PrepareForExcel($values["data_ultimo_score"]);
					else
						echo $values["data_ultimo_score"];
			echo '</td>';
							echo '<td>';
			
									echo $values["min_presenca_aluno"];
			echo '</td>';
							echo '<td>';
			
									echo $values["ultimo_score"];
			echo '</td>';
							echo '<td>';
			
									echo $values["min_atividades"];
			echo '</td>';
			echo "</tr>";
		}
		
		
		if($eventObj->exists("ListFetchArray"))
			$row = $eventObj->ListFetchArray($rs, $pageObject);
		else
			$row = $cipherer->DecryptFetchedArray($rs);
	}
	
}

function XMLNameEncode($strValue)
{
	$search = array(" ","#","'","/","\\","(",")",",","[");
	$ret = str_replace($search,"",$strValue);
	$search = array("]","+","\"","-","_","|","}","{","=");
	$ret = str_replace($search,"",$ret);
	return $ret;
}

function PrepareForExcel($ret)
{
	//$ret = htmlspecialchars($str); commented for bug #6823
	if (substr($ret,0,1)== "=") 
		$ret = "&#61;".substr($ret,1);
	return $ret;

}

function countTotals(&$totals, $totalsFields, $data)
{
	for($i = 0; $i < count($totalsFields); $i ++) 
	{
		if($totalsFields[$i]['totalsType'] == 'COUNT') 
			$totals[$totalsFields[$i]['fName']]["value"] += ($data[$totalsFields[$i]['fName']]!= "");
		else if($totalsFields[$i]['viewFormat'] == "Time") 
		{
			$time = GetTotalsForTime($data[$totalsFields[$i]['fName']]);
			$totals[$totalsFields[$i]['fName']]["value"] += $time[2]+$time[1]*60 + $time[0]*3600;
		} 
		else 
			$totals[$totalsFields[$i]['fName']]["value"] += ($data[$totalsFields[$i]['fName']]+ 0);
		
		if($totalsFields[$i]['totalsType'] == 'AVERAGE')
		{
			if(!is_null($data[$totalsFields[$i]['fName']]) && $data[$totalsFields[$i]['fName']]!=="")
				$totals[$totalsFields[$i]['fName']]['numRows']++;
		}
	}
}
?>
