<?php
/**
* File di gestione della tabella dinamica dhtmlGrid. 
* Viene richiamato dallo script {@link scheda.php} e dalle funzioni javascript.
* 
* @package VFront
* @subpackage RPC
* @author Mario Marcello Verona <marcelloverona@gmail.com>
* @copyright 2007-2010 M.Marcello Verona
* @version 0.96 $Id: rpc.xmlgrid.php 951 2011-04-28 23:27:32Z marciuz $
* @license http://www.gnu.org/licenses/gpl.html GNU Public License
*/

require("./inc/conn.php");
require("./inc/func.comuni.php");
require("./inc/func.frontend.php");

proteggi(1);




/**
 * Da una query SQL viene restituito l'XML generato per la griglia dxhtmlGrid 
 *
 * @param string $sql
 * @param int $offset
 * @param string $filename
 * @param bool $header
 * @param string $PK
 * @return void
 */
function xmlize_grid($sql,$offset=0,$filename=null,$header=true,$PK=null){
	
	global  $vmsql, $vmreg;
	
	$q = $vmsql->query($sql);
	
	if($vmsql->num_rows($q)==0){
		
		return null;	
	}
	
	// Inizia a fare l'xml
	$offset++;
	
	$XML= ($header) ? "<?xml version='1.0' encoding='utf-8'?>\n" : "";
	
	$XML.="<rows>\n";
	
	while($RS=$vmsql->fetch_assoc($q)){
		
		
		
		
		# Se � un contesto di ricerca...
		if(isset($_GET['q'])){
			
			$RS['n_offset'] = (isset($RS['n_offset'])) ? $RS['n_offset']:0;
			
			# identificativo ($RS)
			$offset_ricerca=$RS['n_offset']+1;
			
			$XML.="\t".xmlize_campo('row',array("id"=>$RS['pk']))."\n";
			$XML.="\t\t<cell>".$offset_ricerca."</cell>\n";
			
		}
		else{
			# identificativo (offset)
			$XML.="\t".xmlize_campo('row',array("id"=>$RS['pk']))."\n";
			$XML.="\t\t<cell>".$offset."</cell>\n";
		}
		
		foreach($RS as $k=>$val){
			
					
			// Il campo speciale prendi valore imposta l'offset per la ricerca
			if($k!='pk'){
				
				$XML.="\t\t".xmlize_campo('cell',array());
				
				//$val = vf_utf8_encode(trim($val));
				$val = trim($val);
				
				if(isset($_SESSION['VF_VARS']['max_char_tabella']) && intval($_SESSION['VF_VARS']['max_char_tabella'])>0){
					
					if(strlen($val)>$_SESSION['VF_VARS']['max_char_tabella']) $val = substr($val,0,$_SESSION['VF_VARS']['max_char_tabella'])."...";
					
				}
				
				// togli new line e sostituisci gli spazi
				$val = str_replace(array(" ","-","\n","\r","\n\r","\r\n"),array("&nbsp;","&nbsp;","","","",""),$val);
				
				if($val!='' && !is_numeric($val)) $val="<![CDATA[".$val."]]>";
				
				$XML.=$val;
				$XML.="</cell>\n";
			}
		}
		
		$XML.="\t</row>\n";
		
		
		$offset++;
	}
	
	$XML.="</rows>\n";
	
	
	
	
	if(is_null($filename)){
		
		
		if ( stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml") ) { 
			header("Content-type: application/xhtml+xml"); 
		} 
		else { 
			header("Content-type: text/xml; charset=".FRONT_ENCODING); 
		}
		
		print $XML;
		
	}
	else{
		
		$fp =fopen($filename,"w");
		fwrite($fp,$XML);
		fclose($fp);
		return true;
	}
	
}


/**
 * Genera l'XML dal campo dato con gli eventuali attributi
 *
 * @param string $tag
 * @param array $attr
 * @return string
 */
function xmlize_campo($tag,$attr){
	
		$attributi="";
	
		foreach($attr as $k=>$val){
			
			$attributi .=" $k=\"$val\"";
		}
	
		return "<".$tag.$attributi.">";
	
}


##########################################################################################################

	
	$tabella = $_GET['t'];
	
	if(!is_tabella($tabella)){
		
		echo _("Non-existent table");
		exit;
	}
	
	// prendi la chiave primaria:
	$PK = prendi_PK($tabella);
	
	$OFFSET = (isset($_GET['rowsLoaded'])) ? intval($_GET['rowsLoaded']) : 0;
	// altro modo di prendere l'offset... e sovrascrivo.
	$OFFSET = (isset($_GET['of'])) ? intval($_GET['of']) : $OFFSET;
	
	// PRENDI CAMPI VISIBILI
//	$info_campi = prendi_colonne_frontend($tabella,"column_name",false);

	$sql_campi_tab="SELECT column_name , in_tipo, in_default 
					FROM {$db1['frontend']}{$db1['sep']}registro_col c, {$db1['frontend']}{$db1['sep']}registro_tab t 
					WHERE c.id_table=t.id_table
					AND t.table_name='$tabella'
					AND t.gid='".intval($_SESSION['gid'])."'
					AND c.in_table=1
					ORDER BY c.ordinal_position";
	
	$q_info_campi_tab = $vmreg->query($sql_campi_tab);
	
	/*$info_campi = $vmsql->fetch_row_all($q_info_campi_tab,true);
	
	
	
	list($column_name) = $info_campi;*/
	
	$column_name=array();
	
	while($RS=$vmreg->fetch_assoc($q_info_campi_tab)){
		
		if($RS['in_tipo']=='select_from' && $RS['in_default']!=''){
			
			// key field
			preg_match("|SELECT +([^,]+) *,(.+) *FROM *([a-z0-9_]+)(.*)|iu",$RS['in_default'],$fff);

			// Cerca alias per k
			$k =(preg_match("' +([\w]+) *$'",trim($fff[1]),$alias_k)) ? $alias_k[1] : 'k';
			$print_k = ($k=='k') ? 'k' : '';

			// Cerca alias per v
			$v =(preg_match("' +([\w]+) *$'",trim($fff[2]),$alias_v)) ? $alias_v[1] : 'v';
			$print_v = ($v=='v') ? 'v' : '';

			$pre_query = "SELECT {$fff[1]} AS $print_k , {$fff[2]} AS $print_v FROM {$fff[3]} {$fff[4]} ";


			
		//	$column_name[]="(SELECT {$fff[2]} FROM {$fff[3]} t2 WHERE t2.{$fff[1]}=t1.{$RS['column_name']}) as {$RS['column_name']}";
			$column_name[]="(SELECT $v FROM ($pre_query) t2 WHERE $k=t1.{$RS['column_name']}) as {$RS['column_name']}";
		}
		
		else $column_name[]=$RS['column_name'];
	}
	
	
	unset($info_campi);
	

	// Prendi la variabile di LIMIT
	$LIMIT = (isset($_SESSION['VF_VARS']['n_record_tabella']) && ($_SESSION['VF_VARS']['n_record_tabella']>0)) 
			? $_SESSION['VF_VARS']['n_record_tabella'] : 20;
			
	// Prendi la variabile di LIMIT RICERCA
	$LIMIT_SEARCH = (isset($_SESSION['VF_VARS']['search_limit_results']) && ($_SESSION['VF_VARS']['search_limit_results']>0)) 
			? $_SESSION['VF_VARS']['search_limit_results'] : 1000;
	
	$campi_vis=implode(',',$column_name);
	
	
	// Genera l'order BY
	if(isset($_GET['ord'])){
	
		$orderby_val = $vmsql->escape($_GET['ord']);
		$ORDERBY = (is_campo($orderby_val)) ? "ORDER BY ".$orderby_val : "";
		
	}
	else{
		
		$orderby_val = prendi_orderby($tabella,$_SESSION['gid']);		
		$ORDERBY = ($orderby_val!="") ? "ORDER BY ".$orderby_val : "";	
		
	}
	
	
	

	
		
		
		
	######################################################################
	#
	#	RISPOSTA DI RICERCA CON MOLTI RISULTATI:
	#
	#
	
	if(isset($_GET['q'])){
		$ids = str_replace("|" , "','" , $vmsql->escape($_GET['q']));
	
	
		
		
		$WHERE = " WHERE $PK IN ('".$ids."') ";
		
		$orderby_campo = str_replace(array("ASC","DESC"),"",$orderby_val);
		
		// Imposto un alias per 
		$campi_vis_rep = str_replace("$orderby_campo", "$orderby_campo as prendi_valore", $campi_vis);
		
		$sql ="SELECT $PK as pk, $campi_vis ". 
		"
		  FROM $tabella t1
		  $WHERE
		  $ORDERBY 
		  ".$vmsql->limit($LIMIT_SEARCH,$OFFSET);
		
	}
	
	

	######################################################################
	#
	#	TABELLA NORMALE
	
	else {
		
		 $sql="SELECT $PK as pk, $campi_vis 
		  FROM $tabella t1
		  $ORDERBY 
		  ".$vmsql->limit($LIMIT,$OFFSET);
	}
	
	
	 
	
	// mando il file
	//	DEBUG : 
	//  xmlize_grid($sql,$OFFSET,'test.xml',true,$PK);
	// rpc_debug($sql);
	
	xmlize_grid($sql,$OFFSET,null,true,$PK);
	



?>