* insertar
* borrar
* actualizar
* seleccionar
* borrar
* visibles
*
*
* @version $Id: IgepComunicacion.php,v 1.156 2011-02-21 09:45:03 afelixf Exp $
* @author David:
* @author Keka:
* @author Vero:
* @author Raquel:
* @author Toni:
* @package gvHIDRA
*/
class IgepComunicacion {
/**
* matriz de datos relativos a los campos Dependientes o Calculados
*
* @var array
*/
public $m_datosCamposDependientes;
/**
* Entero referencia a la fila actual
*
* @var integer
*/
public $int_filaSeleccionada;
/**
* matriz de datos relativos a la ventana de Seleccion
*
* @var array
*/
public $m_datosVentanaSeleccion;
/**
* matriz de datos visibles en el panel. Es decir que capturamos todo lo que se vea independientemente de si se les ha practicado algun cambio o no.
*
* @var array
*/
public $m_datos_visiblesTpl;
/**
* Array de definición de los campos que aparecen en un panel
*
* @var array
*/
public $descCampoPanel;
/**
* Array que contiene un conjunto de punteros que recrean los datos insertados en la tpl
*
* @var array
*/
public $m_datos_insertarTpl;
/**
* Array que contiene un conjunto de punteros que recrean los datos modificados en la tpl
*
* @var array
*/
public $m_datos_actualizarTpl;
/**
* Array que contiene un conjunto de punteros que recrean los datos borrados en la tpl
*
* @var array
*/
public $m_datos_borrarTpl;
/**
* Array que contiene un conjunto de punteros que recrean los datos a ser editados en la tpl
*
* @var array
*/
public $m_datos_seleccionarTpl;
/**
* Array que contiene un conjunto de punteros que recrean los datos a ser editados en la tpl
*
* @var array
*/
public $m_datos_postConsultarTpl;
/**
* Array que contiene un conjunto de punteros que recrean los datos seleccionados del padre
* en el método recargar. Se gasta para almacenar la tupla seleccionada por el padre para que
* el programador tenga acceso a esta información.
*
* @var array
*/
public $m_datos_seleccionarPadreTpl;
/**
* Array que contiene los datos del panel de busqueda en el formato TPL
*
* @var array
*/
public $m_datos_buscarTpl;
/**
* Array que contiene los datos de los ficheros que se han subido por Upload
*
* @var array
*/
public $m_datosFicherosUpLoad;
/**
* Array
*
* @var array
*/
public $m_datos_iniciarVentanaTpl;
/**
* Objeto que contiene los destinos de posibles de la acción.
*
* @var array
*/
private $_actionMapping;
/**
* variable para acumular los errores de transformacion en data2Arrays y leerlos en checkDataTypes
*/
private $_transformErrors;
/**
* variable para saber si desde el formulario quieren realizar la validación de datos
*/
private $_checkForm = 1;
/**
* variable privada para identificar el panel gvhidra que está operando
* fil Filtro
* lis Listado
* edi Ficha
*/
private $_panel = null;
/**
* Constructor. Recibe como parámetro el matching con el que trabajará el objeto
*
* @access public
* @param array $matching
*/
public function __construct($descCampoPanel = "") {
$this->descCampoPanel = $descCampoPanel;
$this->m_auxIndices_insertar = array ();
$this->m_auxIndices_borrar = array ();
$this->m_auxIndices_actualizar = array ();
$this->m_auxIndices_seleccionar = array ();
$this->_panel = $_REQUEST['gvhpanel'];
}
/**************************************FUNCIONES DE CONSTRUCCIÓN**************************************/
/**
* Recupera los datos de pantalla y los almacena en estructuras conocidas por el Framework.
* Esto permite un acceso coherente a los datos por parte del programador y del propio sistema.
*
* @access public
* @return void
*/
public function data2Arrays() {
//Checkform
if(isset($_REQUEST['checkForm'])) {
$this->_checkForm = $_REQUEST['checkForm'];
unset($_REQUEST['checkForm']);
}
$this->_panel = $_REQUEST['gvhpanel'];
$this->data2ArraysJson();
}
private function fileUploadConvert($obj) {
$arr = array();
$arr['name'] = $obj->name;
$arr['type'] = $obj->type;
$arr['tmp_name'] = $obj->tmp_name;
$arr['error'] = $obj->error;
$arr['size'] = $obj->size;
return $arr;
}
private function data2ArraysJson() {
/*La estructura de los arrays es la siguiente:
[data] =>
[fila] =>
[estado]=> valor, [campos]=> valor
*/
//Como la forma de seleccionar cambia de un Ficha a un Tabla, tenemos q comprobar de donde viene
$filaActual = 0;
if(isset($_REQUEST['claseManejadora'])) {
$claseManejadora = $_REQUEST['claseManejadora'];
//Si la variable pagActual tiene valor entonces se trata de un Ficha.
if($this->_panel=='edi') {
$filaActual = $_REQUEST['panel']['pagActive'];
}
}
$this->_transformErrors = array();
if(isset($_REQUEST['data'])) {
foreach ($_REQUEST['data'] as $index => $row) {
switch($row['gvhJS_state']) {
case 'insertada':
foreach($row['gvhJS_fields'] as $name => $value) {
if($value['CWPlugin']=='cwupload') {
if(empty($value['files'])) {
$this->m_datosFicherosUpLoad[$index][$name] = array('error' =>array('0'=>4));
}
else {
$val = json_decode($value['files']);
$this->m_datosFicherosUpLoad[$index][$name] = $this->fileUploadConvert($val->file);
}
}
else {
$val = ($value['value']);
$this->transform_User2FW($val,@$this->descCampoPanel[$name]['tipo']);
if ($val != '') {
//m_datos_insertar
$this->m_datos_insertarTpl[$index][$name] = $val;
//Vamos acumularlos como datos Visibles
$this->m_datos_visiblesTpl[$index][$name] = $val;
}
else {
//Para controlar el tema de los obligatorios en estos casos lo introducimos para que salte el error
if(@$this->descCampoPanel[$name]['required'])
$this->m_datos_insertarTpl[$index][$name] = $val;
}
}
}
array_push($this->m_auxIndices_insertar, $index);
//Para almacenar la fila actual
$this->int_filaActual = $index;
break;
case 'modificada':
foreach($row['gvhJS_fields'] as $name => $value) {
if($value['CWPlugin']=='cwupload') {
if(empty($value['files'])) {
$this->m_datosFicherosUpLoad[$index][$name] = array('error' =>array('0'=>4));
}
else {
$val = json_decode($value['files']);
$this->m_datosFicherosUpLoad[$index][$name] = $this->fileUploadConvert($val->file);
}
}
else {
$val = ($value['value']);
$this->transform_User2FW($val,@$this->descCampoPanel[$name]['tipo']);
$this->m_datos_actualizarTpl[$index][$name] = $val;
$valueAnterior = ($value['valueOld']);
$this->transform_User2FW($valueAnterior,@$this->descCampoPanel[$name]['tipo']);
$this->m_datos_antiguosTpl[$index][$name] = $valueAnterior;
//Vamos acumularlos como datos Visibles
$this->m_datos_visiblesTpl[$index][$name] = $val;
}
}
$errs_tr = ConfigFramework::getTransformErrors();
array_push($this->m_auxIndices_actualizar, $index);
if($row['gvhJS_selected'] == 'selected')
{
$this->int_filaActual = $index;
}
else
{
$this->int_filaActual = $filaActual;
}
break;
case 'borrada':
foreach($row['gvhJS_fields'] as $name => $value) {
$val = ($value['value']);
$this->transform_User2FW($val,@$this->descCampoPanel[$name]['tipo']);
$this->m_datos_borrarTpl[$index][$name] = $val;
$valueAnterior = ($value['valueOld']);
$this->transform_User2FW($valueAnterior,@$this->descCampoPanel[$name]['tipo']);
$this->m_datos_antiguosTpl[$index][$name] = $valueAnterior;
//Vamos acumularlos como datos Visibles
$this->m_datos_visiblesTpl[$index][$name] = $val;
}
$errs_tr = ConfigFramework::getTransformErrors();
array_push($this->m_auxIndices_borrar, $index);
if($row['gvhJS_selected'] == 'selected')
{
$this->int_filaActual = 0;
}
else
{
$this->int_filaActual = $filaActual;
}
break;
case 'nada':
foreach($row['gvhJS_fields'] as $name => $value) {
$val = ($value['value']);
$this->transform_User2FW($val,@$this->descCampoPanel[$name]['tipo']);
//Vamos acumularlos como datos Visibles
$this->m_datos_visiblesTpl[$index][$name] = $val;
if($row['gvhJS_selected'] == 'selected' OR ($index==$_REQUEST['panel']['pagActive'] AND $this->_panel=='edi')) {
$this->m_datos_seleccionarTpl[$index][$name] = $val;
array_push($this->m_auxIndices_seleccionar, $index);
}
}
break;
case 'buscar':
foreach($row['gvhJS_fields'] as $name => $value) {
$val = ($value['value']);
$this->transform_User2FW($val,@$this->descCampoPanel[$name]['tipo']);
//Vamos acumularlos como datos Buscar
$this->m_datos_buscarTpl[0][$name] = $val;
//Vamos acumularlos como datos Visibles
$this->m_datos_visiblesTpl[0][$name] = $val;
}
break;
default:
break;
}
// si no se ha llamado a getTransformErrors (en cam), lo hago ahora
if (is_null($errs_tr))
$errs_tr = ConfigFramework::getTransformErrors();
if (!empty($errs_tr))
$this->_transformErrors = array_merge($this->_transformErrors, $errs_tr);
} //fin del foreach
//Externals
if(isset($_REQUEST['external'])) {
//Añadimos los externals que me pasan los plugins
foreach ($_REQUEST['external'] as $name => $value) {
$val = ($value['value']);
$this->transform_User2FW($val,@$this->descCampoPanel[$name]['tipo']);
$this->m_datos_externalTpl[0][$name] = $val;
}
}
//Añadimos los externals que me pasan los plugins
$this->_limpiarRequest();
foreach ($_GET as $name => $value) {
$this->m_datos_externalTpl[0][$name] = $value;
}
}
$this->reset();
} //Fin de data2ArraysJSON
/**
* Construye únicamente el array de Seleccionados. En este caso es importante tener en cuenta si se venimos de un panel
* Ficha o Tabla. Esto se debe a que la forma de marcar la fila seleccionada es diferente de uno a otro (la tabla permite los checks).
*
* @access public
* @return integer
*/
public function construirArraySeleccionar() {
//Checkform
if(isset($_REQUEST['checkForm'])) {
$this->_checkForm = $_REQUEST['checkForm'];
unset($_REQUEST['checkForm']);
}
$this->construirArraySeleccionarJson();
}
private function construirArraySeleccionarJson() {
/*La estructura de los arrays es la siguiente:
[data] =>
[fila] =>
[estado]=> valor, [campos]=> valor
*/
//Como la forma de seleccionar cambia de un Ficha a un Tabla, tenemos q comprobar de donde viene
//if(isset($_REQUEST['claseManejadora'])) {
// $claseManejadora = $_REQUEST['claseManejadora'];
//}
$this->_transformErrors = array();
foreach ($_REQUEST['data'] as $index => $row) {
if (is_array($row['gvhJS_fields']))
{
foreach($row['gvhJS_fields'] as $name => $value) {
if($row['gvhJS_selected'] == 'selected') {
$val = ($value['value']);
$this->transform_User2FW($val,@$this->descCampoPanel[$name]['tipo']);
$this->m_datos_seleccionarTpl[$index][$name] = $val;
array_push($this->m_auxIndices_seleccionar, $index);
$this->int_filaActual = $index;
}
}
}
// si no se ha llamado a getTransformErrors (en cam), lo hago ahora
$errs_tr = ConfigFramework::getTransformErrors();
if (!empty($errs_tr))
$this->_transformErrors = array_merge($this->_transformErrors, $errs_tr);
} //fin del foreach
$this->reset();
} //Fin de data2ArraysJSON
/**
* método privado que utilizamos para quitar del REQUEST las variables internas de IGEP
* @access private
*/
public function _limpiarRequest() {
unset ($_REQUEST['modActv']);
unset ($_REQUEST['action']);
unset ($_REQUEST[session_name()]);
unset ($_REQUEST['claseManejadora']);
unset ($_REQUEST['TreeMenuBranchStatus']);
unset ($_REQUEST['gvhcache']);
unset ($_REQUEST['checkForm']);
unset ($_REQUEST['gvhpanel']);
}
public function _getPosicionRegistroPantalla($nombreCampoEnTpl) {
//Hay que utilizar los explode porque un campo del panel Fil puede tener un _ en el nombre.
$partesCampo = explode("___", $nombreCampoEnTpl);
if (count($partesCampo) == 3) {
$subCampo = explode("_", $partesCampo[2]);
$registro = $subCampo[1];
//En el caso de las listas multiples tenemos que eliminar el sufijo []
if(substr($registro,-2)=='[]')
$registro = substr($registro,0,-2);
}
else
//Es un campo de filtro
$registro = 0;
return ($registro);
}
public function construirArrayBuscar() {
$this->construirArrayBuscarJson();
}
public function construirArrayBuscarJson() {
/*La estructura de los arrays es la siguiente:
[data] =>
[fila] =>
[estado]=> valor, [campos]=> valor
*/
//Como la forma de seleccionar cambia de un Ficha a un Tabla, tenemos q comprobar de donde viene
//if(isset($_REQUEST['claseManejadora'])) {
// $claseManejadora = $_REQUEST['claseManejadora'];
//}
$this->_transformErrors = array();
/*if (isset($_REQUEST[$claseManejadora][$this->_panel]['data'][0]['gvhJS_fields']))
{
foreach($_REQUEST[$claseManejadora][$this->_panel]['data'][0]['gvhJS_fields'] as $name => $value)
*/
if (isset($_REQUEST['data'][0]['gvhJS_fields']))
{
foreach($_REQUEST['data'][0]['gvhJS_fields'] as $name => $value)
{
$plugin = IgepSmarty::utf8ize(($value['CWPlugin']));
if ($plugin != 'cwfilter')
{
$val = IgepSmarty::utf8ize(($value['value']));
$this->transform_User2FW($val,@$this->descCampoPanel[$name]['tipo']);
$errs_tr = ConfigFramework::getTransformErrors();
if (!empty($errs_tr))
$this->_transformErrors = array_merge($this->_transformErrors, $errs_tr);
$this->m_datos_buscarTpl[0][$name] = $val;
}
else {
$val = IgepSmarty::utf8ize(($value['rulesSQL']));
$val = $value['rulesSQL'];
$this->m_datos_buscarTpl[0]['rulesSQL'] = $val;
}
}
}
$this->reset();
return 0;
}
/**
* Carga los datos al iniciar la ventana. No tiene m_datos normal porque ningún campo puede tener matching
*/
public function construirArrayIniciarVentana() {
//Limpiamos el REQUEST.
$this->_limpiarRequest();
$this->m_datos_iniciarVentanaTpl = null;
foreach ($_REQUEST as $prop => $val) {
$this->m_datos_iniciarVentanaTpl[0][$prop] = $val;
}
return 0;
}
/**
* Construye el array especial para los campos Dependientes. Esta función hace uso de los métodos proporcionados por phrame.
*
* @access private
*/
public function buildDataRefreshUI($actionForm) {
$this->m_datosCamposDependientes['formulario'] = $actionForm->get('gvHfname');
$this->m_datosCamposDependientes['origen'] = $actionForm->get('gvHfrom');
$this->m_datosCamposDependientes['destino'] = $actionForm->get('gvHtarget');
$this->m_datosCamposDependientes['valor'] = $actionForm->get('gvHvalue');
$this->m_datosCamposDependientes['claseManejadora'] = $actionForm->get('gvHclass');
//Calculamos la posicion del registro en la matriz.
$posicionReal = null;
$claseManejadora = $actionForm->get('gvHclass');
$posicionRelativa = $this->_getPosicionRegistroPantalla($this->m_datosCamposDependientes['origen']);
if ( ($_REQUEST[$claseManejadora][$this->_panel]['panel']['pagActive'] == 0) )
{
$posicionReal = $posicionRelativa;
}
elseif ($_REQUEST[$claseManejadora][$this->_panel]['panel']['rowsPag'] == -1) {
$posicionReal = $_REQUEST[$claseManejadora][$this->_panel]['panel']['pagActive'];
}
else {
$posicionReal = ($_REQUEST[$claseManejadora][$this->_panel]['panel']['pagActive']*$_REQUEST[$claseManejadora][$this->_panel]['panel']['rowsPag']) + $posicionRelativa;
}
$this->m_datosCamposDependientes['registroActivo'] = $posicionReal;
unset ($_REQUEST['gvHfname']);
unset ($_REQUEST['gvHfrom']);
unset ($_REQUEST['gvHtarget']);
unset ($_REQUEST['gvHvalue']);
unset ($_REQUEST['gvHclass']);
}
public function construirArrayOrdenarTabla($actionForm) {
$this->m_datosOrdenarTabla['claseManejadora'] = $actionForm->get('claseManejadora');
$this->m_datosOrdenarTabla['columna'] = $actionForm->get('IGEPcol');
$this->m_datosOrdenarTabla['orden'] = $actionForm->get('IGEPord');
}
/**
* Método privado de igep que gastamos para construir los datos necesarios para abrir una ventana de Selección
*
* @access private
*/
public function construirArrayAbrirVentanaSeleccion($actionForm) {
$this->m_datosVentanaSeleccion['claseManejadora'] = $actionForm->get('claseManejadora');
//Capturamos el nombre del campo
$campo = $actionForm->get('nomCampo');
$this->m_datosVentanaSeleccion['nomCampo'] = $campo;
$this->m_datosVentanaSeleccion['nomForm'] = $actionForm->get('nomForm');
//Calculamos el índice
$this->m_datosVentanaSeleccion['filaActual'] = $actionForm->get('filaActual');
$this->m_datosVentanaSeleccion['panelActua'] = $actionForm->get('panelActua');
$this->m_datosVentanaSeleccion['actionOrigen'] = $actionForm->get('actionOrigen');
$this->m_datosVentanaSeleccion['modoPanelOrigen'] = $actionForm->get('modoPanelOrigen');
}
/**
* Método privado de igep que gastamos para construir los datos necesarios para buscar en una ventana de Selección
*
* @access private
* @return integer
*/
public function construirArrayBuscarVentanaSeleccion($actionForm) {
$this->m_datosVentanaSeleccion['nomForm'] = $actionForm->get('nomForm');
$this->m_datosVentanaSeleccion['nomCampo'] = $actionForm->get('nomCampo');
$this->m_datosVentanaSeleccion['camposBusqueda'] = $actionForm->get('camposBusqueda');
$this->m_datosVentanaSeleccion['valor'] = $_REQUEST['data'][0]['gvhJS_fields']['campoBuscar']['value']; //$actionForm->get('campoBuscar');
$this->m_datosVentanaSeleccion['filaActual'] = $actionForm->get('filaActual');
$this->m_datosVentanaSeleccion['panelActua'] = $actionForm->get('panelActua');
$this->m_datosVentanaSeleccion['claseManejadora'] = $actionForm->get('claseManejadoraOrigen');
$this->m_datosVentanaSeleccion['actionOrigen'] = $actionForm->get('actionOrigen');
$this->m_datosVentanaSeleccion['modoPanelOrigen'] = $actionForm->get('modoPanelOrigen');
}
/*----------------------------------------------FUNCIONES DE ENTREGA----------------------------------------------*/
/**
* Esta funcion se encargará de realizar la validación de los datos en el servidor
* antes de realizar una operación de inserción o actualización en la BD
* Si ha habido errores previamente en la transformacion, estan en ConfigFramework
*
* @access private
* @return int|string Devuelve 0 si no hay errores y un string con el error en caso de error.
*/
public function checkDataTypes() {
$mensajeErrorValidacion = $this->_transformErrors;
//En el caso de no tener operacion, fijamos como operacion los visibles.
$noOperationFixed = false;
if($this->getOperation()=='') {
$noOperationFixed = true;
$this->setOperation('visibles');
}
$datos = $this->getAllTuplas();
if(is_array($datos) and count($datos)>0) {
foreach($datos as $tupla){
foreach($tupla as $campo => $valor){
//Si el campo tiene descripción lo validamos:
if(isset($this->descCampoPanel[$campo]['instance'])){
$typeValidator = unserialize($this->descCampoPanel[$campo]['instance']);
try{
$typeValidator->validate($valor);
}
catch(Exception $e){
//Si tiene etiqueta utilizamos esa
$nombreEtiqueta = $typeValidator->getLabel();
if(empty($nombreEtiqueta))
$nombreEtiqueta = $campo;
$mensajeErrorValidacion[]="Campo $nombreEtiqueta: ".$e->getMessage();
}
}//fin del if si existe definición del campo
}//fin del foreach de los campos de la tupla
}//fin del foreach de las tuplas
}
//Si no había operacion fijada, lo dejamos asi.
$noOperationFixed = false;
if($noOperationFixed)
$this->setOperation('');
if(empty($mensajeErrorValidacion))
return 0;
else
return '
- '.implode('
- ', $mensajeErrorValidacion);
}
/**
* Devuelve los datos que con anterioridad se han recuperado y clasificado. Para ello solicita una operación y una tabla de la BD.
*
* @access private
* @param string $operacion
* @param string $nombreTabla
* @return array
*/
public function dameDatos($operacion, $nombreTabla = '') {
switch ($operacion) {
case 'camposDependientes' :
return $this->m_datosCamposDependientes;
break;
case 'abrirVentanaSeleccion' :
return $this->m_datosVentanaSeleccion;
break;
case 'buscarVentanaSeleccion' :
return $this->m_datosVentanaSeleccion;
break;
case 'ordenarTabla' :
return $this->m_datosOrdenarTabla;
break;
default :
die('Dame Datos.Operacion desconocida.');
break;
}
}
/**
* Devuelve los datos Antiguos para una tabla dada.
*
* @access private
* @param string $nombreTabla
* @return array
*/
public function dameDatosAntiguos($nombreTabla) {
return $this->m_datos_antiguos[$nombreTabla];
} //fin de dameDatosAntiguos
/**
* Retorna el valor de la fila actual
*
* @access private
* @return integer
*/
public function dameFilaActual()
{
return $this->int_filaActual;
} //fin de dameFilaActual
/*PROVISIONAL HASTA Q LO COJAMOS DE PLUGINS*/
public function damePanelActivo()
{
return $this->_panel;
} //fin de damePanelActivo
/************************************* NUEVO *********************************************/
/**
* String que contiene la operación que se está realizando
*
* @var string
* @access private
*/
public $str_operacionActual;
/**
* Integer indice de 2o nivel para referenciar la matriz "ficticia" de inserciones
*
* @var int
* @access private
*/
public $int_insertarIndice;
/**
* Matriz de referencias a las tuplas insertadas
*
* @var array
* @access private
*/
public $m_auxIndices_insertar;
/**
* Integer indice de 2o nivel para referenciar la matriz "ficticia" de modificaciones
*
* @var int
* @access private
*/
public $int_actualizarIndice;
/**
* Matriz de referencias a las tuplas modificadas
*
* @var array
* @access private
*/
public $m_auxIndices_actualizar;
/**
* Integer indice de 2o nivel para referenciar la matriz "ficticia" de borrados
*
* @var int
* @access private
*/
public $int_borrarIndice;
/**
* Matriz de referencias a las tuplas borradas
*
* @var array
* @access private
*/
public $m_auxIndices_borrar;
/**
* Integer indice de 2o nivel para referenciar la matriz "ficticia" de seleccionados
*
* @var int
* @access private
*/
public $int_seleccionarIndice;
/**
* Matriz de referencias a las tuplas seleccionadas
*
* @var array
* @access private
*/
public $m_auxIndices_seleccionar;
/**
* Integer indice de 2o nivel para referenciar la matriz "ficticia" de postConsultar
*
* @var int
* @access private
*/
public $int_postConsultarIndice;
/**
* Integer indice de 2o nivel para referenciar la matriz "ficticia" de postConsultar
*
* @var int
* @access private
*/
public $int_seleccionarPadreIndice;
/**
* Integer indice de 2o nivel para referenciar la matriz "ficticia" de buscar
*
* @var int
* @access private
*/
public $int_buscarIndice;
/**
* Integer indice de 2o nivel para referenciar la matriz "ficticia" de iniciarVentana
*
* @var int
* @access private
*/
public $int_iniciarVentanaIndice;
/**
* Integer indice de 2o nivel para referenciar la matriz "ficticia" de external
*
* @var int
* @access private
*/
public $int_externalIndice;
/**
* Integer indice de 2o nivel para referenciar la matriz "ficticia" de visibles
*
* @var int
* @access private
*/
public $int_visiblesIndice;
/**
* Este método se encarga de inicializar el indice del cursor que pertenece a la operación.
*
* @access public
* @params $parametroOperacion la operación sobre la que se quiere reinicializar el cursor
* @return void
*/
public function reset($parametroOperacion = '') {
//Seleccionamos la operacion
if ($parametroOperacion != '') {
$operacion = $parametroOperacion;
//Inicializamos el indice de la operacion a 0
$indice = 'int_'.$operacion.'Indice';
$this-> $indice = 0;
}
else {
$operacionesBasicas = array ('insertar', 'borrar', 'actualizar', 'seleccionar', 'external', 'visibles');
foreach ($operacionesBasicas as $operacion) {
$indice = 'int_'.$operacion.'Indice';
$this-> $indice = 0;
}
}
}
/**
* Este método indica a la instancia cual es la operación en curso e inicializa el indice del cursor de dicha
* operación. La operación en curso se utilizará siempre que no se especifique como parámetro para el resto de
* métodos. OJO: Falta dar una lista clara de las operaciones para el usuario (internas puede haber más)
*
* @access public
* @params $parametroOperacion el tipo de operación: insertar, borrar, actualizar, ... hay que dar una lista fija y clara
* @return void
*/
public function setOperation($parametroOperacion) {
if (($parametroOperacion == 'visibles') && ($this->isEmpty('visibles')))
$parametroOperacion = 'external';
$this->str_operacionActual = $parametroOperacion;
$this->reset($parametroOperacion);
} //Fin function setOperacion
public function setArrayOperacion($m_datos) {
$str_operacion = $this->getOperation();
$nombreMatriz = 'm_datos_'.$str_operacion.'Tpl';
if (is_array($m_datos))
$this-> $nombreMatriz = $m_datos;
else
$this-> $nombreMatriz = array ();
}
/**
* Este método permite el acceso a la propiedad interna que indica la operación actual.
*
* @access public
* @return string
*/
public function getOperation() {
return $this->str_operacionActual;
} //Fin function getOperation
/**
* Este método devuelve el valor del indice del cursor sobre la operación.
*
* @access public
* @params $parametroOperacion el tipo de operación, si no se indica se coge el fijado para la instancia
* @return integer
*/
public function getIndex($parametroOperacion = '') {
if ($parametroOperacion != '')
$operacion = $parametroOperacion;
else
$operacion = $this->getOperation();
$indice = 'int_'.$operacion.'Indice';
return ($this-> $indice);
}
/**
* posicionarEnTupla, coloca los índices en la fila/tupla que se le indique por parámetro
*
* @access private
* @params $parametroOperacion el tipo de operación, si no se indica se coge el fijado para la instancia
* @return integer
*/
public function posicionarEnTupla($indiceFila, $parametroOperacion = '') {
if ($parametroOperacion != '')
$operacion = $parametroOperacion;
else
$operacion = $this->getOperation();
$indice = 'int_'.$operacion.'Indice';
if (!empty ($indiceFila))
$this-> $indice = $indiceFila;
else
$this-> $indice = 0;
}
/**
* Este método avanza el indice del cursor sobre la operación y lo devuelve.
*
* @access private
* @params $parametroOperacion el tipo de operación, si no se indica se coge el fijado para la instancia
* @return integer
*/
public function _next($parametroOperacion = '') {
if ($parametroOperacion != '')
$operacion = $parametroOperacion;
else
$operacion = $this->getOperation();
$indice = 'int_'.$operacion.'Indice';
$this-> $indice ++;
return $this-> $indice;
}
/**
* Este método, para un indice de cursor le devuelve el indice en la matriz de la operación.
*
* @access private
* @params $indiceGlobal indica el valor del indice del cursor de la operación
* @return integer
*/
public function _getIndiceInterno($operacion, $indiceGlobal = -1) {
if ($indiceGlobal == -1)
$indiceGlobal = $this->getIndex($operacion);
if (($operacion == 'buscar') or ($operacion == 'postConsultar') or ($operacion == 'seleccionarPadre') or ($operacion == 'external') or ($operacion == 'visibles') or ($operacion == 'iniciarVentana'))
return $indiceGlobal;
//if( ($operacion=='buscar') ) return ($indiceGlobal+1);
//if( ($operacion=='postConsultar') or ($operacion=='seleccionarPadre') or ($operacion=='external') or ($operacion=='visibles')) return $indiceGlobal;
$matrizAuxIndice = 'm_auxIndices_'.$operacion;
$matrizGlobal = & $this-> $matrizAuxIndice;
if (isset ($matrizGlobal[$indiceGlobal]))
return $matrizGlobal[$indiceGlobal];
else
return -1;
}
/**
* Este método devuelve una matriz con los campos que aparecen en la tpl para la tupla actual
* dentro del cursor de la operacion. No avanza la posiccion en el cursor.
*
* @access public
* @params $parametroOperacion el tipo de operación, si no se indica se coge el fijado para la instancia
* @return array
*/
public function currentTupla($parametroOperacion = '') {
if ($parametroOperacion != '')
$operacion = $parametroOperacion;
else
$operacion = $this->getOperation();
$nombreMatriz = 'm_datos_'.$operacion.'Tpl';
$indiceInterno = $this->_getIndiceInterno($operacion);
$matrizInterna = & $this-> $nombreMatriz;
if (isset ($matrizInterna[$indiceInterno])) {
//Para evitar el problema de referencias a objetos clonamos
$row = $matrizInterna[$indiceInterno];
foreach($row as $field => $value){
if(is_object($value))
$row[$field] = clone $value;
}
return $row;
}
else {
return 0;
}
} //Fin function currentTupla
public function getCampo($nombreCampo, $parametroOperacion = '') {
if ($parametroOperacion != '')
$operacion = $parametroOperacion;
else
$operacion = $this->getOperation();
$resultado = $this->currentTupla($operacion);
if (isset ($resultado[$nombreCampo]))
return $resultado[$nombreCampo];
else
return null;
} //Fin function getCampo
/**
* Este método devuelve el valor antiguo de una campo para la operacion activa.
*
* @access public
* @params $nombreCampo el nombre del campo del cual se quiere conocer el valor antiguo
* @return string
*/
public function getOldValue($nombreCampo){
$operacion = $this->getOperation();
$indice = $this->_getIndiceInterno($operacion);
return $this->m_datos_antiguosTpl[$indice][$nombreCampo];
}
public function setCampo($nombreCampo, $valorCampo, $parametroOperacion = '') {
if ($parametroOperacion != '')
$operacion = $parametroOperacion;
else
$operacion = $this->getOperation();
$indiceInterno = $this->_getIndiceInterno($operacion);
$nombreMatrizTpl = 'm_datos_'.$operacion.'Tpl';
$matrizInternaTpl = & $this-> $nombreMatrizTpl;
//Tenemos que añadirlo en el array adecuado.
$matrizInternaTpl[$indiceInterno][$nombreCampo] = $valorCampo;
} //Fin function setCampo
/**
* Este método devuelve una matriz con los campos que aparecen en la tpl para la tupla actual
* dentro del cursor de la operacion y avanza a la siguiente posición del cursor.
*
* @access public
* @params $parametroOperacion el tipo de operación, si no se indica se coge el fijado para la instancia
* @return array
*/
public function fetchTupla($parametroOperacion = '') {
if ($parametroOperacion != '')
$operacion = $parametroOperacion;
else
$operacion = $this->getOperation();
$resultado = $this->currentTupla($operacion);
$this->_next($operacion);
return $resultado;
} //Fin function fetchTupla
/**
* Este método avanza a la siguiente posición del cursor y devuelve verdadero
* si quedan tuplas/registros en el cursor, y falso cuando se llega al final
*
* @access public
* @params $parametroOperacion el tipo de operación, si no se indica se coge el fijado para la instancia
* @return boolean
*/
public function nextTupla($parametroOperacion = '') {
if ($parametroOperacion != '')
$operacion = $parametroOperacion;
else
$operacion = $this->getOperation();
$this->_next($operacion);
$resultado = $this->currentTupla($operacion);
return (!empty ($resultado));
} //Fin function nextTupla
public function setTupla($tupla, $str_operacion = '') {
if ($str_operacion != '')
$operacion = $str_operacion;
else
$operacion = $this->getOperation();
$indiceGlobal = ($ind = $this->getIndex($operacion)) > 0 ? ($ind -1) : 0;
$indiceInterno = $this->_getIndiceInterno($operacion, $indiceGlobal);
$nombreMatrizTpl = 'm_datos_'.$operacion.'Tpl';
$matrizInternaTpl = & $this-> $nombreMatrizTpl;
foreach ($tupla as $nombreCampo => $valorCampo) {
$matrizInternaTpl[$indiceInterno][$nombreCampo] = $valorCampo;
}
return 1;
} //Fin function setTupla
/**
* getAllTuplas metodo que devuelve la matriz de datos de la operación activa.
* @access public
*
* Este metodo devuelve todo el conjunto de la operacion activa. Se le puede
* pasar por parametro una operacion si no se quiere obtener los datos pertenecientes
* a la operacion activa.
*
* @param string $parametroOperacion indica la operacion de la que se quiere obtener la matriz, no es obligatorio
* @return mixed
*
*/
public function getAllTuplas($parametroOperacion = '') {
if ($parametroOperacion != '')
$operacion = $parametroOperacion;
else
$operacion = $this->getOperation();
$this->reset($operacion);
$nombreMatriz = 'm_datos_'.$operacion.'Tpl';
if (isset ($this-> $nombreMatriz))
return $this->array_values_with_clone($this-> $nombreMatriz);
else
return 0;
} //Fin function getAllTuplas
/**
* array_values_with_clone funcion creada para evitar pasar referencias a objetos con la matriz.
* @access private
*
* Esta funcion evita que pasemos referencias a objetos cuando obtenemos la matriz de datos. Esto
* evita que si un programador modifica el objeto obtenido y luego no hace el setAllTuplas, no tenga
* problemas con dicha modificacion.
*
* @param mixed $matrix matriz de datos
* @return mixed
*
*/
private function array_values_with_clone($matrix) {
//inicializamos la variables
$clone = false;
$result = array();
if(!is_array($matrix))
return $result;
if(count($matrix)==0)
return array();
//Comprobamos en la primera fila si tiene objetos
$validation = $matrix[key($matrix)];
if (is_array($validation))
foreach($validation as $field) {
if(is_object($field)) {
$clone = true;
break;
}
}
reset($matrix);
//Construimos la matriz resultado clonando si es necesario
foreach($matrix as $row) {
if($clone) {
foreach($row as $field => $value) {
if(is_object($value))
$row[$field] = clone $value;
}
}
$result[]=$row;
}
return $result;
}
/**
* Este método devuelve todas las tuplas de antiguas para una operacion dada.
*/
public function getAllTuplasAntiguas($parametroOperacion = '') {
if ($parametroOperacion != '')
$operacion = $parametroOperacion;
else
$operacion = $this->getOperation();
$this->reset($operacion);
$indice = 0;
$resultado = array ();
while (($indiceInterno = $this->_getIndiceInterno($operacion)) != -1) {
$resultado[$indice] = $this->m_datos_antiguosTpl[$indiceInterno];
++$indice;
$this->_next();
}
return $resultado;
} //Fin de getAllTuplasAntiguas
public function setAllTuplas($vTuplas, $parametroOperacion = '') {
if ($parametroOperacion != '') {
$operacion = $parametroOperacion;
}
else {
$operacion = $this->getOperation();
}
$this->reset();
//Si tiene más tuplas de las que teniamos borramos el contenido de la matriz TPL
if (count($vTuplas) != count($this->getAllTuplas($operacion))) {
$matrizInternaTpl = 'm_datos_'.$operacion.'Tpl';
$matrizInterna = 'm_datos_'.$operacion;
$this-> $matrizInternaTpl = array ();
$this-> $matrizInterna = array ();
//Regeneramos el indice de las tuplas
$numTotalTuplas = count($vTuplas);
$matrizAuxIndices = 'm_auxIndices_'.$operacion;
$this-> $matrizAuxIndices = array();
$i = 0;
while($i<$numTotalTuplas) {
array_push($this-> $matrizAuxIndices,$i);
++$i;
}
}
if (!is_array($vTuplas)) {
throw new Exception('IgepComunicacion::setAllTuplas ha de recibir un array, ahora recibe: '.var_export($vTuplas,true));
}
foreach ($vTuplas as $tupla) {
$this->_next($operacion);
$this->setTupla($tupla, $operacion);
}
return 1;
} //Fin de setAllTuplas
/**
* Este método guarda todas las tuplas de antiguas.
*/
public function _setAllTuplasAntiguas($vTuplas, $parametroOperacion = '') {
if ($parametroOperacion != '')
$operacion = $parametroOperacion;
else
$operacion = $this->getOperation();
$this->reset($operacion);
$indice = 0;
$resultado = array ();
while (($indiceInterno = $this->_getIndiceInterno($operacion)) != -1) {
$this->m_datos_antiguosTpl[$indiceInterno] = $vTuplas[$indice];
++$indice;
$this->_next();
}
return $resultado;
} //Fin de getAllTuplasAntiguas
public function setList($nombreCampo, $v_lista, $parametroOperacion = '') {
//Este método sólo tiene sentido en un postConsultar (postBuscar, postEditar, postRecargar)
//Por estar razón sólo se escribirá en la matriz TPL
if ($parametroOperacion != '')
$operacion = $parametroOperacion;
else
$operacion = $this->getOperation();
$indiceInterno = $this->_getIndiceInterno($operacion);
$nombreMatrizTpl = 'm_datos_'.$operacion.'Tpl';
$matrizInternaTpl = & $this-> $nombreMatrizTpl;
$matrizInternaTpl[$indiceInterno][$nombreCampo] = $v_lista;
}
public function isEmpty($parametroOperacion = '') {
if ($parametroOperacion != '')
$operacion = $parametroOperacion;
else
$operacion = $this->getOperation();
$nombreMatriz = 'm_datos_'.$operacion.'Tpl';
if(!isset($this-> $nombreMatriz) OR count($this-> $nombreMatriz)==0)
return TRUE;
return FALSE;
} //fin de isEmpty
/** Método que devuelve para una tupla dada la información de un campo de tipo 'FILE'
* que se ha subido al servidor.
* @access private
* @param string nombreCampo Nombre del campo FILE del que se quiere obtener la información
* @param string parametroOperacion Indica la operación sobre la que se quiere la tupla
* @return array
*/
public function getFileInfo($nombreCampo, $parametroOperacion){
if ($parametroOperacion != '')
$operacion = $parametroOperacion;
else
$operacion = $this->getOperation();
$indiceInterno = $this->_getIndiceInterno($operacion);
return $this->m_datosFicherosUpLoad[$indiceInterno][$nombreCampo];
}
//REVIEW: Toni Para poder conseguir que las acciones de negocio tengan acceso a mapeos diferentes a los ya especificados
public function setMapping(ActionMapping $actionMapping){
$this->_actionMapping = $actionMapping;
}
/**
* Método que devuelve el forward name de la acción en curso. Buscará la respuesta identificada por name en la accion actual definida en mappings.php
* @access public
* @param string name Nombre de la respuesta deseada
* @return object
*/
public function getForward($name) {
//Si no existe, lanzamos excepcion que informara en el debugger del error.
if(!$this->_actionMapping->containsKey($name))
throw new Exception('Error: actionForward '.$name.' no existe. Consulte el fichero de mapeos.');
if(isset($this->_actionMapping))
return $this->_actionMapping->get($name);
}
/**
* Devuelve el valor de checkform para saber si se tiene que validar el formulario
*
* @return integer
*/
public function getCheckForm() {
return $this->_checkForm;
}
/**
* Realizar las conversiones desde formato usuario a formato FW
*
* @access public
* @param array a_parametros Vector de asociativo de elementos a transformar
* @param string a_tipo Nombre de la respuesta deseada
*/
public static function transform_User2FW(& $a_parametros, $a_tipo=TIPO_CARACTER)
{
ConfigFramework::setTransformErrors(array());
if (empty($a_tipo) and !is_array($a_tipo))
{
$a_tipo = TIPO_CARACTER;
}
if (!is_array($a_parametros))
{
// le doy estructura de vector para no repetir el codigo
$vector = false;
$a_parametros = array(array('col'=>$a_parametros,),);
$a_tipo = array('col'=>array('tipo'=>$a_tipo,),);
}
else
{
$vector = true;
}
if (is_array($a_tipo))
{
$transformer = new IgepTransformer(true);
$car_i = ConfigFramework::getNumericSeparatorsUser();
$car_n = ConfigFramework::getNumericSeparatorsFW();
$transformer->setDecimal($car_i['DECIMAL'],$car_n['DECIMAL'],$car_i['GROUP'],$car_n['GROUP']);
$fecha_i = ConfigFramework::getDateMaskUser();
$fecha_n = ConfigFramework::getDateMaskFW();
$transformer->setDate($fecha_i, $fecha_n);
foreach ($a_parametros as $fila => $tupla)
{
foreach ($a_tipo as $campo => $descTipo)
{
$tipo_efectivo = ($descTipo['tipo']==TIPO_ENTERO? TIPO_DECIMAL: $descTipo['tipo']);
if (empty($a_parametros[$fila][$campo]))
{
if($tipo_efectivo==TIPO_FECHA or $tipo_efectivo==TIPO_FECHAHORA)
{
$a_parametros[$fila][$campo] = null;
}
continue;
}
$num_errores = count($transformer->getTransformErrors());
$a_parametros[$fila][$campo] = $transformer->process($tipo_efectivo, $tupla[$campo]);
if ($tipo_efectivo == TIPO_FECHA or $tipo_efectivo == TIPO_FECHAHORA)
{
if (count($transformer->getTransformErrors())==$num_errores)
{
$a_parametros[$fila][$campo] = new gvHidraTimestamp($a_parametros[$fila][$campo]);
}
else
{
$a_parametros[$fila][$campo] = null;
}
}
}
}
ConfigFramework::setTransformErrors($transformer->getTransformErrors());
}
if (!$vector)
{
$a_parametros = $a_parametros[0]['col'];
}
}//Fin IgepComunicacion
/**
* Método que permite indicar el panel de trabajo de gvhidra
*
* fil
* lis
* edi
*
* @param string $panel
*/
public function setPanel($panel) {
$this->_panel = $panel;
}
public function getPanel() {
return $this->_panel;
}
} //Fin de IgepComunicacion
?>