<?php

error_reporting (E_ALL ^ E_NOTICE);

set_time_limit(0);
include_once("adodb5/adodb.inc.php");

//include_once("adodb5/adodb-exceptions.inc.php");
include_once("adodb5/toexport.inc.php");
include_once('adodb5/tohtml.inc.php'); # load code common to ADOdb




//define('ADODB_ERROR_LOG_TYPE', 3);
//define('ADODB_ERROR_LOG_DEST', 'adodb_errors.log');

include_once("system/settings.php"); //logging settings and other general settings


{
 //   session_set_save_handler("open", "close", "read", "write", "destroy", "gc");

    session_start();
    $error_handler = set_error_handler("engineErrorHandler");
    register_shutdown_function('shutdownFunction');
}


$mode = $_GET['mode'];
//deleteSessionFiles($sess_id);
if ($gs['test_level']!='128199101')
{
  if (!validateLicense()) $mode="terminate";
}


//$log_file_handle = fopen(getLogFileName($report_file), "w");

$report_file = $_GET['report'];
include ($report_file);
include($database_config);



  $portlet_id= $_GET['portlet'];


//echo "test".$db_array;
$url_param_str=processUrlParams(); //this will put any drill or other needed URL parameters into session variables

if ((!$mode||$mode=="HTML")  && (isset($report_file)) ) //if mode is empty or set to HTML and report file provided
{
  getHtml($report_file);
}
else if ($mode=="PARAM")
{
  processParam();
}
else if ($mode=="XML")
{

  getXML($portlet_id);
}
else if ($mode=="CHARTXML")
{
    getChartXML($portlet_id);
}
else if ($mode=="GAUGE")
{
 getGaugeData($portlet_id);
}
else if ($mode=="CSV")
{
  getCSVFile($portlet_id);
}
else if ($mode=="HTMLTABLE")
{
    getDataAsHtml($portlet_id);
}
else if ($mode=="TEST")
{
testMode($portlet_id);

}
else if ($mode=="CLEAR_LOG")
{
  clear_log();

}
else if ($mode=="terminate")
    {
    echo "<h3>Please register.</h3>";
}
else
{
echo "Report definition file missing in the URL<br><br>";

echo "Usage report_engine.php?report=test_report  for test_report.php report definition file";
}  



function getHtml($report_file)
{
elog(0,"report_engine.getHtml started ");
//include ($report_file.".php");
global $plet;
global $dashboard_id;
global $button_text;
global $qlet;
global $url_param_str;
global $plet_group;
global $dashboard_report;
global $d_options;
global $gs;
if ($gs["logging_enabled"]=='Y' )
{
 $log_link="<a href=\"".getLogFileName()."\" target=\"re_log\">session log</a> <a href=\"report_engine.php?mode=CLEAR_LOG&report={$report_file}\" target=\"re_log\">clear log</a>  ";
}
else
{
    $log_link="";
}
///BEGIN Parameter processing
//get list of date parameters and assign a date picker for each.define an empty variable first (don;t know if this reqd in php)
if ($d_options['use_plet_positions'])
{
  $param_array=getParameterStrFixed();
}
else
{
  $param_array=getParameterStr();
}

/*
$param['reset_str']=$resetFunction;
$param['param_str']=$str;
$param['date_str']
*/
$resetFunction = $param_array['reset_str'];
$dateHeader=$param_array['date_str'];

$str=$param_array['param_str'];


//$str.="<div style=\"display:block;clear:both;\"></div>";
///get portlet details
$portlet_str=buildPortlet();
$refresh_str=getDrawPortletCommand();


$portlet_markup = getPortletBodyMarkup(); //markup needed to stay in html body

$drill_str = buildDrillLinks();

$header = <<<EOD
<html>
<head>
<!--META HTTP-EQUIV="REFRESH" CONTENT="30"-->
<title>{$dashboard_report}</title>


<link rel="stylesheet" type="text/css" media="screen" href="jqueryui/css/redmond/jquery-ui-1.7.2.custom.css"> 
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
<link rel="stylesheet" type="text/css" media="screen" href="report_engine.css" />


<!---Chart Related--->
<script language="javascript">AC_FL_RunContent = 0;</script>
<script language="javascript"> DetectFlashVer = 0; </script>
<script src="charts/AC_RunActiveContent.js" language="javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
var requiredMajorVersion = 9;
var requiredMinorVersion = 0;
var requiredRevision = 45;
-->
</script>
<!---Chart related end--->


<!-- Of course we should load the jquery library -->
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<!-- and at end the jqGrid Java Script file -->
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>

<script src="jqueryui/js/jquery-ui-1.7.2.custom.min.js" type="text/javascript"></script>



<!-- required plugins -->
<script type="text/javascript">

function open_win(url)
{
window.open(url);
}
  function drawPortlets()
  {
      {$refresh_str}
   }
   
   {$resetFunction}
   
   {$drill_str}

   function selectSubmitParameters()
   {
    //checked
    var checked = $('input[type=checkbox]').is(':checked');
   if (!checked) return;
   submitParameters();
   }

   function submitParameters()
	{


				//the post call below calls the process param funciton in the script by passing the serialized form elements
				$.post("report_engine.php?mode=PARAM&report={$report_file}{$url_param_str}"
				,
				  $("#{$dashboard_id} :input").serialize()
				, function(data) {
					$("#status p").html(data);
					drawPortlets();
				});
				return false;

	}
   function initialSubmitParameters()
	{


				//the post call below calls the process param funciton in the script by passing the serialized form elements
				$.post("report_engine.php?mode=PARAM&report={$report_file}{$url_param_str}"
				,
				  $("#{$dashboard_id} :input").serialize()
				);
				return false;

	}

	
jQuery(document).ready(function()
{ 
initialSubmitParameters();
$("#{$dashboard_id}").submit(submitParameters);
          $("#clearbutton").click( resetFormInput  );
		  {$portlet_str} 
			//
				
			 
		//dateheader, for each date type it attaches the calendar editor. This is pre-computed variable	
          {$dateHeader}	
//window.setInterval("drawPortlets()", 10000); script for autorefresh
}); //document ready end

</script>

</head> 
<body>
                                    
<!--<H2>You are logged in as {$_SESSION['login_name']}</H2>-->
 


<form  name="{$dashboard_id}" id="{$dashboard_id}" method="post">

   <input type="submit" value="{$button_text}" style="position:absolute;  left:{$d_options['top_button_x_location']}px; top:{$d_options['top_button_y_location']}px; width:{$d_options['top_button_width']}px; height:{$d_options['top_button_height']}px; "/>
<INPUT TYPE=CHECKBOX NAME="use_go_button" style="position:absolute;  left:{$d_options['use_go_checkobx_x_location']}px; top:{$d_options['top_button_y_location']}px;  "/>
 {$log_link}

EOD;

/*former footer code for clear and export button
 * <input type="button" value="Clear" id="clearbutton">&nbsp;
<input type=button value="Export" onclick="open_win('report_engine.php?mode=CSV&report=$report_file{$url_param_str}')" />
<div style="position:absolute; top:3px; left:10px; width:100px; height:20px>
 */

$footer = <<<EOD



  

<!--<a  href="report_engine.php?mode=CSV&report=$report_file{$url_param_str}">Export</a>-->


	<div id="status">
		
	</div>




</form>
                                   
<!--divx style="display:block;float:left;position:relative;"-->
{$portlet_markup}
<!--/div-->


</body> 
</html>
EOD;


$body = $header . $str . $footer;


echo $body;
}


function getStaticArray($plet_id)
{

        elog(0,"report_engine.getstaticarrary started plet_id= {$plet_id}");

    global $report_file;
global $plet;
global $dashboard_id;
global $url_param_str;
global $d_options;

$val= $plet[$plet_id]['static_values'];
$display_val =$plet[$plet_id]['static_display_values'];

 if (isset($plet[$plet_id]['default_value']) ) //if there is a default value provided use it
 {
     elog(0,"report_engine.getstaticarrary default value provided= {$plet[$plet_id]['default_value']}");
   $currentValue=$plet[$plet_id]['default_value'];
 }
 
   if (isset($_SESSION[$dashboard_id][$plet_id])) //check if value was set previously, this will overriden by the default value
 {


  $currentValue=$_SESSION[$dashboard_id][$plet_id];
  elog(0,"report_engine.getstaticarrary sessionv value provided= {$currentValue}");
 }
 
   if (isset($plet[$plet_id]['display_members']) ) 
   {
     if ($plet[$plet_id]['display_members']!="1")
	 {
	   $multilist=" multiple size={$plet[$plet_id]['display_members']}";
	 }
   }
 
///<SELECT  NAME="{$plet_id}[]" id="{$plet_id}" {$multilist}>  --TODO-- use this to fix the multi value passing
 //<SELECT NAME="{$plet_id}" id="{$plet_id}" style="width:{$plet[$plet_id]['width']}px; height:{$plet[$plet_id]['height']}px;">
//<SELECT NAME="{$plet_id}" id="{$plet_id}" style="width:{$plet[$plet_id]['width']}px; height:{$plet[$plet_id]['height']}px; {$plet[$plet_id]['font']} ; color:{$plet[$plet_id]['font_color']} ; background-color:{$plet[$plet_id]['background_color']}" {$multilist}>
$selectValues = <<<EOD
<SELECT NAME="{$plet_id}" id="{$plet_id}"  onchange="selectSubmitParameters('{$plet_id}')"  style="width:{$plet[$plet_id]['width']}px; height:{$plet[$plet_id]['height']}px; {$plet[$plet_id]['font']} ; color:{$plet[$plet_id]['font_color']} ; background-color:{$plet[$plet_id]['background_color']}" {$multilist}>
EOD;

$i=0;
 foreach ($val as &$value) 
  {

          if ($value==$currentValue)
	  {
                     if (isset($display_val))
                         {
		          $selectValues.="\n<option SELECTED value=\"". $value. "\">". $display_val[$i]; //$i is the counter set at the start of the loop, each value in the list has a correponding display value if they are different
                         }
                     else
                         {
                          $selectValues.="\n<option SELECTED value=\"". $value. "\">". $value; //$i is the counter set at the start of the loop, each value in the list has a correponding display value if they are different
                         }
	  }
	  else
	  {
            if (isset($display_val))
            {
              $selectValues.="\n<option value=\"". $value. "\">". $display_val[$i];
            }
            else
            {
                $selectValues.="\n<option SELECTED value=\"". $value. "\">". $value;
            }
	  }
    $i++;
  } 
  $selectValues.="\n</select>";
  elog(0,"report_engine.getstaticarrary selectValues= {$selectValues}");
  return $selectValues;
}

function wrapField($plet_id,$value)
{
    elog(0,"report_engine.wrapField started= {$plet_id} , {$value}");
   global $plet;

   if (!isset($value) || empty($value)) $value="null";
   
        if ($plet[$plet_id]['enable_all']=='INCLUDE_ALL_AS_CHAR')
        {
           return "#~".$value."#~";
        }
        elseif ($plet[$plet_id]['enable_all']=='INCLUDE_ALL_AS_NUM')
        {
           return "#~".$value."#~";
            
        }
        else
            return $value;
}

function unWrapField($plet_id,$value)
{
    elog(0,"report_engine.unWrapField started= {$plet_id} , {$value}");
    global $plet;

        if ($plet[$plet_id]['enable_all']=='INCLUDE_ALL_AS_CHAR')
        {
           $value = str_replace("#~#~","','",$value);
           $value = str_replace("#~","'",$value);
           return $value;
        }
        elseif ($plet[$plet_id]['enable_all']=='INCLUDE_ALL_AS_NUM')
        {
           $value = str_replace("#~#~",",",$value);
           $value = str_replace("#~","",$value);
           return $value;


        }
        else
            return $value;
}


function getSQLArray($plet_id,$SQL)
{
    elog(0,"report_engine.getSQLArray  started= {$plet_id} , {$SQL}");
try
    {
global $db_array; //get all the database settings
global $database_config;

global $report_file;
global $plet;
global $dashboard_id;
global $url_param_str;
global $d_options;
$currentValue=" ";

          $selectValuesHdr = <<<EOD

        <SELECT NAME="{$plet_id}" id="{$plet_id}" onchange="selectSubmitParameters('{$plet_id}')" style="width:{$plet[$plet_id]['width']}px; height:{$plet[$plet_id]['height']}px; {$plet[$plet_id]['font']} ; color:{$plet[$plet_id]['font_color']} ; background-color:{$plet[$plet_id]['background_color']}">
EOD;

$selectValues = "\n<option SELECTED value=\"Error\">connection error</select>";

//use_comma_values will indicate later if this value is to be set as the default value
if (   ($plet[$plet_id]['enable_all']=='INCLUDE_ALL_AS_NUM' ||$plet[$plet_id]['enable_all']=='INCLUDE_ALL_AS_CHAR') )

{

    if (($plet[$plet_id]['default_value']=='ALL' || $plet[$plet_id]['default_value']=='%') )
    {
      $use_default_comma_values="SELECTED";
    }
    else
    {
       $use_default_comma_values=" ";
       if (isset($plet[$plet_id]['default_value']))
         $currentValue=wrapField($plet_id,$plet[$plet_id]['default_value']);
       else $currentValue=" ";
    }
}
else $currentValue=$plet[$plet_id]['default_value']; //if normal all then use the value as it is


 if (isset($_SESSION[$dashboard_id][$plet_id])) //get the session value if it is set, so that we can set the value as selected
 {
  $currentValue=$_SESSION[$dashboard_id][$plet_id];
  $use_default_comma_values=" ";
 }

  $db = getConnection($plet[$plet_id]['connection']);
     elog(0,"report_engine.getSQLArray  after connection call= ");
  if (is_null($db)|| empty($db))
  {
      elog(0,"report_engine.getSQLArray  database handle is null ");
    return   $selectValuesHdr.  $selectValues;
  }
//echo print_r($db,true);
/*
   $db = ADONewConnection($db_array[$database_config]['type']); 
    //$db->debug = true; 
    $db->Connect($db_array[$database_config]['host'].":".$db_array[$database_config]['port'], $db_array[$database_config]['user']
	, $db_array[$database_config]['pass'], $db_array[$database_config]['name']); 

	*/
$SQL = $plet[$plet_id]['sql'];

$selectValues ='';

$recordSet = &$db->Execute($SQL);
$comma_separated_values="";

if (!$recordSet)
{
elog(0,"report_engine.getSQLArray  record set error ");
         print $db->ErrorMsg();
}
else
{
    $column_cnt = $recordSet->FieldCount(); //number of columns
  while (!$recordSet->EOF) 
  {


      //we select #~ as word wrapper assuming very less chance the data itself will have #~ in it
      if ($column_cnt>1) //more than one column in the parameter then the second column is the actual value to be passed
      {
        $value=wrapField($plet_id,$recordSet->fields[1]);
      }
      else
      {
        $value=wrapField($plet_id,$recordSet->fields[0]);
      }

      $comma_separated_values.=$value; //cover the field with #~, so at the end #~f1#~#~f2#~#~f3#~,
         if ($value==$currentValue) //scan through each value as it is added and if a match to the session value then set it as selected
		  {
		     $selectValues.="\n<option SELECTED value=\"".$value . "\">". $recordSet->fields[0];
		  }
         else
          {		 
             $selectValues.="\n<option value=\"".$value. "\">". $recordSet->fields[0];
		  }	 

         $recordSet->MoveNext();

  }
  $selectValues.="\n</select>";

  //Get the all values constructed
  //<input type="text" name="{$value}" id="{$value}" value="{$currentValue}"style="width:{$plet[$value]['width']}px; height:{$plet[$value]['height']}px;">
  //filter:progid:DXImageTransform.Microsoft.Gradient(endColorstr='#ccffcc', startColorstr='#ffffff', gradientType='0');
  //backup - <SELECT NAME="{$plet_id}" id="{$plet_id}" style="width:{$plet[$plet_id]['width']}px; height:{$plet[$plet_id]['height']}px; {$plet[$plet_id]['font']} ; color:{$plet[$plet_id]['font_color']} ; background-color:{$plet[$plet_id]['background_color']}">


        $selectValueAll="";

        //$plet['track_p34']['enable_all']='INCLUDE_ALL_AS_CHAR'
        if ($plet[$plet_id]['enable_all']=='INCLUDE_ALL_AS_CHAR')
        {


          $selectValueAll.="\n<option {$use_default_comma_values} value=\"". $comma_separated_values. "\">". $plet[$plet_id]['all_label'];
        }
        elseif ($plet[$plet_id]['enable_all']=='INCLUDE_ALL_AS_NUM')
        {
//            $comma_separated_values = str_replace("#~#~",",",$comma_separated_values);
  //          $comma_separated_values = str_replace("#~","",$comma_separated_values);

          $selectValueAll.="\n<option {$use_default_comma_values} value=\"". $comma_separated_values. "\">". $plet[$plet_id]['all_label'];
        }
        elseif ($plet[$plet_id]['enable_all']=='Y' || $plet[$plet_id]['enable_all']=='INCLUDE_ALL_AS_LIKE')
        {
              $selectValueAll.="\n<option value=\"". $plet[$plet_id]['all_value']. "\">". $plet[$plet_id]['all_label'];
        }

  $selectValues = $selectValuesHdr.$selectValueAll.$selectValues;
}
    
  // $recordSet->Close(); # optional

   $db->Close(); # optional

    elog(0,"report_engine.getSQLArray = {$selectValues}");
   return $selectValues;

    }
    catch(exception $e)
    {
        elog(2,"report_engine.getSQLArray ".print_r($e,true));
    }

}

function processUrlParams()
{
 elog(0,"report_engine.processUrlParams  started");
    global $report_file;
global $dashboard_id;
global $d_options;

//if the url parameter matches any of the form parameter then set the session variable

//$param_str=" ";
//process the GET parameters and put them in session variable also. This will take care of the parameters being passed through url
  foreach($_GET as $key=>$value)
  {
     if ($key=="report" || $key=="portlet") continue;
	 
//        $_SESSION[$dashboard_id][$key] = $value; //this will work good in drill purpose
		$param_str.="&{$key}={$value}";

		
  }

$_SESSION["log_".$report_file]['drill_params']=$param_str;

  return $param_str;

}

function processParam()
{
     elog(0,"report_engine.processParam  started");

$param_val='';
global $report_file;
global $dashboard_id;
global $plet;
global $debug;
global $d_options;

//process only the parameters that r listed in the dashboard or report defintion


  foreach($_POST as $key=>$value) 
  {
  /* --TODO-- improve the logic below to include all values with number and char values, include %
    if (is_array($value))
	{
	  $implode_str="','";
	 if (isset($plet[$key]['data_type']) )
	 {
	   if ($plet[$key]['data_type']=="NUMBER")
	   {
	     $implode_str=",";
	   }
	   
	 }
      $_SESSION[$dashboard_id."_".$key] = "'".implode($implode_str, $value)."'";
	  $param_val.= $key." = '".implode($implode_str, $value)."' , "." -- {$plet[$key]['data_type']}";
	  
	}
	else
	*/
	{
	  if (!isset($value) && isset($plet[$key]['default_value']) ) //if a particular param is not set then use the default value if available
	  {
	    $_SESSION[$dashboard_id][$key] = $plet[$key]['default_value'];
		$param_val.= $key." = ".$plet[$key]['default_value']." , ";
	  }
	  else
	  {
        $_SESSION[$dashboard_id][$key] = $value;
		$param_val.= $key." = ".$value." , ";
      }		
	  
	  
	}  
  }	
  
 elog(0,"process param: ".print_r($_SESSION[$dashboard_id],true));

}

function displaySession()
{

global $dashboard_id;

global $debug;
if ($debug!="1") return;

$param_val=" ";

  foreach($_SESSION[$dashboard_id] as $key=>$value) 
  {
    
	$param_val.= $key." = ".$value." , ";
  }	

  return $param_val;

}

function buildDrillLinks()
{
     elog(0,"report_engine. buildDrillLinks()  started");

global $report_file;
global $qlet;
global $dashboard_id;
global $url_param_str;
//  return "<a href={$qlet[$value]['drill_url'][$qlet[$value]['drill_columns'][$i]]}"+"&"+options.colModel['name']+"="+cellvalue +"&{$qlet[$value]['column_names'][0]}="+ options.rowId+ "{$url_param_str}>" + cellvalue + "</a>";
$drill_str=" ";
  foreach ($qlet['list'] as &$value) 
  {
    $drill_cnt = count($qlet[$value]['drill_columns']);
    for ($i=0;$i<$drill_cnt; $i++)
	{
$drill_function = <<<EOD
  function drill_{$value}_{$qlet[$value]['drill_columns'][$i]}(cellvalue, options, rowObject) 
       {

            return "<a href={$qlet[$value]['drill_url'][$qlet[$value]['drill_columns'][$i]]}"+"&"+options.colModel['name']+"="+cellvalue +"&{$qlet[$value]['column_names'][0]}="+ options.rowId+ "{$url_param_str} target=\"drill\">" + cellvalue + "</a>";
        }

EOD;
     $drill_str.=$drill_function;
    }
    }//for i=0 drill count

	return $drill_str;
}

function buildPortlet()
{
elog(0,"report_engine. buildPortlet()  started");
    global $report_file;
global $qlet;
global $dashboard_id;
global $url_param_str;
global $grid_height_offset;
global $d_options;

$portlet_header = " ";

foreach ($qlet['list'] as $portlet_id) //for each portlet build the jqGrid code
{
//just process table type portlets
//
        if ($qlet[$portlet_id]['type']!='table') continue;//
        //$portlet_id = "q1"; //--TODO-- make it dynamic

        //build column list
        $column_cnt=count($qlet[$portlet_id]['column_names']);
        $column_names="colNames :[ ";
        $column_model="colModel :[ \n";

        for ($i=0; $i<$column_cnt; $i++)
        {
          $column_names.="'{$qlet[$portlet_id]['column_display_names'][$i]}'";


          if (isset($qlet[$portlet_id]['drill_url'][$qlet[$portlet_id]['column_names'][$i]]))
          {
            $column_model.="      {name:'{$qlet[$portlet_id]['column_names'][$i]}' ,index:'{$qlet[$portlet_id]['column_names'][$i]}' ,  width:{$qlet[$portlet_id]['column_width'][$i]}, sortable:true, align:'{$qlet[$portlet_id]['column_alignment'][$i]}' ,formatter: drill_{$portlet_id}_{$qlet[$portlet_id]['column_display_names'][$i]} }";
          }
          else
          {
            $column_model.="      {name:'{$qlet[$portlet_id]['column_names'][$i]}' ,index:'{$qlet[$portlet_id]['column_names'][$i]}' ,  width:{$qlet[$portlet_id]['column_width'][$i]}, sortable:true, align:'{$qlet[$portlet_id]['column_alignment'][$i]}' {$qlet[$portlet_id]['format'][$qlet[$portlet_id]['column_display_names'][$i]]}  }";
          }

          if ($i+1<$column_cnt) //reached the last array value
          {
            $column_names.=", ";
                $column_model.=", \n";
          }
        }


        //add the ending "]" bracket
        $column_names.=" ] ";
        $column_model.=" \n            ]";

        if (isset($qlet[$portlet_id]['sort']))
        {
          $sort=$qlet[$portlet_id]['sort'];
        }
        else
        {
          $sort=$qlet[$portlet_id]['column_names'][0];
        }

        $xh=getAdjustedHeight($qlet[$portlet_id]['height'],$d_options['grid_height_offset']);

        $pager_str="";
        if ($qlet[$portlet_id]['show_pager']) $pager_str="pager: jQuery('#pager_{$portlet_id}'),";


        /*
          <a href="report_engine.php?mode=CSV&report={$report_file}{$url_param_str}&portlet={$portlet_id}"><img src="img/page_excel.png" border="0" border="0"></a>
 <a href="report_engine.php?mode=HTMLTABLE&report={$report_file}{$url_param_str}&portlet={$portlet_id}" target="_new"><img src="img/html.png" border="0"></a>
         */
$portlet_str = <<<EOD

  jQuery("#{$portlet_id}").jqGrid({
    url:'report_engine.php?mode=XML&report={$report_file}&portlet={$portlet_id}{$url_param_str}',
    datatype: 'xml',
    mtype: 'POST',
    {$column_names},
    {$column_model},
    {$pager_str}
    rowNum:100,
    rowList:[100,200,300],
    sortname: '{$sort}',
    sortorder: "desc",
    rowHeight:10,
    scrollOffset:0,
    viewrecords: false,
        height:{$xh},
        width:{$qlet[$portlet_id]['width']},
    imgpath: 'themes/basic/images',
    caption: '{$qlet[$portlet_id]['name']} <a href="report_engine.php?mode=CSV&report={$report_file}{$url_param_str}&portlet={$portlet_id}">Export to Excel<img src="img/page_excel.png" border="0"></a>',
                footerrow : false,
        userDataOnFooter : false,
        viewsortcols: true,
        altRows:true,
        altclass: 'other_row',
        loadError : function(xhr,st,err)
        {
    	//jQuery("#status").html("Type: "+st+"; Response: "+ xhr.status + " "+xhr.statusText);
        },
        loadComplete: function()
        {
               
        }
  });
EOD;

    $portlet_header.=$portlet_str;
}

return $portlet_header;
  
}

function getAdjustedHeight($orig,$offset)
{
    elog(0,"report_engine.getAdjustedHeight  started");
    return $orig+$offset;
}

//get a list of commands to refresh the portlets
function getDrawPortletCommand()
{
    elog(0,"report_engine.getDrawPortletCommand()  started");

global $report_file;
global $qlet;
global $dashboard_id;
global $url_param_str;


  $str=" ";
  foreach ($qlet['list'] as &$portlet)
  {
    if ($qlet[$portlet]['type']=='table' )
    {
     $str.= <<< EOD
	 $("#{$portlet}").trigger("reloadGrid");
	 
EOD;
    }
    else if ( startsWith("chart", $qlet[$portlet]['type']))
    {
      $str .= <<< EOD
        document.{$portlet}.Update_URL( "report_engine.php?mode=CHARTXML&report={$report_file}&portlet={$portlet}{$url_param_str}", true, 60, 1, "reset" );
EOD;
    }
    else if ( startsWith("gauge", $qlet[$portlet]['type']))
    {
      $str .= <<< EOD

        document.{$portlet}.SetVariable("update_url", "report_engine.php?mode=GAUGE&report={$report_file}&portlet={$portlet}{$url_param_str}" );
EOD;
    }

   }
   
   return $str;
  
}

//process all the $_PVAL so that the default and null valeus are handeld
function processSqlParam($sql)
{
elog(0,"report_engine.processSqlParam  started");
//echo "before:<br>";
//echo "$sql";

global $_PVAL;
global $dashboard_id;
global $plet;

//if (!isset($dashboard_id)) return $sql;
//if (!isset($_SESSION[$dashboard_id])) return $sql;

if (!isset($_SESSION[$dashboard_id])) return $sql;

  foreach($_SESSION[$dashboard_id] as $key=>$value) 
  {

    
	{
	 if ($_GET['mode']=='TEST') echo "$key value len = ".$value."<br>";
	  if (isset($_GET[$key]))
	  {
	    $_PVAL[$key]=$_GET[$key];
	  }
	  else if ((!isset($value) || is_null($value) || empty($value)) && isset($plet[$key]['default_null_value']) ) //if a particular param is not set then use the default value if available
	  {
	   // echo "$key =it is null<br>";
	    $_PVAL[$key] = $plet[$key]['default_null_value'];
      }
	  else
	  {
	    $_PVAL[$key] = $value;
	  }

          $_PVAL[$key] = unWrapField($key,$_PVAL[$key]);
  /*
	//  echo "$key = $_PVAL[$key] -x <br>";
          if ( $plet[$key]['enable_all']=="INCLUDE_ALL_AS_CHAR")
              {
	             $_PVAL[$key] = str_replace("#~#~","','",$_PVAL[$key]);
                     $_PVAL[$key] = str_replace("#~","'",$_PVAL[$key]);
              }
*/
	  //now replace the sql
	  $sql = str_replace("PVAL['$key']",$_PVAL[$key],$sql);
	 
    }
  }
  
  //now process all drill parameters
  if ($_GET['mode']=='TEST') echo "All get values";
  
  foreach ($_GET as $key=>$value)
  {
  
   if ($_GET['mode']=='TEST') echo "$key value  = ".$value."<br>";
	  if (isset($_GET[$key]))
	  {
	    $_PVAL[$key]=$_GET[$key];
	  }  
  
  	  //now replace the sql
	  $sql = str_replace("PVAL['$key']",$_PVAL[$key],$sql);
  }
  
//  echo "after:<br>";
//echo "$sql";

  return $sql;
}

/**
 *
 * @global <type> $db_array
 * @global <type> $database_config
 * @global <type> $report_file
 * @global <type> $qlet
 * @global <type> $plet
 * @global <type> $dashboard_id
 * @global <type> $_PVAL
 * @global <type> $debug
 * @param <type> $portlet_id
 *
 * This function returns the needed markup for each portlet, qlet + glet. It includes the div tags and the pager tags
 */
function getPortletBodyMarkup()
{
    elog(0,"report_engine.getPortletBodyMarkup  started");

global $qlet;
global $dashboard_id;
global $url_param_str;
global $dashboard_report;
global $report_file;
global $d_options;

    $portlet_markup="<!---Begin Portlet Body---><br>\n"; //initialize the string with some comment



foreach ($qlet['list'] as $portlet)
{
  //  echo "currently processing --> {$portlet} which is of type {$qlet[$portlet]['type']}";
  //  echo "width = {$qlet[$portlet]['width']}";

    $yx= $qlet[$portlet]['y_position']+$d_options['top_button_offset'];
    
    if ($qlet[$portlet]['type']=='table')
        {


    $table_str= <<<EOD

<div style="position: absolute; left: {$qlet[$portlet]['x_position']}px; top: {$yx}px; width: {$qlet[$portlet]['width']}px; height: {$qlet[$portlet]['height']}px;">
   <table id="{$portlet}" class="scroll"></table> 
   <div id="pager_{$portlet}" class="scroll" style="text-align:center;"></div> 
</div>    
EOD;
        }

    else if ( startsWith("chart", $qlet[$portlet]['type']) )
            {
$y_csv=$yx-16;
//$x_csv=$qlet[$portlet]['x_position'] +$qlet[$portlet]['width'] - 50;
        $table_str= <<<EOD
        <div style="position: absolute; left: {$qlet[$portlet]['x_position']}px; top: {$y_csv}px; ">
<a href="report_engine.php?mode=CSV&report={$report_file}{$url_param_str}&portlet={$portlet}"><img src="img/page_excel.png" border="0"></a>
 <a href="report_engine.php?mode=HTMLTABLE&report={$report_file}{$url_param_str}&portlet={$portlet}" target="_new"><img src="img/html.png"  border="0"></a>
</div>
<div style="position: absolute; left: {$qlet[$portlet]['x_position']}px; top: {$yx}px; width: {$qlet[$portlet]['width']}px; height: {$qlet[$portlet]['height']}px;">
        <script language="JavaScript" type="text/javascript">
<!--
if (AC_FL_RunContent == 0 || DetectFlashVer == 0)
{
	alert("This page requires AC_RunActiveContent.js.");
} else
{
	var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
	if(hasRightVersion)
	{
		AC_FL_RunContent
		(
			'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,45,0',
			'width', '{$qlet[$portlet]['width']}',
			'height', '{$qlet[$portlet]['height']}',
			'scale', 'noscale',
			'salign', 'TL',
			'bgcolor', '#{$qlet[$portlet]['background_color']}',
			'wmode', 'opaque',
			'movie', 'charts/charts',
			'src', 'charts/charts',
			'FlashVars', 'timeout=90&library_path=charts/charts_library&xml_source=report_engine.php%3Freport%3D{$report_file}%26mode%3DCHARTXML%26portlet%3D{$portlet}{$url_param_str}',
			'id', '{$portlet}',
			'name', '{$portlet}',
			'menu', 'true',
			'allowFullScreen', 'true',
			'allowScriptAccess','sameDomain',
			'quality', 'high',
			'align', 'middle',
			'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
			'play', 'true',
			'devicefont', 'false'
		);
	} else
	{
		var alternateContent = 'This content requires the Adobe Flash Player. '
		+ '<u><a href=http://www.macromedia.com/go/getflash/>Get Flash</a></u>.';
		document.write(alternateContent);
	}
}
// -->
</script>
<noscript>
	<P>This content requires JavaScript.</P>
</noscript>
</div>
EOD;
        }

        else if ( startsWith("gauge",$qlet[$portlet]['type']))
                //$qlet[$portlet]['type']=='gauge_dial') //if not a gauge type chart
        {

        $y_csv=$yx-16;
$table_str = <<<GOD
<div style="position: absolute; left: {$qlet[$portlet]['x_position']}px; top: {$y_csv}px; ">
  <a href="report_engine.php?mode=CSV&report={$report_file}{$url_param_str}&portlet={$portlet}"><img src="img/page_excel.png" border="0"></a>
   <a href="report_engine.php?mode=HTMLTABLE&report={$report_file}{$url_param_str}&portlet={$portlet}" target="_new"><img src="img/html.png"  border="0"></a>
</div>
<div style="position: absolute; left: {$qlet[$portlet]['x_position']}px; top: {$yx}px; width: {$qlet[$portlet]['width']}px; height: {$qlet[$portlet]['height']}px;">
<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
	codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"
	WIDTH="{$qlet[$portlet]['width']}"
	HEIGHT="{$qlet[$portlet]['height']}"
	id="{$portlet}">
<PARAM NAME="movie" VALUE="charts/gauge.swf?xml_source=report_engine.php%3Freport%3D{$report_file}%26mode%3DGAUGE%26portlet%3D{$portlet}{$url_param_str}" />
<PARAM NAME="quality" VALUE="high" />
<PARAM NAME="bgcolor" VALUE="#{$qlet[$portlet]['background_color']}" />
<param name="wmode" value="transparent" />
<param name="allowScriptAccess" value="sameDomain" />

<EMBED src="charts/gauge.swf?timeout=90&xml_source=report_engine.php%3Freport%3D{$report_file}%26mode%3DGAUGE%26portlet%3D{$portlet}{$url_param_str}"
	quality="high"
	bgcolor="#{$qlet[$portlet]['background_color']}" 
	WIDTH="{$qlet[$portlet]['width']}"
	HEIGHT="{$qlet[$portlet]['height']}"
	wmode="transparent" 
	NAME="{$portlet}"
	allowScriptAccess="sameDomain"
	swLiveConnect="true"
	TYPE="application/x-shockwave-flash"
	PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">
</EMBED>
</OBJECT>
</div>
GOD;


        }
    
   $portlet_markup.=$table_str;
    $session_id=session_id();
    $portlet_markup.="<!--session= {$session_id}-->";
}


$portlet_markup.="<!---End Portlet Body ----><br>\n";

if (! $d_options['use_plet_positions'])
{
    $portlet_markup=
    "<div style=\"display:block;float:left;position:relative;\">
         {$portlet_markup}
     </div>
    ";
}

return $portlet_markup;

}



/*
 * setAngleRange(-120,120)
  * setsubRange(-20,30,Green)
 * setRange(30,60,Blue)
 * setRange(60,90,Red)
 * setValue
 */
function getGaugeData($portlet_id)
{
 elog(0,"report_engine.getGaugeData  started");
    global $qlet;
global $dashboard_id;
global $url_param_str;
global $dashboard_report;
global $report_file;
//report_engine.php%3Freport%3D{$report_file}%26mode%3DCHARTXML%26portlet%3D{$portlet}{$url_param_str}
//sleep(60);
$data_array = getDataArray($portlet_id);

$pointer_value=number_format($data_array['data'][0][0]
        ,$qlet[$portlet_id]['pointer']['value']['decimals']
        ,$qlet[$portlet_id]['pointer']['value']['decimal_str']
        ,$qlet[$portlet_id]['pointer']['value']['thousand_separator']
        ); //pointer value is a dynamic value

//calculate the start and end value of the complete range by getting the minimum of all start value and maximum of all end values
$range_min= $qlet[$portlet_id]['range'][0]['start_value'];

$range_count = count($qlet[$portlet_id]['range']);
$range_max = $qlet[$portlet_id]['range'][$range_count-1]['end_value'];

//RadialTicks (              $x_center, $y_center, $radius,  $length, $start_angle, $end_angle, $ticks_count, $thickness,              $color )
$radial_ticks = radialTicks( $qlet[$portlet_id]['x_center'],
                             $qlet[$portlet_id]['y_center'],
                             $qlet[$portlet_id]['tick_radius'] ,
                             $qlet[$portlet_id]['major_ticks']['length'] ,
                             $qlet[$portlet_id]['ticks_range_angle']['start_angle'] ,
                             $qlet[$portlet_id]['ticks_range_angle']['end_angle']   ,
                             $qlet[$portlet_id]['major_ticks']['number_of_parts'] ,
                             $qlet[$portlet_id]['major_ticks']['thickness']       ,
                             $qlet[$portlet_id]['major_ticks']['color']
                           );

//for the minor tick radius we need to add the length difference between major and minor so that the minor tick is aligned to the rim of the circle
$radial_ticks .= radialTicks( $qlet[$portlet_id]['x_center'],
                             $qlet[$portlet_id]['y_center'],
                             $qlet[$portlet_id]['tick_radius'] +  $qlet[$portlet_id]['major_ticks']['length'] - $qlet[$portlet_id]['minor_ticks']['length'],
                             $qlet[$portlet_id]['minor_ticks']['length'] ,
                             $qlet[$portlet_id]['ticks_range_angle']['start_angle'] ,
                             $qlet[$portlet_id]['ticks_range_angle']['end_angle']   ,
                             $qlet[$portlet_id]['minor_ticks']['number_of_parts'] * $qlet[$portlet_id]['major_ticks']['number_of_parts'] ,
                             $qlet[$portlet_id]['minor_ticks']['thickness']       ,
                             $qlet[$portlet_id]['minor_ticks']['color']
                           );


	$radial_numbers = radialNumbers(
                             $qlet[$portlet_id]['x_center'],
                             $qlet[$portlet_id]['y_center'],
                             $qlet[$portlet_id]['number_radius'] ,
                             $range_min ,
                             $range_max,
                             $qlet[$portlet_id]['ticks_range_angle']['start_angle'] ,
                             $qlet[$portlet_id]['ticks_range_angle']['end_angle']   ,
                             $qlet[$portlet_id]['major_ticks']['number_of_parts'] ,
                             $qlet[$portlet_id]['tick_numbers']['font_size']       ,
                             $qlet[$portlet_id]['tick_numbers']['color']
                                        );



$dial_range_str=get_dial_range($portlet_id, $range_max,$range_min);
$pointer_code_str = get_pointer($portlet_id, $range_max, $range_min, $pointer_value);
/*
$qlet[$portlet_id]['template']=
"
<gauge>

	<circle x='#x_center#' y='#y_center#' radius='#radius#' fill_color='FFFFFF' fill_alpha='100' line_thickness='6' line_color='333333' line_alpha='90' />

     	#range_code#


        <circle x='#x_center#' y='#y_center#' radius='30' fill_color='FFFFFF' fill_alpha='255' line_thickness='0' line_alpha='50' />

        #pointer_code#

        <circle x='#x_center#' y='#y_center#' radius='80' start='135' end='225' fill_color='111111' fill_alpha='80' />
        <circle x='#x_center#' y='#y_center#' radius='20' fill_color='111111' fill_alpha='100' line_thickness='5' line_alpha='50' />

	#radial_ticks#

        #radial_numbers#



	<text x='95' y='180' width='100' size='14' color='cccfff' alpha='70' align='center'>#pointer_value# Sales/Month</text>


</gauge>
";
*/
/*
 * <link>

          <area x='0'
            y='0'
            width='{$qlet[$portlet_id]['width']}'
            height='{$qlet[$portlet_id]['height']}'
            url='http://www.reportingdashboard.com'
            target='_new'
            alpha='75'
            />
 </link>
 */
$gauge_str= "
<gauge>

   <license>IMWQ9X4BXN6T2CDHGV-5ND6AIDY5BK</license>


".$qlet[$portlet_id]['template']."





</gauge>
";

$gauge_str = str_ireplace("#x_center#", $qlet[$portlet_id]['x_center'] , $gauge_str);
$gauge_str = str_ireplace("#y_center#", $qlet[$portlet_id]['y_center'] , $gauge_str);
$gauge_str = str_ireplace("#radius#", $qlet[$portlet_id]['radius']     , $gauge_str);
$gauge_str = str_ireplace("#radial_numbers#", $radial_numbers     , $gauge_str);
$gauge_str = str_ireplace("#radial_ticks#", $radial_ticks     , $gauge_str);
$gauge_str = str_ireplace("#range_code#", $dial_range_str     , $gauge_str);
$gauge_str = str_ireplace("#pointer_code#", $pointer_code_str     , $gauge_str);
$gauge_str = str_ireplace("#pointer_value#", $pointer_value     , $gauge_str);

if ($qlet[$portlet_id]['type']=="gauge_meter")
{
  $gauge_str = str_ireplace("#meter_legend#", $qlet[$portlet_id]['legend_xml']     , $gauge_str);
}

#meter_legend#


/*
$gauge_str = <<<EOD
<gauge>
      
	<circle x='145' y='130' radius='110' fill_color='FFFFFF' fill_alpha='100' line_thickness='6' line_color='333333' line_alpha='90' />
	<circle  start='-120' end='-20'  x='145' y='130' radius='100'fill_color='99bbff' fill_alpha='90' line_thickness='1' line_alpha='20' />
        <circle start='-20' end='20' x='145' y='130' radius='100' fill_color='CCFF33' fill_alpha='90' line_thickness='1' line_alpha='20' />
        <circle start='20' end='120' x='145' y='130' radius='100' fill_color='FF6633' fill_alpha='90' line_thickness='1' line_alpha='20' />



        <circle x='145' y='130' radius='30' fill_color='FFFFFF' fill_alpha='255' line_thickness='0' line_alpha='50' />

        <rotate x='145' y='130' start='-40' span='0' step='0' shake_frequency='0' shake_span='2' shadow_alpha='15'>
	  
        	<polygon fill_color='ffffff' fill_alpha='90' line_alpha='0'>
			<point x='145' y='129' />
			<point x='145' y='132' />
			<point x='245' y='132' />
			<point x='245' y='129' />
		</polygon>
	</rotate>

        <circle x='145' y='130' radius='80' start='135' end='225' fill_color='111111' fill_alpha='80' />
        <circle x='145' y='130' radius='20' fill_color='111111' fill_alpha='100' line_thickness='5' line_alpha='50' />
              {$radial_ticks}
        {$radial_numbers}


	<text x='95' y='180' width='100' size='14' color='cccfff' alpha='70' align='center'>x1000 r/min</text>

	
</gauge>
EOD;
        */
echo $gauge_str;

}

function get_pointer($portlet_id,$range_max,$range_min,$value)
{
elog(0,"report_engine.get_pointer  started");
    global $qlet;
global $dashboard_id;
global $url_param_str;
global $dashboard_report;
global $report_file;

//echo $value;
$v=$value;
if ($value >$range_max) $value=$range_max;
if ($value < $range_min) $value=$range_min;

//echo "after ".$value;
$point_cnt= count($qlet[$portlet_id]['pointer']['points']);
$pointer_str=$qlet[$portlet_id]['pointer']['attributes'];

for ($pi=0;$pi<$point_cnt;$pi++)
{
    $x=$qlet[$portlet_id]['x_center']+ $qlet[$portlet_id]['pointer']['points'][$pi]['x']; //add the center to the polygon points to get new reference
    $y=$qlet[$portlet_id]['y_center']+ $qlet[$portlet_id]['pointer']['points'][$pi]['y'];
  $pointer_str.="      <point x='$x' y='$y'/>\n";
}

$pointer_str.="</polygon>";

$angle_increment = get_angle_increment($portlet_id, $range_max, $range_min);
$pointer_rotation_angle = $qlet[$portlet_id]['ticks_range_angle']['start_angle'] + ($value-$range_min)*$angle_increment;

//echo "value = {$v}, rotation = {$pointer_rotation_angle}";
$final_pointer_str = "<rotate x='{$qlet[$portlet_id]['x_center']}' y='{$qlet[$portlet_id]['y_center']}' start='{$pointer_rotation_angle}' span='0' shake_frequency='0'>\n   {$pointer_str}  \n</rotate>";

return $final_pointer_str;
}

function get_angle_increment($portlet_id,$range_max,$range_min)
{
 elog(0,"report_engine.get_angle_increment  started");
    global $qlet;
global $dashboard_id;
global $url_param_str;
global $dashboard_report;
global $report_file;

        //determine the range circle code
        //first get the angle increment per number value
        //get the difference between high-low range numbers and high-low angle degrees
     $num_diff=$range_max - $range_min;
//$qlet[$portlet_id]['ticks_range_angle']= array(start_angle => -120, end_angle =>120); //The 12 o'clock position is the zero angle position. Anything clockwise from 12'0clock position is positive angle and anything anti-clockwise is -ve angle. For complete circle use -180 to +80.
     $angle_diff = $qlet[$portlet_id]['ticks_range_angle']['end_angle'] - $qlet[$portlet_id]['ticks_range_angle']['start_angle'];
     //now get angle per number increment
     $angle_per_number = $angle_diff / $num_diff;

   //       echo " insided angle increment - num diff betw {$range_max} - {$range_min} = {$num_diff}, angle diff = {$angle_diff}, angle per ={$angle_per_number}";
     return $angle_per_number;
}

//get the colorful range code
function get_dial_range($portlet_id,$range_max,$range_min)
{
     elog(0,"report_engine.get_dial_range  started");
    global $qlet;
global $dashboard_id;
global $url_param_str;
global $dashboard_report;
global $report_file;

/*
        //determine the range circle code
        //first get the angle increment per number value
        //get the difference between high-low range numbers and high-low angle degrees
     $num_diff=$range_max - $range_min;
//$qlet[$portlet_id]['ticks_range_angle']= array(start_angle => -120, end_angle =>120); //The 12 o'clock position is the zero angle position. Anything clockwise from 12'0clock position is positive angle and anything anti-clockwise is -ve angle. For complete circle use -180 to +80.
     $angle_diff = $qlet[$portlet_id]['ticks_range_angle']['end_angle'] - $qlet[$portlet_id]['ticks_range_angle']['start_angle'];
     */

     //now get angle per number increment
     $angle_per_number = get_angle_increment($portlet_id, $range_max, $range_min);

    // echo " num diff betw {$range_max} - {$range_min} = {$num_diff}, angle diff = {$angle_diff}, angle per ={$angle_per_number}";
     //now loop through each range and get the circle code and append to the range string
     $dial_range_str=" ";
     $range_count = count($qlet[$portlet_id]['range']);
     for ($rx=0; $rx <$range_count; $rx++)
     {

         //start_angle + (number - start_number)*angle_per_number - 180
         $range_angle_start = $qlet[$portlet_id]['ticks_range_angle']['start_angle'] +
                        (  $qlet[$portlet_id]['range'][$rx]['start_value']
                         - $qlet[$portlet_id]['range'][0]['start_value']
                        )* $angle_per_number;

         $range_angle_end = $qlet[$portlet_id]['ticks_range_angle']['start_angle'] +
                        (  $qlet[$portlet_id]['range'][$rx]['end_value']
                         - $qlet[$portlet_id]['range'][0]['start_value']
                        )* $angle_per_number;

         //replace the center and radius for each range template
         $range_str = $qlet[$portlet_id]['range'][$rx]['attributes'];
         $range_str = str_ireplace("#x_center#",$qlet[$portlet_id]['x_center'],$range_str);
         $range_str = str_ireplace("#y_center#",$qlet[$portlet_id]['y_center'],$range_str);
         $range_str = str_ireplace("#radius#",$qlet[$portlet_id]['range_radius'],$range_str);
         $range_str = str_ireplace("circle","circle start='{$range_angle_start}' end='{$range_angle_end}'",$range_str); //insert the start and end angle for the range circle definition

        $dial_range_str.=$range_str."\n";
     }

     return $dial_range_str;
}

function testMode($portlet_id)
{

elog(0,"report_engine.testMode  started");
global $db_array; //get all the database settings
global $database_config;

global $report_file;
global $qlet;
global $plet;
global $dashboard_id;
global $_PVAL;
global $debug;
//include the information needed for the connection to MySQL data base server. 
// we store here username, database and password 

if (isset($portlet_id))
    {
      print_r($_SESSION["log_".$report_file][$portlet_id]);
    }
else
    {
      print_r($_SESSION["log_".$report_file]);
    }


echo "-----------------------------------------session variables-----------------------<br>";
print_r($_SESSION[$dashboard_id]);

echo "-----------------------------------------session LOG variables-----------------------<br>";


} //testmode


function getXML($portlet_id)
{
elog(0,"report_engine.getXML  started");
    global $db_array; //get all the database settings
global $database_config;

global $report_file;
global $qlet;
global $plet;
global $dashboard_id;
global $_PVAL;
global $debug;

try
{

//include the information needed for the connection to MySQL data base server.
// we store here username, database and password





// to the url parameter are added 4 parameters as described in colModel
// we should get these parameters to construct the needed query
// Since we specify in the options of the grid that we will use a GET method
// we should use the appropriate command to obtain the parameters.
// In our case this is $_GET. If we specify that we want to use post
// we should use $_POST. Maybe the better way is to use $_REQUEST, which
// contain both the GET and POST variables. For more information refer to php documentation.
// Get the requested page. By default grid sets this to 1.
$page = $_POST['page'];

$limit = $_POST['rows'];
//$limit = 1;

// get index row - i.e. user click to sort. At first time sortname parameter -
// after that the index from colModel
$sidx = $_POST['sidx'];

// sorting order - at first time sortorder
$sord = $_POST['sord'];

// get how many rows we want to have into the grid - rowNum parameter in the grid
$recs = $_POST['rows'];

// if we not pass at first time index use the first column for the index or what you want
if(!$sidx) $sidx =1;

if (!$page) $page=1;

 if (!$recs) $recs=10;

 //echo "p0 = $portlet_id <br>";
//echo "p1 = $qlet[$portlet_id]['connection']<br>";

$db=getConnection($qlet[$portlet_id]['connection']);

/*
// connect to the MySQL database server
   $db = ADONewConnection($db_array[$database_config]['type']);
    //$db->debug = true;
    $db->Connect($db_array[$database_config]['host'].":".$db_array[$database_config]['port'], $db_array[$database_config]['user']
	, $db_array[$database_config]['pass'], $db_array[$database_config]['name']);
if (!$db) die("Connection failed for ".$db_array[$database_config]['host'].":".$db_array[$database_config]['port']." > ".$db_array[$database_config]['user']
." > ".$db_array[$database_config]['pass']." > ".$db_array[$database_config]['name']);
*/
//	print_r($_PVAL);



	if (isset($qlet[$portlet_id]['enable_column_sort']) && $qlet[$portlet_id]['enable_column_sort']=="Y")
	{
      $SQL = $qlet[$portlet_id]['sql']." ORDER BY $sidx $sord";
	}
	else
	{
	 $SQL = $qlet[$portlet_id]['sql'];//." ORDER BY $sidx $sord";
	}
$SQL = processSqlParam($SQL);
elog(1,"report_engine.getXML SQL={$SQL}");
$_SESSION["log_".$report_file][$portlet_id]['sidx']=$sidx;
$_SESSION["log_".$report_file][$portlet_id]['sord']=$sord;
$_SESSION["log_".$report_file][$portlet_id]['recs']=$recs;
$_SESSION["log_".$report_file][$portlet_id]['sql']=$SQL;

        $stmt = $db->Prepare($SQL);
		if ($db_array[$qlet[$portlet_id]['connection']]['type'] == 'oci8')
		  {
		    $rs = $db->Execute($stmt);//, $recs ,$page);
		  }
		else
           {
		     if (!($qlet[$portlet_id]['show_pager']))
			  {
			    $rs = $db->PageExecute($stmt, $recs ,$page);
			   }
			   else
		       {$rs = $db->Execute($SQL);}
		   }
        if ($rs)
		{
			rs2xml( $rs, $page,$portlet_id, true);
		}
        else
            {
            elog(2,"report_engine.getXML error in resultset for SQL={SQL}");
        }
        

}
    catch(exception $e)
    {
        elog(5,"report_engine.getXML ".print_r($e,true));
    }

} //getXML





 function startsWith($needle, $haystack) 
 {
     return preg_match('/^'.preg_quote($needle)."/", $haystack);
 }

 function endsWith($needle, $haystack) 
 {
     return preg_match("/".preg_quote($needle) .'$/', $haystack);
 }


 /*
  *
  * for drill the portlet should have the single drill defined
  * $qlet['byproductcategory_q33']['drill']['column']=1; //just index of the column where the link should appear

$qlet['byproductcategory_q33']['drill']['url'] = 'http://www.infocaptor.com?x='; //P0 stands for the value of the first column, P1 stands for the value of the second column

  */
function rs2xml( &$rs, $page, $portlet_id, $id=false)
{

global $qlet;
elog(0,"report_engine.rs2xml  started");
try
{
header("Content-type: application/xhtml+xml;charset=utf-8");
	/*if ( stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml") ) {
  		header("Content-type: application/xhtml+xml;charset=utf-8"); } else {
  		header("Content-type: text/xml;charset=utf-8");
	}*/

	 $maxRows=$rs->MaxRecordCount();
	 elog(0,"Total rows = {$maxRows}");
   $$echo_str.= "";
  $et = ">";
  //$$echo_str.= "<?xml version='1.0' encoding='utf-8'?{$et}\n";
  try
  {
	  if( $page > $rs->LastPageNo())
	  {
		$page=$rs->LastPageNo();
	  } 	
	  
  elog(0,"report_engine.rs2xml set the page number = {$page} > {$rs->LastPageNo()}");
  }
  catch (exception $ex1)
  {
    elog(1,"error while setting the page number");
	
  }
  
  if ($page<=0) $page=1;

	if ($maxRows<=0) 
	{
	  
	  $echo_str.=  "<rows>";
		$echo_str.=  "<page>"."1"."</page>";
		$echo_str.=  "<total>"."1"."</total>";
		$echo_str.=  "<records>"."0"."</records>";
	  $echo_str.="</rows>";
	  elog(0,$echo_str);
	  echo $echo_str;
	  return;
	}
	else
	{
		  $echo_str.=  "<rows>";
			$echo_str.=  "<page>".$page."</page>";
			$echo_str.=  "<total>".$rs->LastPageNo()."</total>";
			$echo_str.=  "<records>".$maxRows."</records>";
	}
	 /* $echo_str.=  "<userdata name=\"x\"> 240.00 </userdata>";
  $echo_str.=  "<userdata name=\"tax\"> 40.00 </userdata>";
  $echo_str.=  "<userdata name=\"total\"> 280.00 </userdata>";
  $echo_str.=  "<userdata name=\"invid\"> Total </userdata>";*/
  elog(0,"rs2xml initiating movefirst");
  $rs->MoveFirst();
  elog(0,"rs2xml initiated movefirst");

  $fldcnt = $rs->FieldCount();
    elog(1,"report_engine.rs2xml() columns = {$fldcnt}");
  elog(-2,"report_engine.rs2xml() result = ".print_r($rs,true));
  if( $id ) $start = 0; else $start=1;
  $row=0;
    elog(0,"rs2xml parsing resultset");

  while (!$rs->EOF) {
    $echo_str.=  "<row id='".$rs->fields[0]."'>";
        $row_str="";
    for ($i=$start; $i<$fldcnt; $i++) 
    {
        $v = $rs->fields[$i];
        $fld = $rs->FetchField($i);
        $type = $rs->MetaType($fld->type);
        if ($log_level<0)
            {
                $row_str.="{$v}(type={$type}), ";
            }
        else
            {
            
               if (isset($qlet[$portlet_id]['drill']['column']))
                   {
                   if ($qlet[$portlet_id]['drill']['column']==$i)
                       {
                            $link=$qlet[$portlet_id]['drill']['url'].$v;
                            $tag=<<<EOD
<a href="{$link}" target="_new">{$v}</a>;
EOD;
                            $v=$tag;
                        }
                   }
                $row_str.="{$v}, ";
            }
        $echo_str.=  "<cell>".$v."</cell>";
        /*
        switch($type) {
        case 'N':
            $echo_str.=  "<cell>",$v,'</cell>';
            break;
        case 'I':
            $echo_str.=  "<cell>",$v,'</cell>';
            break;
        case 'D':
            $echo_str.=  "<cell>",$v,'</cell>';
            break;
        case 'T':
             $echo_str.=  "<cell>",$v,'</cell>';
            break;
        default :
		    if (endsWith("Subtotal",$v))
			{
              $echo_str.=  "<cell><![CDATA[ <font color=red>",$v," </font>]]></cell>";
			}
            else if ($v=="Grand Total") 
            {
			   $echo_str.=  "<cell><![CDATA[ <font color=blue>",$v," </font>]]></cell>";
            }			
			else $echo_str.=  "<cell><![CDATA[",$v,"]]></cell>";
        }
        */
    }
    $rs->MoveNext();
    $row++;
    $echo_str.=  '</row>';
    elog(-2,"$row_cnt : [$row_str ]");
  }
  $echo_str.=  '</rows>';
  elog(0,"echoing the result set");
  echo $echo_str;
  elog(0,$echo_str);
}
    catch(exception $e)
    {
        elog(5,"report_engine.rs2xml ".print_r($e,true));
    }
}




function getDataAsHtml($portlet_id)
{
elog(0,"report_engine.getDataAsHtml  started");

global $db_array; //get all the database settings
global $database_config;

global $report_file;
global $qlet;
global $plet;
global $dashboard_id;
global $_PVAL;
global $debug;
//include the information needed for the connection to MySQL data base server.
// we store here username, database and password

$data_array = getDataArray($portlet_id);

$html_str = <<< EOD
<html>
<head>
       <title>{$qlet[$portlet_id]['name']}</title>
       <link rel="stylesheet" type="text/css" media="screen" href="jqueryui/css/redmond/jquery-ui-1.7.2.custom.css">
       <link rel="stylesheet" type="text/css" media="screen" href="report_engine.css" />
       <link rel="stylesheet" type="text/css" media="screen" href="{$portlet_id}.css" />
</head>
<body>

EOD;

       echo $html_str;


       //$data_array['number_of_rows']
       //$data_array['number_of_columns']
       //$data_array['data'][$row][$i]
  echo "<table class='ui-widget' border=1>\n";
  echo "<thead class='ui-widget-header'>
    	<tr>\n";

  for ($ci=0;$ci<$data_array['number_of_columns'];$ci++)
  {
       echo "<th scope=\"col\">{$data_array['column_names'][$ci]}</th>\n";
  }
  echo "</tr>\n </thead> \n";
  echo "<tbody class='ui-widget-content'>\n";

  for ($ri=0;$ri < $data_array['number_of_rows'];$ri++)
  {
      echo "<tr>\n";
      for ($ci=0;$ci < $data_array['number_of_columns'];$ci++)
      {
          echo "<td>{$data_array['data'][$ri][$ci]}  </td>\n";

      }
      echo "</tr>\n";
  }
  echo "</tbody>\n";
  echo "</table>";
  echo "</body>";
  echo "</html>";


}


function getDataAsHtml1($portlet_id)
{
elog(0,"report_engine.getDataAsHtml1  started");

global $db_array; //get all the database settings
global $database_config;

global $report_file;
global $qlet;
global $plet;
global $dashboard_id;
global $_PVAL;
global $debug;
//include the information needed for the connection to MySQL data base server.
// we store here username, database and password

$data_array = getDataArray($portlet_id);

$html_str = <<< EOD
<html>
<head>
       <title>{$qlet[$portlet_id]['name']}</title>

       <link rel="stylesheet" type="text/css" media="screen" href="report_engine.css" />
       <link rel="stylesheet" type="text/css" media="screen" href="{$portlet_id}.css" />
</head>
<body>

EOD;

       echo $html_str;


       //$data_array['number_of_rows']
       //$data_array['number_of_columns']
       //$data_array['data'][$row][$i]
  echo "<table id=\"data_table\">\n";
  echo "<thead>
    	<tr>\n";

  for ($ci=0;$ci<$data_array['number_of_columns'];$ci++)
  {
       echo "<th scope=\"col\">{$data_array['column_names'][$ci]}</th>\n";
  }
  echo "</tr>\n </thead> \n";
  echo "<tbody>\n";

  for ($ri=0;$ri < $data_array['number_of_rows'];$ri++)
  {
      echo "<tr>\n";
      for ($ci=0;$ci < $data_array['number_of_columns'];$ci++)
      {
          echo "<td>{$data_array['data'][$ri][$ci]}  </td>\n";

      }
      echo "</tr>\n";
  }
  echo "</tbody>\n";
  echo "</table>";
  echo "</body>";
  echo "</html>";


}

//get the sql results in an array -
function getDataArray($portlet_id)
{

elog(0,"report_engine.getDataArray  started");
global $db_array; //get all the database settings
global $database_config;

global $report_file;
global $qlet;
global $plet;
global $dashboard_id;
global $_PVAL;
global $debug;
//include the information needed for the connection to MySQL data base server.
// we store here username, database and password



$page=1; //defaulted to zero, since we are using the page execute function. For charts it will always be zero
 $recs=100;



$db=getConnection($qlet[$portlet_id]['connection']);
/*
// connect to the MySQL database server
   $db = ADONewConnection($db_array[$database_config]['type']);
    //$db->debug = true;
    $db->Connect($db_array[$database_config]['host'].":".$db_array[$database_config]['port'], $db_array[$database_config]['user']
	, $db_array[$database_config]['pass'], $db_array[$database_config]['name']);
if (!$db) die("Connection failed for ".$db_array[$database_config]['host'].":".$db_array[$database_config]['port']." > ".$db_array[$database_config]['user']
." > ".$db_array[$database_config]['pass']." > ".$db_array[$database_config]['name']);
*/
//	print_r($_PVAL);

$SQL = $qlet[$portlet_id]['sql'];
$SQL = processSqlParam($SQL);


$_SESSION["log_".$report_file][$portlet_id]['recs']=$recs;
$_SESSION["log_".$report_file][$portlet_id]['sql']=$SQL;

//        $stmt = $db->Prepare($SQL);
//        $rs = $db->Execute($stmt, $recs ,$page);
		
		elog(0,"report_engine.getDataArray sql = {$SQL}");
        $stmt = $db->Prepare($SQL);
		if ($db_array[$qlet[$portlet_id]['connection']]['type'] == 'oci8')
		  {
		    $rs = $db->Execute($stmt);//, $recs ,$page);
		  }
		else
           {
		     if (!($qlet[$portlet_id]['show_pager']))
			  {
			    $rs = $db->PageExecute($stmt, $recs ,$page);
			   }
			   else
		       {$rs = $db->Execute($SQL);}
		   }
		   
  if ($rs)
  {
          $rs->MoveFirst();
          $fldcnt = $rs->FieldCount(); //number of columns
          $data_array['number_of_columns']=$fldcnt;
          //get all column names
          for ($fi=0; $fi<$fldcnt; $fi++)
          {
                    $fld = $rs->FetchField($fi);
                    $data_array['column_names'][$fi]=$fld->name;
                  //  echo $column_name[$fi];
          }

          $row=0;


          while (!$rs->EOF)
          {

            for ($i=0; $i<$fldcnt; $i++)
            {
                $v = $rs->fields[$i];
                $data_array['data'][$row][$i]=$v; //
                //echo $result_data[$i][$row];//
                //
                //$fld = $rs->FetchField($i);
                //$type = $rs->MetaType($fld->type);

            }
            $rs->MoveNext();
            $row++;

          }
          $data_array['number_of_rows']=$row;

  }

return $data_array;

} //getdataarray


function getChartXML($portlet_id)
{
elog(0,"report_engine.getChartXML  started");
try
{
    global $db_array; //get all the database settings
global $database_config;

global $report_file;
global $qlet;
global $plet;
global $dashboard_id;
global $_PVAL;
global $debug;
//include the information needed for the connection to MySQL data base server.
// we store here username, database and password



$page=1; //defaulted to zero, since we are using the page execute function. For charts it will always be zero
 $recs=100;



$db=getConnection($qlet[$portlet_id]['connection']);

/*
// connect to the MySQL database server
   $db = ADONewConnection($db_array[$database_config]['type']);
    //$db->debug = true;
    $db->Connect($db_array[$database_config]['host'].":".$db_array[$database_config]['port'], $db_array[$database_config]['user']
	, $db_array[$database_config]['pass'], $db_array[$database_config]['name']);
if (!$db) die("Connection failed for ".$db_array[$database_config]['host'].":".$db_array[$database_config]['port']." > ".$db_array[$database_config]['user']
." > ".$db_array[$database_config]['pass']." > ".$db_array[$database_config]['name']);
*/
//	print_r($_PVAL);

$SQL = $qlet[$portlet_id]['sql'];
$SQL = processSqlParam($SQL);


$_SESSION["log_".$report_file][$portlet_id]['recs']=$recs;
$_SESSION["log_".$report_file][$portlet_id]['sql']=$SQL;

        //$stmt = $db->Prepare($SQL);
        //$rs = $db->PageExecute($stmt, $recs ,$page);
        $rs = $db->Execute($SQL);
        if ($rs)
		{
			rs2chart( $db, $stmt, $rs, $page, $portlet_id);
		}
         else
         {
           echo "
               <chart> \n
      <license>JTAMVPF7P2O.H4X5CWK-2XOI1X0-7L</license>
      <chart_data>
      <row>
                         <string>No Data</string>
			<string>No data</string>
		</row>
		<row>
			<string>NA..</string>
			<number>0</number>
		</row>
      </chart_data>
                 </chart>         
                 ";    
         }


}
    catch(exception $e)
    {
        elog(5,"report_engine.getChartXML - sending No Data due to Error...");
        elog(5,"report_engine.getChartXML ".print_r($e,true));
        echo "
               <chart> \n
      <license>JTAMVPF7P2O.H4X5CWK-2XOI1X0-7L</license>
      <chart_data>
      <row>
                         <string>No Data</string>
			<string>No data</string>
		</row>
		<row>
			<string>NA..</string>
			<number>0</number>
		</row>
      </chart_data>
                 </chart>
                 ";
    }


} //getChartXML


/**
 *
 * @param <type> $needle
 * @param <type> $haystack
 * @return <type>
 * This function converts the result set into appropriate chart data for flash engine
 * Don't see why you need an 'includeif' function at all.  include() will
not stop the script (fatal error) if the file isn't there like require()
will.  include() will only throw an error which you can supress with '@'

@include ( "nonexistant.txt" )

include() will also return true or false.  So if you want to run some
code only if the include file is there...

if ( @include ( "thisfile.txt" ) ) {
	//  do this
	some code;
}

 */
function rs2chart(&$db, &$stmt,  &$rs, $page, $portlet_id)
{


elog(0,"report_engine.rs2Chart  started");
try
{
    global $qlet;
global $dashboard_id;
global $url_param_str;
global $dashboard_report;
global $report_file;

  $rs->MoveFirst();
  $column_cnt = $rs->FieldCount(); //number of columns
//echo "no of columns -> ".$fndcnt;

  //get all column names
  for ($fi=0; $fi<$column_cnt; $fi++)
  {
            $fld = $rs->FetchField($fi);
            $column_name[$fi]=$fld->name;
          //  echo $column_name[$fi];
  }

  $row=0;

 
//echo "no of columns -> ".$column_cnt;
//print_r($column_name);
  $column_cnt;
  while (!$rs->EOF && $row< $qlet[$portlet_id]['max_rows'])
  {

    for ($i=0; $i<$column_cnt; $i++)
    {
        $v = $rs->fields[$i];
        $result_data[$i][$row]=$v; //
        //echo $result_data[$i][$row];//
        //
        //$fld = $rs->FetchField($i);
        //$type = $rs->MetaType($fld->type);
   
    }
	
	if ($qlet[$portlet_id]['type']==  'chart_stacked column' ||$qlet[$portlet_id]['type']==  'chart_3d stacked column')	
	{
	  //build the required arrays for stack column, required 3 columns from the results is assumed here
	  $col1[$result_data[0][$row]]=1;
	  $col2[$result_data[1][$row]]=1;
	  $pivot[$result_data[1][$row]][$result_data[0][$row]]=$result_data[2][$row];
	}
    $rs->MoveNext();
    $row++;
    
  }

  //catch any error or no rows found exception
  if ($row<=0)
      {
                 echo "
               <chart> \n
      <license>JTAMVPF7P2O.H4X5CWK-2XOI1X0-7L</license>
      <column_cnt={$column_cnt}/>
      <row_cnt={$row}/>

      <chart_data>
      <row>
                         <string>No Data</string>
			<string>No data</string>
		</row>
		<row>
			<string>NA..</string>
			<number>0</number>
		</row>
      </chart_data>
                 </chart>
                 ";
                 return;


  }

  //call the chart data hook. The hook has the power to modify the data before presenting to the chart engine.
 $link_xml="";
 /*
  "
      <link>

          <area x='0'
            y='0'
            width='{$qlet[$portlet_id]['width']}'
            height='{$qlet[$portlet_id]['height']}'
            url='report_engine.php?mode=HTMLTABLE&portlet={$portlet_id}&report=$report_file'
            target='_new'
            alpha='75'
            />
 </link>
";
*/
$chart_xml=
  "<chart> \n
      <license>JTAMVPF7P2O.H4X5CWK-2XOI1X0-7L</license>
      <column_cnt={$column_cnt}/>
      <row_cnt={$row}/>
  ". $qlet[$portlet_id]['template'].
  "\n


   </chart>\n
  ";

$chart_data="
      <chart_data> \n
  ";

$column_total=0;
$pie_chart=false;
if ($qlet[$portlet_id]['type']==  'chart_3d pie' ||$qlet[$portlet_id]['type']==  'chart_pie')
    {
      $pie_chart=true;
      $column_total = getColumnTotal($result_data[1]);
    }

if ($qlet[$portlet_id]['type']==  'chart_stacked column' ||$qlet[$portlet_id]['type']==  'chart_3d stacked column')	
{
elog(0,"report_engine.rs2Chart pivot".print_r($pivot,true));
elog(0,"just the categories");
$row1="<row>\n     <null/>\n";
 foreach ($col1 as $k => $v)
 {
	$row1.="     <string>".$k."</string>\n";
 }
$row1.="</row>\n";
//elog(0,$row1);
$output="";
//col2 is the resultset column index 2
//col1 is the resultset column index 1
//but in the pivot, col2 is the top and then comes col1
//col2 keys form the x axis
//col1 keys form the stack divisions
foreach ($col2 as $xval => $v1)
{
	$output.="<row>\n     <string>{$xval}</string>\n";
	foreach ($col1 as $stack_val => $v2)
	{
		$val=$pivot[$xval][$stack_val];
		if (!isset($val)) $val="0";
			    if ($qlet[$portlet_id]['display_tooltip']) //should we display tooltip, why not?
				{   
                  $tooltip = $qlet[$portlet_id]['tooltip_template'];
                   $tooltip=str_replace("#label#",$xval." - ".$stack_val,$tooltip);
                   $tooltip=str_replace("#value#",$val,$tooltip);

                }
		$output.="     <number  tooltip=\"{$tooltip}\">{$val}</number>\n";
		//$output.="     <number>{$val}</number>\n";
	}
	$output.="</row>\n";
}
 /*foreach ($pivot as $k1 => $v1)
 {
	$output.="<row>\n     <string>{$k1}</string>\n";
	foreach($v1 as $c1 => $val)
	{
	            if ($qlet[$portlet_id]['display_tooltip']) //should we display tooltip, why not?
				{   
                  $tooltip = $qlet[$portlet_id]['tooltip_template'];
                   $tooltip=str_replace("#label#",$k1." - ".$c1,$tooltip);
                   $tooltip=str_replace("#value#",$val,$tooltip);

                }


		$output.="     <number  tooltip=\"{$tooltip}\">{$val}</number>\n";
	}
	$output.="</row>\n";
 }*/

//elog(0,"stk output".$output);

$chart_data.=$row1;
$chart_data.=$output;

  
  
}
else
{
	
  //now build the chart data XMLpreg_replace("/[^a-zA-Z0-9\s]/", "", $string)
  for ($x=0; $x<$column_cnt; $x++)
  {

      $chart_data.= "       <row>\n";
            $chart_data.= "            <string>{$column_name[$x]}</string>\n";
      for ($y=0; $y<$row; $y++)
      {
          if ($x==0)
          {
              $c1=preg_replace("/[^a-zA-Z0-9\s]/","", $result_data[$x][$y]);
              $len_max=$qlet[$portlet_id]['legend']['label_max_length'];
              if (strlen($c1)>$len_max) $c1=substr($c1,0,$len_max)."..";
              
              $chart_data.= "            <string>{$c1}</string>\n";
          }
          else
          {
              $percent_value=0;
              $percent_value_str=" ";
              $tooltip="";
              if ($qlet[$portlet_id]['display_tooltip']) //should we display tooltip, why not?
              {   
                  $tooltip = $qlet[$portlet_id]['tooltip_template'];
                  if ($pie_chart && $column_total<>0)
                  {
                    $percent_value = ($result_data[$x][$y]*100)/$column_total;
                    $percent_value_str= number_format($percent_value,2,'.',',');
                    $tooltip=str_replace("#percent#",$percent_value_str,$tooltip);
                  }
                   $tooltip=str_replace("#label#",$result_data[0][$y],$tooltip);
                   $tooltip=str_replace("#value#",$result_data[$x][$y],$tooltip);

              }

            $chart_data.= "            <number tooltip=\"{$tooltip}\">{$result_data[$x][$y]}</number>\n";
          }
      }
      $chart_data.= "        </row>\n";
  }
  
} //else

  $chart_data.=
  "
      </chart_data>\n
  ";
  

$chart_xml = str_ireplace('#chart_type#', str_ireplace("chart_","",$qlet[$portlet_id]['type']), $chart_xml); //strip the chart_ prefix from the chart type
$chart_xml = str_ireplace('#chart_data#', $chart_data, $chart_xml);
$chart_xml = str_ireplace('#link_data#',$link_xml,$chart_xml);

elog(1,"report_engine.getChartXML = {$chart_xml}");
echo $chart_xml;
//echo "rocount = $row";
}
    catch(exception $e)
    {
        elog(5,"report_engine.getSQLArray ".print_r($e,true));
    }


  //now process all cached data

}

//useful for pie chart showing percent and number value
function getColumnTotal($column_data)
{
 elog(0,"report_engine.getColumnTotal  started");
    $cnt=count($column_data);
    $total=0;
    for ($i=0; $i<$cnt; $i++)
    {
        $total+=$column_data[$i];
    }
    return $total;
}
function getCSVFile($portlet_id)
{

global $db_array; //get all the database settings
global $database_config;

global $report_file;
global $qlet;
global $plet;
global $dashboard_id;
global $_PVAL;
global $debug;

try
{
//strtolower($str);
//str_replace("%body%", "black", "<body text='%body%'>");

$file_name = $portlet_id;

//$portlet_id="q1"; //--TODO-- use the array and generalize

header("Content-type: application/vnd.ms-excel");
header("Content-disposition:  attachment; filename=".$file_name."_" . date("Y-m-d").".csv");



$db=getConnection($qlet[$portlet_id]['connection']);

$SQL = $qlet[$portlet_id]['sql'];
$SQL = processSqlParam($SQL);

$rs = $db->Execute($SQL);


print rs2csv($rs); # return a string, CSV format

}
    catch(exception $e)
    {
        elog(2,"report_engine.getCSVfile ".print_r($e,true));
    }

}

function endSession()
{


}

///Utility functions
function nvl(&$var, $default = "")
{
    return isset($var) ? $var
                       : $default;
}

	//PHP function that generates the XML code to draw radial ticks
	function radialTicks ( $x_center, $y_center, $radius,  $length, $start_angle, $end_angle, $ticks_count, $thickness, $color )
        {
         elog(0,"report_engine.radialTicks  started");
            // echo "end ang= {$end_angle} , start ang= {$start_angle}, tick_count={$ticks_count}";
            if($ticks_count==0) $ticks_count=10;


            $increment=($end_angle-$start_angle)/($ticks_count);
            $ticks=" ";
		for ( $i=$start_angle; $i<=$end_angle; $i+=$increment ){
			$ticks.= "	<line x1='".($x_center+sin(deg2rad($i))*$radius)."' y1='".($y_center-cos(deg2rad($i))*$radius)."' x2='".($x_center+sin(deg2rad($i))*($radius+$length))."' y2='".($y_center-cos(deg2rad($i))*($radius+$length))."' thickness='".$thickness."' color='".$color."' /> \n";

		}

                if ($i<$end_angle)
                    {
               $ticks.= "	<line x1='".($x_center+sin(deg2rad($end_angle))*$radius)."' y1='".($y_center-cos(deg2rad($end_angle))*$radius)."' x2='".($x_center+sin(deg2rad($end_angle))*($radius+$length))."' y2='".($y_center-cos(deg2rad($end_angle))*($radius+$length))."' thickness='".$thickness."' color='".$color."' /> \n";
                    }
                return $ticks;
	}
	//====================================
	//PHP function that generates the XML code to draw radial numbers
	function radialNumbers ( $x_center, $y_center, $radius,  $start_number, $end_number, $start_angle, $end_angle, $ticks_count, $font_size, $color )
         {
            elog(0,"report_engine.radialNumbers  started");
            $tick_numbers=" ";
            $half_font_size=$font_size/2;
            $width=50;
            $half_width = $width/2;

		$number=$start_number;
                if($ticks_count==0) $ticks_count=10;
                $increment=($end_angle-$start_angle)/($ticks_count);

		for( $i=$start_angle; $i<=$end_angle; $i+=$increment )
                {


                    $tick_numbers .=
                    "	<text x='".($x_center+sin(deg2rad($i))*$radius - $half_width)."' y='".($y_center-cos(deg2rad($i))*$radius - $half_font_size)."' width='{$width}' height='20' size='".$font_size."' color='".$color."' align='center'  >".$number."</text> \n";
			$number += ($end_number-$start_number)/($ticks_count);

		}

                if ($i<$end_angle)
                    {
                $tick_numbers .=
                    "	<text x='".($x_center+sin(deg2rad($end_angle))*$radius - $half_width)."' y='".($y_center-cos(deg2rad($end_angle))*$radius - $half_font_size)."' width='{$width}' height='20' size='".$font_size."' color='".$color."' align='center'  >".$number."</text> \n";
			$number += ($end_number-$start_number)/($ticks_count);
                    }
                return $tick_numbers;
	}

//return the db handle after connection
function getConnection($connection_name)
{
elog(0,"report_engine.getConnection  started");
    global $dashboard_id;
global $dashboard_report;
global $report_file;
global $db_array;

elog(0,"report_engine.getConnection connection_name={$connection_name}");
elog(2,"report_engine.getConnection db_array=".print_r($db_array,true));
try
{
     //echo "connectio name => $connection_name";
    //   echo $db_array[$connection_name]['type'];
 if ($db_array[$connection_name]['type']=="excel")
  {
      $db =& ADONewConnection('odbc');


    if (!$db)
    {
        elog(2,"report_engine.getConnection db_array=".print_r($db_array,true));
          elog(2,"report_engine.get_connection !db".$db->ErrorMsg());
         return null;
    }

      //for excel files are locked when connection is established
      //so we copy the excel file to temporary session name file
      //during session maintenance the previous day sessions should be deleted and new ones created
      $originalExcelFile=realpath($db_array[$connection_name]['name']);

//                    $excelFile=$originalExcelFile;

      /*
      $newExcelFile="temp/xls".session_id().getAlphaNumeric($connection_name);

      if (file_exists($newExcelFile))
      {
          $excelFile=$newExcelFile;
      }
      else
      {
          if (copy($originalExcelFile,$newExcelFile))
          {
              $excelFile=$newExcelFile;

          }
          else
          {
              $excelFile=$originalExcelFile;
          }

      }
      */
      //echo $newExcelFile."<br>";
      //copy($originalExcelFile,)
      $excelFile=$originalExcelFile; // this is not needed when the caching logic is implemented
      $excelFile = realpath($excelFile);
      $excelDir = dirname($excelFile);
      //echo "dir=".$excelDir."\n<br>";
      //echo "file=".$excelFile."\n<br>";

      $db_url="Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq={$excelFile};DefaultDir={$excelDir}";
      //echo "url={$db_url}\n<br>";
      $db->Connect($db_url , '', '');
 
      $_SESSION["log_".$report_file][$connection]['error']=$db->ErrorMsg();

      return $db;
  }
 else if ($db_array[$connection_name]['type']=="access")
  {
      $db =& ADONewConnection('access');
      if (!$db)
    {
          elog(2,"report_engine.getConnection db_array=".print_r($db_array,true));
          elog(2,"report_engine.get_connection !db".$db->ErrorMsg());
        return null;
    }
      $originalAccessFile=realpath($db_array[$connection_name]['name']);

	$db_url = "Driver={Microsoft Access Driver (*.mdb,*.accdb)};Dbq={$originalAccessFile};Uid=Admin;Pwd=;";
        $db->Connect($db_url , '', '');

        $_SESSION["log_".$report_file][$connection]['error']=$db->ErrorMsg();

        return $db;
  }
  else  if ($db_array[$connection_name]['type']=="odbc")
  {
      $db =& ADONewConnection('odbc');
    if (!$db)
    {
        elog(2,"report_engine.getConnection db_array=".print_r($db_array,true));
          elog(2,"report_engine.get_connection !db".$db->ErrorMsg());
          return null;
    }
    $db->Connect($db_array[$connection_name]['host'], $db_array[$connection_name]['user']
	, $db_array[$connection_name]['pass'], $db_array[$connection_name]['name']);


        $_SESSION["log_".$report_file][$connection]['error']=$db->ErrorMsg();



    return $db;
  }
    else  if ($db_array[$connection_name]['type']=="db2_odbc")
  {
      $db =& ADONewConnection('odbc');
    if (!$db)
    {
        elog(2,"report_engine.getConnection db_array=".print_r($db_array,true));
          elog(2,"report_engine.get_connection !db".$db->ErrorMsg());
        return null;
    }
    $db->Connect($db_array[$connection_name]['name'], $db_array[$connection_name]['user']
	, $db_array[$connection_name]['pass']);


        $_SESSION["log_".$report_file][$connection]['error']=$db->ErrorMsg();



    return $db;
  }
  else  if ($db_array[$connection_name]['type']=="mssql")
  {

      $db =& ADONewConnection('mssql');
      if (!$db)
    {
          elog(2,"report_engine.getConnection db_array=".print_r($db_array,true));
          elog(2,"report_engine.get_connection !db".$db->ErrorMsg());
         return null;
    }
//$db->debug = true;
    $db->Connect($db_array[$connection_name]['host'].",".$db_array[$connection_name]['port'], $db_array[$connection_name]['user']
	, $db_array[$connection_name]['pass'], $db_array[$connection_name]['name']);

    $db->Execute('SET QUOTED_IDENTIFIER ON');

       $_SESSION["log_".$report_file][$connection]['error']=$db->ErrorMsg();
    return $db;
  }
    // echo "connectio name => $connection_name";
     //  echo $db_array[$connection_name]['type'];
   elog(2,"report_engine.getConnection before calling connection db_array=".print_r($db_array,true));
   try
   {
       $db = NewADOConnection($db_array[$connection_name]['type']);
   }
   catch (exception $e)
   {
       elog(2,"report_engine.getConnection exception at NewADOConnection".print_r($e,true));
   }
    if (!$db)
    {
        elog(2,"report_engine.getConnection db_array=".print_r($db_array,true));
          elog(2,"report_engine.get_connection !db".$db->ErrorMsg());
        return null;
    }
    //$db->debug = true;
    elog(2,"report_engine.getConnection now calling the connect");
    try
    {
    $db->Connect($db_array[$connection_name]['host'].":".$db_array[$connection_name]['port'], $db_array[$connection_name]['user']
	, $db_array[$connection_name]['pass'], $db_array[$connection_name]['name']);
    elog(2,"report_engine.getConnection fetched database handle");
    }
   catch (exception $e)
   {
       elog(2,"report_engine.getConnection exception at db-Connect".print_r($e,true));
   }

   // $_SESSION["log_".$report_file][$connection]['error']=$db->ErrorMsg();

    elog(2,"report_engine.getConnection error connecting stage L");
    return $db;

}
catch(exception $e)
{
        elog(2,"report_engine.getConnection exception bottom getconnection".print_r($e,true));
        return null;
}

}


function getParameterStr()
{
elog(0,"report_engine.getParameterStr  started");

//include ($report_file.".php");
global $plet;
global $dashboard_id;
global $button_text;
global $qlet;
global $url_param_str;
global $plet_group;
global $dashboard_report;
global $d_options;

if (!isset($plet_group['list'])) return;

///BEGIN Parameter processing
//get list of date parameters and assign a date picker for each.define an empty variable first (don;t know if this reqd in php)
$dateHeader=" ";

$str=" ";

$resetFunction="
function resetFormInput()
{
";


foreach ($plet_group['list'] as $grp)
{

//each group is given a floating block
$str.="
<div style=\"display:block;float:left;margin: 0px 10px 0px 0px;\">
<fieldset>
<legend>{$plet_group[$grp]['label']}</legend>
";

//<label for="from_date">From Date </label>
      //<input type="text" name="from_date" id="from_date" size="10" value="$first_day_of_month">
foreach ($plet_group[$grp]['members'] as &$value)
{


 if (!($plet[$value]['raw_type']=="PLET" || $plet[$value]['raw_type']=="DATE" ||$plet[$value]['raw_type']=="FIELD")) continue;

 //first check if there is a GET value
 $currentValue=$_GET[$value]; //this value if set is coming from drill link

 if (!isset($currentValue)) //if there is no value coming from drill then check if there is a session value
 {
   $currentValue=$_SESSION[$dashboard_id][$value];
 }

 if (!isset($currentValue))
 {
   $currentValue = $plet[$value]['default_value'];
 }

 //make sure we set the session variable with the default values. When the dashboard is loaded for the first time
 //the session variables are empty and so the portlets will not return any data. So during building of the parameters,
 //we set the session variables with default values. remember, the only time session variables are set is when the user
 //clicks on the go button on the dashboard. So do you display a blank dashboard or a dashboard with the default values
 //of the parameters
 if (!isset ($_SESSION[$dashboard_id]))
     {
       $_SESSION[$dashboard_id][$value]=$currentValue;
     }

  if ($plet[$value]['type']=="date")
  {
$dateStr = <<<DOD
	   $("#{$value}").datepicker({ dateFormat: '{$plet[$value]['format']}'});

DOD;

$dateHeader .= $dateStr;

  }

$field_name="x";
if ($use_plet_positions)
{
$div_class = <<<EOD

<div style="position:absolute; top:{$plet[$value]['y_position']}px; left:{$plet[$value]['x_position']}}px;>
EOD;
}
else
{
$div_class="\n ";
}
//<div style="position:absolute; top:{$plet[$value]['y_position']}px; left:{$plet[$value]['x_position']}}px;>

$field_label = <<<EOD

<label for="{$value}">{$plet[$value]['name']}</label>
EOD;

  if ($plet[$value]['type']=="text" || $plet[$value]['type']=="date")
{
$field_name= <<<EOD
 <input type="text" name="{$value}" id="{$value}" value="{$currentValue}"style="width:{$plet[$value]['width']}px;">
EOD;
  if ($plet[$value]['type']=="text")
  {
    $resetFunction.=" $(\"#{$value}\").val(\"\");\n";
  }
}
  else if ($plet[$value]['type']=="dynamic_lov"  )
{
$field_name= getSQLArray($value,$plet[$value]['sql']);

}
else if ($plet[$value]['type']=="static_lov"  )
{
  $field_name = getStaticArray($value);
}

    $str.= $div_class;
    $str.= $field_label;
	$str.= "\n".$field_name." &nbsp;";

if ($plet['position']=="FIXED")
{
	$str.= "\n</div>";
}

}

$str.="</fieldset>
</div>";

} //group for end

$resetFunction.="}";  //this variable builds the code that will reset all the parameter values to null or default

$param['reset_str']=$resetFunction;
$param['param_str']=$str;
$param['date_str']=$dateHeader;

return $param;

} //end getParameters


function getParameterStrFixed()
{
elog(0,"report_engine.getParameterStrFixed  started");

//include ($report_file.".php");
global $plet;
global $dashboard_id;
global $button_text;
global $qlet;
global $url_param_str;
global $plet_group;
global $dashboard_report;
global $use_plet_positions;
global $d_options;


if (!isset($plet_group['list'])) return;

///BEGIN Parameter processing
//get list of date parameters and assign a date picker for each.define an empty variable first (don;t know if this reqd in php)
$dateHeader=" ";

$str=" ";

$resetFunction="
function resetFormInput()
{
";


foreach ($plet_group['list'] as $grp)
{

//each group is given a floating block
$str.="
 <!--no group-->
";

//<label for="from_date">From Date </label>
      //<input type="text" name="from_date" id="from_date" size="10" value="$first_day_of_month">
foreach ($plet_group[$grp]['members'] as &$value)
{
 if (!($plet[$value]['raw_type']=="STATIC" || $plet[$value]['raw_type']=="PLET" || $plet[$value]['raw_type']=="DATE" ||$plet[$value]['raw_type']=="FIELD")) continue;

//first check if there is a GET value

 $currentValue=$_GET[$value]; //this value if set is coming from drill link

 if (!isset($currentValue)) //if there is no value coming from drill then check if there is a session value
 {
   $currentValue=$_SESSION[$dashboard_id][$value];
 }

 if (!isset($currentValue))
 {
   $currentValue = $plet[$value]['default_value'];
 }

 //make sure we set the session variable with the default values. When the dashboard is loaded for the first time
 //the session variables are empty and so the portlets will not return any data. So during building of the parameters,
 //we set the session variables with default values. remember, the only time session variables are set is when the user
 //clicks on the go button on the dashboard. So do you display a blank dashboard or a dashboard with the default values
 //of the parameters
 if (!isset ($_SESSION[$dashboard_id]))
     {
       $_SESSION[$dashboard_id][$value]=$currentValue;
     }

  if ($plet[$value]['type']=="date")
  {
$dateStr = <<<DOD
	   $("#{$value}").datepicker({ dateFormat: '{$plet[$value]['format']}'});

DOD;

$dateHeader .= $dateStr;

  }

$field_name="x";

$yp=$plet[$value]['y_position']+$d_options['top_button_offset'];

$div_class = <<<EOD

<div style="position:absolute; top:{$yp}px; left:{$plet[$value]['x_position']}px; width: {$plet[$value]['width']}px; height: {$plet[$value]['height']}px;">
EOD;

//<div style="position:absolute; top:{$plet[$value]['y_position']}px; left:{$plet[$value]['x_position']}}px;>

$field_label = <<<EOD

<label for="{$value}">{$plet[$value]['name']}</label>
EOD;

  if ($plet[$value]['type']=="text" || $plet[$value]['type']=="date")
{
$field_name= <<<EOD
 <input type="text" name="{$value}" id="{$value}" value="{$currentValue}"style="width:{$plet[$value]['width']}px; height:{$plet[$value]['height']}px;">
EOD;
  if ($plet[$value]['type']=="text")
  {
    $resetFunction.=" $(\"#{$value}\").val(\"\");\n";
  }
}
  else if ($plet[$value]['type']=="dynamic_lov"  )
{
$field_name= getSQLArray($value,$plet[$value]['sql']);

}
else if ($plet[$value]['type']=="static_lov"  )
{
  $field_name = getStaticArray($value);
}
else if ($plet[$value]['raw_type']=="STATIC")
{
     $displayText = str_replace("\n","<br>",$plet[$value]['sql']);
  $field_name = <<<POD
    <div style="background:{$plet[$value]['background_color']};color:{$plet[$value]['font_color']};{$plet[$value]['font']};">
{$displayText}
    </div>
POD;
}
    $str.= $div_class;
     $str.= $field_label;
	$str.= "\n".$field_name;

$str.="</div>\n\n";

}


} //group for end

$resetFunction.="}";  //this variable builds the code that will reset all the parameter values to null or default

$param['reset_str']=$resetFunction;
$param['param_str']=$str;
$param['date_str']=$dateHeader;

return $param;

} //end getParametersFixed


function validateLicense()
{
 elog(0,"report_engine.WorkerAgent  started");


   
    
    $valid=true;

    return $valid;
}
function GetDomain($url)
{
$nowww = preg_replace('/www\./','',$url);

$domain = parse_url($nowww);

if(!empty($domain["host"]))
    {
     return $domain["host"];
     } else
     {
     return $domain["path"];
     }

}
function terminate($message)
{
    echo "<h2>error#$message</h2>";
    return;
}

function decode($string,$key)
{
    $key = sha1($key);
    $strLen = strlen($string);
    $keyLen = strlen($key);
    $j = 0;
    for ($i = 0; $i < $strLen; $i+=2) {
        $ordStr = hexdec(base_convert(strrev(substr($string,$i,2)),36,16));
        if ($j == $keyLen) { $j = 0; }
        $ordKey = ord(substr($key,$j,1));
        $j++;
        $hash .= chr($ordStr - $ordKey);
    }
    return $hash;
}

function getAlphaNumeric($str)
{
    return preg_replace("/[^a-zA-Z0-9\.\s]/","", $str);
}


function sess_destroy($sess_id)
{
  deleteSessionFiles($sess_id);
}

function deleteSessionFiles($sess_id)
{
    $dir = 'temp/';
   foreach(glob($dir.'*.*') as $v)
   {
     echo $v;
     if (startsWith("temp/xls".$sess_id,$v))
     {
       unlink($v);
     }
   }
}

function open($save_path, $session_name)
{
//  global $sess_save_path;

  //$sess_save_path = $save_path;
  return(true);
}

function close()
{
  return(true);
}

function read($id)
{
  //global $sess_save_path;
  return true;
  //$sess_file = "$sess_save_path/sess_$id";
  //return (string) @file_get_contents($sess_file);
}

function write($id, $sess_data)
{
    return true;
  //global $sess_save_path;
/*
  $sess_file = "$sess_save_path/sess_$id";
  if ($fp = @fopen($sess_file, "w")) {
    $return = fwrite($fp, $sess_data);
    fclose($fp);
    return $return;
  } else {
    return(false);
  }
  */
}

function destroy($id)
{
  global $sess_save_path;
  sess_destroy($id);
  return true;
}

function gc($maxlifetime)
{
    /*
  global $sess_save_path;

  foreach (glob("$sess_save_path/sess_*") as $filename) {
    if (filemtime($filename) + $maxlifetime < time()) {
      @unlink($filename);
    }
  }
  */
  return true;
}

function engineErrorHandler($errno, $errstr, $errfile, $errline)
{


global $dashboard_id;
global $dashboard_report;
global $report_file;
global $debug;

    //include_once "error_util.php";


 elog(-1,"------ \n   errno={$errno} \n   errstr={$errstr} \n   errfile={$errfile} \n   errline={$errline}");
    switch ($errno) {
		case E_ERROR:
             elog(5,"report_engine. engineErrorHandler E_ERROR= ".errorKill($errstr));
	   break;
	case E_WARNING:
			elog(5,$errstr);
             elog(5,"report_engine. engineErrorHandler E_WARNING= ".errorKill($errstr));
                echo $errstr."<br>Some serious error.. Please check the <a href=\"".getLogFileName()."\">session log</a> for details";
              die();
	   break;
	case E_NOTICE:
             elog(-3,"report_engine. engineErrorHandler  E_NOTICE= ".errorKill($errstr));
  	//echo "-------->Run-time notices.";
	  // $_SESSION["log_".$report_file]['error_e_notice'][$errno."-".$errline]=errorKill($errstr);
	   break;
	

    case E_USER_ERROR:
         elog(-1,"report_engine. engineErrorHandler  E_USER_Error= ".errorKill($errstr));
       // $_SESSION["log_".$report_file]['error_e_user_error'][$errno."-".$errline]=errorKill($errstr);
        break;

    case E_USER_WARNING:
         elog(-2,"report_engine. engineErrorHandler  E_USER_WARNING= ".errorKill($errstr));
	//$_SESSION["log_".$report_file]['error_e_user_warning'][$errno."-".$errline]=errorKill($errstr);
        	
			
        break;

    case E_USER_NOTICE:
         elog(-3,"report_engine. engineErrorHandler  E_USER_NOTICE= ".errorKill($errstr));
    //$_SESSION["log_".$report_file]['error_e_user_notice'][$errno."-".$errline]=errorKill($errstr);
	
        break;

    default:
         elog(-1,"report_engine. engineErrorHandler  Other Error= ".errorKill($errstr));
       // $_SESSION["log_".$report_file]['error_e_other'][$errno."-".$errline]=errorKill($errstr);
	//echo "-----#### Other Error {$errno} #####------.";  
        	//errorKill($errstr); 
        break;
    }


    /* Don't execute PHP internal error handler */
    return true;
}

function getLogFileName()
{
    //$path_parts = pathinfo($report_file);
    //$log_file="log/".str_replace(".php", "", $path_parts['filename']);
    return "log/re_".session_id().".log";
}


 // pretty-print var_export
function var_format($v)
{
    return (str_replace(array("\n"," ","array"),
array("<br>","&nbsp;","&nbsp;<i>array</i>"),
var_export($v,true))."<br>");
}

function errorKill($info)
{

    $out="<br>MSG='$info'";
    $bt=debug_backtrace();
    $sp=0;
    $trace="";
    foreach($bt as $k=>$v)
    {
        extract($v);
        $file=substr($file,1+strrpos($file,"/"));

        $trace.=str_repeat("&nbsp;",++$sp); //spaces(++$sp);
        $trace.="file=$file, line=$line, function=$function<br>";
    }
    $out.="<br>".$trace;
    if(substr($info,0,4)=="XXX ") // special errrors when db is inaccessible
    {
        $out=str_replace("<br>","\n",$out);
        $out=str_replace("&nbsp;"," ",$out);

    }
  return $out;

}
function clear_log()
{
   $fd = fopen(getLogFileName(), "w"); 
   
// close file
fclose($fd);
}

function shutDownFunction()
{
    $error = error_get_last();
   // echo "shutting down..";
    print_r($error,true);
}

function elog($level, $msg)
{

 global $gs;


if (!($gs["logging_enabled"]=='Y' && $gs["log_level"]<=$level)) return;

// open file
$fd = fopen(getLogFileName(), "a");
// append date/time to message
$str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg;
// write string
fwrite($fd, $str . "\n");
// close file
fclose($fd);
}



?>