/*
function ordenarCampos($acampos, $tabla = null)
function ordenar($field, $mode, $tabla = null)
function obtener ($afiltro=null)
function obtenerRango ($afiltro, $afiltroDesde, $afiltroHasta )
function obtenerRangoCampos ($campos, $afiltro, $afiltroDesde, $afiltroHasta )
function obtenerBuscadorWeb ( $cadena, $camposB = null )
function filtrarBuscadorWeb ( $cadena, , $camposB = null, $tabla = null )
function obtenerBuscador( $cadena, $camposB = null )
function obtenerCampos ($campos, $afiltro=null)
function obtenerNumRegistrosRango( $afiltro, $afiltroDesde, $afiltroHasta )
function obtenerNumRegistros( $afiltro=null )
function insertar ($aregistro)
function insertarFilas ($aregistroV)
function modificarOInsertar( $afiltro, $aregistro )
function modificar ($afiltro, $aregistro)
function borrar ($afiltro)
function borrarRango($afiltro, $afiltroDesde, $afiltroHasta)
function filtrar ( $filtro, $tabla = null )
function filtrarBuscador ( $cadena, $camposB=null, $tabla = null )
function filtrarPaginar ( $regInicio, $regFin, $tabla = null )
function filtrarRango ( $filtro, $filtroDesde, $filtroHasta, $tabla = null )
function filtrarMaximo ( $campo, $tabla = null )
function filtrarCampos ( $campos, $tabla = null )
function filtrarDistintos ( $campos, $tabla = null )
function filtrarSuma ( $campo, $tabla = null )
function getFlagComprobarAntesGrabar()
function setFlagComprobarAntesGrabar( $valor )
function getFlagCopiaSeguridad()
function setFlagCopiaSeguridad( $valor )
function ordenarCampos($acampos, $tabla = null)
function ordenar($field, $mode, $tabla = null)
function obtener ($afiltro=null)
function obtenerRango ($afiltro, $afiltroDesde, $afiltroHasta )
function obtenerRangoCampos ($campos, $afiltro, $afiltroDesde, $afiltroHasta )
function obtenerBuscadorWeb ( $cadena, $camposB = null )
function filtrarBuscadorWeb ( $cadena, $camposB = null, $tabla = null )
function obtenerBuscador( $cadena, $camposB = null )
function obtenerCampos ($campos, $afiltro=null)
function obtenerNumRegistrosRango( $afiltro, $afiltroDesde, $afiltroHasta )
function obtenerNumRegistros( $afiltro=null )
function insertar ($aregistro)
function insertarFilas ($aregistroV)
function modificar ($afiltro, $aregistro)
function borrar ($afiltro)
function borrarRango($afiltro, $afiltroDesde, $afiltroHasta)
function filtrar ( $filtro, $tabla = null )
function filtrarBuscador ( $cadena, $camposB=null, $tabla = null )
function filtrarPaginar ( $regInicio, $regFin, $tabla = null )
function filtrarRango ( $filtro, $filtroDesde, $filtroHasta, $tabla = null )
function filtrarMaximo ( $campo, $tabla = null )
function filtrarCampos ( $campos, $tabla = null )
function filtrarDistintos ( $campos, $tabla = null )
function filtrarSuma ( $campo, $tabla = null )
function getFlagComprobarAntesGrabar()
function setFlagComprobarAntesGrabar( $valor )
function getFlagCopiaSeguridad()
function setFlagCopiaSeguridad( $valor )
function getFlagFiltroEstricto()
function setFlagFiltroEstricto( $valor )
function getFlagEscribirFicheroLog()
function setFlagEscribirFicheroLog( $valor )
function bloquearTabla()
function desbloquearTabla()
function Tabla( $file=null )
*/
class Tabla {
var $xml;
//var $contador=0;
var $nombre;
var $fila;
var $filtro;
var $filtroDesde;
var $filtroHasta;
var $campos;
var $resultado;
//~ var $fp;
var $filasAfectadas;
var $registro;
var $cadenaBusqueda;
var $camposBuqueda;
//~ var $flagCopiaSeguridad = true;
var $flagComprobarAntesGrabar = true;
var $flagFiltroEstricto = true; // Si está a true si los el registro no tiene la clave del filtro no se dará por bueno
var $flagCometarioDatosXML = true;
//~ var $bErrorEscribirFichero = false;
//~ var $flagEscribirFicheroLog = true;
var $claseEscribirTabla;
var $claseLogTabla;
var $numCaracteresLeidos; // Se hace esta ñapa para las versiones anteriores a la 4.3.11
function _inicializar() {
$this->filtro = null;
$this->filtroDesde = null;
$this->filtroHasta = null;
$this->campos = null;
$this->filasAfectadas = 0;
$this->registro = null;
$this->cadenaBusqueda = null;
$this->camposBuqueda = null;
}
function _startElement($parser, $name, $attrs) {
// print " INICIO :: ".$name."
";
$this->nombre = $name;
if ($name == 'REGISTRO'){
$this->fila=null;
}
}
//----------------------------------------------------------------------------
function _endElementObtener($parser, $name) {
// global $contador, $resultado, $fila;
// print " FIN :: ".$name."
";
if ($name == 'REGISTRO'){
if ( $this->_isEndElementObtener() ){
$this->resultado[ count($this->resultado) ] = $this->fila;
}
}
$this->nombre = $name;
}
//----------------------------------------------------------------------------
function _endElementObtenerNumRegistros($parser, $name) {
if ($name == 'REGISTRO'){
if ( $this->_isEndElementObtenerRango( $this->fila ) ){
if ( ! isset ( $this->resultado[0] ) ){
$this->resultado[0] = 1;
} else {
$this->resultado[0] ++;
}
} // De if ( $this->_isEndElementObtener() )
}
$this->nombre = $name;
}
//----------------------------------------------------------------------------
function _endElementObtenerRango($parser, $name) {
// global $contador, $resultado, $fila;
// print " FIN :: ".$name."
";
if ( $name == 'REGISTRO' ) {
if ( $this->_isEndElementObtenerRango($this->fila) ) {
$this->resultado[ count($this->resultado) ] = $this->fila;
}
} // De if ($name == 'REGISTRO')
$this->nombre = $name;
}
//----------------------------------------------------------------------------
function _isEndElementObtenerRango($fila) {
$contador = 0;
$contadorBuenas = 0;
if ( ! is_null($this->filtro) ){
$contador++;
if ( $this->_isEncontrado($fila, $this->filtro) ){
$contadorBuenas++;
}
} // de if ( ! is_null($this->filtro) )
if ( ! is_null($this->filtroDesde) ){
$contador++;
if ( $this->_isEncontradoDesdeHasta($fila, $this->filtroDesde, ">=") ){
$contadorBuenas++;
}
} // de if ( ! is_null($this->filtroDesde) )
if ( ! is_null($this->filtroHasta) ) {
$contador++;
if ( $this->_isEncontradoDesdeHasta($fila, $this->filtroHasta, "<=") ){
$contadorBuenas++;
}
} // if ( ! is_null($this->filtroHasta) )
/*
trazaDepurar ("contador", $contador);
trazaDepurar ("contadorBuenas", $contadorBuenas);
trazaDepurar ("name", $name);
*/
if ( $contador == $contadorBuenas ) {
return true;
} else {
return false;
}
}
//----------------------------------------------------------------------------
function _endElementObtenerRangoCampos($parser, $name) {
// global $contador, $resultado, $fila;
// print " FIN :: ".$name."
";
if ($name == 'REGISTRO'){
if ( $this->_isEndElementObtenerRango($this->fila) ) {
$this->fila = $this->_filtrarRegistro ($this->fila, $this->campos);
$this->resultado[ count($this->resultado) ] = $this->fila;
}
} // De if ($name == 'REGISTRO')
$this->nombre = $name;
}
//----------------------------------------------------------------------------
function _endElementObtenerCampos($parser, $name) {
// global $contador, $resultado, $fila;
// print " FIN :: ".$name."
";
if ($name == 'REGISTRO'){
if ( $this->_isEndElementObtener() ) {
$this->fila = $this->_filtrarRegistro ($this->fila, $this->campos);
$this->resultado[ count($this->resultado) ] = $this->fila;
}
}
$this->nombre = $name;
}
//----------------------------------------------------------------------------
function _endElementObtenerBuscador($parser, $name) {
// global $contador, $resultado, $fila;
// print " FIN :: ".$name."
";
if ($name == 'REGISTRO'){
if ( $this->_isEndElementObtenerBuscador() ) {
$this->fila = $this->_filtrarRegistro ($this->fila, $this->campos);
$this->resultado[ count($this->resultado) ] = $this->fila;
}
}
$this->nombre = $name;
}
//----------------------------------------------------------------------------
function _isEndElementObtenerBuscador() {
$chivato = false;
if ( $this->_isEncontradoBuscador ($this->fila, $this->cadenaBusqueda, $this->camposBuqueda ) ) {
$chivato = true;
}
return $chivato;
}
//----------------------------------------------------------------------------
function _isEndElementObtener() {
$chivato = false;
if ( is_null($this->filtro) ){
$chivato = true;
}else if ( $this->_isEncontrado($this->fila, $this->filtro) ){
$chivato = true;
}
return $chivato;
}
//----------------------------------------------------------------------------
function _endElementInsertar ($parser, $name) {
// global $contador, $resultado, $fila;
// print " FIN :: ".$name."
";
if ($name == 'REGISTRO'){
$this-> _escribirRegistro($this->fila);
}
$this->nombre = $name;
}
//----------------------------------------------------------------------------
function _endElementModificar ($parser, $name) {
if ($name == 'REGISTRO'){
if ( $this->_isEncontrado($this->fila, $this->filtro) ){
$this->fila = $this->_modificarRegistro($this->fila, $this->registro) ;
$this->filasAfectadas++;
}
$this-> _escribirRegistro($this->fila);
}
$this->nombre = $name;
}
//----------------------------------------------------------------------------
function _endElementBorrarRango ($parser, $name) {
if ($name == 'REGISTRO'){
if ( $this->_isEndElementObtenerRango($this->fila) ){
$this->filasAfectadas ++;
}else{
$this-> _escribirRegistro($this->fila);
}
}
$this->nombre = $name;
}
//----------------------------------------------------------------------------
// function _endElementBorrar ($parser, $name) {
// if ($name == 'REGISTRO'){
// if ( $this->_isEncontrado($this->fila, $this->filtro) ){
// $this->filasAfectadas ++;
// }else{
// $this-> _escribirRegistro($this->fila);
// }
// }
// $this->nombre = $name;
// }
function _escribirRegistro($registro){
$res = $this->claseEscribirTabla->escribirAFichero ("\n");
if ( ! ( $res === false) ) {
foreach($registro as $key => $value) {
$cadena = $value;
if ($this->flagCometarioDatosXML) {
$cadena = "";
}
$cadena ="<".$key.">".$cadena."<".chr(47).$key.">\n";
$res = $this->claseEscribirTabla->escribirAFichero($cadena);
if ( $res === false ) {
break 1;
}
}
} // De if ( ! ( $res === false) )
if ( ! ( $res === false) ) {
$res = $this->claseEscribirTabla->escribirAFichero ("\n");
}
} // De function _escribirRegistro($registro)
//----------------------------------------------------------------------------
function _modificarRegistro($afila, $registro){
$fila = $afila;
foreach($registro as $key => $value) {
// Para evitar problemas
// if ( isset( $fila[$key] ) ) {
$fila[$key] = $value;
// }
}
return $fila;
}
//----------------------------------------------------------------------------
function _characterData($parser, $data) {
if ( ! isset( $this->fila [$this->nombre] ) && strtoupper( trim( $this->nombre ) ) != "REGISTRO" ) {
$this->fila [$this->nombre] = "";
}
if ( !(is_null($data) || trim($data)=="") ){
// if ( version_compare("5.0.0", phpversion() ) == -1 ) {
if ( version_compare("4.3.11", phpversion() ) < 0 ) {
// Versiones posteriores a la 5
$this->fila [$this->nombre] .= $data;
} else { // Del if ( version_compare("5.0.0", phpversion() ) == -1 )
// Versiones anteriores a la 4.3.11
if ( !( is_null( $this->fila [$this->nombre] ) || trim( $this->fila [$this->nombre] ) =="" ) ) {
// ÑAPA. siempre $data tiene 1024 o menos caracteres. Si antes se ha leído
// 1024 no se concatena con el salto de línea. Es la mejor solución que se me ha
// ocurrido pero no es definitiva. NO SOLUCIONA EL PROBLEMA
if ( $this->numCaracteresLeidos < 1024 ){
$data = "\n".$data ;
}
$this->fila [$this->nombre] .= $data;
} else{
$this->fila [$this->nombre] .= $data;
}
} // Del else if ( version_compare("5.0.0", phpversion() ) == -1 )
} // De if ( !(is_null($data) || trim($data)=="") )
$this->numCaracteresLeidos = strlen( $data );
}
//----------------------------------------------------------------------------
function ordenarCampos($acampos, $tabla = null) {
$this->_inicializar();
$resultado = $tabla;
foreach( array_reverse ( $acampos ) as $campo => $valor ) {
$resultado = $this->_ordenar( $campo, $valor, true, $resultado );
} // De foreach( array_reverse ( $acampos ) as $campo => $valor )
$resultado = $this->_ordenar( '_ORDENSELECT', 0, false,$resultado );
return $resultado;
} // de function ordenarCampos($field, $mode, $tabla = null)
//----------------------------------------------------------------------------
function ordenar($field, $mode, $tabla = null) {
$this->_inicializar();
return $this->_ordenar($field, $mode, 0, $tabla);
}
//----------------------------------------------------------------------------
function _ordenar($field, $mode, $anadirordenar, $tabla = null) {
if ($tabla === null ){
$tabla = $this->resultado;
}
$i_cnt = count($tabla);
if ( $i_cnt == 0 ){
return $tabla;
}
for($i=0;$i<$i_cnt;$i++) {
foreach($tabla[$i] as $key => $value) {
$array[$key][$i] = $this->_remplazarAcentosOn ($value);
}
}
$mode == 0 ? asort($array[$field]) : arsort($array[$field]);
$_keys = array_keys($array[$field]);
if ( $anadirordenar ) {
$longitud = strlen ( $i_cnt."" ) ;
}
$contador = 0;
for($i=0;$i<$i_cnt;$i++) {
$key = ""; $value = "";
foreach($array as $key => $value) {
if ($key != '_ORDENSELECT') {
if ( ! isset( $array[$key][$_keys[$i]] ) ) {
$array[$key][$_keys[$i]] = "";
} // De if ( ! isset( $array[$key][$_keys[$i]] ) )
$_hash[$i][$key] = $this->_remplazarAcentosOff( $array[$key][$_keys[$i]] );
} // De if ($key != '_ORDENSELECT')
}
if ( $anadirordenar ) {
if ($i > 0 && ( $_hash[$i-1][$field] != $_hash[$i][$field] ) ) {
$contador ++;
}
if ( ! isset( $array['_ORDENSELECT'][$_keys[$i]] ) ) {
$array['_ORDENSELECT'][$_keys[$i]] = "";
}
$_hash[$i]['_ORDENSELECT'] = 'a'.str_pad( $contador, $longitud, "0", STR_PAD_LEFT ).$array['_ORDENSELECT'][$_keys[$i]];
} // De if ( $anadirordenar )
} // Del for($i=0;$i<$i_cnt;$i++)
return $_hash;
} // Del function _ordenar($field, $mode, $anadirordenar, $tabla = null)
//----------------------------------------------------------------------------
function _leerXML($funcion) {
//~ $funcionesBloqueo = array("_endElementBorrar", "_endElementBorrarRango",
//~ "_endElementInsertar", "_endElementModificar");
// Traza
//~ trazaDepurar( "_leerXML", $this->xml );
// Fin de traza
$xml_parser = xml_parser_create("ISO-8859-1");
//xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
// Con esta linea se le al parser la clase para que puedan leer las funciones de la clase
//xml_set_object($xml_parser, &$this);
xml_set_object($xml_parser, $this);
xml_set_element_handler($xml_parser, "_startElement", $funcion);
xml_set_character_data_handler($xml_parser, "_characterData");
if (!($fp = fopen($this->xml, "r"))) {
$sentenciaError = "Metodo : $funcion. No se puede abrir el XML";
$this->claseLogTabla->escribirAFicheroLog($sentenciaError);
die( $sentencia );
}
// Para estas funciones se bloquea el fichero para lectura
//~ if ( in_array( $funcion, $funcionesBloqueo ) ) {
//~ flock( $fp, LOCK_SH, true ) ;
//~ }
while ($data = fgets ($fp, 1024)) {
if (! xml_parse($xml_parser, $data, feof($fp))) {
$sentenciaError = sprintf("Metodo : $funcion. XML error: %s en la linea %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser));
$this->claseLogTabla->escribirAFicheroLog($sentenciaError);
//~ die( $sentenciaError);
$this->claseEscribirTabla->setBErrorEscribirFichero( true ); // Error de fichero para el commit;
break 1;
}
}
xml_parser_free($xml_parser);
// Se desbloquea el fichero
//~ if ( in_array( $funcion, $funcionesBloqueo ) ) {
//~ flock( $fp, LOCK_UN ) ;
//~ }
fclose( $fp );
} // De function _leerXML($funcion)
//----------------------------------------------------------------------------
function obtener ($afiltro=null){
$this->_inicializar();
$this->resultado = array();
$this->filtro = $this->_inicializarFiltros( $afiltro );
$this->_leerXML("_endElementObtener");
return $this->resultado;
}
//----------------------------------------------------------------------------
function obtenerRango ($afiltro, $afiltroDesde, $afiltroHasta ) {
// Traza
//~ trazaDepurar("obtenerRango", $this->xml);
// Fin de traza
$this->_inicializar();
$this->resultado = array();
$this->filtro = $this->_inicializarFiltros( $afiltro );
$this->filtroDesde = $this->_inicializarFiltros( $afiltroDesde );
$this->filtroHasta = $this->_inicializarFiltros( $afiltroHasta );
$this->_leerXML("_endElementObtenerRango");
return $this->resultado;
}
//----------------------------------------------------------------------------
function obtenerRangoCampos ($campos, $afiltro, $afiltroDesde, $afiltroHasta ) {
$this->_inicializar();
$this->resultado = array();
$this->filtro = $this->_inicializarFiltros( $afiltro );
$this->filtroDesde = $this->_inicializarFiltros( $afiltroDesde );
$this->filtroHasta = $this->_inicializarFiltros( $afiltroHasta );
$this->campos = $campos;
$this->_leerXML("_endElementObtenerRangoCampos");
return $this->resultado;
}
//----------------------------------------------------------------------------
function obtenerBuscadorWeb ( $cadena, $camposB = null ) {
$cadenaVector = $this->_troceaCadena($cadena);
$primera = true;
$vectorResultados = array();
foreach( $cadenaVector as $cadenaUnica ) {
if ( $primera ) {
$vectorResultados = $this->obtenerBuscador( $cadenaUnica, $camposB );
$primera = false;
} else {
$vectorResultados = $this->filtrarBuscador( $cadenaUnica, $camposB, $vectorResultados );
}
} // De foreach( $cadenaVector as $cadenaUnica )
$this->resultado = $vectorResultados;
return $this->resultado;
} // De function obtenerBuscadorWeb ( $cadena, $camposB = null )
//----------------------------------------------------------------------------
function filtrarBuscadorWeb ( $cadena, $camposB = null, $tabla = null ) {
if ($tabla === null ){
$tabla = $this->resultado;
}
if ( trim( $cadena."" ) == "") {
return $tabla;
}
$cadenaVector = $this->_troceaCadena($cadena);
$vectorResultados = array();
if ( count( $tabla ) == 0 ) {
return $vectorResultados;
} else {
$vectorResultados = $tabla;
}
foreach( $cadenaVector as $cadenaUnica ) {
$vectorResultados = $this->filtrarBuscador( $cadenaUnica, $camposB, $vectorResultados );
} // De foreach( $cadenaVector as $cadenaUnica )
return $vectorResultados;
} // De function obtenerBuscadorWeb ( $cadena, $camposB = null )
//----------------------------------------------------------------------------
function obtenerBuscador( $cadena, $camposB = null ){
$this->_inicializar();
$this->resultado = array();
$this->cadenaBusqueda = $cadena;
$this->camposBuqueda = $camposB;
$this->_leerXML("_endElementObtenerBuscador");
return $this->resultado;
}
//----------------------------------------------------------------------------
function obtenerCampos ($campos, $afiltro=null){
$this->_inicializar();
$this->resultado = array();
$this->filtro = $this->_inicializarFiltros( $afiltro );
$this->campos = $campos;
$this->_leerXML("_endElementObtenerCampos");
return $this->resultado;
}
//----------------------------------------------------------------------------
function obtenerNumRegistrosRango( $afiltro, $afiltroDesde, $afiltroHasta ) {
$this->_inicializar();
$this->resultado = array();
$this->filtro = $this->_inicializarFiltros( $afiltro );
$this->filtroDesde = $this->_inicializarFiltros( $afiltroDesde );
$this->filtroHasta = $this->_inicializarFiltros( $afiltroHasta );
$this->_leerXML("_endElementObtenerNumRegistros");
if ( ! isset( $this->resultado[0] ) || $this->resultado[0] == null ) {
$this->resultado[0] = 0;
}
return $this->resultado[0];
}
//----------------------------------------------------------------------------
function obtenerNumRegistros( $afiltro=null ) {
return $this->obtenerNumRegistrosRango( $afiltro, null, null );
}
//----------------------------------------------------------------------------
function insertar ($aregistro){
// Traza
//~ trazaDepurar("insertar()");
// Fin de traza
$this->_inicializar();
$this->registro = $aregistro;
//~ $archivoCop = $this->xml."~";
if ($this->claseEscribirTabla->abrirFichero() == 0){
$this->filasAfectadas = -1;
return $this->filasAfectadas;
}
$this->_escribirRegistro($aregistro);
$this->_leerXML("_endElementInsertar");
$this->claseEscribirTabla->cerrarFichero();
if ( $this->claseEscribirTabla->bErrorEscribirFichero ) {
$this->filasAfectadas = -1;
return $this->filasAfectadas;
}
$this->filasAfectadas = 1;
return $this->filasAfectadas;
}
//----------------------------------------------------------------------------
function insertarFilas ($aregistroV){
// Traza
//~ trazaDepurar("insertarFilas()");
// Fin de traza
if ( !is_array( $aregistroV ) || count($aregistroV) == 0 ) {
return;
}
$this->_inicializar();
//~ $archivoCop = $this->xml."~";
if ( $this->claseEscribirTabla->abrirFichero() == 0){
$this->filasAfectadas = -1;
return $this->filasAfectadas;
}
foreach( $aregistroV as $registro ) {
$this->registro = $registro;
$this->_escribirRegistro($registro);
if ( $this->claseEscribirTabla->bErrorEscribirFichero ) {
break 1;
}
$this->filasAfectadas ++;
} // De foreach($aregistroV as $registro)
$this->_leerXML("_endElementInsertar");
$this->claseEscribirTabla->cerrarFichero();
if ( $this->claseEscribirTabla->bErrorEscribirFichero ) {
$this->filasAfectadas = -1;
}
return $this->filasAfectadas;
}
//----------------------------------------------------------------------------
function modificarOInsertar( $afiltro, $aregistro ) {
$regArray = $this->obtener( $afiltro );
$numRegistros = count( $regArray );
// Traza
// trazaDepurar( "numRegistros", $numRegistros );
// Fin de traza
if ( $numRegistros == 1 ) {
return $this->modificar ( $afiltro, $aregistro );
} else if ( $numRegistros == 0 ) {
return $this->insertar ( $aregistro );
}
// Si llega hasta aquí es que las filas afectadas es que ha ocurrido un error
$this->filasAfectadas = -1;
return $this->filasAfectadas;
}
//----------------------------------------------------------------------------
function modificar ($afiltro, $aregistro){
// Traza
//~ trazaDepurar("modificar()");
// Fin de traza
if ( $this->flagComprobarAntesGrabar ) {
if ( $this->obtenerNumRegistros( $afiltro ) == 0 ) {
return;
}
} // De if ( $this->flagComprobarAntesGrabar )
$this->_inicializar();
$this->registro = $aregistro;
$this->filtro = $afiltro;
if ( $this->claseEscribirTabla->abrirFichero() == 0 ){
$this->filasAfectadas = -1;
return $this->filasAfectadas;
}
$this->_leerXML("_endElementModificar");
$this->claseEscribirTabla->cerrarFichero();
if ( $this->claseEscribirTabla->bErrorEscribirFichero ) {
$this->filasAfectadas = -1;
}
return $this->filasAfectadas;
}
//----------------------------------------------------------------------------
function borrar ($afiltro){
return $this->borrarRango($afiltro, null, null);
}
//----------------------------------------------------------------------------
function borrarRango($afiltro, $afiltroDesde, $afiltroHasta){
if ( $this->flagComprobarAntesGrabar ) {
if ( $this->obtenerNumRegistrosRango( $afiltro, $afiltroDesde, $afiltroHasta ) == 0 ) {
return;
}
}
$this->_inicializar();
$this->filtro = $afiltro;
$this->filtro = $this->_inicializarFiltros( $afiltro );
$this->filtroDesde = $this->_inicializarFiltros( $afiltroDesde );
$this->filtroHasta = $this->_inicializarFiltros( $afiltroHasta );
//~ $archivoCop = $this->xml."~";
if ( $this->claseEscribirTabla->abrirFichero() == 0){
$this->filasAfectadas = -1;
return $this->filasAfectadas;
}
$this->_leerXML("_endElementBorrarRango");
$this->claseEscribirTabla->cerrarFichero();
if ( $this->claseEscribirTabla->bErrorEscribirFichero ) {
$this->filasAfectadas = -1;
}
return $this->filasAfectadas;
}
//----------------------------------------------------------------------------
function filtrar ( $filtro, $tabla = null ){
$contador = 0;
if ($tabla === null ){
$tabla = $this->resultado;
}
$filtroResultado = array();
if ( count( $tabla ) == 0 ) {
return $filtroResultado;
}
foreach($tabla as $valor) {
$encontrado = $this->_isEncontrado($valor, $filtro);
if ($encontrado){
$filtroResultado[$contador]= $valor;
$contador++;
}
} // De foreach($tabla as $valor)
/*if ($tabla == $this->resultado){
$this->resultado =$filtroResultado;
}*/
return $filtroResultado;
} // De function filtrar ( $filtro, $tabla = null )
//----------------------------------------------------------------------------
function filtrarBuscador ( $cadena, $camposB=null, $tabla = null ){
if ($tabla === null ){
$tabla = $this->resultado;
}
$filtroResultado = array();
if ( count( $tabla ) == 0 ) {
return $filtroResultado;
}
foreach($tabla as $valor) {
$encontrado = $this->_isEncontradoBuscador ($valor, $cadena, $camposB );
if ($encontrado){
$filtroResultado[]= $valor;
}
} // De foreach($tabla as $valor)
return $filtroResultado;
} // De function filtrar ( $filtro, $tabla = null )
//----------------------------------------------------------------------------
function _filtrarRangoDesdeHasta ( $filtro, $signo, $tabla = null ){
$contador = 0;
if ($tabla === null ){
$tabla = $this->resultado;
}
$filtroResultado = array();
if ( count( $tabla ) == 0 ) {
return $filtroResultado;
}
foreach($tabla as $valor) {
$encontrado = $this->_isEncontradoDesdeHasta($valor, $filtro, $signo);
if ($encontrado){
$filtroResultado[$contador]= $valor;
$contador++;
}
} // De foreach($tabla as $valor)
/*if ($tabla == $this->resultado){
$this->resultado =$filtroResultado;
}*/
return $filtroResultado;
} // De function filtrar ( $filtro, $tabla = null )
//----------------------------------------------------------------------------
function filtrarPaginar ( $regInicio, $regFin, $tabla = null ) {
if ($tabla === null ){
$tabla = $this->resultado;
}
$filtroResultado = array();
if ( count( $tabla ) == 0 ) {
return $filtroResultado;
}
$contadorControl = 0;
foreach($tabla as $valor) {
if ( $contadorControl >= $regInicio && $contadorControl < $regFin ){
$filtroResultado[]= $valor;
}
$contadorControl ++;
} // De foreach($tabla as $valor)
return $filtroResultado;
}
//----------------------------------------------------------------------------
function filtrarRango ( $filtro, $filtroDesde, $filtroHasta, $tabla = null ){
$filtroResultado = array();
$sitabla = false;
if ( ! is_null ( $filtro ) ){
$filtroResultado = $this->_filtrarRangoDesdeHasta ( $filtro, "==", $tabla);
$sitabla = true;
}
if ( ! is_null ( $filtroDesde ) ){
if ( $sitabla ) {
$filtroResultado = $this->_filtrarRangoDesdeHasta ( $filtroDesde, ">=", $filtroResultado);
} else {
$filtroResultado = $this->_filtrarRangoDesdeHasta ( $filtroDesde, ">=", $tabla);
$sitabla = true;
}
} // de if ( ! is_null ( $filtroDesde ) )
if ( ! is_null ( $filtroHasta ) ){
if ($sitabla) {
$filtroResultado = $this->_filtrarRangoDesdeHasta ( $filtroHasta, "<=", $filtroResultado );
} else {
$filtroResultado = $this->_filtrarRangoDesdeHasta ( $filtroHasta, "<=", $tabla );
$sitabla = true;
}
} // De if ( ! is_null ( $filtroDesde ) )
if ( ! $sitabla ) {
$filtroResultado = $this->resultado;
}
return $filtroResultado;
} // De function filtrar ( $filtro, $tabla = null )
//----------------------------------------------------------------------------
function _isEncontrado($registro, $filtro){
$encontrado = true;
foreach($filtro as $key => $value) {
// Si el flga de filtro estricto esta a false ( por defecto a true) y la clave no está definida en el
// registro se da por buena y se continua.
if ( ! $this->getFlagFiltroEstricto() && ! isset ( $registro[$key] ) ) {
continue;
}
if ( is_null( $registro[$key] ) || $filtro[$key] != $registro[$key] ) {
$encontrado = false;
break;
}
}
return $encontrado;
}
//----------------------------------------------------------------------------
function _isEncontradoBuscador($registro, $cadena, $camposBusqueda){
$encontrado = false;
if ($cadena == null || $cadena == "") {
return $false;
}
// Si campos de Buqueda es nulo entonces se busca en todo el registro
if ( $camposBusqueda == null ) {
$camposBusqueda = array_keys( $registro );
} // Del if ( $camposBuqueda == null )
foreach( $camposBusqueda as $nombreCampo ) {
$pos = strpos( strtoupper( $this->_remplazarAcentosOn ($registro[$nombreCampo], "" ) ), strtoupper( $this->_remplazarAcentosOn($cadena, "") ) );
// Traza
/*
print'
';var_dump($nombreCampo);print'
';
print'';var_dump($registro[$nombreCampo]);print'
';
print'';var_dump($cadena);print'
';
print'';var_dump($pos);print'
';
*/
// Fin de traza
if ($pos === false) {
$pos = -1;
}
if ( $pos >= 0 ) {
// Traza
// echo 'Paso por el TRUE
';
// Fin de traza
$encontrado = true;
break;
}
} // De foreach( $camposBusqueda as $nombreCampo )
return $encontrado;
} // De function _isEncontradoBuscador($registro, $cadena, $camposBusqueda)
//----------------------------------------------------------------------------
function _isEncontradoDesdeHasta ($registro, $filtro, $desdeHasta){
$encontrado = false;
$contadorCoincidencias = 0;
$contador = 0;
if (is_null ($filtro) ) {
return $encontrado;
}
foreach($filtro as $key => $value) {
// Si el flga de filtro estricto esta a false ( por defecto a true) y la clave no está definida en el
// registro se da por buena y se continua.
if ( ! $this->getFlagFiltroEstricto() && ! isset ( $registro[$key] ) ) {
continue;
}
$contador++;
if ( ! is_null( $registro[$key] ) ) {
if ( $desdeHasta =="<=") {
if ($filtro[$key] >= $registro[$key] ) {
$contadorCoincidencias++;
}
} else if ( $desdeHasta =="<") {
if ($filtro[$key] > $registro[$key] ) {
$contadorCoincidencias++;
}
} else if ( $desdeHasta ==">") {
if ($filtro[$key] < $registro[$key] ) {
$contadorCoincidencias++;
}
} else if ( $desdeHasta ==">=") {
if ($filtro[$key] <= $registro[$key] ) {
$contadorCoincidencias++;
}
} else if ( $desdeHasta =="==") {
if ($filtro[$key] == $registro[$key] ) {
$contadorCoincidencias++;
}
}
} // De if ( ! is_null( $registro[$key] ) )
} // De foreach($filtro as $key => $value)
if ( $contador == $contadorCoincidencias ){
return true;
} else {
return false;
}
}
//----------------------------------------------------------------------------
function _filtrarRegistro ($fila, $campos) {
if ( ! isset( $campos ) || $campos == null || ! is_array($campos) ) {
return $fila;
}
foreach($campos as $value) {
if ( !is_null ($fila[$value]) ) {
$resultado[$value] = $fila[$value];
}
}
return $resultado;
} // De function _filtrarRegistro ($fila, $campos)
//----------------------------------------------------------------------------
function filtrarMaximo ( $campo, $tabla = null ) {
if ($tabla === null ){
$tabla = $this->resultado;
}
$resultado = null;
if ( ! is_array($tabla) ) {
return $resultado;
}
foreach($tabla as $valor) {
$valorCampoAux = isset( $valor[$campo] ) ? $valor[$campo] : null ;
if ( ! is_null ( $valorCampoAux ) ) {
if ( is_null( $resultado ) || ( $valor[$campo] > $resultado ) ) {
$resultado = $valor[$campo];
} // de if ( is_null( $resultado ) || ( $valor[$campo] > $resultado ) )
} // De if ( !is_null ($valor[$campo]) )
} // de foreach($tabla as $valor)
return $resultado;
} // De function filtrarMaximo ( $campo, $tabla = null )
//----------------------------------------------------------------------------
function filtrarCampos ( $campos, $tabla = null ) {
if ($tabla === null ){
$tabla = $this->resultado;
}
$resultado = null;
if ( ! is_array($tabla) ) {
return $resultado;
}
foreach( $tabla as $valor) {
$registro = array();
foreach ( $valor as $clave => $valor2 ) {
if ( in_array( $clave, $campos ) ) {
$registro[ $clave] = $valor2;
}
}
if ( count( $registro ) != 0 ) {
$resultado[] = $registro;
}
} // de foreach($tabla as $valor)
return $resultado;
}
//----------------------------------------------------------------------------
function filtrarDistintos ( $campos, $tabla = null ) {
if ($tabla === null ){
$tabla = $this->resultado;
}
$resultado = null;
if ( ! is_array($tabla) ) {
return $resultado;
}
$tabla = $this-> filtrarCampos( $campos, $tabla );
// Se ordena los campos
$camposOrdenar = array();
foreach ( $campos as $campoReg ) {
$camposOrdenar[$campoReg] = 0;
}
$resOrdenado = $this->ordenarCampos( $camposOrdenar, $tabla );
$valorAux = array();
foreach( $resOrdenado as $valorReg) {
$chivato = false;
foreach ( $valorReg as $clave => $valor ) {
$valor2 = isset( $valorAux[$clave] ) ? $valorAux[$clave] : null;
if ( $valor != $valor2 ) {
$chivato = true;
break 1;
}
} // De foreach ( $valorReg as $clave => $valor )
if ( $chivato ) { // Si hay valores distintos se inserta
$resultado[] = $valorReg;
}
// Se actualiza el valor Auxiliar
$valorAux = $valorReg;
} // de foreach($tabla as $valor)
return $resultado;
} // De function filtrarMaximo ( $campo, $tabla = null )
//----------------------------------------------------------------------------
function filtrarSuma ( $campo, $tabla = null ) {
if ($tabla === null ){
$tabla = $this->resultado;
}
$resultado = 0;
if ( ! is_array($tabla) ) {
return $resultado;
}
foreach($tabla as $valor) {
if ( !is_null ($valor[$campo]) ) {
$resultado += $valor[$campo];
} // De if ( !is_null ($valor[$campo]) )
} // de foreach($tabla as $valor)
return $resultado;
} // De function filtrarMaximo ( $campo, $tabla = null )
//----------------------------------------------------------------------------
function _remplazarAcentosOn ($cadena, $caracter = "~"){
$resultado = $cadena;
$resultado = str_replace ("á", "a".$caracter, $resultado);
$resultado = str_replace ("é", "e".$caracter, $resultado);
$resultado = str_replace ("í", "i".$caracter, $resultado);
$resultado = str_replace ("ó", "o".$caracter, $resultado);
$resultado = str_replace ("ú", "u".$caracter, $resultado);
$resultado = str_replace ("Á", "A".$caracter, $resultado);
$resultado = str_replace ("É", "E".$caracter, $resultado);
$resultado = str_replace ("Í", "I".$caracter, $resultado);
$resultado = str_replace ("Ó", "O".$caracter, $resultado);
$resultado = str_replace ("Ú", "U".$caracter, $resultado);
return $resultado;
}
//----------------------------------------------------------------------------
function _remplazarAcentosOff ($cadena){
$resultado = $cadena;
$resultado = str_replace ('a~', 'á', $resultado);
$resultado = str_replace ('e~', 'é', $resultado);
$resultado = str_replace ('i~', 'í', $resultado);
$resultado = str_replace ('o~', 'ó', $resultado);
$resultado = str_replace ('u~', 'ú', $resultado);
$resultado = str_replace ('A~', 'Á', $resultado);
$resultado = str_replace ('E~', 'É', $resultado);
$resultado = str_replace ('I~', 'Í', $resultado);
$resultado = str_replace ('O~', 'Ó', $resultado);
$resultado = str_replace ('U~', 'Ú', $resultado);
return $resultado;
}
//----------------------------------------------------------------------------
function _inicializarFiltros( $afiltro ){
$resultado = null;
if ( isset( $afiltro ) && $afiltro != NULL && is_array( $afiltro ) && count($afiltro) > 0 ) {
$resultado = $afiltro;
}
return $resultado;
}
//----------------------------------------------------------------------------
function _troceaCadena ($cadena) {
$posicion = false;
$cadenaauxiliar = strstr ( $cadena, '"');
$resto = array();
$trocea = array();
while ($cadenaauxiliar != false) {
if ($cadenaauxiliar != false){
# Obtenenos la posición de la primera " en la cadena auxiliar.
$posicion= strpos ($cadenaauxiliar, '"', 1);
if ($posicion != false) {
// $cadena = str_replace(chr(92), '', $cadena);
//$cadenaauxiliar = str_replace(chr(92), '', $cadenaauxiliar);
# si encuentra la segunda " se saca la longitud de la cadena auxiliar
$longitud = strlen ($cadenaauxiliar);
# Se obtiene cadena auxiliar. El trozo de cadena desde la primera " hasta la segunda
//$cadenaauxiliar = substr ($cadenaauxiliar,1,$posicion-2);
$cadenaauxiliar = substr ($cadenaauxiliar,1,$posicion-1);
$posicionbis = strpos($cadena,'"');
# Se obtiene el trozo de cadena desde el primer caracter hasta la primera "
$cadenaprimera = substr($cadena,0,$posicionbis);
# Se obtiene el trozo de cadena desde la segunda " hasta el final de la cadena
$posicionsegunda = strpos($cadena,'"',$posicionbis + 1);
$cadenasegunda = substr($cadena,$posicionsegunda + 1);
# Se concatena la primera cadena con la segunada, quedando la cadena sin la parte de las comillas
$cadena= $cadenaprimera." ".$cadenasegunda;
if ($cadenaauxiliar != null && trim($cadenaauxiliar) != "") {
$resto[] = $cadenaauxiliar ;
}
# CADENA AUXILIAR TIENE LA CADENA A PARTIR DE LA PRIMERA " SIN INCLUIR ESTA
$cadenaauxiliar = strstr ( $cadena, '"');
} else { // Del if ($posicion != false)
# SI NO LA CADENA AUXILIAR ES FALSE
$cadenaauxiliar = false;
} // Del else del if ($posicion != false)
} // De if ($cadenaauxiliar != false)
} // De while ($cadenaauxiliar != false)
# Se trocea la cadena en un array en el que los elementos son palabras sueltas
$encontrado = true;
$cadena = trim( $cadena );
while( $encontrado ){
$cadena = str_replace(" ", " ", $cadena);
$pos = strpos ($cadenaauxiliar, " ");
if ( $pos === false) {
$encontrado = false;
} // Del if ( $pos === false)
} // Del while( $encontrado )
if ( $cadena != "" ) {
$trocea = split (" ", $cadena);
}
foreach( $resto as $reg ) {
if ($reg != null && trim($reg) != "") {
$trocea[]=$reg;
}
}
return $trocea;
}
//----------------------------------------------------------------------------
function getFlagComprobarAntesGrabar() {
return $this->flagComprobarAntesGrabar;
} // De function getFlagComprobarAntesGrabar()
//----------------------------------------------------------------------------
function setFlagComprobarAntesGrabar( $valor ) {
if ( $valor === true || $valor === false ) {
$this->flagComprobarAntesGrabar = $valor;
}
} // De function setFlagComprobarAntesGrabar( $valor )
//----------------------------------------------------------------------------
function getFlagFiltroEstricto() {
return $this->flagFiltroEstricto;
} // De function getFlagComprobarAntesGrabar()
//----------------------------------------------------------------------------
function setFlagFiltroEstricto( $valor ) {
if ( $valor === true || $valor === false ) {
$this->flagFiltroEstricto = $valor;
}
} // De function setFlagComprobarAntesGrabar( $valor )
//----------------------------------------------------------------------------
function getFlagCopiaSeguridad() {
return $this->claseEscribirTabla->getFlagCopiaSeguridad();
} // De function getflagCopiaSeguridad()
//----------------------------------------------------------------------------
function setFlagCopiaSeguridad( $valor ) {
$this->claseEscribirTabla-> setFlagCopiaSeguridad( $valor );
} // De function setflagCopiaSeguridad( $valor )
//----------------------------------------------------------------------------
function getFlagEscribirFicheroLog() {
return $this->claseLogTabla->getFlagEscribirFicheroLog();
} // De function getflagCopiaSeguridad()
//----------------------------------------------------------------------------
function setFlagEscribirFicheroLog( $valor ) {
$this->claseLogTabla->setFlagEscribirFicheroLog( $valor );
} // De function setflagCopiaSeguridad( $valor )
//----------------------------------------------------------------------------
function bloquearTabla(){
return $this->claseEscribirTabla->bloquearTabla();
}
//----------------------------------------------------------------------------
function desbloquearTabla(){
return $this->claseEscribirTabla->desbloquearTabla();
}
//----------------------------------------------------------------------------
function esTablaBloqueada() {
return $this->claseEscribirTabla->esTablaBloqueada();
}
//----------------------------------------------------------------------------
function Tabla($file=null){
$this->xml= $file;
$this->resultado = array();
$this->claseLogTabla = new LogTabla( $this->xml );
$this->claseEscribirTabla = new EscribirTabla( $this->xml, $this->claseLogTabla );
$this->_inicializar();
// Traza
//~ trazaDepurar ("claseEscribirTabla Constructor", $this->claseEscribirTabla);
// Fin de traza
} // De function Tabla($file=null)
} // De class Tabla
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
function EscribirTabla($file=null, $claseLogTabla)
function escribirAFichero ( $sentencia )
function bloquearTabla()
function esTablaBloqueada()
function desbloquearTabla()
function cerrarFichero()
function abrirFichero()
function getFlagCopiaSeguridad()
function setFlagCopiaSeguridad( $valor )
function getBErrorEscribirFichero()
function setBErrorEscribirFichero( $valor )
*/
class EscribirTabla {
var $xml;
var $bErrorEscribirFichero = false;
var $fp;
var $aleatorio;
var $fpBloqueo;
var $flagCopiaSeguridad = true;
var $bTablaBloqueada = false;
var $claseLogTabla;
//----------------------------------------------------------------------------
function EscribirTabla($file=null, $claseLogTabla){
$this->xml= $file;
$this->claseLogTabla = $claseLogTabla;
$this->_inicializar();
// Traza
//~ trazaDepurar("EscribirTabla xml", $this->xml);
// Fin de traza
}
//----------------------------------------------------------------------------
function _obtenerNombreFicheroBloqueo(){
$archivoBloq = $this->xml."~_";
return $archivoBloq;
}
//----------------------------------------------------------------------------
function _obtenerNombreFicheroCopia() {
$archivoCopia = $this->xml."~".$this->aleatorio;
return $archivoCopia;
}
//----------------------------------------------------------------------------
function escribirAFichero ( $sentencia ) {
if ( $this->bErrorEscribirFichero ) {
return false;
}
// Traza
//~ trazaDepurar("escribirAFichero");
// Fin de traza
$this->claseLogTabla->abrirSalidaPantalla();
// Se pasa el formato a Unix de final de línea
//~ $sentencia = stripslashes( $sentencia );
//~ $sentencia = str_replace( chr(13).chr(10), chr(10), $sentencia);
//~ $sentencia = str_replace(chr(13), chr(10), $sentencia);
$res = fputs ($this->fp , $sentencia);
if ( $res !== false ) {
// Se escribe en el fichero
$res = fflush( $this->fp );
}
if ( $res === false ) {
$salida = $this->claseLogTabla->obtenerSalidaPantalla();
$sentenciaError = "Error en escribirAFichero. $salida";
$this->bErrorEscribirFichero = true;
}
$this->claseLogTabla->cerrarSalidaPantalla();
if ( $res === false ) {
$this->claseLogTabla->escribirAFicheroLog( $sentenciaError );
}
return $res;
} // De function escribirAFichero ( $sentencia )
//----------------------------------------------------------------------------
function bloquearTabla() {
// Traza
//~ trazaDepurar( "bloquearTabla" );
// Fin de traza
if ( $this->bTablaBloqueada ) {
return false;
}
$res = $this->_crearBloqueo();
if ( $res ) {
$this->bTablaBloqueada = true;
}
return $res;
} // De function bloquearTabla()
//----------------------------------------------------------------------------
function esTablaBloqueada() {
return $this->bTablaBloqueada;
}
//----------------------------------------------------------------------------
function desbloquearTabla() {
// Traza
//~ trazaDepurar( "desbloquearTabla" );
// Fin de traza
if ( ! $this->bTablaBloqueada ) {
return false;
}
$this->bTablaBloqueada = false;
$res = $this->_quitarBloqueo();
if ( ! $res ) {
$this->bTablaBloqueada = true;
}
return $res;
} // De function desbloquearTabla()
//----------------------------------------------------------------------------
function _crearBloqueo(){
// Traza
//~ trazaDepurar( "_crearBloqueo", $this->bTablaBloqueada );
// Fin de traza
$res = true;
if ( $this->bTablaBloqueada ) {
return $res;
}
// Traza
//~ trazaDepurar( "_crearBloqueo Se bloquea");
// Fin de traza
$archivoBloq = $this->_obtenerNombreFicheroBloqueo();
$this->fpBloqueo = fopen ( $archivoBloq, "w" );
if ( $this->fpBloqueo === false ) {
$res = false;
}
if ( $res ) {
//~ if ( ! flock( $this->fpBloqueo, LOCK_EX | LOCK_NB ) ) { // Se genera un bloqueo exclusivo escritura
if ( ! flock( $this->fpBloqueo, LOCK_EX ) ) { // Se genera un bloqueo exclusivo escritura
$res = false;
}
}
return $res;
}
//----------------------------------------------------------------------------
function _quitarBloqueo(){
// Traza
//~ trazaDepurar( "_quitarBloqueo", $this->bTablaBloqueada );
// Fin de traza
if ( $this->bTablaBloqueada ) {
return true;
}
// Traza
//~ trazaDepurar( "_quitarBloqueo Se desbloquea");
// Fin de traza
$archivoBloq = $this->_obtenerNombreFicheroBloqueo();
$res = flock( $this->fpBloqueo, LOCK_UN ) ;
// Se cierra siempre
$res = fclose( $this->fpBloqueo ) && $res;
return $res;
}
//----------------------------------------------------------------------------
function cerrarFichero(){
// Traza
//~ trazaDepurar("cerrarFichero");
// Fin de traza
$res = $this->_cerrarFichero();
$res = $this->_commit();
}
//----------------------------------------------------------------------------
function _escribirFinalFichero() {
$res = $this->escribirAFichero ("\n");
return $res;
} // De function _escribirFinalFichero()
//----------------------------------------------------------------------------
function _cerrarFichero(){
// Se escribe el final del fichero
$this->_escribirFinalFichero();
$this->claseLogTabla->abrirSalidaPantalla();
$contError = 0;
// Se libera el bloqueo
if ( ! flock( $this->fp, LOCK_UN) ) {
$contError ++ ;
}
// Se cierra siempre
$res = fclose( $this->fp );
if ( $res === false ) {
$contError ++ ;
}
if ( $contError > 0 ) {
$salida = $this->claseLogTabla->obtenerSalidaPantalla();
$sentenciaError = "Error en _cerrarFichero. $salida";
}
$this->claseLogTabla->cerrarSalidaPantalla();
if ( $contError > 0 ) {
$this->bErrorEscribirFichero = true;
$this->claseLogTabla->escribirAFicheroLog( $sentenciaError );
}
}
//----------------------------------------------------------------------------
function _inicializar() {
$this->bErrorEscribirFichero = false;
$this->aleatorio = rand ( 10000, 99999);
// Liberamos el cache
//~ clearstatcache();
} // De function inicializar()
//----------------------------------------------------------------------------
function abrirFichero(){
// Traza
//~ trazaDepurar("abrirFichero");
// Fin de traza
$this->_inicializar();
$archivoCop = $this->_obtenerNombreFicheroCopia();
$archivoBloq = $this->_obtenerNombreFicheroBloqueo();
// Archivo de bloqueo
if ( ! $this->_crearBloqueo() ) {
$this->claseLogTabla->escribirAFicheroLog( "Ha fallado el bloqueo" );
$this->bErrorEscribirFichero = true;
return 0;
}
// Pruebas BORRAR!!! BORRAR!!! BORRAR!!! BORRAR!!! BORRAR!!!
//~ trazaDepurar ( "tiempo 1", time() );
//~ sleep(10);
//~ trazaDepurar ( "tiempo 2", time() );
// Fin de Pruebas BORRAR!!! BORRAR!!! BORRAR!!! BORRAR!!! BORRAR!!!
$this->claseLogTabla->abrirSalidaPantalla();
$bError = false;
$this->fp = fopen ( $archivoCop, "w" );
if ( $this->fp === false ) {
$bError = true;
}
if ( ! $bError ) {
if ( ! flock( $this->fp, LOCK_EX | LOCK_NB ) ) { // Se genera un bloqueo exclusivo escritura
$bError = true;
}
}
if ( $bError ) {
$salida = $this->claseLogTabla->obtenerSalidaPantalla();
$sentenciaError = "Error en _abrirFichero. $salida";
}
$this->claseLogTabla->cerrarSalidaPantalla();
if ( $bError ) {
$this->bErrorEscribirFichero = true;
$this->claseLogTabla->escribirAFicheroLog( $sentenciaError );
return -1;
}
$res = $this->_escribirCabeceraFichero();
if ( $res === false ) {
return -1;
}
// Si llega aquí todo correcto
return 1;
}
//----------------------------------------------------------------------------
function _escribirCabeceraFichero() {
$res = $this->escribirAFichero ("\n");
if ( $res === false ) {
return -1;
}
$res = $this->escribirAFichero ("\n");
if ( $res === false ) {
return -1;
}
// Si llega aquí todo correcto
return 1;
} // De function _escribirCabeceraFichero()
//----------------------------------------------------------------------------
function _borrarFichero (){
$this->claseLogTabla->abrirSalidaPantalla();
$res = unlinK( $this->_obtenerNombreFicheroCopia() );
if ( $res === false ) {
$salida = $this->claseLogTabla->obtenerSalidaPantalla();
$sentenciaErrorUnlink = "Error en _borrarFichero (unlinK). $salida";
}
$this->claseLogTabla->cerrarSalidaPantalla();
if ( $res === false ) {
$this->bErrorEscribirFichero = true;
$this->claseLogTabla->escribirAFicheroLog( $sentenciaErrorUnlink );
}
// Se borra el bloqueo
$this->_quitarBloqueo();
return $res;
} // De function _borrarFichero ()
//----------------------------------------------------------------------------
function _copiarFichero () {
$this->claseLogTabla->abrirSalidaPantalla();
if ( $this->bErrorEscribirFichero ) {
$sentenciaErrorbError = "Error en _copiarFichero this->bErrorEscribirFichero es true";
$this->claseLogTabla->escribirAFicheroLog( $sentenciaErrorbError );
return false;
}
$res = true;
if ($this->flagCopiaSeguridad) {
$res = copy ($this->xml, $this->xml.".".date ('YmdHis') );
if ( $res == false ) {
$this->bErrorEscribirFichero = true;
$salida = $this->claseLogTabla->obtenerSalidaPantalla();
$sentenciaErrorCopySeguridad = "Error en _copiarFichero (copy seguridad). $salida";
}
}
if ( $res == true ) {
$res = copy ($this->_obtenerNombreFicheroCopia(), $this->xml);
if ( $res === false ) {
$this->bErrorEscribirFichero = true;
$salida = $this->claseLogTabla->obtenerSalidaPantalla();
$sentenciaErrorCopy = "Error en _copiarFichero (copy). $salida";
}
}
$this->claseLogTabla->cerrarSalidaPantalla();
// Se escribe el error en el fichero de log si procede
if ( isset( $sentenciaErrorCopySeguridad ) ) {
$this->claseLogTabla->escribirAFicheroLog( $sentenciaErrorCopySeguridad );
}
if ( isset( $sentenciaErrorCopy ) ) {
$this->claseLogTabla->escribirAFicheroLog( $sentenciaErrorCopy );
}
return $res;
}
//----------------------------------------------------------------------------
function _commit() {
$res = $this->_copiarFichero();
$res = $this->_borrarFichero();
} // De function _commit()
//----------------------------------------------------------------------------
function getFlagCopiaSeguridad() {
return $this->flagCopiaSeguridad;
} // De function getflagCopiaSeguridad()
//----------------------------------------------------------------------------
function setFlagCopiaSeguridad( $valor ) {
if ( $valor === true || $valor === false ) {
$this->flagCopiaSeguridad = $valor;
}
} // De function setflagCopiaSeguridad( $valor )
//----------------------------------------------------------------------------
function getBErrorEscribirFichero() {
return $this->bErrorEscribirFichero;
} // De function getflagCopiaSeguridad()
//----------------------------------------------------------------------------
function setBErrorEscribirFichero( $valor ) {
if ( $valor === true || $valor === false ) {
$this->bErrorEscribirFichero = $valor;
}
} // De function setflagCopiaSeguridad( $valor )
//----------------------------------------------------------------------------
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
function LogTabla( $file )
function escribirAFicheroLog ( $salida )
function abrirSalidaPantalla()
function cerrarSalidaPantalla( $resConfiguracion = null )
function obtenerSalidaPantalla()
function getFlagEscribirFicheroLog()
function setFlagEscribirFicheroLog( $valor )
*/
class LogTabla {
var $resConfiguracion ;
var $flagEscribirFicheroLog = true;
var $xml;
function LogTabla( $file ){
$resConfiguracion = null;
$this->xml = $file;
}
//----------------------------------------------------------------------------
function escribirAFicheroLog ( $salida ) {
if ( ! $this->flagEscribirFicheroLog ) {
return;
}
$ficheroLog = dirname(__FILE__).DIRECTORY_SEPARATOR."errorlog.log";
$gestor = fopen( $ficheroLog, 'a');
$salida = date ('Y.m.d..H.i.s')." -> TABLA (".$this->xml.") :: $salida\r\n";
fwrite($gestor, $salida);
fclose($gestor);
} // De function _escribirAFicheroLog ( $sentencia )
//----------------------------------------------------------------------------
function abrirSalidaPantalla() {
$html_errors = ini_get ( "html_errors" );
$error_reporting = error_reporting( E_ALL );
ini_set ( "html_errors", 0 );
ob_start();
$resConfiguracion = array();
$resConfiguracion["error_reporting"] = $error_reporting;
$resConfiguracion["html_errors"] = $html_errors;
$this->resConfiguracion = $resConfiguracion;
return $resConfiguracion;
}
//----------------------------------------------------------------------------
function cerrarSalidaPantalla( $resConfiguracion = null ) {
if ( $resConfiguracion == null ){
$resConfiguracion = $this->resConfiguracion;
}
ob_end_clean ( );
$html_errors = isset( $resConfiguracion["html_errors"] ) ? $resConfiguracion["html_errors"] : 1;
$error_reporting = isset( $resConfiguracion["error_reporting"] ) ? $resConfiguracion["error_reporting"] : E_ALL;
ini_set ( "html_errors", $html_errors );
error_reporting( $error_reporting );
}
//----------------------------------------------------------------------------
function obtenerSalidaPantalla() {
$salida = ob_get_contents();
return $salida;
}
//----------------------------------------------------------------------------
function getFlagEscribirFicheroLog() {
return $this->flagEscribirFicheroLog;
} // De function getflagCopiaSeguridad()
//----------------------------------------------------------------------------
function setFlagEscribirFicheroLog( $valor ) {
if ( $valor === true || $valor === false ) {
$this->flagEscribirFicheroLog = $valor;
}
} // De function setflagCopiaSeguridad( $valor )
//----------------------------------------------------------------------------
} // De class LogTabla
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
function Vista( $tabla1, $tabla2, $union )
function obtener( $filtro = null )
function obtenerCampos ( $campos, $filtro = null)
function obtenerRango ($afiltro, $afiltroDesde, $afiltroHasta )
function obtenerBuscador( $cadena, $camposB = null )
function obtenerRangoCampos ($campos, $filtro, $filtroDesde, $filtroHasta )
*/
class Vista extends Tabla {
//class Vista {
var $tablaMaestra;
var $tablaSierva;
var $union;
//----------------------------------------------------------------------------
function Vista( $tabla1, $tabla2, $union ) {
$this->tablaMaestra = $tabla1;
$this->tablaSierva = $tabla2;
$this->union = $union;
} // De function Tabla( $tabla1, $tabla2, $union )
//----------------------------------------------------------------------------
function obtener( $filtro = null ) {
return $this->obtenerRango( $filtro, null, null );
} // De function obtener ()
//----------------------------------------------------------------------------
function obtenerCampos ( $campos, $filtro = null){
return $this->obtenerRangoCampos ($campos, $filtro, null, null );
} // De function obtener ()
//----------------------------------------------------------------------------
function _asignarObtenerTablas( $filtro, $filtroDesde, $filtroHasta ) {
$tabla1 = $this->tablaMaestra;
$tabla2 = $this->tablaSierva;
// Se obtiene el flagFiltroEstricto de cada una de las tablas
$flagFiltroEstrictoTabla1 = $tabla1->getFlagFiltroEstricto();
$flagFiltroEstrictoTabla2 = $tabla2->getFlagFiltroEstricto();
// Se ponen a false. Esto nos permite hacer un filtrado con claves en los filtros que no están
// definidos en los registros de las tablas, lo que permite no realizar la obtención de los datos
// con todas los registros de las tablas.
$tabla1->setFlagFiltroEstricto( false );
$tabla2->setFlagFiltroEstricto( false );
// Se obtiene los valores de la tablas
$tabla1->obtenerRango( $filtro, $filtroDesde, $filtroHasta );
$tabla2->obtenerRango( $filtro, $filtroDesde, $filtroHasta );
// Traza
//~ trazaDepurar( '_asignarObtenerTablas filtro' , $filtro);
//~ trazaDepurar( '_asignarObtenerTablas filtroDesde' , $filtroDesde);
//~ trazaDepurar( '_asignarObtenerTablas filtroHasta' , $filtroHasta);
//~ trazaDepurar( 'Tabla1 ' . $tabla1->xml , $tabla1->resultado );
//~ trazaDepurar( 'Tabla2 ' . $tabla2->xml , $tabla2->resultado );
//~ trazaDepurar( 'Tabla1 ' . $tabla1->xml , count( $tabla1->resultado ) );
//~ trazaDepurar( 'Tabla2 ' . $tabla2->xml , count( $tabla2->resultado ) );
// Fin de traza
// Se comprueban los resultados y se asigna la tabla Maestra y la sierva
if ( count( $tabla2->resultado ) > count( $tabla1->resultado ) ) {
$this->tablaSierva = $tabla1;
$this->tablaMaestra = $tabla2;
} else {
$this->tablaSierva = $tabla2;
$this->tablaMaestra = $tabla1;
} // De if ( count( $tabla2->resultado ) > count( $tabla1->resultado ) )
// Se vuelven a poner los flags de las tablas como antes
$tabla1->setFlagFiltroEstricto( $flagFiltroEstrictoTabla1 );
$tabla2->setFlagFiltroEstricto( $flagFiltroEstrictoTabla2 );
} // De function obtener ()
//----------------------------------------------------------------------------
function obtenerRango ($afiltro, $afiltroDesde, $afiltroHasta ) {
$this->_inicializar() ;
$this->_asignarObtenerTablas ( $afiltro, $afiltroDesde, $afiltroHasta ) ;
// Asignación de variables
$this->filtro = $this->_inicializarFiltros( $afiltro );
$this->filtroDesde = $this->_inicializarFiltros( $afiltroDesde );
$this->filtroHasta = $this->_inicializarFiltros( $afiltroHasta );
$this->resultado = $this->_meclar ();
$this->_liberarTablas ();
return $this->resultado;
} // De function obtenerRango ($afiltro, $afiltroDesde, $afiltroHasta )
//----------------------------------------------------------------------------
function obtenerBuscador( $cadena, $camposB = null ) {
$this->_inicializar() ;
$this->_asignarObtenerTablas ( null, null, null ) ;
$this->resultado = $this->_meclar ();
$this->resultado = $this->filtrarBuscador($cadena, $camposB);
$this->_liberarTablas ();
return $this->resultado;
} // De function obtenerRango ($afiltro, $afiltroDesde, $afiltroHasta )
//----------------------------------------------------------------------------
function obtenerRangoCampos ($campos, $filtro, $filtroDesde, $filtroHasta ) {
$this->_inicializar() ;
$this->_asignarObtenerTablas ( $filtro, $filtroDesde, $filtroHasta ) ;
$this->filtro = $filtro;
$this->filtroDesde = $filtroDesde;
$this->filtroHasta = $filtroHasta;
$this->campos = $campos;
$this->resultado = $this->_meclar ();
$this->_liberarTablas ();
return $this->resultado;
}
//----------------------------------------------------------------------------
function _liberarTablas () {
$tabla1 = $this->tablaMaestra;
$tabla2 = $this->tablaSierva;
$tabla1->resultado = null;
$tabla2->resultado = null;
$this->tablaMaestra = $tabla1;
$this->tablaSierva = $tabla2;
} // De function obtener ()
//----------------------------------------------------------------------------
function _meclar () {
// Se recoge la tabla maestra
$tablaMaestra = $this->tablaMaestra;
$tablaSierva = $this->tablaSierva;
$union = $this->union;
$resultado = array();
foreach($tablaMaestra->resultado as $registro) {
// Se recorre los campos de la Union
$filtro = array();
foreach ( $union as $valor ) {
$filtro[$valor] = $registro[$valor];
} // De foreach ( $union as $valor )
$registro2 = $tablaSierva->filtrar($filtro) ;
if ( count( $registro2 ) >= 1 ) {
foreach( $registro2 as $registroUnico ) {
$registroTotal = array_merge( $registro, $registroUnico);
$chivato = true;
$chivato = $this->_isEndElementObtenerRango($registroTotal);
if ( $chivato ) {
if ( ! is_null( $this->campos ) ) {
$registroTotal = $this->_filtrarRegistro ($registroTotal , $this->campos);
} // de if ( ! is_null( $this->campos ) )
$resultado[ ] = $registroTotal ;
} // de if ( $chivato )
} // Del foreach( $registro2 as $registroUnico )
} // de if ( count( $registro2 ) > 0 )
} // De foreach($tablaMaestra as $key => $value)
return $resultado ;
} // De function obtener ()
//----------------------------------------------------------------------------
function modificarOInsertar( $afiltro, $aregistro ) {
return -1;
}
} // class Vista extends Tabla
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
// Pruebas
$tabla1 = new Tabla('../datos/provincia.datos');
$tabla2 = new Tabla('../datos/com_autonoma.datos');
$union[0] = 'AUT_ID';
$campos[0] = 'AUT_DESCRIPCION';
$campos[1] = 'PRO_DESCRIPCION';
$filtro['AUT_ID'] = 1;
$vista = new Vista($tabla1, $tabla2, $union);
$vista->obtenerCampos( $campos, $filtro);
$resultado = $vista->ordenar ("AUT_DESCRIPCION",1);
// Traza
//print'';print_r($vista->resultado);print'
';
print'';print_r($resultado);print'
';
// fin de Traza
$tabla = new Tabla('../datos/provincia.datos');
$tabla->obtener();
// Traza
print'';print_r($tabla->filtrarBuscador ('ale'));print'
';
// fin de Traza
$registro['CIR_ID']=100;
$registro['TCI_ID']='MX';
$registro['AUT_ID']=1;
$registro['PRO_ID']=11;
$registro['CIR_LOCALIDAD']='localidad de prueba';
$registro['CIR_NOMBRE']='nombre del circuito';
$registro['CIR_MOTOCLUB'] ='motoclubdel circuito';
$registro['CIR_OBSERVACIONES']='Es de tierra roja y muy variado. Tiene riego y suele ser arreglado todos meses ser cobra por montar.
Se encuentra junto al campo de f?tbol.';
$registro['CIR_FECHAALTA']=20040101;
$registro['CIR_MAPA']="javascript:top.contenido.anadirmapa('aragonmp/Zmallen.gif')";
$filtro['CIR_ID']=2;
$registro['CIR_NOMBRE']='Casiopea';
$registro['CIR_LOCALIDAD']='Esto parece que funciona';
$tabla->borrar ($registro);
//$filtroprueba["AUT_ID"] = 7;
//$filtroprueba = $tabla->filtrar ($filtroprueba);
//$filtroprueba = $tabla->ordenar ("PRO_DESCRIPCION",1,$filtroprueba);
*/
// Fin de pruebas
?>
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR."notaltetiqueta.class.php");
class Noticias {
var $tabla = null;
var $numeroRegistrosPagina = null;
var $pagina = null;
var $resultado = null;
var $paginar = null;
var $fechaModificacion = null;
var $numeroRegistros = null;
var $numeroTotalRegistros = null;
var $regIni = null;
var $regFin = null;
var $ARCHIVO;
var $TODAS;
var $RECIENTES;
/////////////////////////////////////////////
function Noticias( $tabla) {
$this->tabla = $tabla;
$this->resultado = array();
$this->resultado['NOTICIA'] = array();
$this->resultado['NOTICIA_BLOQUES'] = array();
$this->resultado['ULTIMOS_TITULARES'] = array();
$this->resultado['PAGINACION'] = array();
$this->paginar = array();
$this->paginar['ES_SIGUIENTE'] = false;
$this->paginar['PAGINA_SIGUIENTE'] = 0;
$this->paginar['ES_ANTERIOR'] = false;
$this->paginar['PAGINA_ANTERIOR'] = 0;
$this->fechaModificacion = "00000000";
$this->numeroRegistros = 0;
$this->numeroTotalRegistros = 0;
$this->regIni = 0;
$this->regFin = 0;
$this->ARCHIVO = "A";
$this->RECIENTES = "R";
$this->TODAS = "T";
} // De function Noticias( $tabla )
/////////////////////////////////////////////
function _obtenerUltimosTitulares ($notId , $todas, $numeroTitulares ) {
$resultado = array();
$filtro = null ;
$filtroHasta = null;
$filtroDesde = null;
if ( ! $todas ) { // Se mira las que están editadas y las que tengan fecha igual o anterior a la de hoy
$filtro['NOT_EDICION_SN'] = 'S';
$filtro['NOT_BLOQUES_SN'] = 'S';
$filtroHasta['NOT_FECHA'] = date ('Ymd');
$filtroDesde['NOT_FECHA_FIN'] = date ('Ymd');
}
$resultado2 = $this->tabla->obtenerRango ($filtro, $filtroDesde, $filtroHasta );
if (count( $this->tabla->resultado ) > 0 ) {
unset($orden);
$orden['NOT_FECHA'] = 1;
$orden['NOT_ID'] = 1;
$resultado2 = $this->tabla->ordenarCampos( $orden);
} // De if (count( $this->resultado ) > 0 )
// Traza
// trazaDepurar("resultado2", $resultado2);
// Fin de traza
// Se sacan filtran los resultados menos los del id que se pasan
$i = 0;
// Traza
// trazaDepurar( "this->tabla->resultado", $this->tabla->resultado );
// Fin de traza
foreach ($resultado2 as $valor) {
if ( $valor['NOT_ID'] != $notId) {
$valorAux = array();
$valorAux['NOT_ID'] = $valor['NOT_ID'];
$valorAux['NOT_TITULAR'] = sustituirHTMLXML( $valor['NOT_TITULAR'] );
$valorAux['NOT_FECHA'] = formatoFecha( $valor['NOT_FECHA'] ) ;
$resultado[] = $valorAux;
$i++;
}
if ( $i == $numeroTitulares ) {
break 1;
} // De if ( $i == $numeroTitulares )
} // De foreach ($this->tabla->resultado as $valor)
$this->resultado['ULTIMOS_TITULARES'] = $resultado;
} // De function obtenerUltimosTitulares ($notId , $todas)
/////////////////////////////////////////////
function _obtenerDatosSQLIdNoticias($notId , $todas) {
$filtro['NOT_ID'] = $notId ;
$filtroHasta = null;
$filtroDesde = null;
if ( ! $todas ) { // Se mira las que están editadas y las que tengan fecha igual o anterior a la de hoy
$filtro['NOT_EDICION_SN'] = 'S';
$filtroHasta['NOT_FECHA'] = date ('Ymd');
//~ $filtroDesde['NOT_FECHA_FIN'] = date ('Ymd');
}
// Traza
// trazaDepurar( "filtro", $filtro );
// trazaDepurar( "filtroDesde", $filtroDesde );
// trazaDepurar( "filtroHasta", $filtroHasta );
// Fin de traza
// Se obtienen los datos
$this->tabla->obtenerRango ($filtro, $filtroDesde, $filtroHasta );
if ( count( $this->tabla->resultado) == 1) {
$this->resultado['NOTICIA'] = $this->tabla->resultado[0];
}
// Si ha devuelto una fila se calculan sus bloques
if ( count( $this->resultado['NOTICIA'] ) > 0 && $this->resultado['NOTICIA']['NOT_BLOQUES_SN'] == 'S') {
$this->_obtenerDatosSQLIdNoticiasBolques ( $notId );
}
} // Defunction _obtenerDatosSQL()
/////////////////////////////////////////////
function _obtenerDatosSQLIdNoticiasBolques( $notId ) {
$filtro['NOT_ID'] = $notId ;
// Se crea la tabla
$xmlBloques = $this->_obtenerXMLBloques();
$tablaNoticiasBloques = new Tabla ( $xmlBloques );
// Se obtienen los datos
$tablaNoticiasBloques->obtener ($filtro);
$res = $tablaNoticiasBloques->ordenar("NBL_ID", 0);
$this->resultado['NOTICIA_BLOQUES'] = $res;
unset ($tablaNoticiasBloques);
} // Defunction _obtenerDatosSQL()
/////////////////////////////////////////////
function _borrarFotos( $resultado, $clave, $rutaRelativa ) {
$error = "";
$i=1;
// if (! is_array( $resultado ) ) {
// return $error;
// }
foreach( $resultado as $registro ) {
$foto = trim( $registro[$clave]."" ) ;
if ( $foto != "" ) {
$res = borrarFichero ( $rutaRelativa.$foto);
if ( ! $res["resultado"] ) {
$error .= "Error al borrar el registro $i. ".$res["error"]."
";
}
} // De if ( $foto != "" )
$i++;
} // De foreach( $resultado as $registro )
return $error;
} // De function _borrarFotos( $resultado, $clave )
/////////////////////////////////////////////
function _obtenerXMLBloques(){
$xmlBloques = $this->tabla->xml;
$xmlBloques = str_replace('noticias.datos', 'noticias_bloques.datos', $xmlBloques);
return $xmlBloques;
}
/////////////////////////////////////////////
function _obtenerXMLNotEtiquetas(){
$xmlBloques = $this->tabla->xml;
$xmlBloques = str_replace('noticias.datos', 'noticias_etiquetas.datos', $xmlBloques);
return $xmlBloques;
}
/////////////////////////////////////////////
function _borrarEtiquetas( $filtro ) {
$res = array();
$res['filasAfectadas'] = -1;
$res['error'] = "";
// Taza
//~ trazaDepurar( "NOT_ETIQUETAS_SN", $this->resultado["NOTICIA"]["NOT_ETIQUETAS_SN"] );
// Fin de traza
if (! isset( $this->resultado["NOTICIA"]["NOT_ETIQUETAS_SN"] )
|| strtoupper ( trim( $this->resultado["NOTICIA"]["NOT_ETIQUETAS_SN"] ) ) != "S") {
$res['resultado'] = false;
return $res;
}
$xmlEtiquetas = $this->_obtenerXMLNotEtiquetas();
$tablaEtiquetas = new Tabla ( $xmlEtiquetas );
$res['filasAfectadas'] = $tablaEtiquetas->borrar( $filtro );
if ( $res <= -1 ) {
$res['error'] .= "No se ha borrado las etiquetas de la noticia";
return $res;
}
$res['resultado'] = true;
return $res;
}
/////////////////////////////////////////////
function _borrarBloque( $vector, $filtro, $rutaRelativa ) {
$res = array();
$res['filasAfectadas'] = -1;
$res['resultado'] = false;
$res['error'] = "";
$errorRes = $this->_borrarFotos( $vector, "NBL_FOTO", $rutaRelativa ) ;
if ( trim( $errorRes ) != "" ) {
$res['error'] .= "No se ha borrado la foto del bloques de noticia:
$errorRes
";
return $res;
}
// Se borran los bloques de la noticia. No se controlan los errores
$xmlBloques = $this->_obtenerXMLBloques();
$tablaNoticiasBloques = new Tabla ( $xmlBloques );
$tablaNoticiasBloques->borrar($filtro);
$res['filasAfectadas'] = $tablaNoticiasBloques->filasAfectadas;
$res['resultado'] = true;
return $res;
} // De function _borrarBloque( $vector, $filtro, $rutaRelativa )
/////////////////////////////////////////////
function borrarBloque( $nblId, $rutaRelativa ) {
$res = array();
$res['filasAfectadas'] = -1;
$res['resultado'] = false;
$res['error'] = "";
$vector = $this->resultado['NOTICIA_BLOQUES'];
$numeroBloques = count( $vector );
if ( $numeroBloques <= 0 ) {
$res['error'] .= "No existe ningún bloque que borrar";
return $res;
}
$tablaVacia = new Tabla ( );
$filtro["NBL_ID"] = $nblId;
$vector = $tablaVacia->filtrar( $filtro, $vector );
$res = $this->_borrarBloque( $vector, $filtro, $rutaRelativa );
if ( ! $res['resultado'] ) {
return $res;
}
if ( $numeroBloques == 1 ) { // Se actualiza la noticia
$this->_modNotBloquesSN();
} // De if ( $numeroBloques == 1 )
return $res;
} // De function borrarBloque( $nblId, $rutaRelativa )
/////////////////////////////////////////////
function _modNotBloquesSN( ) {
$filtro["NOT_ID"] = $this->resultado['NOTICIA']['NOT_ID'];
$reg["NOT_BLOQUES_SN"] = "N";
$this->tabla->modificar( $filtro, $reg );
} // De function _modNotBloquesSN( )
/////////////////////////////////////////////
function borrarNoticia( $rutaRelativa ) {
$res = array();
$res['filasAfectadas'] = -1;
$res['resultado'] = false;
$res['error'] = "";
$noticiaBloquesV = $this->resultado['NOTICIA_BLOQUES'];
$filtro["NOT_ID"] = $this->resultado['NOTICIA']['NOT_ID'];
// Se borran los bloques no se controlan los errores
$res2 = $this->_borrarBloque( $noticiaBloquesV, $filtro, $rutaRelativa );
$res['error'] .= $res2['error'];
// Se borran las etiquetas de la noticia
$res2 = $this->_borrarEtiquetas( $filtro ) ;
$res['error'] .= $res2['error'];
// Se borra la foto de la noticia
unset( $noticiaV );
$noticiaV[] = $this->resultado['NOTICIA'];
$errorRes = $this->_borrarFotos( $noticiaV, "NOT_FOTO", $rutaRelativa ) ;
if ( trim( $errorRes ) != "" ) {
$res['error'] .= "No se ha borrado la foto de la noticia:
$errorRes
";
}
// Se borrar la tabla de noticias
$this->tabla->borrar($filtro);
$res['filasAfectadas'] = $this->tabla->filasAfectadas;
$res['resultado'] = true;
return $res;
} // De function borrarNoticia( $rutaRelativa )
/////////////////////////////////////////////
function _obtenerArrayMenuModificarBorrar( $parametro ){
$modificarMenu = array();
$modificarMenu["-1"] = "Seleccione una opción";
$modificarMenu["0"] = "$parametro noticia" ;
$bloques = $this->resultado['NOTICIA_BLOQUES'];
$i = 1;
foreach ( $bloques as $bloque) {
$modificarMenu[ $bloque["NBL_ID"] ] = "$parametro bloque ".$i;
$i++;
}
return $modificarMenu;
} // De function obtenerArrayMenuModificar()
/////////////////////////////////////////////
function obtenerArrayMenuModificar(){
return $this->_obtenerArrayMenuModificarBorrar("Modificar");
} // De function obtenerArrayMenuModificar()
/////////////////////////////////////////////
function obtenerArrayMenuBorrar(){
return $this->_obtenerArrayMenuModificarBorrar("Borrar");
} // De function obtenerArrayMenuModificar()
/////////////////////////////////////////////
function obtenerArrayMenuAlta(){
$altaMenu = array();
$altaMenu["-1"] = "Seleccione una opción";
$altaMenu["0"] = "Alta noticia" ;
$altaMenu["1"] = "Alta bloque" ;
return $altaMenu;
} // De function obtenerArrayMenuModificar()
/////////////////////////////////////////////
function _obtenerDatosSQL() {
$filtro['NOT_EDICION_SN'] = 'S';
$campos[] = 'MEC_PREGUNTA';
$campos[] = 'MEC_QUIEN';
$campos[] = 'NOT_ID';
$campos[] = 'NOT_FECHA';
$campos[] = 'NOT_EDICION_SN';
// Se obtienen los datos
$this->tabla->obtenerCampos ($campos, $filtro);
$orden['ENL_NOMBRE'] = 0;
// Se ordenan los datos
$this->resultado = $this->tabla->ordenar('NOT_FECHA', 1);
} // Defunction _obtenerDatosSQL()
/////////////////////////////////////////////
function _obtenerDatosSQLBuscador( $cadenaBuqueda, $todas = "N" ) {
// Se obtienen los datos
if ( $todas == $this->TODAS ) {
$this->tabla->obtener();
} else {
$filtro = null;
$filtroDesde = null;
$filtroHasta = null;
$filtro["NOT_EDICION_SN"] = "S";
$filtroHasta["NOT_FECHA"] = date ('Ymd');
if ( $todas == $this->ARCHIVO ) { // Se sacan las de archivo
$filtroHasta['NOT_FECHA_FIN'] = ( date ('Ymd') ) -1;
} else { // Se sacan las recientes
$filtroDesde['NOT_FECHA_FIN'] = date ('Ymd');
}
$this->tabla->obtenerRango ($filtro, $filtroDesde, $filtroHasta );
} // De if ( $todas )
$this->resultado = $this->tabla->resultado;
$this->resultado = $this->tabla->filtrarBuscadorWeb( $cadenaBuqueda );
// Se calcula el número de registros antes de paginar
$this->_numeroRegistros();
// Se ordenan los datos
if (count( $this->resultado ) > 0 ) {
unset($orden);
$orden['NOT_FECHA'] = 1;
$orden['NOT_ID'] = 1;
$this->resultado = $this->tabla->ordenarCampos( $orden, $this->resultado );
} // De if (count( $this->resultado ) > 0 )
} // Defunction _obtenerDatosSQL()
/////////////////////////////////////////////
function _paginacion() {
// Si la página es -1
if ( $this->pagina == -1 ) {
return;
}
$regIni = $this->pagina * $this->numeroRegistrosPagina;
$regFin = ( $this->pagina + 1 ) * $this->numeroRegistrosPagina;
$this->regIni = $regIni + 1;
$this->regFin = $regFin;
if ( $regFin > count($this->resultado) ) {
$this->regFin = count($this->resultado);
}
$numeroPaginas = ceil ( count( $this->resultado) / $this->numeroRegistrosPagina );
if ( ( $this->pagina + 1 ) < $numeroPaginas ) {
$this->paginar['ES_SIGUIENTE'] = true;
$this->paginar['PAGINA_SIGUIENTE'] = $this->pagina + 1;
}
if ( $this->pagina > 0 ) {
$this->paginar['ES_ANTERIOR'] = true;
$this->paginar['PAGINA_ANTERIOR'] = $this->pagina - 1;
}
$this->resultado = $this->tabla->filtrarPaginar( $regIni, $regFin, $this->resultado );
// Valores para el template de la paginacion
// for ($i=0; $i < $numeroPaginas; $i++){
// $this->paginar[$i]= $i +1 .' de '.$numeroPaginas;
// } // De for ($i=0; $i < $numeroPaginas; $i++)
} // Defunction _obtenerDatosSQL()
/////////////////////////////////////////////
function _colocarResultados( $todas = false ) {
$resultado = array();
foreach ($this->resultado as $registro) {
$resultado[] = $this->_colocarResultadosRegistro( $registro, $todas );
} // De foreach ($tablaMecanica->resultado as $registro)
$this->resultado= $resultado;
} // Defunction _colocarResultados()
/////////////////////////////////////////////
function _colocarResultadosNoticia( $todas = false ) {
$this->resultado['NOTICIA'] = $this->_colocarResultadosRegistro( $this->resultado['NOTICIA'], $todas );
} // De function _colocarResultadosNoticia( )
////////////////////////////////////////////
function _colocarResultadosBloques( ) {
for ($i=0 ; $iresultado['NOTICIA_BLOQUES'] ); $i++ ) {
$this->resultado['NOTICIA_BLOQUES'][$i] = $this->_colocarResultadosRegistro( $this->resultado['NOTICIA_BLOQUES'][$i] );
} // De foreach ($i=0 ; $iresultado['NOTICIA_BLOQUES'] ); $i++ )
} // De function _colocarResultadosNoticia( )
/////////////////////////////////////////////
function _preProcesador( $valor, $notId ) {
$resultado = quitarCaracteresNoNecesarios( $valor );
$resultado = preProcesador( $resultado );
$resultado = str_replace( "[LEERMAS/]" , "(leer más)" ,$resultado );
return $resultado;
} // De function _preProcesador( $valor )
/////////////////////////////////////////////
function _colocarResultadosRegistro( $registro, $todas = false ) {
$reg= array();
if ( isset( $registro["NOT_ID"] ) ){
$notId = $registro['NOT_ID'];
foreach ($registro as $clave => $valor) {
$reg[$clave] = $this->_preProcesador( sustituirHTMLXML( $valor ) , $notId);
}
}
// Se le quita el nombre de la ruta
if ( isset( $registro["NBL_FOTO"] ) ){
$reg["NBL_FOTO_S"] = substr( $registro["NBL_FOTO"], strrpos ( $registro["NBL_FOTO"], '/') +1 );
}
if ( isset( $registro["NOT_FOTO"] ) ){
$reg["NOT_FOTO_S"] = substr( $registro["NOT_FOTO"], strrpos ( $registro["NOT_FOTO"], '/') +1 );
}
$reg["NOT_FUERA_FECHAS_SN"] = "S";
if ( isset( $reg["NOT_FECHA"] ) && isset( $reg["NOT_FECHA_FIN"] ) ) {
if ( $reg["NOT_FECHA"] <= date ('Ymd') && $reg["NOT_FECHA_FIN"] >= date ('Ymd') ){
$reg["NOT_FUERA_FECHAS_SN"] = "N";
}
} // De if ( isset( $reg["NOT_FECHA"] ) && isset( $reg["NOT_FECHA_FIN"] ) )
if ( isset( $reg["NOT_FECHA"]) ) {
$reg["NOT_FECHA"] = formatoFecha( $reg["NOT_FECHA"] ) ;
} // De if ( isset( $this->resultado['NOTICIA']['NOT_FECHA']) )
if ( isset( $reg["NOT_FECHA_FIN"]) ) {
$reg["NOT_FECHA_FIN"] = formatoFecha( $reg["NOT_FECHA_FIN"] ) ;
} // De if ( isset( $this->resultado['NOTICIA']['NOT_FECHA']) )
if ( $todas
&& isset ( $reg["NOT_ETIQUETAS_SN"] )
&& strtoupper( trim( $reg["NOT_ETIQUETAS_SN"] ) ) == "S" ) {
$reg[ "NOT_ETIQUETAS"] = $this->_obtenerEtiquetas( $reg[ "NOT_ID"] );
}
return $reg;
} // Defunction _colocarResultados()
/////////////////////////////////////////////
function _obtenerEtiquetas( $notId ) {
$xmlNotEtiquetas = $this->_obtenerXMLNotEtiquetas();
$notAltEtiqueta = new NotAltEtiqueta( $xmlNotEtiquetas );
$salida = $notAltEtiqueta->obtenerEtiquetasNoticiaDes( $notId );
return $salida;
}
/////////////////////////////////////////////
function _numeroRegistros() {
$this->numeroTotalRegistros = count($this->tabla->resultado);
$this->numeroRegistros = count($this->resultado);
} // Defunction _colocarResultados()
/////////////////////////////////////////////
function _fechaModificacion() {
$this->fechaModificacion = fechaModificacion( $this->tabla, 'NOT_FECHA', '00000000' );
$this->fechaModificacion = formatoFechaCorto( $this->fechaModificacion );
} // Defunction _colocarResultados()
/////////////////////////////////////////////
function obtenerDatosBuscador( $cadenaBuqueda, $numeroRegistrosPagina, $pagina, $todas = "N") {
$this->numeroRegistrosPagina = $numeroRegistrosPagina;
$this->resultado['PAGINACION']['PAGINA'] = $this->numeroRegistrosPagina;
$this->pagina = $pagina;
$this->_obtenerDatosSQLBuscador( $cadenaBuqueda, $todas);
$this->_paginacion();
$this->_colocarResultados( $todas == $this->TODAS );
$this->_fechaModificacion();
// Se inicializa la tabla
$xml = $this->tabla->xml;
$this->tabla = new Tabla( $xml );
} // De function obtenerDatos()
/////////////////////////////////////////////
function obtenerDatosId( $notId , $todas = false, $numeroTitulares = 5) {
$this->_obtenerDatosSQLIdNoticias( $notId , $todas);
$this->_obtenerUltimosTitulares($notId , $todas, $numeroTitulares) ;
$this->_colocarResultadosNoticia( $todas );
$this->_colocarResultadosBloques();
// $this->_fechaModificacion();
// Se inicializa la tabla
$xml = $this->tabla->xml;
$this->tabla = new Tabla( $xml );
} // De function obtenerDatos()
/////////////////////////////////////////////
function getResultado() {
return $this->resultado;
}
/////////////////////////////////////////////
} // De class Noticias
?>
//----------------------------------------------------------------------------
function rotarFicheroEstadisiticas( $aTablaEstadisticasNombre ) {
if ( strtoupper( $GLOBALS["gValoresIni"]['ESTADISTICAS']['rotarFichero'] ) != 'S' ) {
return $aTablaEstadisticasNombre;
}
$fecha = date ('_Y-m');
$tablaEstadisticasNombre = str_replace( ".datos", "$fecha.datos", $aTablaEstadisticasNombre );
// Si el fichero no existe se crea
if ( ! is_file( $tablaEstadisticasNombre ) ) {
touch( $tablaEstadisticasNombre );
}
return $tablaEstadisticasNombre;
}
//----------------------------------------------------------------------------
function insertarEstadistica( $pagina, $aTablaEstadisticasNombre ) {
// Se escribe a fichero de logs estadísticas más detalladas.
estadisticasFicheroLog( $pagina );
// Fin de se escribe a fichero de logs estadísticas más detalladas.
// Se rota el fichero de Estadisticas cada mes
$tablaEstadisticasNombre = rotarFicheroEstadisiticas( $aTablaEstadisticasNombre );
// Se saca la fecha de Hoy
$fechaActual = date ('Ymd');
// Se crea el objeto Tabla
$tablaEstadisticas = new Tabla( $tablaEstadisticasNombre );
// Se bloquea la tabla
$res = $tablaEstadisticas->bloquearTabla( ) ;
// Si devuelve error no se hace nada
if ( ! $res ) {
return;
}
// Se comprueba que no haya ningúna línea en la tabla estadisticas con esa fecha y ese Script
unset ($filtro);
$filtro["EST_PAGINA"] = $pagina;
$filtro["EST_FECHA"] = $fechaActual;
$registros = $tablaEstadisticas->obtenerRango($filtro, null, null );
// No se hace copia de seguridad
$tablaEstadisticas->setFlagCopiaSeguridad( false );
if ( count( $registros ) == 1 ) {
modificarTablaEstadisticas( $tablaEstadisticas, $registros, $filtro, $pagina ) ;
} else if ( count( $registros ) == 0) {
insertarTablaEstadisticas( $tablaEstadisticas, $registros, $filtro, $pagina );
} // Del f (count( $registros ) == 1)
// Se desbloquea la tabla
$tablaEstadisticas->desbloquearTabla();
// Se actualiza la página
if ( siNoPaginaVisitada( $pagina ) ) {
$_SESSION["paginasVistas"][] = $pagina;
}
} // De function insertarEstadistica( $pagina, $tablaEstadisticasNombre )
//----------------------------------------------------------------------------
function insertarTablaEstadisticas( &$tablaEstadisticas, $registros, $filtro, $pagina ) {
$reg = $filtro;
$reg["EST_CONTADOR"]= 1;
$reg["EST_CONTVISITAS"] = 0;
$reg["EST_CONTENTRADAS"] = 0;
if ( siEntrada() ) {
$reg["EST_CONTENTRADAS"] = 1;
}
if ( siNoPaginaVisitada( $pagina ) ){
$reg["EST_CONTVISITAS"] = 1;
}
$tablaEstadisticas->insertar( $reg );
} // De function insertarTablaEstadisticas( $tablaEstadisticas, $registros, $filtro )
//----------------------------------------------------------------------------
function modificarTablaEstadisticas( &$tablaEstadisticas, $registros, $filtro, $pagina ) {
$reg["EST_CONTADOR"] = $registros[0]["EST_CONTADOR"];
$reg["EST_CONTADOR"] ++;
if ( siEntrada() ) {
$reg["EST_CONTENTRADAS"] = $registros[0]["EST_CONTENTRADAS"] + 1 ;
}
if ( siNoPaginaVisitada( $pagina ) ){
$reg["EST_CONTVISITAS"] = $registros[0]["EST_CONTVISITAS"] + 1 ;
}
// No se comprueba antes de modificar porque ya se ha hecho
$tablaEstadisticas->setFlagComprobarAntesGrabar( false );
$tablaEstadisticas->modificar( $filtro, $reg );
} // De function modificarTablaEstadisticas( $tablaEstadisticas, $registros, $filtro )
//----------------------------------------------------------------------------
function siEntrada() {
return ! isset ( $_SESSION["paginasVistas"] );
} // De function siEntrada()
//----------------------------------------------------------------------------
function siNoPaginaVisitada( $pagina ) {
if ( siEntrada() ) {
return true;
}
return ! in_array( $pagina, $_SESSION["paginasVistas"] ) ;
} // De function siPaginaVisitada( $pagina )
//----------------------------------------------------------------------------
function estadisticasFicheroLog( $pagina ) {
// No se hace nada si no está habilitado el registro de logs
if ( strtoupper( $GLOBALS["gValoresIni"]['ESTADISTICAS']['escribirFichero'] ) != 'S' ) {
return;
}
$logfile =dirname(__FILE__).DIRECTORY_SEPARATOR;
$logfile .= "..". DIRECTORY_SEPARATOR . "lgs" . DIRECTORY_SEPARATOR . date ("Y_m").".log";
if ( ! isset ( $_SESSION["paginasPorSesion"] ) ) {
$_SESSION["paginasPorSesion"] = 0;
}
if ( file_exists($logfile) ) {
$fp = fopen ( $logfile, "aw" );
} else {
$fp = fopen ( $logfile, "w" );
$cabecera = "#SESION #FECHA #IP #NUM_PAG #PAG #PAG_ANT #URI #URI_ANT #DESDE #NAVEGADOR\n";
fputs ( $fp, $cabecera );
}
$cadena = "";
$cadena .= session_id()."\t"; // Id Sesion
$cadena .= date( "YmdHis" )."\t"; // Fecha
$cadena .= $_SERVER["REMOTE_ADDR"]."\t"; // Ip
// Páginas por sesión
$_SESSION["paginasPorSesion"] = isset( $_SESSION["paginasPorSesion"] ) ? $_SESSION["paginasPorSesion"] : 0;
$cadena .= ++$_SESSION["paginasPorSesion"] ."\t"; // Paginas por Session
// Página
$cadena .= $pagina ."\t"; // Página;
// Página Anterior
$_SESSION["paginaAnterior"] = isset( $_SESSION["paginaAnterior"] ) ? $_SESSION["paginaAnterior"] : "";
$cadena .= $_SESSION["paginaAnterior"] ."\t"; $_SESSION["paginaAnterior"] = $pagina; // Página Anterior
// Dirección
$cadena .= str_replace ("|", "", $_SERVER["REQUEST_URI"] ) ."\t"; // Dirección
// Dirección de la página anterior
$_SESSION["paginaAnteriorUri"] = isset( $_SESSION["paginaAnteriorUri"] ) ? $_SESSION["paginaAnteriorUri"] : "";
$cadena .= str_replace ("|", "", $_SESSION["paginaAnteriorUri"] ) ."\t"; $_SESSION["paginaAnteriorUri"] = $_SERVER["REQUEST_URI"]; // Dirección Anterior
// Desde donde
$httpReferer = isset( $_SERVER["HTTP_REFERER"] ) ? $_SERVER["HTTP_REFERER"] : "";
$cadena .= str_replace ("|", "", $httpReferer ) ."\t"; // Desde donde;
// Navegador
$cadena .= str_replace ("|", "", $_SERVER["HTTP_USER_AGENT"] ); // Navegador
$cadena .= "\n";
fputs ( $fp, $cadena );
fclose( $fp );
} // De function estadistiacasFicheroLog( $pagina )
?>
class ImgRepetidor {
var $direccionesVector;
// Constructor
function ImgRepetidor( $direcciones ) {
$this->direccionesVector = array();
$this->direccionesVector = explode( " ", $direcciones);
} // De function ImgRepetidor()
function dameDireccion( $direccionDefecto ) {
$numeroTotal = count( $this->direccionesVector ) - 1;
if ( $numeroTotal < 0 ) {
return $direccionDefecto;
}
$numero = rand( 0, $numeroTotal );
return ( $this->direccionesVector[$numero] );
}
#################################
} // De class Mantenimiento
?>