diff --git a/Ajax.php b/Ajax.php index 546b1d0..8968274 100644 --- a/Ajax.php +++ b/Ajax.php @@ -1,6 +1,5 @@ . - * */ //Clase encargada de procesar las peticiones ajax require_once 'inc/configuracion.inc'; @@ -25,64 +23,71 @@ require_once 'Sql.php'; $ajax = new Ajax(); echo $ajax->procesa(); -class Ajax { +class Ajax +{ private $sql; private $tabla; - + public function __construct() { $this->sql = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS); if ($this->sql->error()) { return $this->respuesta($this->mensaje(false, 'Error conectando con la Base de Datos')); - }; + } $this->tabla = $_GET['tabla']; } + private function respuesta($mensaje) { header('Content-Type: application/json', true, 200); + return $mensaje; } + public function procesa() { $opc = $_GET['opc']; switch ($opc) { - case "get": return $this->obtiene(); - case "put": return $this->actualiza(); + case 'get': return $this->obtiene(); + case 'put': return $this->actualiza(); } } + private function mensaje($exito, $texto) { - return json_encode(array("success" => $exito, "msj" => $texto)); + return json_encode(['success' => $exito, 'msj' => $texto]); } + private function actualiza() { - if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { - $comando = "update " . mysql_escape_string($this->tabla) . " set " . mysql_escape_string($_POST['name']) . " = '" . mysql_escape_string($_POST['value']) . "' where id = '" . mysql_escape_string($_POST['pk']). "';"; + if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { + $comando = 'update '.mysql_escape_string($this->tabla).' set '.mysql_escape_string($_POST['name'])." = '".mysql_escape_string($_POST['value'])."' where id = '".mysql_escape_string($_POST['pk'])."';"; $this->sql->ejecuta($comando); $exito = !$this->sql->error(); $mensaje = $this->sql->mensajeError(); - $resp = $this->mensaje($exito, $mensaje); + $resp = $this->mensaje($exito, $mensaje); + return $this->respuesta($resp); } } + private function obtiene() { - if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { - $comando = "select id, descripcion from " . $this->tabla . " order by descripcion asc;"; + if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { + $comando = 'select id, descripcion from '.$this->tabla.' order by descripcion asc;'; $this->sql->ejecuta($comando); $exito = !$this->sql->error(); $mensaje = $this->sql->mensajeError(); if (!$exito) { return $this->respuesta($this->mensaje($exito, $mensaje)); } - $filas = array(); - while($r = $this->sql->procesaResultado()) { - $filas[] = array($r['id'] => $r['descripcion']); + $filas = []; + while ($r = $this->sql->procesaResultado()) { + $filas[] = [$r['id'] => $r['descripcion']]; } $resp = json_encode($filas); + return $this->respuesta($resp); } } -} - -?> +} diff --git a/AportaContenido.php b/AportaContenido.php index b2785a9..87d1a35 100644 --- a/AportaContenido.php +++ b/AportaContenido.php @@ -1,6 +1,5 @@ . - * */ -define('PIE', '
GPL v3' . - 'Sitio web creado con Apache' . - 'Gestor de bases de datos mySQL' . +define('PIE', '
GPL v3'. + 'Sitio web creado con Apache'. + 'Gestor de bases de datos mySQL'. 'PHP Language
'); -define('FORMULARIO_ACCESO', '
' . - 'Usuario


Clave
' . +define('FORMULARIO_ACCESO', ''. + 'Usuario


Clave
'. '

'); define('MENSAJE_DEMO', 'Puede Iniciar sesión con
usuario demo
contraseña demo
'); define('USUARIO_INCORRECTO', '

'); @@ -40,7 +38,7 @@ define('CREDITOS_CABECERA', ' @@ -50,18 +48,17 @@ define('CREDITOS_PIE', '

Copyright © 2008-2014 Ricard '); // Esta clase aportará el contenido a la plantilla -class AportaContenido { - +class AportaContenido +{ /** - * - * @var boolean Aporta información sobre si el usuario está registrado o no. + * @var bool Aporta información sobre si el usuario está registrado o no. */ private $registrado; /** * @var string Nombre del usuario */ - private $usuario = NULL; + private $usuario = null; /** * @var Menu Menú de la página. @@ -79,7 +76,7 @@ class AportaContenido { private $opcionActual; /** - * @var boolean Usuario y clave incorrectos? + * @var bool Usuario y clave incorrectos? */ private $usuario_inc = false; @@ -89,19 +86,20 @@ class AportaContenido { private $perfil; /** - * * @var array Datos pasados en la URL */ - private $datosURL = array(); + private $datosURL = []; // El constructor necesita saber cuál es la opción actual + /** - * Constructor de la clase. - * @param BaseDatos $baseDatos Manejador de la base de datos - * @param boolean $registrado usuario registrado si/no - * @param String $usuario Nombre del usuario - * @param array $perfil Permisos de acceso del usuario - * @param String $opcion Opción elegida por el usuario + * Constructor de la clase. + * + * @param BaseDatos $baseDatos Manejador de la base de datos + * @param bool $registrado usuario registrado si/no + * @param string $usuario Nombre del usuario + * @param array $perfil Permisos de acceso del usuario + * @param string $opcion Opción elegida por el usuario */ public function __construct($baseDatos, $registrado, $usuario, $perfil, $opcion) { @@ -112,52 +110,56 @@ class AportaContenido { $this->perfil = $perfil; $this->opcionActual = $opcion; } - + /** * Devuelve una tabla HTML con el contenido de las bibliotecas/módulos utilizadas en la aplicación - * Si el perfil del usuario es de Configuración devuelve también las versiones de las bibliotecas - * @return string + * Si el perfil del usuario es de Configuración devuelve también las versiones de las bibliotecas. + * + * @return string */ public function creaTablaAcercaDe() { - $poner = $this->perfil['Config']; $tabla = ''; - $tabla .=''.($poner?'':'').''; - $tabla .=''; - $tabla .=''.($poner?'':'').''; - $tabla .=''.($poner?'':'').''; - $tabla .=''.($poner?'':'').''; - $tabla .=''.($poner?'':'').''; - $tabla .=''.($poner?'':'').''; - $tabla .=''.($poner?'':'').''; - $tabla .=''.($poner?'':'').''; - $tabla .=''.($poner?'':'').''; - $tabla .=''.($poner?'':'').''; - $tabla .=''.($poner?'':'').''; - $tabla .=''.($poner?'':'').''; - $tabla .=''.($poner?'':'').''; - $tabla .=''; - $tabla .='
Biblioteca/MóduloVersiónLicencia
jquery2.1.0MIT
Twitter Bootstrap3.1.1MIT
FPDF1.7Libre
PHP QR Code Enconder1.1.4LGPL
Zebra_Image2.2.3LGPL
Jasny Bootstrap3.1.0Apache 2.0
Bootstrap Validator0.2.1MIT
jquery-simplecolorpicker0.3.0MIT
Bootstrap datetimepicker2.1.32MIT
Bootstrap-select1.5.4MIT
X-editable1.5.1MIT
Moment.js2.5.1MIT
'; + $tabla .= 'Biblioteca/Módulo'.($poner ? 'Versión' : '').'Licencia'; + $tabla .= ''; + $tabla .= 'jquery'.($poner ? '2.1.0' : '').'MIT'; + $tabla .= 'Twitter Bootstrap'.($poner ? '3.1.1' : '').'MIT'; + $tabla .= 'FPDF'.($poner ? '1.7' : '').'Libre'; + $tabla .= 'PHP QR Code Enconder'.($poner ? '1.1.4' : '').'LGPL'; + $tabla .= 'Zebra_Image'.($poner ? '2.2.3' : '').'LGPL'; + $tabla .= 'Jasny Bootstrap'.($poner ? '3.1.0' : '').'Apache 2.0'; + $tabla .= 'Bootstrap Validator'.($poner ? '0.2.1' : '').'MIT'; + $tabla .= 'jquery-simplecolorpicker'.($poner ? '0.3.0' : '').'MIT'; + $tabla .= 'Bootstrap datetimepicker'.($poner ? '2.1.32' : '').'MIT'; + $tabla .= 'Bootstrap-select'.($poner ? '1.5.4' : '').'MIT'; + $tabla .= 'X-editable'.($poner ? '1.5.1' : '').'MIT'; + $tabla .= 'Moment.js'.($poner ? '2.5.1' : '').'MIT'; + $tabla .= ''; + $tabla .= ''; + return $tabla; } /** - * Devuelve la fecha actual + * Devuelve la fecha actual. + * * @param string $formato formato de devolución de la fecha - * @param string $idioma idioma para formatear la fecha, p.ej. es_ES + * @param string $idioma idioma para formatear la fecha, p.ej. es_ES + * * @return string */ public function fechaActual($formato = '', $idioma = 'es_ES') { - if ($formato == '') - $formato = "%d-%b-%y"; + if ($formato == '') { + $formato = '%d-%b-%y'; + } setlocale(LC_TIME, $idioma); + return strftime($formato); } /** - * * @return string Mensaje el usuario debe registrarse. */ private function mensajeRegistro() @@ -167,78 +169,87 @@ class AportaContenido { // Procesaremos todas las invocaciones a métodos en // la función __call() + /** * Procesa las peticiones de contenido de la plantilla. - * @param string $metodo Método a ejecutar + * + * @param string $metodo Método a ejecutar * @param string $parametros Parámetros del método + * * @return string Contenido devuelto por el método */ public function __call($metodo, $parametros) { switch ($metodo) { // Dependiendo del método invocado case 'usuario': - if ($this->registrado) + if ($this->registrado) { return "Usuario=$this->usuario"; - else + } else { return ''; + } case 'fecha': $script = '"; - $campo = ''; - $etiqueta = ''; - return $etiqueta . $campo . $script; - case 'aplicacion': - $nombre = explode(" ", PROGRAMA); + $campo = ''; + $etiqueta = ''; + + return $etiqueta.$campo.$script; + case 'aplicacion': + $nombre = explode(' ', PROGRAMA); $nombre = $nombre[2]; - return $nombre . " v" . VERSION; + + return $nombre.' v'.VERSION; case 'menu': // el menú if ($this->registrado) { return $this->miMenu->insertaMenu(); } else { $salida = FORMULARIO_ACCESO; if ($this->usuario_inc) { - $salida.=USUARIO_INCORRECTO; + $salida .= USUARIO_INCORRECTO; } //$salida.=MENSAJE_DEMO; return $salida; } case 'opcion': - if (strstr($this->opcionActual, "&")) { - list($opcion, $parametro) = explode("&", $this->opcionActual); + if (strstr($this->opcionActual, '&')) { + list($opcion, $parametro) = explode('&', $this->opcionActual); } else { - $opcion = $this->opcionActual; $parametro = ""; + $opcion = $this->opcionActual; + $parametro = ''; } switch ($opcion) { case 'bienvenido': - return "Menú Principal"; + return 'Menú Principal'; case 'principal': - return "Pantalla Inicial"; - case 'articulos': $opcion = "artículos"; + return 'Pantalla Inicial'; + case 'articulos': $opcion = 'artículos'; case 'elementos': case 'ubicaciones': case 'usuarios': case 'test': - return "Mantenimiento " . ucfirst($opcion); + return 'Mantenimiento '.ucfirst($opcion); case 'configuracion': return 'Configuración y Preferencias'; - case 'informeInventario':return "Informe de Inventario"; + case 'informeInventario':return 'Informe de Inventario'; case 'descuadres':return 'Informe de descuadres'; case 'importacion': return 'Importación de datos'; case 'copiaseg': return 'Copia de seguridad de datos'; } + return ''; case 'control': - if ($this->registrado) + if ($this->registrado) { return 'Cerrar Sesión '; - else + } else { return ''; + } // Para incluir el contenido central de la página case 'contenido': // tendremos en cuenta cuál es la opción actual @@ -248,52 +259,56 @@ class AportaContenido { // if (!$this->registrado) { // return $this->mensajeRegistro(); // } - if (strstr($this->opcionActual, "&")) { - list($opcion, $parametro) = explode("&", $this->opcionActual); + if (strstr($this->opcionActual, '&')) { + list($opcion, $parametro) = explode('&', $this->opcionActual); } else { - $opcion = $this->opcionActual; $parametro = ""; + $opcion = $this->opcionActual; + $parametro = ''; } switch ($opcion) { case 'bienvenido': $mensaje = '
'; - $mensaje .= 'Bienvenid@ ' . $this->usuario . '
'; + $mensaje .= 'Bienvenid@ '.$this->usuario.''; case 'principal': // contenido inicial - $mensaje = ""; + $mensaje = ''; $creditos = "$('#creditos').modal({keyboard: false});"; - $centro = '
' . CENTRO . '
'; + $centro = '
'.CENTRO.'
'; $tabla = $this->creaTablaAcercaDe(); $rama_texto = trim(substr(file_get_contents('.git/HEAD'), 16)); - $rama = ($rama_texto != 'master' ? '
':''); - return $mensaje . '

' . PROGRAMA . '' . - '

' . $rama . '
' . CREDITOS_CABECERA . $tabla . CREDITOS_PIE; + $rama = ($rama_texto != 'master' ? '
' : ''); + + return $mensaje.'

'.PROGRAMA.''. + '

'.$rama.'
'.CREDITOS_CABECERA.$tabla.CREDITOS_PIE; case 'articulos': case 'ubicaciones': case 'test': case 'elementos': $this->cargaDatosURL(); - if ($this->datosURL['opc'] == "informe") { + if ($this->datosURL['opc'] == 'informe') { if ($this->perfil['Informe']) { $this->procesaURL(); - $fichero = 'xml/informe' . ucfirst($opcion) . '.xml'; - $salida = TMP.'/informe' . ucfirst($opcion) . '.xml'; + $fichero = 'xml/informe'.ucfirst($opcion).'.xml'; + $salida = TMP.'/informe'.ucfirst($opcion).'.xml'; //Establece los posibles parámetros del listado. $orden = $this->datosURL['orden']; - $sentido = $this->datosURL['sentido'] == "asc" ? ' ' : ' desc '; + $sentido = $this->datosURL['sentido'] == 'asc' ? ' ' : ' desc '; $filtro = isset($this->datosURL['buscar']) ? $this->bdd->filtra($this->datosURL['buscar']) : ''; - $plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla ' . $fichero); - $plantilla = str_replace("{filtro}", $filtro, $plantilla); - $plantilla = str_replace("{orden}", $orden . $sentido, $plantilla); - file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida); + $plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla '.$fichero); + $plantilla = str_replace('{filtro}', $filtro, $plantilla); + $plantilla = str_replace('{orden}', $orden.$sentido, $plantilla); + file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla '.$salida); $informe = new InformePDF($this->bdd, $salida, $this->registrado); $informe->crea($salida); $informe->cierraPDF(); + return $this->devuelveInforme($informe); } else { - return $this->mensajePermisos("Informes"); + return $this->mensajePermisos('Informes'); } } if ($this->perfil['Consulta']) { $ele = new Mantenimiento($this->bdd, $this->perfil, $opcion); + return $ele->ejecuta(); } else { return $this->mensajePermisos(ucfirst($opcion)); @@ -301,28 +316,30 @@ class AportaContenido { case 'usuarios': if ($this->perfil['Usuarios']) { $this->cargaDatosURL(); - if ($this->datosURL['opc'] == "informe") { + if ($this->datosURL['opc'] == 'informe') { if (!$this->pefil['Informe']) { $this->procesaURL(); - $fichero = 'xml/informe' . ucfirst($opcion) . '.xml'; - $salida = TMP.'/informe' . ucfirst($opcion) . '.xml'; + $fichero = 'xml/informe'.ucfirst($opcion).'.xml'; + $salida = TMP.'/informe'.ucfirst($opcion).'.xml'; //Establece los posibles parámetros del listado. $orden = $this->datosURL['orden']; - $sentido = $this->datosURL['sentido'] == "asc" ? ' ' : ' desc '; + $sentido = $this->datosURL['sentido'] == 'asc' ? ' ' : ' desc '; $filtro = isset($this->datosURL['buscar']) ? $this->bdd->filtra($this->datosURL['buscar']) : ''; - $plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla ' . $fichero); - $plantilla = str_replace("{filtro}", $filtro, $plantilla); - $plantilla = str_replace("{orden}", $orden . $sentido, $plantilla); - file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida); + $plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla '.$fichero); + $plantilla = str_replace('{filtro}', $filtro, $plantilla); + $plantilla = str_replace('{orden}', $orden.$sentido, $plantilla); + file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla '.$salida); $informe = new InformePDF($this->bdd, $salida, $this->registrado); $informe->crea($salida); $informe->cierraPDF(); + return $this->devuelveInforme($informe); } else { - return $this->mensajePermisos("Informes"); + return $this->mensajePermisos('Informes'); } } $ele = new Mantenimiento($this->bdd, $this->perfil, $opcion); + return $ele->ejecuta(); } else { return $this->mensajePermisos('Usuarios'); @@ -330,6 +347,7 @@ class AportaContenido { case 'configuracion': if ($this->perfil['Config']) { $conf = new Configuracion(); + return $conf->ejecuta(); } else { return $this->mensajePermisos('Configuración'); @@ -337,6 +355,7 @@ class AportaContenido { case 'informeInventario': if ($this->perfil['Informe']) { $info = new InformeInventario($this->bdd); + return $info->ejecuta(); } else { return $this->mensajePermisos('Informes'); @@ -344,36 +363,39 @@ class AportaContenido { case 'importacion': if ($this->perfil['Modificacion'] && $this->perfil['Borrado']) { $import = new Importacion($this->bdd, $this->registrado); + return $import->ejecuta(); } else { - return $this->mensajePermisos("Actualización, creación y borrado de elementos"); + return $this->mensajePermisos('Actualización, creación y borrado de elementos'); } case 'copiaseg': if ($this->perfil['Config']) { $copia = new CopiaSeguridad(); - if (isset($_GET['confirmado']) && $_GET['confirmado'] == "1") { + if (isset($_GET['confirmado']) && $_GET['confirmado'] == '1') { if (!$copia->creaCopia()) { - $tipo = "danger"; - $cabecera = "ERROR"; + $tipo = 'danger'; + $cabecera = 'ERROR'; } else { - $tipo = "info"; - $cabecera = "INFORMACIÓN"; + $tipo = 'info'; + $cabecera = 'INFORMACIÓN'; } + return $this->panel($cabecera, $copia->mensaje(), $tipo); } else { return $copia->dialogo(); } } else { - return $this->mensajePermisos("Copias de seguridad"); + return $this->mensajePermisos('Copias de seguridad'); } } // Fin del contenido case 'usuario_incorrecto': $this->usuario_inc = true; + return; case 'registro': // Si está registrado mostrar bienvenida // si no, un enlace if ($this->bEstaRegistrado) { - return "Bienvenid@ $this->sUsuario
" . + return "Bienvenid@ $this->sUsuario
". 'Cerrar sesión'; } else { return ''; @@ -394,35 +416,36 @@ class AportaContenido { } /** - * * @param string $tipo + * * @return string */ public function mensajePermisos($tipo) { - return $this->panel("ERROR", "No tiene permiso para acceder a $tipo", "danger"); + return $this->panel('ERROR', "No tiene permiso para acceder a $tipo", 'danger'); } - + private function devuelveInforme($informe) { - $letras = "abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; - $nombre = TMP."/informe" . substr(str_shuffle($letras), 0, 10) . ".pdf"; + $letras = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; + $nombre = TMP.'/informe'.substr(str_shuffle($letras), 0, 10).'.pdf'; $informe->guardaArchivo($nombre); + return '
- - + + '; } - + public function panel($cabecera, $mensaje, $tipo) { - $panel = '
'; - $panel .= '

' . $cabecera . '

'; + $panel = '
'; + $panel .= '

'.$cabecera.'

'; $panel .= '
'; $panel .= $mensaje; $panel .= '
'; + return $panel; } } -?> \ No newline at end of file diff --git a/Configuracion.php b/Configuracion.php index bcb4bc0..47281ff 100644 --- a/Configuracion.php +++ b/Configuracion.php @@ -1,6 +1,5 @@ . - * */ -class Configuracion { - private $configuracion = "inc/configuracion.inc"; - private $confNueva = "inc/configuracion.new"; - private $confAnterior = "inc/configuracion.ant"; +class Configuracion +{ + private $configuracion = 'inc/configuracion.inc'; + private $confNueva = 'inc/configuracion.new'; + private $confAnterior = 'inc/configuracion.ant'; private $datosConf; //Campos del fichero de configuración que se van a editar. - private $lista = array('SERVIDOR', 'PUERTO', 'BASEDATOS', 'BASEDATOSTEST', 'USUARIO', 'CLAVE', 'CENTRO', 'NUMFILAS', 'ESTILO', 'PLANTILLA', 'COLORLAT', 'COLORFON', 'MYSQLDUMP', 'GZIP', 'TMP'); + private $lista = ['SERVIDOR', 'PUERTO', 'BASEDATOS', 'BASEDATOSTEST', 'USUARIO', 'CLAVE', 'CENTRO', 'NUMFILAS', 'ESTILO', 'PLANTILLA', 'COLORLAT', 'COLORFON', 'MYSQLDUMP', 'GZIP', 'TMP']; private $campos; - + public function __construct() { - $this->campos = implode(",", $this->lista); + $this->campos = implode(',', $this->lista); } - + //Hecho público para poder efectuar los tests correspondientes. public function obtieneFichero() { return file_get_contents($this->configuracion, FILE_TEXT); } - + public function obtieneLista() { return $this->lista; } - + public function obtieneDatos($linea, &$clave, &$valor) { - $filtro = str_replace("'", "", $linea); - list($clave, $valor) = explode(",", $filtro); - list($resto, $campo) = explode("(", $clave); - list($valor, $resto) = explode(")", $valor); - list($resto, $clave) = explode("(", $clave); + $filtro = str_replace("'", '', $linea); + list($clave, $valor) = explode(',', $filtro); + list($resto, $campo) = explode('(', $clave); + list($valor, $resto) = explode(')', $valor); + list($resto, $clave) = explode('(', $clave); $valor = trim($valor); } - + private function creaTitulo($titulo, $ayuda) { return ''.$titulo.''; } - - public function ejecuta() { + + public function ejecuta() + { $fichero = $this->obtieneFichero(); $datos = explode("\n", $fichero); $grabar = isset($_POST['SERVIDOR']); if ($grabar) { - $fsalida = @fopen($this->confNueva, "wb"); + $fsalida = @fopen($this->confNueva, 'wb'); } foreach ($datos as $linea) { - if (stripos($linea, "DEFINE") !== false) { + if (stripos($linea, 'DEFINE') !== false) { //Comprueba que tenga una definición correcta - $this->obtieneDatos($linea, $clave, $valor); + $this->obtieneDatos($linea, $clave, $valor); $this->datosConf[$clave] = $valor; if ($grabar && stripos($this->campos, $clave) !== false) { $linea = str_replace($valor, $_POST[$clave], $linea); @@ -78,96 +78,98 @@ class Configuracion { //$salida .= "Post=" . var_export($_POST, true); } if ($grabar) { - $registro = substr($linea, 0, 2) == "?>" ? $linea : $linea . "\n"; + $registro = substr($linea, 0, 2) == '?>' ? $linea : $linea."\n"; fwrite($fsalida, $registro); } } $salida = $this->formulario(); if ($grabar) { - $salida.='
Configuración guardada correctamente
'; + $salida .= '
Configuración guardada correctamente
'; fclose($fsalida); //unlink($this->confAnterior); rename($this->configuracion, $this->confAnterior); rename($this->confNueva, $this->configuracion); unlink($this->confAnterior); } + return $salida; } - private function formulario() { - $coloresLateral = array("Original" => "#C4FAEC", "Verde" => "#7bd148", "Azul marino" => "#5484ed", "Azul" => "#a4bdfc", "Turquesa" => "#46d6db", - "Verde claro" => "#7ae7bf", "Verde oscuro" => "#51b749", "Amarillo" => "#fbd75b", "Naranja" => "#ffb878", "Morado" => "#6633FF", - "Rojo oscuro" => "#dc2127", "Púrpura" => "#dbadff", "Gris" => "#e1e1e1"); - $coloresFondo = array("Verde" => "#7bd148", "Azul marino" => "#5484ed", "Azul" => "#a4bdfc", "Turquesa" => "#46d6db", - "Verde claro" => "#7ae7bf", "Verde oscuro" => "#51b749", "Amarillo" => "#fbd75b", "Naranja" => "#ffb878", "Rojo" => "#ff887c", - "Rojo oscuro" => "#dc2127", "Púrpura" => "#dbadff", "Gris" => "#e1e1e1", "Original" => '#F3FEC8'); - $personal = $this->datosConf['ESTILO'] == "personal" ? 'selected' : ' '; - $bluecurve = $this->datosConf['ESTILO'] == "bluecurve" ? 'selected' : ' '; - $cristal = $this->datosConf['ESTILO'] == "cristal" ? 'selected' : ' '; - $bootst = $this->datosConf['ESTILO'] == "bootstrap" ? 'selected' : ' '; - $normal = $this->datosConf['PLANTILLA'] == "normal" ? 'selected' : ' '; - $bootstrap = $this->datosConf['PLANTILLA'] == "bootstrap" ? 'selected' : ' '; + private function formulario() + { + $coloresLateral = ['Original' => '#C4FAEC', 'Verde' => '#7bd148', 'Azul marino' => '#5484ed', 'Azul' => '#a4bdfc', 'Turquesa' => '#46d6db', + 'Verde claro' => '#7ae7bf', 'Verde oscuro' => '#51b749', 'Amarillo' => '#fbd75b', 'Naranja' => '#ffb878', 'Morado' => '#6633FF', + 'Rojo oscuro' => '#dc2127', 'Púrpura' => '#dbadff', 'Gris' => '#e1e1e1']; + $coloresFondo = ['Verde' => '#7bd148', 'Azul marino' => '#5484ed', 'Azul' => '#a4bdfc', 'Turquesa' => '#46d6db', + 'Verde claro' => '#7ae7bf', 'Verde oscuro' => '#51b749', 'Amarillo' => '#fbd75b', 'Naranja' => '#ffb878', 'Rojo' => '#ff887c', + 'Rojo oscuro' => '#dc2127', 'Púrpura' => '#dbadff', 'Gris' => '#e1e1e1', 'Original' => '#F3FEC8']; + $personal = $this->datosConf['ESTILO'] == 'personal' ? 'selected' : ' '; + $bluecurve = $this->datosConf['ESTILO'] == 'bluecurve' ? 'selected' : ' '; + $cristal = $this->datosConf['ESTILO'] == 'cristal' ? 'selected' : ' '; + $bootst = $this->datosConf['ESTILO'] == 'bootstrap' ? 'selected' : ' '; + $normal = $this->datosConf['PLANTILLA'] == 'normal' ? 'selected' : ' '; + $bootstrap = $this->datosConf['PLANTILLA'] == 'bootstrap' ? 'selected' : ' '; $salida = '
'; //$salida.='

'; - $salida.='

'; - $salida.=''; - $salida.=''.$this->creaTitulo("Nombre del Centro","Nombre que aparecerá en los informes y en la página principal de la aplicación").''; - $salida.=''.$this->creaTitulo("Número de filas","Número de filas que aparecerán en la pantalla de consulta de los maestros. Valor entre 10 y 25.").''; - $salida.=''.$this->creaTitulo("Plantilla","Plantilla html utilizada para mostrar el contenido de la aplicación.").''; - $salida.=''.$this->creaTitulo("Estilo","Estilo de los botones de control en los mantenimientos de los maestros").''; - $salida.=''.$this->creaTitulo("Color Lateral","Color que se aplicará a la parte izquierda de la aplicación donde aparece el menú").'
Preferencias
'; + $salida .= ''; + $salida .= ''.$this->creaTitulo('Nombre del Centro', 'Nombre que aparecerá en los informes y en la página principal de la aplicación').''; + $salida .= ''.$this->creaTitulo('Número de filas', 'Número de filas que aparecerán en la pantalla de consulta de los maestros. Valor entre 10 y 25.').''; + $salida .= ''.$this->creaTitulo('Plantilla', 'Plantilla html utilizada para mostrar el contenido de la aplicación.').''; + $salida .= ''.$this->creaTitulo('Estilo', 'Estilo de los botones de control en los mantenimientos de los maestros').''; + $salida .= ''.$this->creaTitulo('Color Lateral', 'Color que se aplicará a la parte izquierda de la aplicación donde aparece el menú').''; - $salida.=''.$this->creaTitulo("Color Fondo","Color que aparecerá como fondo en todas las pantallas de la aplicación").''; + $salida .= ''.$this->creaTitulo('Color Fondo', 'Color que aparecerá como fondo en todas las pantallas de la aplicación').''; - $salida.=''.$this->creaTitulo("Directorio tmp","Directorio donde se almacenarán los archivos temporales de la aplicación y también los archivos e informes que genera").''; - $salida.=''; - $salida.=''.$this->creaTitulo("Servidor","Nombre o dirección IP del servidor MySQL. Normalmente localhost").''; - $salida.=''.$this->creaTitulo("Puerto","Número de puerto donde el servidor admite conexiones MySQL. Normalmente 3306").''; - $salida.=''.$this->creaTitulo("Base de datos","Nombre de la base de datos donde se almacenarán los datos de la aplicación").''; - $salida.=''.$this->creaTitulo("Base de datos Tests","Nombre de la base de datos donde se almacenarán los datos de prueba de la aplicación").''; - $salida.=''.$this->creaTitulo("Usuario","Usuario con permisos de lectura/escritura en la base de datos").''; - $salida.=''.$this->creaTitulo("Clave","Contraseña del usuario con permisos sobre la base de datos").''; - $salida.=''.$this->creaTitulo("mysqldump","Ruta completa a la utilidad mysqldump. Este programa es necesario para que se puedan hacer las copias de seguridad de la aplicación").''; - $salida.=''.$this->creaTitulo("gzip","Ruta completa a la utilidad gzip. Este programa es necesario para que se puedan comprimir las copias de seguridad de la aplicación").''; - $salida.=''; + $salida .= ''.$this->creaTitulo('Directorio tmp', 'Directorio donde se almacenarán los archivos temporales de la aplicación y también los archivos e informes que genera').''; + $salida .= ''; + $salida .= ''.$this->creaTitulo('Servidor', 'Nombre o dirección IP del servidor MySQL. Normalmente localhost').''; + $salida .= ''.$this->creaTitulo('Puerto', 'Número de puerto donde el servidor admite conexiones MySQL. Normalmente 3306').''; + $salida .= ''.$this->creaTitulo('Base de datos', 'Nombre de la base de datos donde se almacenarán los datos de la aplicación').''; + $salida .= ''.$this->creaTitulo('Base de datos Tests', 'Nombre de la base de datos donde se almacenarán los datos de prueba de la aplicación').''; + $salida .= ''.$this->creaTitulo('Usuario', 'Usuario con permisos de lectura/escritura en la base de datos').''; + $salida .= ''.$this->creaTitulo('Clave', 'Contraseña del usuario con permisos sobre la base de datos').''; + $salida .= ''.$this->creaTitulo('mysqldump', 'Ruta completa a la utilidad mysqldump. Este programa es necesario para que se puedan hacer las copias de seguridad de la aplicación').''; + $salida .= ''.$this->creaTitulo('gzip', 'Ruta completa a la utilidad gzip. Este programa es necesario para que se puedan comprimir las copias de seguridad de la aplicación').''; + $salida .= '

'; - $salida.=''; - $salida.=""; + return $salida; } } -?> \ No newline at end of file diff --git a/CopiaSeguridad.php b/CopiaSeguridad.php index 6fd136b..8dfc75a 100644 --- a/CopiaSeguridad.php +++ b/CopiaSeguridad.php @@ -1,6 +1,5 @@ . - * */ -class CopiaSeguridad { +class CopiaSeguridad +{ private $mensaje; private $baseDatos; private $imagenes; - + public function creaCopia() { if (!$this->copiaBaseDatos()) { @@ -34,95 +33,106 @@ class CopiaSeguridad { if (!$this->empaqueta()) { return false; } + return true; } + public function dialogo() { $dialogo = '

Copia de Seguridad

¿Desea realizar una copia de seguridad de todos los datos de la Base de Datos y de todas las Imágenes?

-

Volver - +

Volver + Continuar

'; + return $dialogo; } - private function copiaBaseDatos() + + private function copiaBaseDatos() { - $archivo_sql = TMP."/baseDatos" . BASEDATOS . ".sql"; - $baseDatosComprimida = $archivo_sql . ".gz"; + $archivo_sql = TMP.'/baseDatos'.BASEDATOS.'.sql'; + $baseDatosComprimida = $archivo_sql.'.gz'; $this->baseDatos = $baseDatosComprimida; if (file_exists($baseDatosComprimida)) { unlink($baseDatosComprimida); } - $comando = escapeshellcmd(MYSQLDUMP . ' -h ' . SERVIDOR . ' -P ' . PUERTO . ' -u ' . USUARIO . ' --password=' . CLAVE . ' --result-file=' . $archivo_sql . ' ' . BASEDATOS); - $comando2 = escapeshellcmd(GZIP . ' -9f ' . $archivo_sql); + $comando = escapeshellcmd(MYSQLDUMP.' -h '.SERVIDOR.' -P '.PUERTO.' -u '.USUARIO.' --password='.CLAVE.' --result-file='.$archivo_sql.' '.BASEDATOS); + $comando2 = escapeshellcmd(GZIP.' -9f '.$archivo_sql); exec($comando); exec($comando2); if (filesize($baseDatosComprimida) < 1024) { //No se ha realizado la copia de seguridad - $mensaje = "La copia de seguridad no se ha realizado correctamente.

"; - $mensaje .= "Compruebe que las rutas a los programas mysqldump y gzip en configuración están correctamente establecidas "; - $mensaje .= "y que los datos de acceso a la base de datos sean correctos.
"; - $mensaje .= "mysqldump=[" . MYSQLDUMP . "]
"; - $mensaje .= "gzip=[" . GZIP . "]"; + $mensaje = 'La copia de seguridad no se ha realizado correctamente.

'; + $mensaje .= 'Compruebe que las rutas a los programas mysqldump y gzip en configuración están correctamente establecidas '; + $mensaje .= 'y que los datos de acceso a la base de datos sean correctos.
'; + $mensaje .= 'mysqldump=['.MYSQLDUMP.']
'; + $mensaje .= 'gzip=['.GZIP.']'; $this->mensaje = $mensaje; $this->error = true; + return false; } + return true; } + private function copiaImagenes() { - $copiaImagenes = TMP."/Imagenes.tbz"; + $copiaImagenes = TMP.'/Imagenes.tbz'; $this->imagenes = $copiaImagenes; if (file_exists($copiaImagenes)) { unlink($copiaImagenes); } - $comando = escapeshellcmd('tar cf ' . $copiaImagenes . ' ' . IMAGEDATA); + $comando = escapeshellcmd('tar cf '.$copiaImagenes.' '.IMAGEDATA); exec($comando); - + if (filesize($copiaImagenes) == 0) { $this->error = true; - $mensaje = "No se ha podido comprimir el directorio de las imágenes " . IMAGEDATA . "
"; - $mensaje .= "Compruebe que la ruta de acceso al programa tar en configuración está correctamente establecida"; + $mensaje = 'No se ha podido comprimir el directorio de las imágenes '.IMAGEDATA.'
'; + $mensaje .= 'Compruebe que la ruta de acceso al programa tar en configuración está correctamente establecida'; $this->mensaje = $mensaje; + return false; } + return true; } + private function empaqueta() - { - // Empaqueta los dos archivos en el que va a devolver - $nombreCopia = TMP."/Copia" . BASEDATOS . strftime("%Y%m%d%H%M") . ".tar"; + { + // Empaqueta los dos archivos en el que va a devolver + $nombreCopia = TMP.'/Copia'.BASEDATOS.strftime('%Y%m%d%H%M').'.tar'; if (file_exists($nombreCopia)) { unlink($nombreCopia); } - $comando = escapeshellcmd('tar cf ' . $nombreCopia . ' ' . $this->baseDatos . ' ' . $this->imagenes); + $comando = escapeshellcmd('tar cf '.$nombreCopia.' '.$this->baseDatos.' '.$this->imagenes); exec($comando); - if (filesize($nombreCopia) ==0 || !file_exists($nombreCopia)) { + if (filesize($nombreCopia) == 0 || !file_exists($nombreCopia)) { $this->error = true; - $mensaje = "No se ha creado el paquete con los archivos de imágenes en [" . $this->imagenes . "] y
"; - $mensaje .= " con el archivo de Base de Datos [" . $this->baseDatos . "]

"; - $mensaje .= "Compruebe que los datos de configuración están correctamente establecidos
"; - $mensaje .= "El comando de copia fue [" . $comando . "]
"; - $mensaje .= "gzip=[" . GZIP . "]"; + $mensaje = 'No se ha creado el paquete con los archivos de imágenes en ['.$this->imagenes.'] y
'; + $mensaje .= ' con el archivo de Base de Datos ['.$this->baseDatos.']

'; + $mensaje .= 'Compruebe que los datos de configuración están correctamente establecidos
'; + $mensaje .= 'El comando de copia fue ['.$comando.']
'; + $mensaje .= 'gzip=['.GZIP.']'; $this->mensaje = $mensaje; + return false; } $this->error = false; - unlink ($this->baseDatos); - unlink ($this->imagenes); + unlink($this->baseDatos); + unlink($this->imagenes); $mensaje = 'Copia de seguridad realizada con éxito.

Pulse sobre el siguiente enlace para descargar:

'; - $mensaje .= 'Descargar Copia de Seguridad de Datos

'; + $mensaje .= 'Descargar Copia de Seguridad de Datos

'; $mensaje .= 'El paquete de copia contiene un archivo con la copia de la información de la base de datos y un archivo que contiene el directorio de las fotografías e imágenes asociadas a los datos'; $this->mensaje = $mensaje; + return true; } - public function mensaje () + + public function mensaje() { return $this->mensaje; } } - -?> diff --git a/Csv.php b/Csv.php index a4bcbca..4dac844 100644 --- a/Csv.php +++ b/Csv.php @@ -1,7 +1,6 @@ . - * */ -class Csv { - +class Csv +{ /** - * - * @var String Nombre del fichero csv + * @var string Nombre del fichero csv */ private $nombre; /** * @var FILE manejador del fichero */ - private $fichero = NULL; + private $fichero = null; /** * @var xml conulta asociada a este fichero @@ -43,7 +40,6 @@ class Csv { private $bdd; /** - * * @var int Número de registros en el fichero csv */ private $numRegistros; @@ -59,8 +55,7 @@ class Csv { private $datosFichero; /** - * Indices a los campos correspondientes - * + * Indices a los campos correspondientes. */ private $idElemento; private $idArticulo; @@ -70,11 +65,11 @@ class Csv { private $cantidadReal; private $nSerie; - /** - // El constructor necesita saber cuál es la opción actual - /** - * Constructor de la clase. + * // El constructor necesita saber cuál es la opción actual. + * /** + * Constructor de la clase. + * * @param BaseDatos $baseDatos Manejador de la base de datos */ public function __construct($baseDatos) @@ -83,22 +78,22 @@ class Csv { } /** - * Crea un fichero csv con el nombre especificado - * @param String $fichero Nombre del fichero + * Crea un fichero csv con el nombre especificado. + * + * @param string $fichero Nombre del fichero */ public function crea($fichero) { $this->nombre = $fichero; - $this->fichero = fopen($this->nombre, "w") or die("No puedo abrir " . $this->nombre . " para escritura."); + $this->fichero = fopen($this->nombre, 'w') or die('No puedo abrir '.$this->nombre.' para escritura.'); } /** - * * @param array $datos escribe la línea en el archivo */ public function escribeLinea($datos) { - fputcsv($this->fichero, $datos, ',', '"') or die("No puedo escribir en el fichero csv"); + fputcsv($this->fichero, $datos, ',', '"') or die('No puedo escribir en el fichero csv'); } public function __destruct() @@ -108,18 +103,17 @@ class Csv { public function cierra() { - fclose($this->fichero) or die("No puedo cerrar el archivo csv"); + fclose($this->fichero) or die('No puedo cerrar el archivo csv'); } /** - * - * @param String $fichero Archivo xml que contiene la definición de la consulta + * @param string $fichero Archivo xml que contiene la definición de la consulta */ public function ejecutaConsulta($fichero) { - $consulta = simplexml_load_file($fichero) or die("No puedo cargar el fichero xml " . $fichero . " al csv"); + $consulta = simplexml_load_file($fichero) or die('No puedo cargar el fichero xml '.$fichero.' al csv'); // Escribe la cabecera del fichero - $this->escribeLinea(array($consulta->Pagina->Cabecera, $consulta->Titulo['id'], $consulta->Titulo['Texto'])); + $this->escribeLinea([$consulta->Pagina->Cabecera, $consulta->Titulo['id'], $consulta->Titulo['Texto']]); foreach ($consulta->Pagina->Cuerpo->Col as $campo) { $campos[] = $campo['Titulo']; } @@ -127,7 +121,7 @@ class Csv { // Escribe los datos de los campos $this->bdd->ejecuta($consulta->Datos->Consulta); while ($fila = $this->bdd->procesaResultado()) { - $campos = array(); + $campos = []; foreach ($consulta->Pagina->Cuerpo->Col as $campo) { $campos[] = $fila[(string) $campo['Nombre']]; } @@ -136,13 +130,12 @@ class Csv { } /** - * - * @param String $ficheroCSV Nombre del archivo csv + * @param string $ficheroCSV Nombre del archivo csv */ public function cargaCSV($ficheroCSV) { $this->nombre = $ficheroCSV; - $this->fichero = fopen($this->nombre, "r") or die('No puedo abrir el archivo ' . $this->nombre . " para lectura."); + $this->fichero = fopen($this->nombre, 'r') or die('No puedo abrir el archivo '.$this->nombre.' para lectura.'); list($archivo, $idCabecera, $cabecera) = fgetcsv($this->fichero); while ($linea = fgetcsv($this->fichero)) { $datosFichero[] = $linea; @@ -154,70 +147,69 @@ class Csv { } /** - * Muestra un resumen de los datos del fichero csv cargado por pantalla - * + * Muestra un resumen de los datos del fichero csv cargado por pantalla. */ public function resumen() { //$mensaje .= - $mensaje = "

Archivo [inventario" . $this->cabecera[0] . "]

"; - $mensaje .= "

id=[" . $this->cabecera[1] . "] Descripción=[" . $this->cabecera[2] . "]


"; + $mensaje = '

Archivo [inventario'.$this->cabecera[0].']

'; + $mensaje .= '

id=['.$this->cabecera[1].'] Descripción=['.$this->cabecera[2].']


'; $mensaje .= '
Preferencias
Base de datos
- Volver + $salida .= '
Base de datos
+ Volver
'; foreach ($this->datosFichero[0] as $campo) { $dato = $campo; $mensaje .= ""; } - $mensaje .= ""; - $mensaje .=""; + $mensaje .= ''; + $mensaje .= ''; $this->cargaIndices($this->datosFichero[0]); //echo "$mensaje contar Datosfichero=[".count($datosFichero)."]"; for ($i = 1; $i < count($this->datosFichero); $i++) { - $mensaje .= ""; + $mensaje .= ''; $primero = true; foreach ($this->datosFichero[$i] as $dato) { if ($primero) { $primero = false; switch ($dato) { - case 'S': $estado = "-Baja-"; - $color = "danger"; + case 'S': $estado = '-Baja-'; + $color = 'danger'; break; - case 'Alta': $estado = "-Alta-"; - $color = "primary"; + case 'Alta': $estado = '-Alta-'; + $color = 'primary'; break; - case "N" : $estado = $this->compruebaCantidades($i); + case 'N': $estado = $this->compruebaCantidades($i); if ($estado != 0) { - $color = "warning"; + $color = 'warning'; if ($estado > 0) { - $estado = "+" . $estado; + $estado = '+'.$estado; } } else { - $estado = "igual"; - $color = "info"; + $estado = 'igual'; + $color = 'info'; } break; default: throw new Exception("El archivo csv tiene un formato incorrecto.
Bajas=[$dato]"); } } - $mensaje .= ""; + $mensaje .= ''; } - $mensaje .= ''; - $mensaje .= ""; + $mensaje .= ''; + $mensaje .= ''; } - $mensaje .= "
$datoAcción
Acción
" . $dato . "'.$dato.'


"; + $mensaje .= '


'; $mensaje .= $this->panelMensaje('Si se produce cualquier error en el procesamiento del fichero, no se aplicará ningún cambio en la base de datos.'); $mensaje .= '
- + - +
'; return $mensaje; } /** - * - * @param $array línea de datos del fichero csv para comprobar las cantidades si se han modificado o no + * @param $array línea de datos del fichero csv para comprobar las cantidades si se han modificado o no + * * @return string */ private function compruebaCantidades($i) @@ -226,61 +218,62 @@ class Csv { return $this->datosFichero[$i][$this->cantidadReal] - $this->datosFichero[$i][$this->cantidad]; } - private function panelMensaje($info, $tipo = "danger", $cabecera = "¡Atención!") + private function panelMensaje($info, $tipo = 'danger', $cabecera = '¡Atención!') { - $mensaje = '
'; - $mensaje .= '

' . $cabecera . '

'; + $mensaje = '
'; + $mensaje .= '

'.$cabecera.'

'; $mensaje .= '
'; $mensaje .= $info; $mensaje .= '
'; $mensaje .= '
'; + return $mensaje; } private function escribeLog($comando) { - $fp = fopen($this->nombre . ".log", "a"); - $linea = strftime("%Y/%m/%d") . "|" . $this->nombre . "|" . $comando; - fputs($fp, $linea . "\n"); + $fp = fopen($this->nombre.'.log', 'a'); + $linea = strftime('%Y/%m/%d').'|'.$this->nombre.'|'.$comando; + fwrite($fp, $linea."\n"); fclose($fp); } private function bajaElemento($i) { $id = $this->datosFichero[$i][$this->idElemento]; - $comando = 'delete from Elementos where id="' . $id . '";'; + $comando = 'delete from Elementos where id="'.$id.'";'; $this->escribeLog($comando); if (!$this->bdd->ejecuta($comando)) { - throw new Exception("Baja-" . $this->bdd->mensajeError, $this->bdd->error); + throw new Exception('Baja-'.$this->bdd->mensajeError, $this->bdd->error); } } private function modificaElemento($i) { $id = $this->datosFichero[$i][$this->idElemento]; - $comando = 'update Elementos set Cantidad=' . $this->datosFichero[$i][$this->cantidadReal] . ' where id="' . $id . '";'; + $comando = 'update Elementos set Cantidad='.$this->datosFichero[$i][$this->cantidadReal].' where id="'.$id.'";'; $this->escribeLog($comando); if (!$this->bdd->ejecuta($comando)) { - throw new Exception("Modifica-" . $this->bdd->mensajeError, $this->bdd->error); + throw new Exception('Modifica-'.$this->bdd->mensajeError, $this->bdd->error); } } private function altaElemento($i) { - if ($this->cabecera[0] == "Articulo") { + if ($this->cabecera[0] == 'Articulo') { $idUbicacion = $this->datosFichero[$i][$this->idUbicacion]; $idArticulo = $this->cabecera[1]; - $comando = 'select id from Ubicaciones where Descripcion="' . $this->datosFichero[$i][$this->desUbicacion] . '";'; + $comando = 'select id from Ubicaciones where Descripcion="'.$this->datosFichero[$i][$this->desUbicacion].'";'; } else { $idUbicacion = $this->cabecera[1]; $idArticulo = $this->datosFichero[$i][$this->idArticulo]; } $idArt = $datosFichero[$i]; - $comando = 'insert into Elementos () values (null,' . $idArticulo . ',' . $idUbicacion . ',"' . $this->datosFichero[$i][$this->nSerie]; - $comando .= '",' . $this->datosFichero[$i][$this->cantidadReal] . ',"' . $this->datosFichero[$i][$this->fechaCompra] . '");'; + $comando = 'insert into Elementos () values (null,'.$idArticulo.','.$idUbicacion.',"'.$this->datosFichero[$i][$this->nSerie]; + $comando .= '",'.$this->datosFichero[$i][$this->cantidadReal].',"'.$this->datosFichero[$i][$this->fechaCompra].'");'; $this->escribeLog($comando); if (!$this->bdd->ejecuta($comando)) { - throw new Exception("Alta-" . $this->bdd->mensajeError, $this->bdd->error); + throw new Exception('Alta-'.$this->bdd->mensajeError, $this->bdd->error); } } @@ -288,19 +281,19 @@ class Csv { { for ($i = 0; $i < count($campos); $i++) { switch ($campos[$i]) { - case "Cant. Real": $this->cantidadReal = $i; + case 'Cant. Real': $this->cantidadReal = $i; break; - case "Fecha C.": $this->fechaCompra = $i; + case 'Fecha C.': $this->fechaCompra = $i; break; - case "idUbic": $this->idUbicacion = $i; + case 'idUbic': $this->idUbicacion = $i; break; - case "idArt": $this->idArticulo = $i; + case 'idArt': $this->idArticulo = $i; break; - case "idElem": $this->idElemento = $i; + case 'idElem': $this->idElemento = $i; break; - case "Cantidad": $this->cantidad = $i; + case 'Cantidad': $this->cantidad = $i; break; - case "N Serie": $this->nSerie = $i; + case 'N Serie': $this->nSerie = $i; break; } } @@ -309,7 +302,7 @@ class Csv { } /** - * Procesa contra la base de datos todas las acciones del archivo + * Procesa contra la base de datos todas las acciones del archivo. */ public function ejecutaFichero() { @@ -334,15 +327,17 @@ class Csv { $acciones++; } break; - default: throw new Exception("Acción no reconocida en la importacion [" . $this->datosFichero[0] . "]"); + default: throw new Exception('Acción no reconocida en la importacion ['.$this->datosFichero[0].']'); } } $mensaje = "Se han procesado correctamente $acciones acciones en la Base de Datos."; $this->bdd->confirmaTransaccion(); - return $this->panelMensaje($mensaje, "success", "Información"); + + return $this->panelMensaje($mensaje, 'success', 'Información'); } catch (Exception $e) { $this->bdd->abortaTransaccion(); - $mensaje = "Se ha producido el error [" . $e->getMessage() . "]
NO se ha realizado ningún cambio en la Base de Datos."; + $mensaje = 'Se ha producido el error ['.$e->getMessage().']
NO se ha realizado ningún cambio en la Base de Datos.'; + return $this->panelMensaje($mensaje); } } @@ -353,13 +348,10 @@ class Csv { for ($i = 1; $i < 80; $i++) { //sleep(1); $progreso = $i; - echo ''; + echo ''; //echo str_repeat(' ',1024*64); flush(); //echo '$(".bar").css("width", "'.$progreso.'");'; } } - } - -?> diff --git a/Distribucion.php b/Distribucion.php index 80822b6..7e7d3e2 100644 --- a/Distribucion.php +++ b/Distribucion.php @@ -1,23 +1,21 @@ . - * - */ +/** + * @copyright Copyright (c) 2008, Ricardo Montañana Gómez + * @license http://www.gnu.org/licenses/gpl-3.0.txt + * This file is part of Inventario. + * Inventario is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Inventario is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Inventario. If not, see . + */ // // Esta clase procesará una página sustituyendo // las marcas {} por el contenido que proceda. @@ -27,46 +25,49 @@ // y una referencia al objeto cuyos métodos deberán // aportar los contenidos. // -class Distribucion { - // Variable para conservar la plantilla - private $plantilla; - // Matriz que contendrá los nombres de elementos - private $elementos; - // Referencia al objeto cuyos métodos serán - // invocados para aportar el contenido - private $objeto; - // Constructor de la clase - public function __construct($archivo, $objeto) - { - // Recuperamos el contenido del archivo - $this->plantilla=file_get_contents($archivo) +class Distribucion +{ + // Variable para conservar la plantilla + private $plantilla; + // Matriz que contendrá los nombres de elementos + private $elementos; + // Referencia al objeto cuyos métodos serán + // invocados para aportar el contenido + private $objeto; + + // Constructor de la clase + public function __construct($archivo, $objeto) + { + // Recuperamos el contenido del archivo + $this->plantilla = file_get_contents($archivo) or die('Fallo en la apertura de la plantilla '.$archivo); - // y guardamos la referencia al objeto - $this->objeto=$objeto; - // Extraemos todas las marcas de contenido - preg_match_all('/\{[A-Za-z]+\}/', $this->plantilla,$el, PREG_PATTERN_ORDER); - // Nos quedamos con la matriz de resultados - $this->elementos=$el[0]; - } - // Este método es el encargado de procesar la plantilla - public function procesaPlantilla() - { - // Tomamos la plantilla en una variable local, para - // así no modificar el contenido original - $pagina=$this->plantilla; - // Recorremos la matriz de marcas de contenido - foreach($this->elementos as $el) { - // Eliminamos los delimitadores { y } - $el=substr($el,1,strlen($el)-2); - // invocamos a la función del objeto - $resultado=$this->objeto->$el(); - // e introducimos su contenido en lugar de la marca - $pagina=str_replace('{'.$el.'}',$resultado,$pagina); - } - /** - * @todo Tratar de activar la compresión. - */ - // Si es posible comprimir + // y guardamos la referencia al objeto + $this->objeto = $objeto; + // Extraemos todas las marcas de contenido + preg_match_all('/\{[A-Za-z]+\}/', $this->plantilla, $el, PREG_PATTERN_ORDER); + // Nos quedamos con la matriz de resultados + $this->elementos = $el[0]; + } + + // Este método es el encargado de procesar la plantilla + public function procesaPlantilla() + { + // Tomamos la plantilla en una variable local, para + // así no modificar el contenido original + $pagina = $this->plantilla; + // Recorremos la matriz de marcas de contenido + foreach ($this->elementos as $el) { + // Eliminamos los delimitadores { y } + $el = substr($el, 1, strlen($el) - 2); + // invocamos a la función del objeto + $resultado = $this->objeto->$el(); + // e introducimos su contenido en lugar de la marca + $pagina = str_replace('{'.$el.'}', $resultado, $pagina); + } + /* + * @todo Tratar de activar la compresión. + */ + // Si es posible comprimir // if(strstr($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip')) { // // introducimos la cabecera que indica que el contenido está comprimido // header('Content-Encoding: gzip'); @@ -74,6 +75,5 @@ class Distribucion { // return gzencode($pagina, 9); // } return $pagina; // enviamos sin comprimir - } + } } -?> \ No newline at end of file diff --git a/EtiquetasPDF.php b/EtiquetasPDF.php index daf46ae..8951cb9 100644 --- a/EtiquetasPDF.php +++ b/EtiquetasPDF.php @@ -1,12 +1,13 @@ + * * @version 1.0 - * @package Inventario + * * @copyright Copyright (c) 2008, Ricardo Montañana - * @package Inventario * @copyright Copyright (c) 2008, Ricardo Montañana Gómez * @license http://www.gnu.org/licenses/gpl-3.0.txt * This file is part of Inventario. @@ -14,22 +15,20 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. - * + * * Inventario is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with Inventario. If not, see . - * */ require_once 'phpqrcode.php'; -class EtiquetasPDF { - +class EtiquetasPDF +{ /** - * * @var basedatos Controlador de la base de datos */ private $bdd; @@ -39,19 +38,21 @@ class EtiquetasPDF { private $nombreFichero; /** - * El constructor recibe como argumento el nombre del archivo XML con la definición, encargándose de recuperarla y guardar toda la información localmente - * @param basedatos $bdd manejador de la base de datos - * @param string $definicion fichero con la definición del informe en XML - * @param boolean $registrado usuario registrado si/no + * El constructor recibe como argumento el nombre del archivo XML con la definición, encargándose de recuperarla y guardar toda la información localmente. + * + * @param basedatos $bdd manejador de la base de datos + * @param string $definicion fichero con la definición del informe en XML + * @param bool $registrado usuario registrado si/no + * * @return ficheroPDF - * todo: cambiar este comentario + * todo: cambiar este comentario */ public function __construct($bdd, $definicion, $registrado) { if (!$registrado) { return 'Debe registrarse para acceder a este apartado'; } - $this->nombreFichero = TMP."/informeEtiquetas.pdf"; + $this->nombreFichero = TMP.'/informeEtiquetas.pdf'; // Recuperamos la definición del informe $this->def = simplexml_load_file($definicion); $this->bdd = $bdd; @@ -61,7 +62,7 @@ class EtiquetasPDF { $this->pdf->setAutoPageBreak(false); //echo $def->Titulo.$def->Cabecera; $this->pdf->setAuthor(AUTOR, true); - $creador = CENTRO . " " . PROGRAMA . VERSION; + $creador = CENTRO.' '.PROGRAMA.VERSION; $this->pdf->setCreator(html_entity_decode($creador), true); $this->pdf->setSubject($this->def->Titulo, true); //$this->pdf->setAutoPageBreak(true, 10); @@ -78,12 +79,13 @@ class EtiquetasPDF { $this->pdf->AddPage(); $tamLinea = 5; $fila = -1; - $primero = true; $i = 0; - $url = explode("/", $_SERVER['SCRIPT_NAME']); + $primero = true; + $i = 0; + $url = explode('/', $_SERVER['SCRIPT_NAME']); $aplicacion = $url[1]; - $protocolo = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443 ? "https://" : "http://"; - $enlace = $protocolo . $_SERVER['SERVER_NAME'] . "/" . $aplicacion . "/index.php?elementos&opc=editar&id="; - while($tupla = $this->bdd->procesaResultado()) { + $protocolo = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443 ? 'https://' : 'http://'; + $enlace = $protocolo.$_SERVER['SERVER_NAME'].'/'.$aplicacion.'/index.php?elementos&opc=editar&id='; + while ($tupla = $this->bdd->procesaResultado()) { for ($j = 0; $j < $tupla['cantidad']; $j++) { //Hay que generar tantas etiquetas como ponga la cantidad de cada elemento if ($i % 2) { @@ -104,31 +106,31 @@ class EtiquetasPDF { $primero = false; } $py = 6 + 41 * $fila; - $enlace2=$enlace.$tupla['idEl']; - $fichero = TMP."/etiq".rand(1000,9999).".png"; + $enlace2 = $enlace.$tupla['idEl']; + $fichero = TMP.'/etiq'.rand(1000, 9999).'.png'; QRcode::png($enlace2, $fichero); $this->pdf->image($fichero, $etiq2, $py, 30, 30); unlink($fichero); $this->pdf->setxy($etiq1, $py); $this->pdf->Cell(30, 10, utf8_decode($tupla['articulo'])); - $py+=$tamLinea; + $py += $tamLinea; $this->pdf->setxy($etiq1, $py); $this->pdf->Cell(30, 10, utf8_decode($tupla['marca'])); - $py+=$tamLinea; + $py += $tamLinea; $this->pdf->setxy($etiq1, $py); $this->pdf->Cell(30, 10, utf8_decode($tupla['modelo'])); - $py+=$tamLinea; + $py += $tamLinea; $this->pdf->setxy($etiq1, $py); $this->pdf->Cell(30, 10, utf8_decode($tupla['numserie'])); - $py+=$tamLinea; + $py += $tamLinea; $this->pdf->setxy($etiq1, $py); $this->pdf->Cell(30, 10, $tupla['fechaCompra']); - $py+=$tamLinea-1; + $py += $tamLinea - 1; $this->pdf->setxy($etiq2, $py); $this->pdf->Cell(30, 10, utf8_decode($tupla['ubicacion'])); - $py+=$tamLinea-1; + $py += $tamLinea - 1; $this->pdf->setxy($etiq2, $py); - $cadena = "idElemento=" . $tupla['idEl'] . " / idArticulo=" . $tupla['idArt'] . " / idUbicacion=" . $tupla['idUbic']; + $cadena = 'idElemento='.$tupla['idEl'].' / idArticulo='.$tupla['idArt'].' / idUbicacion='.$tupla['idUbic']; $this->pdf->Cell(30, 10, $cadena); $i++; } @@ -149,15 +151,16 @@ class EtiquetasPDF { public function getCabecera() { - $cabecera = "Content-type: application/pdf"; - $cabecera = $cabecera . "Content-length: " . strlen($this->docu); - $cabecera = $cabecera . "Content-Disposition: inline; filename=" . $this->nombreFichero; + $cabecera = 'Content-type: application/pdf'; + $cabecera = $cabecera.'Content-length: '.strlen($this->docu); + $cabecera = $cabecera.'Content-Disposition: inline; filename='.$this->nombreFichero; + return $cabecera; } public function guardaArchivo($nombre) { - $fichero = fopen($nombre, "w"); + $fichero = fopen($nombre, 'w'); fwrite($fichero, $this->getCabecera()); fwrite($fichero, $this->getContenido(), strlen($this->getContenido())); $this->nombreFichero = $nombre; @@ -166,10 +169,10 @@ class EtiquetasPDF { public function enviaCabecera() { - header("Content-type: application/pdf"); + header('Content-type: application/pdf'); $longitud = strlen($this->docu); header("Content-length: $longitud"); - header("Content-Disposition: inline; filename=" . $this->nombreFichero); + header('Content-Disposition: inline; filename='.$this->nombreFichero); } public function imprimeInforme() @@ -178,5 +181,3 @@ class EtiquetasPDF { echo $this->docu; } } - -?> diff --git a/FPDF.php b/FPDF.php index 308406b..2b599b4 100644 --- a/FPDF.php +++ b/FPDF.php @@ -7,1798 +7,1849 @@ * Author: Olivier PLATHEY * *******************************************************************************/ -define('FPDF_VERSION','1.7'); +define('FPDF_VERSION', '1.7'); class FPDF { -var $page; // current page number -var $n; // current object number -var $offsets; // array of object offsets -var $buffer; // buffer holding in-memory PDF -var $pages; // array containing pages -var $state; // current document state -var $compress; // compression flag -var $k; // scale factor (number of points in user unit) -var $DefOrientation; // default orientation -var $CurOrientation; // current orientation -var $StdPageSizes; // standard page sizes -var $DefPageSize; // default page size -var $CurPageSize; // current page size -var $PageSizes; // used for pages with non default sizes or orientations -var $wPt, $hPt; // dimensions of current page in points -var $w, $h; // dimensions of current page in user unit -var $lMargin; // left margin -var $tMargin; // top margin -var $rMargin; // right margin -var $bMargin; // page break margin -var $cMargin; // cell margin -var $x, $y; // current position in user unit -var $lasth; // height of last printed cell -var $LineWidth; // line width in user unit -var $fontpath; // path containing fonts -var $CoreFonts; // array of core font names -var $fonts; // array of used fonts -var $FontFiles; // array of font files -var $diffs; // array of encoding differences -var $FontFamily; // current font family -var $FontStyle; // current font style -var $underline; // underlining flag -var $CurrentFont; // current font info -var $FontSizePt; // current font size in points -var $FontSize; // current font size in user unit -var $DrawColor; // commands for drawing color -var $FillColor; // commands for filling color -var $TextColor; // commands for text color -var $ColorFlag; // indicates whether fill and text colors are different -var $ws; // word spacing -var $images; // array of used images -var $PageLinks; // array of links in pages -var $links; // array of internal links -var $AutoPageBreak; // automatic page breaking -var $PageBreakTrigger; // threshold used to trigger page breaks -var $InHeader; // flag set when processing header -var $InFooter; // flag set when processing footer -var $ZoomMode; // zoom display mode -var $LayoutMode; // layout display mode -var $title; // title -var $subject; // subject -var $author; // author -var $keywords; // keywords -var $creator; // creator -var $AliasNbPages; // alias for total number of pages -var $PDFVersion; // PDF version number + public $page; // current page number +public $n; // current object number +public $offsets; // array of object offsets +public $buffer; // buffer holding in-memory PDF +public $pages; // array containing pages +public $state; // current document state +public $compress; // compression flag +public $k; // scale factor (number of points in user unit) +public $DefOrientation; // default orientation +public $CurOrientation; // current orientation +public $StdPageSizes; // standard page sizes +public $DefPageSize; // default page size +public $CurPageSize; // current page size +public $PageSizes; // used for pages with non default sizes or orientations +public $wPt; + public $hPt; // dimensions of current page in points + public $w; + public $h; // dimensions of current page in user unit +public $lMargin; // left margin +public $tMargin; // top margin +public $rMargin; // right margin +public $bMargin; // page break margin +public $cMargin; // cell margin +public $x; + public $y; // current position in user unit +public $lasth; // height of last printed cell +public $LineWidth; // line width in user unit +public $fontpath; // path containing fonts +public $CoreFonts; // array of core font names +public $fonts; // array of used fonts +public $FontFiles; // array of font files +public $diffs; // array of encoding differences +public $FontFamily; // current font family +public $FontStyle; // current font style +public $underline; // underlining flag +public $CurrentFont; // current font info +public $FontSizePt; // current font size in points +public $FontSize; // current font size in user unit +public $DrawColor; // commands for drawing color +public $FillColor; // commands for filling color +public $TextColor; // commands for text color +public $ColorFlag; // indicates whether fill and text colors are different +public $ws; // word spacing +public $images; // array of used images +public $PageLinks; // array of links in pages +public $links; // array of internal links +public $AutoPageBreak; // automatic page breaking +public $PageBreakTrigger; // threshold used to trigger page breaks +public $InHeader; // flag set when processing header +public $InFooter; // flag set when processing footer +public $ZoomMode; // zoom display mode +public $LayoutMode; // layout display mode +public $title; // title +public $subject; // subject +public $author; // author +public $keywords; // keywords +public $creator; // creator +public $AliasNbPages; // alias for total number of pages +public $PDFVersion; // PDF version number /******************************************************************************* * * * Public methods * * * *******************************************************************************/ -function FPDF($orientation='P', $unit='mm', $size='A4') -{ - // Some checks - $this->_dochecks(); - // Initialization of properties - $this->page = 0; - $this->n = 2; - $this->buffer = ''; - $this->pages = array(); - $this->PageSizes = array(); - $this->state = 0; - $this->fonts = array(); - $this->FontFiles = array(); - $this->diffs = array(); - $this->images = array(); - $this->links = array(); - $this->InHeader = false; - $this->InFooter = false; - $this->lasth = 0; - $this->FontFamily = ''; - $this->FontStyle = ''; - $this->FontSizePt = 12; - $this->underline = false; - $this->DrawColor = '0 G'; - $this->FillColor = '0 g'; - $this->TextColor = '0 g'; - $this->ColorFlag = false; - $this->ws = 0; - // Font path - if(defined('FPDF_FONTPATH')) - { - $this->fontpath = FPDF_FONTPATH; - if(substr($this->fontpath,-1)!='/' && substr($this->fontpath,-1)!='\\') - $this->fontpath .= '/'; - } - elseif(is_dir(dirname(__FILE__).'/font')) - $this->fontpath = dirname(__FILE__).'/font/'; - else - $this->fontpath = ''; - // Core fonts - $this->CoreFonts = array('courier', 'helvetica', 'times', 'symbol', 'zapfdingbats'); - // Scale factor - if($unit=='pt') - $this->k = 1; - elseif($unit=='mm') - $this->k = 72/25.4; - elseif($unit=='cm') - $this->k = 72/2.54; - elseif($unit=='in') - $this->k = 72; - else - $this->Error('Incorrect unit: '.$unit); - // Page sizes - $this->StdPageSizes = array('a3'=>array(841.89,1190.55), 'a4'=>array(595.28,841.89), 'a5'=>array(420.94,595.28), - 'letter'=>array(612,792), 'legal'=>array(612,1008)); - $size = $this->_getpagesize($size); - $this->DefPageSize = $size; - $this->CurPageSize = $size; - // Page orientation - $orientation = strtolower($orientation); - if($orientation=='p' || $orientation=='portrait') - { - $this->DefOrientation = 'P'; - $this->w = $size[0]; - $this->h = $size[1]; - } - elseif($orientation=='l' || $orientation=='landscape') - { - $this->DefOrientation = 'L'; - $this->w = $size[1]; - $this->h = $size[0]; - } - else - $this->Error('Incorrect orientation: '.$orientation); - $this->CurOrientation = $this->DefOrientation; - $this->wPt = $this->w*$this->k; - $this->hPt = $this->h*$this->k; - // Page margins (1 cm) - $margin = 28.35/$this->k; - $this->SetMargins($margin,$margin); - // Interior cell margin (1 mm) - $this->cMargin = $margin/10; - // Line width (0.2 mm) - $this->LineWidth = .567/$this->k; - // Automatic page break - $this->SetAutoPageBreak(true,2*$margin); - // Default display mode - $this->SetDisplayMode('default'); - // Enable compression - $this->SetCompression(true); - // Set default PDF version number - $this->PDFVersion = '1.3'; -} - -function SetMargins($left, $top, $right=null) -{ - // Set left, top and right margins - $this->lMargin = $left; - $this->tMargin = $top; - if($right===null) - $right = $left; - $this->rMargin = $right; -} - -function SetLeftMargin($margin) -{ - // Set left margin - $this->lMargin = $margin; - if($this->page>0 && $this->x<$margin) - $this->x = $margin; -} - -function SetTopMargin($margin) -{ - // Set top margin - $this->tMargin = $margin; -} - -function SetRightMargin($margin) -{ - // Set right margin - $this->rMargin = $margin; -} - -function SetAutoPageBreak($auto, $margin=0) -{ - // Set auto page break mode and triggering margin - $this->AutoPageBreak = $auto; - $this->bMargin = $margin; - $this->PageBreakTrigger = $this->h-$margin; -} - -function SetDisplayMode($zoom, $layout='default') -{ - // Set display mode in viewer - if($zoom=='fullpage' || $zoom=='fullwidth' || $zoom=='real' || $zoom=='default' || !is_string($zoom)) - $this->ZoomMode = $zoom; - else - $this->Error('Incorrect zoom display mode: '.$zoom); - if($layout=='single' || $layout=='continuous' || $layout=='two' || $layout=='default') - $this->LayoutMode = $layout; - else - $this->Error('Incorrect layout display mode: '.$layout); -} - -function SetCompression($compress) -{ - // Set page compression - if(function_exists('gzcompress')) - $this->compress = $compress; - else - $this->compress = false; -} - -function SetTitle($title, $isUTF8=false) -{ - // Title of document - if($isUTF8) - $title = $this->_UTF8toUTF16($title); - $this->title = $title; -} - -function SetSubject($subject, $isUTF8=false) -{ - // Subject of document - if($isUTF8) - $subject = $this->_UTF8toUTF16($subject); - $this->subject = $subject; -} - -function SetAuthor($author, $isUTF8=false) -{ - // Author of document - if($isUTF8) - $author = $this->_UTF8toUTF16($author); - $this->author = $author; -} - -function SetKeywords($keywords, $isUTF8=false) -{ - // Keywords of document - if($isUTF8) - $keywords = $this->_UTF8toUTF16($keywords); - $this->keywords = $keywords; -} - -function SetCreator($creator, $isUTF8=false) -{ - // Creator of document - if($isUTF8) - $creator = $this->_UTF8toUTF16($creator); - $this->creator = $creator; -} - -function AliasNbPages($alias='{nb}') -{ - // Define an alias for total number of pages - $this->AliasNbPages = $alias; -} - -function Error($msg) -{ - // Fatal error - die('FPDF error: '.$msg); -} - -function Open() -{ - // Begin document - $this->state = 1; -} - -function Close() -{ - // Terminate document - if($this->state==3) - return; - if($this->page==0) - $this->AddPage(); - // Page footer - $this->InFooter = true; - $this->Footer(); - $this->InFooter = false; - // Close page - $this->_endpage(); - // Close document - $this->_enddoc(); -} - -function AddPage($orientation='', $size='') -{ - // Start a new page - if($this->state==0) - $this->Open(); - $family = $this->FontFamily; - $style = $this->FontStyle.($this->underline ? 'U' : ''); - $fontsize = $this->FontSizePt; - $lw = $this->LineWidth; - $dc = $this->DrawColor; - $fc = $this->FillColor; - $tc = $this->TextColor; - $cf = $this->ColorFlag; - if($this->page>0) - { - // Page footer - $this->InFooter = true; - $this->Footer(); - $this->InFooter = false; - // Close page - $this->_endpage(); - } - // Start new page - $this->_beginpage($orientation,$size); - // Set line cap style to square - $this->_out('2 J'); - // Set line width - $this->LineWidth = $lw; - $this->_out(sprintf('%.2F w',$lw*$this->k)); - // Set font - if($family) - $this->SetFont($family,$style,$fontsize); - // Set colors - $this->DrawColor = $dc; - if($dc!='0 G') - $this->_out($dc); - $this->FillColor = $fc; - if($fc!='0 g') - $this->_out($fc); - $this->TextColor = $tc; - $this->ColorFlag = $cf; - // Page header - $this->InHeader = true; - $this->Header(); - $this->InHeader = false; - // Restore line width - if($this->LineWidth!=$lw) - { - $this->LineWidth = $lw; - $this->_out(sprintf('%.2F w',$lw*$this->k)); - } - // Restore font - if($family) - $this->SetFont($family,$style,$fontsize); - // Restore colors - if($this->DrawColor!=$dc) - { - $this->DrawColor = $dc; - $this->_out($dc); - } - if($this->FillColor!=$fc) - { - $this->FillColor = $fc; - $this->_out($fc); - } - $this->TextColor = $tc; - $this->ColorFlag = $cf; -} - -function Header() -{ - // To be implemented in your own inherited class -} - -function Footer() -{ - // To be implemented in your own inherited class -} - -function PageNo() -{ - // Get current page number - return $this->page; -} - -function SetDrawColor($r, $g=null, $b=null) -{ - // Set color for all stroking operations - if(($r==0 && $g==0 && $b==0) || $g===null) - $this->DrawColor = sprintf('%.3F G',$r/255); - else - $this->DrawColor = sprintf('%.3F %.3F %.3F RG',$r/255,$g/255,$b/255); - if($this->page>0) - $this->_out($this->DrawColor); -} - -function SetFillColor($r, $g=null, $b=null) -{ - // Set color for all filling operations - if(($r==0 && $g==0 && $b==0) || $g===null) - $this->FillColor = sprintf('%.3F g',$r/255); - else - $this->FillColor = sprintf('%.3F %.3F %.3F rg',$r/255,$g/255,$b/255); - $this->ColorFlag = ($this->FillColor!=$this->TextColor); - if($this->page>0) - $this->_out($this->FillColor); -} - -function SetTextColor($r, $g=null, $b=null) -{ - // Set color for text - if(($r==0 && $g==0 && $b==0) || $g===null) - $this->TextColor = sprintf('%.3F g',$r/255); - else - $this->TextColor = sprintf('%.3F %.3F %.3F rg',$r/255,$g/255,$b/255); - $this->ColorFlag = ($this->FillColor!=$this->TextColor); -} - -function GetStringWidth($s) -{ - // Get width of a string in the current font - $s = (string)$s; - $cw = &$this->CurrentFont['cw']; - $w = 0; - $l = strlen($s); - for($i=0;$i<$l;$i++) - $w += $cw[$s[$i]]; - return $w*$this->FontSize/1000; -} - -function SetLineWidth($width) -{ - // Set line width - $this->LineWidth = $width; - if($this->page>0) - $this->_out(sprintf('%.2F w',$width*$this->k)); -} - -function Line($x1, $y1, $x2, $y2) -{ - // Draw a line - $this->_out(sprintf('%.2F %.2F m %.2F %.2F l S',$x1*$this->k,($this->h-$y1)*$this->k,$x2*$this->k,($this->h-$y2)*$this->k)); -} - -function Rect($x, $y, $w, $h, $style='') -{ - // Draw a rectangle - if($style=='F') - $op = 'f'; - elseif($style=='FD' || $style=='DF') - $op = 'B'; - else - $op = 'S'; - $this->_out(sprintf('%.2F %.2F %.2F %.2F re %s',$x*$this->k,($this->h-$y)*$this->k,$w*$this->k,-$h*$this->k,$op)); -} - -function AddFont($family, $style='', $file='') -{ - // Add a TrueType, OpenType or Type1 font - $family = strtolower($family); - if($file=='') - $file = str_replace(' ','',$family).strtolower($style).'.php'; - $style = strtoupper($style); - if($style=='IB') - $style = 'BI'; - $fontkey = $family.$style; - if(isset($this->fonts[$fontkey])) - return; - $info = $this->_loadfont($file); - $info['i'] = count($this->fonts)+1; - if(!empty($info['diff'])) - { - // Search existing encodings - $n = array_search($info['diff'],$this->diffs); - if(!$n) - { - $n = count($this->diffs)+1; - $this->diffs[$n] = $info['diff']; - } - $info['diffn'] = $n; - } - if(!empty($info['file'])) - { - // Embedded font - if($info['type']=='TrueType') - $this->FontFiles[$info['file']] = array('length1'=>$info['originalsize']); - else - $this->FontFiles[$info['file']] = array('length1'=>$info['size1'], 'length2'=>$info['size2']); - } - $this->fonts[$fontkey] = $info; -} - -function SetFont($family, $style='', $size=0) -{ - // Select a font; size given in points - if($family=='') - $family = $this->FontFamily; - else - $family = strtolower($family); - $style = strtoupper($style); - if(strpos($style,'U')!==false) - { - $this->underline = true; - $style = str_replace('U','',$style); - } - else - $this->underline = false; - if($style=='IB') - $style = 'BI'; - if($size==0) - $size = $this->FontSizePt; - // Test if font is already selected - if($this->FontFamily==$family && $this->FontStyle==$style && $this->FontSizePt==$size) - return; - // Test if font is already loaded - $fontkey = $family.$style; - if(!isset($this->fonts[$fontkey])) - { - // Test if one of the core fonts - if($family=='arial') - $family = 'helvetica'; - if(in_array($family,$this->CoreFonts)) - { - if($family=='symbol' || $family=='zapfdingbats') - $style = ''; - $fontkey = $family.$style; - if(!isset($this->fonts[$fontkey])) - $this->AddFont($family,$style); - } - else - $this->Error('Undefined font: '.$family.' '.$style); - } - // Select it - $this->FontFamily = $family; - $this->FontStyle = $style; - $this->FontSizePt = $size; - $this->FontSize = $size/$this->k; - $this->CurrentFont = &$this->fonts[$fontkey]; - if($this->page>0) - $this->_out(sprintf('BT /F%d %.2F Tf ET',$this->CurrentFont['i'],$this->FontSizePt)); -} - -function SetFontSize($size) -{ - // Set font size in points - if($this->FontSizePt==$size) - return; - $this->FontSizePt = $size; - $this->FontSize = $size/$this->k; - if($this->page>0) - $this->_out(sprintf('BT /F%d %.2F Tf ET',$this->CurrentFont['i'],$this->FontSizePt)); -} - -function AddLink() -{ - // Create a new internal link - $n = count($this->links)+1; - $this->links[$n] = array(0, 0); - return $n; -} - -function SetLink($link, $y=0, $page=-1) -{ - // Set destination of internal link - if($y==-1) - $y = $this->y; - if($page==-1) - $page = $this->page; - $this->links[$link] = array($page, $y); -} - -function Link($x, $y, $w, $h, $link) -{ - // Put a link on the page - $this->PageLinks[$this->page][] = array($x*$this->k, $this->hPt-$y*$this->k, $w*$this->k, $h*$this->k, $link); -} - -function Text($x, $y, $txt) -{ - // Output a string - $s = sprintf('BT %.2F %.2F Td (%s) Tj ET',$x*$this->k,($this->h-$y)*$this->k,$this->_escape($txt)); - if($this->underline && $txt!='') - $s .= ' '.$this->_dounderline($x,$y,$txt); - if($this->ColorFlag) - $s = 'q '.$this->TextColor.' '.$s.' Q'; - $this->_out($s); -} - -function AcceptPageBreak() -{ - // Accept automatic page break or not - return $this->AutoPageBreak; -} - -function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='') -{ - // Output a cell - $k = $this->k; - if($this->y+$h>$this->PageBreakTrigger && !$this->InHeader && !$this->InFooter && $this->AcceptPageBreak()) - { - // Automatic page break - $x = $this->x; - $ws = $this->ws; - if($ws>0) - { - $this->ws = 0; - $this->_out('0 Tw'); - } - $this->AddPage($this->CurOrientation,$this->CurPageSize); - $this->x = $x; - if($ws>0) - { - $this->ws = $ws; - $this->_out(sprintf('%.3F Tw',$ws*$k)); - } - } - if($w==0) - $w = $this->w-$this->rMargin-$this->x; - $s = ''; - if($fill || $border==1) - { - if($fill) - $op = ($border==1) ? 'B' : 'f'; - else - $op = 'S'; - $s = sprintf('%.2F %.2F %.2F %.2F re %s ',$this->x*$k,($this->h-$this->y)*$k,$w*$k,-$h*$k,$op); - } - if(is_string($border)) - { - $x = $this->x; - $y = $this->y; - if(strpos($border,'L')!==false) - $s .= sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-$y)*$k,$x*$k,($this->h-($y+$h))*$k); - if(strpos($border,'T')!==false) - $s .= sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-$y)*$k); - if(strpos($border,'R')!==false) - $s .= sprintf('%.2F %.2F m %.2F %.2F l S ',($x+$w)*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-($y+$h))*$k); - if(strpos($border,'B')!==false) - $s .= sprintf('%.2F %.2F m %.2F %.2F l S ',$x*$k,($this->h-($y+$h))*$k,($x+$w)*$k,($this->h-($y+$h))*$k); - } - if($txt!=='') - { - if($align=='R') - $dx = $w-$this->cMargin-$this->GetStringWidth($txt); - elseif($align=='C') - $dx = ($w-$this->GetStringWidth($txt))/2; - else - $dx = $this->cMargin; - if($this->ColorFlag) - $s .= 'q '.$this->TextColor.' '; - $txt2 = str_replace(')','\\)',str_replace('(','\\(',str_replace('\\','\\\\',$txt))); - $s .= sprintf('BT %.2F %.2F Td (%s) Tj ET',($this->x+$dx)*$k,($this->h-($this->y+.5*$h+.3*$this->FontSize))*$k,$txt2); - if($this->underline) - $s .= ' '.$this->_dounderline($this->x+$dx,$this->y+.5*$h+.3*$this->FontSize,$txt); - if($this->ColorFlag) - $s .= ' Q'; - if($link) - $this->Link($this->x+$dx,$this->y+.5*$h-.5*$this->FontSize,$this->GetStringWidth($txt),$this->FontSize,$link); - } - if($s) - $this->_out($s); - $this->lasth = $h; - if($ln>0) - { - // Go to next line - $this->y += $h; - if($ln==1) - $this->x = $this->lMargin; - } - else - $this->x += $w; -} - -function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=false) -{ - // Output text with automatic or explicit line breaks - $cw = &$this->CurrentFont['cw']; - if($w==0) - $w = $this->w-$this->rMargin-$this->x; - $wmax = ($w-2*$this->cMargin)*1000/$this->FontSize; - $s = str_replace("\r",'',$txt); - $nb = strlen($s); - if($nb>0 && $s[$nb-1]=="\n") - $nb--; - $b = 0; - if($border) - { - if($border==1) - { - $border = 'LTRB'; - $b = 'LRT'; - $b2 = 'LR'; - } - else - { - $b2 = ''; - if(strpos($border,'L')!==false) - $b2 .= 'L'; - if(strpos($border,'R')!==false) - $b2 .= 'R'; - $b = (strpos($border,'T')!==false) ? $b2.'T' : $b2; - } - } - $sep = -1; - $i = 0; - $j = 0; - $l = 0; - $ns = 0; - $nl = 1; - while($i<$nb) - { - // Get next character - $c = $s[$i]; - if($c=="\n") - { - // Explicit line break - if($this->ws>0) - { - $this->ws = 0; - $this->_out('0 Tw'); - } - $this->Cell($w,$h,substr($s,$j,$i-$j),$b,2,$align,$fill); - $i++; - $sep = -1; - $j = $i; - $l = 0; - $ns = 0; - $nl++; - if($border && $nl==2) - $b = $b2; - continue; - } - if($c==' ') - { - $sep = $i; - $ls = $l; - $ns++; - } - $l += $cw[$c]; - if($l>$wmax) - { - // Automatic line break - if($sep==-1) - { - if($i==$j) - $i++; - if($this->ws>0) - { - $this->ws = 0; - $this->_out('0 Tw'); - } - $this->Cell($w,$h,substr($s,$j,$i-$j),$b,2,$align,$fill); - } - else - { - if($align=='J') - { - $this->ws = ($ns>1) ? ($wmax-$ls)/1000*$this->FontSize/($ns-1) : 0; - $this->_out(sprintf('%.3F Tw',$this->ws*$this->k)); - } - $this->Cell($w,$h,substr($s,$j,$sep-$j),$b,2,$align,$fill); - $i = $sep+1; - } - $sep = -1; - $j = $i; - $l = 0; - $ns = 0; - $nl++; - if($border && $nl==2) - $b = $b2; - } - else - $i++; - } - // Last chunk - if($this->ws>0) - { - $this->ws = 0; - $this->_out('0 Tw'); - } - if($border && strpos($border,'B')!==false) - $b .= 'B'; - $this->Cell($w,$h,substr($s,$j,$i-$j),$b,2,$align,$fill); - $this->x = $this->lMargin; -} - -function Write($h, $txt, $link='') -{ - // Output text in flowing mode - $cw = &$this->CurrentFont['cw']; - $w = $this->w-$this->rMargin-$this->x; - $wmax = ($w-2*$this->cMargin)*1000/$this->FontSize; - $s = str_replace("\r",'',$txt); - $nb = strlen($s); - $sep = -1; - $i = 0; - $j = 0; - $l = 0; - $nl = 1; - while($i<$nb) - { - // Get next character - $c = $s[$i]; - if($c=="\n") - { - // Explicit line break - $this->Cell($w,$h,substr($s,$j,$i-$j),0,2,'',0,$link); - $i++; - $sep = -1; - $j = $i; - $l = 0; - if($nl==1) - { - $this->x = $this->lMargin; - $w = $this->w-$this->rMargin-$this->x; - $wmax = ($w-2*$this->cMargin)*1000/$this->FontSize; - } - $nl++; - continue; - } - if($c==' ') - $sep = $i; - $l += $cw[$c]; - if($l>$wmax) - { - // Automatic line break - if($sep==-1) - { - if($this->x>$this->lMargin) - { - // Move to next line - $this->x = $this->lMargin; - $this->y += $h; - $w = $this->w-$this->rMargin-$this->x; - $wmax = ($w-2*$this->cMargin)*1000/$this->FontSize; - $i++; - $nl++; - continue; - } - if($i==$j) - $i++; - $this->Cell($w,$h,substr($s,$j,$i-$j),0,2,'',0,$link); - } - else - { - $this->Cell($w,$h,substr($s,$j,$sep-$j),0,2,'',0,$link); - $i = $sep+1; - } - $sep = -1; - $j = $i; - $l = 0; - if($nl==1) - { - $this->x = $this->lMargin; - $w = $this->w-$this->rMargin-$this->x; - $wmax = ($w-2*$this->cMargin)*1000/$this->FontSize; - } - $nl++; - } - else - $i++; - } - // Last chunk - if($i!=$j) - $this->Cell($l/1000*$this->FontSize,$h,substr($s,$j),0,0,'',0,$link); -} - -function Ln($h=null) -{ - // Line feed; default value is last cell height - $this->x = $this->lMargin; - if($h===null) - $this->y += $this->lasth; - else - $this->y += $h; -} - -function Image($file, $x=null, $y=null, $w=0, $h=0, $type='', $link='') -{ - // Put an image on the page - if(!isset($this->images[$file])) - { - // First use of this image, get info - if($type=='') - { - $pos = strrpos($file,'.'); - if(!$pos) - $this->Error('Image file has no extension and no type was specified: '.$file); - $type = substr($file,$pos+1); - } - $type = strtolower($type); - if($type=='jpeg') - $type = 'jpg'; - $mtd = '_parse'.$type; - if(!method_exists($this,$mtd)) - $this->Error('Unsupported image type: '.$type); - $info = $this->$mtd($file); - $info['i'] = count($this->images)+1; - $this->images[$file] = $info; - } - else - $info = $this->images[$file]; - - // Automatic width and height calculation if needed - if($w==0 && $h==0) - { - // Put image at 96 dpi - $w = -96; - $h = -96; - } - if($w<0) - $w = -$info['w']*72/$w/$this->k; - if($h<0) - $h = -$info['h']*72/$h/$this->k; - if($w==0) - $w = $h*$info['w']/$info['h']; - if($h==0) - $h = $w*$info['h']/$info['w']; - - // Flowing mode - if($y===null) - { - if($this->y+$h>$this->PageBreakTrigger && !$this->InHeader && !$this->InFooter && $this->AcceptPageBreak()) - { - // Automatic page break - $x2 = $this->x; - $this->AddPage($this->CurOrientation,$this->CurPageSize); - $this->x = $x2; - } - $y = $this->y; - $this->y += $h; - } - - if($x===null) - $x = $this->x; - $this->_out(sprintf('q %.2F 0 0 %.2F %.2F %.2F cm /I%d Do Q',$w*$this->k,$h*$this->k,$x*$this->k,($this->h-($y+$h))*$this->k,$info['i'])); - if($link) - $this->Link($x,$y,$w,$h,$link); -} - -function GetX() -{ - // Get x position - return $this->x; -} - -function SetX($x) -{ - // Set x position - if($x>=0) - $this->x = $x; - else - $this->x = $this->w+$x; -} - -function GetY() -{ - // Get y position - return $this->y; -} - -function SetY($y) -{ - // Set y position and reset x - $this->x = $this->lMargin; - if($y>=0) - $this->y = $y; - else - $this->y = $this->h+$y; -} - -function SetXY($x, $y) -{ - // Set x and y positions - $this->SetY($y); - $this->SetX($x); -} - -function Output($name='', $dest='') -{ - // Output PDF to some destination - if($this->state<3) - $this->Close(); - $dest = strtoupper($dest); - if($dest=='') - { - if($name=='') - { - $name = 'doc.pdf'; - $dest = 'I'; - } - else - $dest = 'F'; - } - switch($dest) - { - case 'I': - // Send to standard output - $this->_checkoutput(); - if(PHP_SAPI!='cli') - { - // We send to a browser - header('Content-Type: application/pdf'); - header('Content-Disposition: inline; filename="'.$name.'"'); - header('Cache-Control: private, max-age=0, must-revalidate'); - header('Pragma: public'); - } - echo $this->buffer; - break; - case 'D': - // Download file - $this->_checkoutput(); - header('Content-Type: application/x-download'); - header('Content-Disposition: attachment; filename="'.$name.'"'); - header('Cache-Control: private, max-age=0, must-revalidate'); - header('Pragma: public'); - echo $this->buffer; - break; - case 'F': - // Save to local file - $f = fopen($name,'wb'); - if(!$f) - $this->Error('Unable to create output file: '.$name); - fwrite($f,$this->buffer,strlen($this->buffer)); - fclose($f); - break; - case 'S': - // Return as a string - return $this->buffer; - default: - $this->Error('Incorrect output destination: '.$dest); - } - return ''; -} - -/******************************************************************************* -* * -* Protected methods * -* * -*******************************************************************************/ -function _dochecks() -{ - // Check availability of %F - if(sprintf('%.1F',1.0)!='1.0') - $this->Error('This version of PHP is not supported'); - // Check mbstring overloading - if(ini_get('mbstring.func_overload') & 2) - $this->Error('mbstring overloading must be disabled'); - // Ensure runtime magic quotes are disabled - if(get_magic_quotes_runtime()) - @set_magic_quotes_runtime(0); -} - -function _checkoutput() -{ - if(PHP_SAPI!='cli') - { - if(headers_sent($file,$line)) - $this->Error("Some data has already been output, can't send PDF file (output started at $file:$line)"); - } - if(ob_get_length()) - { - // The output buffer is not empty - if(preg_match('/^(\xEF\xBB\xBF)?\s*$/',ob_get_contents())) - { - // It contains only a UTF-8 BOM and/or whitespace, let's clean it - ob_clean(); - } - else - $this->Error("Some data has already been output, can't send PDF file"); - } -} - -function _getpagesize($size) -{ - if(is_string($size)) - { - $size = strtolower($size); - if(!isset($this->StdPageSizes[$size])) - $this->Error('Unknown page size: '.$size); - $a = $this->StdPageSizes[$size]; - return array($a[0]/$this->k, $a[1]/$this->k); - } - else - { - if($size[0]>$size[1]) - return array($size[1], $size[0]); - else - return $size; - } -} - -function _beginpage($orientation, $size) -{ - $this->page++; - $this->pages[$this->page] = ''; - $this->state = 2; - $this->x = $this->lMargin; - $this->y = $this->tMargin; - $this->FontFamily = ''; - // Check page size and orientation - if($orientation=='') - $orientation = $this->DefOrientation; - else - $orientation = strtoupper($orientation[0]); - if($size=='') - $size = $this->DefPageSize; - else - $size = $this->_getpagesize($size); - if($orientation!=$this->CurOrientation || $size[0]!=$this->CurPageSize[0] || $size[1]!=$this->CurPageSize[1]) - { - // New size or orientation - if($orientation=='P') - { - $this->w = $size[0]; - $this->h = $size[1]; - } - else - { - $this->w = $size[1]; - $this->h = $size[0]; - } - $this->wPt = $this->w*$this->k; - $this->hPt = $this->h*$this->k; - $this->PageBreakTrigger = $this->h-$this->bMargin; - $this->CurOrientation = $orientation; - $this->CurPageSize = $size; - } - if($orientation!=$this->DefOrientation || $size[0]!=$this->DefPageSize[0] || $size[1]!=$this->DefPageSize[1]) - $this->PageSizes[$this->page] = array($this->wPt, $this->hPt); -} - -function _endpage() -{ - $this->state = 1; -} - -function _loadfont($font) -{ - // Load a font definition file from the font directory - include($this->fontpath.$font); - $a = get_defined_vars(); - if(!isset($a['name'])) - $this->Error('Could not include font definition file'); - return $a; -} - -function _escape($s) -{ - // Escape special characters in strings - $s = str_replace('\\','\\\\',$s); - $s = str_replace('(','\\(',$s); - $s = str_replace(')','\\)',$s); - $s = str_replace("\r",'\\r',$s); - return $s; -} - -function _textstring($s) -{ - // Format a text string - return '('.$this->_escape($s).')'; -} - -function _UTF8toUTF16($s) -{ - // Convert UTF-8 to UTF-16BE with BOM - $res = "\xFE\xFF"; - $nb = strlen($s); - $i = 0; - while($i<$nb) - { - $c1 = ord($s[$i++]); - if($c1>=224) - { - // 3-byte character - $c2 = ord($s[$i++]); - $c3 = ord($s[$i++]); - $res .= chr((($c1 & 0x0F)<<4) + (($c2 & 0x3C)>>2)); - $res .= chr((($c2 & 0x03)<<6) + ($c3 & 0x3F)); - } - elseif($c1>=192) - { - // 2-byte character - $c2 = ord($s[$i++]); - $res .= chr(($c1 & 0x1C)>>2); - $res .= chr((($c1 & 0x03)<<6) + ($c2 & 0x3F)); - } - else - { - // Single-byte character - $res .= "\0".chr($c1); - } - } - return $res; -} - -function _dounderline($x, $y, $txt) -{ - // Underline text - $up = $this->CurrentFont['up']; - $ut = $this->CurrentFont['ut']; - $w = $this->GetStringWidth($txt)+$this->ws*substr_count($txt,' '); - return sprintf('%.2F %.2F %.2F %.2F re f',$x*$this->k,($this->h-($y-$up/1000*$this->FontSize))*$this->k,$w*$this->k,-$ut/1000*$this->FontSizePt); -} - -function _parsejpg($file) -{ - // Extract info from a JPEG file - $a = getimagesize($file); - if(!$a) - $this->Error('Missing or incorrect image file: '.$file); - if($a[2]!=2) - $this->Error('Not a JPEG file: '.$file); - if(!isset($a['channels']) || $a['channels']==3) - $colspace = 'DeviceRGB'; - elseif($a['channels']==4) - $colspace = 'DeviceCMYK'; - else - $colspace = 'DeviceGray'; - $bpc = isset($a['bits']) ? $a['bits'] : 8; - $data = file_get_contents($file); - return array('w'=>$a[0], 'h'=>$a[1], 'cs'=>$colspace, 'bpc'=>$bpc, 'f'=>'DCTDecode', 'data'=>$data); -} - -function _parsepng($file) -{ - // Extract info from a PNG file - $f = fopen($file,'rb'); - if(!$f) - $this->Error('Can\'t open image file: '.$file); - $info = $this->_parsepngstream($f,$file); - fclose($f); - return $info; -} - -function _parsepngstream($f, $file) -{ - // Check signature - if($this->_readstream($f,8)!=chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) - $this->Error('Not a PNG file: '.$file); - - // Read header chunk - $this->_readstream($f,4); - if($this->_readstream($f,4)!='IHDR') - $this->Error('Incorrect PNG file: '.$file); - $w = $this->_readint($f); - $h = $this->_readint($f); - $bpc = ord($this->_readstream($f,1)); - if($bpc>8) - $this->Error('16-bit depth not supported: '.$file); - $ct = ord($this->_readstream($f,1)); - if($ct==0 || $ct==4) - $colspace = 'DeviceGray'; - elseif($ct==2 || $ct==6) - $colspace = 'DeviceRGB'; - elseif($ct==3) - $colspace = 'Indexed'; - else - $this->Error('Unknown color type: '.$file); - if(ord($this->_readstream($f,1))!=0) - $this->Error('Unknown compression method: '.$file); - if(ord($this->_readstream($f,1))!=0) - $this->Error('Unknown filter method: '.$file); - if(ord($this->_readstream($f,1))!=0) - $this->Error('Interlacing not supported: '.$file); - $this->_readstream($f,4); - $dp = '/Predictor 15 /Colors '.($colspace=='DeviceRGB' ? 3 : 1).' /BitsPerComponent '.$bpc.' /Columns '.$w; - - // Scan chunks looking for palette, transparency and image data - $pal = ''; - $trns = ''; - $data = ''; - do - { - $n = $this->_readint($f); - $type = $this->_readstream($f,4); - if($type=='PLTE') - { - // Read palette - $pal = $this->_readstream($f,$n); - $this->_readstream($f,4); - } - elseif($type=='tRNS') - { - // Read transparency info - $t = $this->_readstream($f,$n); - if($ct==0) - $trns = array(ord(substr($t,1,1))); - elseif($ct==2) - $trns = array(ord(substr($t,1,1)), ord(substr($t,3,1)), ord(substr($t,5,1))); - else - { - $pos = strpos($t,chr(0)); - if($pos!==false) - $trns = array($pos); - } - $this->_readstream($f,4); - } - elseif($type=='IDAT') - { - // Read image data block - $data .= $this->_readstream($f,$n); - $this->_readstream($f,4); - } - elseif($type=='IEND') - break; - else - $this->_readstream($f,$n+4); - } - while($n); - - if($colspace=='Indexed' && empty($pal)) - $this->Error('Missing palette in '.$file); - $info = array('w'=>$w, 'h'=>$h, 'cs'=>$colspace, 'bpc'=>$bpc, 'f'=>'FlateDecode', 'dp'=>$dp, 'pal'=>$pal, 'trns'=>$trns); - if($ct>=4) - { - // Extract alpha channel - if(!function_exists('gzuncompress')) - $this->Error('Zlib not available, can\'t handle alpha channel: '.$file); - $data = gzuncompress($data); - $color = ''; - $alpha = ''; - if($ct==4) - { - // Gray image - $len = 2*$w; - for($i=0;$i<$h;$i++) - { - $pos = (1+$len)*$i; - $color .= $data[$pos]; - $alpha .= $data[$pos]; - $line = substr($data,$pos+1,$len); - $color .= preg_replace('/(.)./s','$1',$line); - $alpha .= preg_replace('/.(.)/s','$1',$line); - } - } - else - { - // RGB image - $len = 4*$w; - for($i=0;$i<$h;$i++) - { - $pos = (1+$len)*$i; - $color .= $data[$pos]; - $alpha .= $data[$pos]; - $line = substr($data,$pos+1,$len); - $color .= preg_replace('/(.{3})./s','$1',$line); - $alpha .= preg_replace('/.{3}(.)/s','$1',$line); - } - } - unset($data); - $data = gzcompress($color); - $info['smask'] = gzcompress($alpha); - if($this->PDFVersion<'1.4') - $this->PDFVersion = '1.4'; - } - $info['data'] = $data; - return $info; -} - -function _readstream($f, $n) -{ - // Read n bytes from stream - $res = ''; - while($n>0 && !feof($f)) - { - $s = fread($f,$n); - if($s===false) - $this->Error('Error while reading stream'); - $n -= strlen($s); - $res .= $s; - } - if($n>0) - $this->Error('Unexpected end of stream'); - return $res; -} - -function _readint($f) -{ - // Read a 4-byte integer from stream - $a = unpack('Ni',$this->_readstream($f,4)); - return $a['i']; -} - -function _parsegif($file) -{ - // Extract info from a GIF file (via PNG conversion) - if(!function_exists('imagepng')) - $this->Error('GD extension is required for GIF support'); - if(!function_exists('imagecreatefromgif')) - $this->Error('GD has no GIF read support'); - $im = imagecreatefromgif($file); - if(!$im) - $this->Error('Missing or incorrect image file: '.$file); - imageinterlace($im,0); - $f = @fopen('php://temp','rb+'); - if($f) - { - // Perform conversion in memory - ob_start(); - imagepng($im); - $data = ob_get_clean(); - imagedestroy($im); - fwrite($f,$data); - rewind($f); - $info = $this->_parsepngstream($f,$file); - fclose($f); - } - else - { - // Use temporary file - $tmp = tempnam('.','gif'); - if(!$tmp) - $this->Error('Unable to create a temporary file'); - if(!imagepng($im,$tmp)) - $this->Error('Error while saving to temporary file'); - imagedestroy($im); - $info = $this->_parsepng($tmp); - unlink($tmp); - } - return $info; -} - -function _newobj() -{ - // Begin a new object - $this->n++; - $this->offsets[$this->n] = strlen($this->buffer); - $this->_out($this->n.' 0 obj'); -} - -function _putstream($s) -{ - $this->_out('stream'); - $this->_out($s); - $this->_out('endstream'); -} - -function _out($s) -{ - // Add a line to the document - if($this->state==2) - $this->pages[$this->page] .= $s."\n"; - else - $this->buffer .= $s."\n"; -} - -function _putpages() -{ - $nb = $this->page; - if(!empty($this->AliasNbPages)) - { - // Replace number of pages - for($n=1;$n<=$nb;$n++) - $this->pages[$n] = str_replace($this->AliasNbPages,$nb,$this->pages[$n]); - } - if($this->DefOrientation=='P') - { - $wPt = $this->DefPageSize[0]*$this->k; - $hPt = $this->DefPageSize[1]*$this->k; - } - else - { - $wPt = $this->DefPageSize[1]*$this->k; - $hPt = $this->DefPageSize[0]*$this->k; - } - $filter = ($this->compress) ? '/Filter /FlateDecode ' : ''; - for($n=1;$n<=$nb;$n++) - { - // Page - $this->_newobj(); - $this->_out('<_out('/Parent 1 0 R'); - if(isset($this->PageSizes[$n])) - $this->_out(sprintf('/MediaBox [0 0 %.2F %.2F]',$this->PageSizes[$n][0],$this->PageSizes[$n][1])); - $this->_out('/Resources 2 0 R'); - if(isset($this->PageLinks[$n])) - { - // Links - $annots = '/Annots ['; - foreach($this->PageLinks[$n] as $pl) - { - $rect = sprintf('%.2F %.2F %.2F %.2F',$pl[0],$pl[1],$pl[0]+$pl[2],$pl[1]-$pl[3]); - $annots .= '<_textstring($pl[4]).'>>>>'; - else - { - $l = $this->links[$pl[4]]; - $h = isset($this->PageSizes[$l[0]]) ? $this->PageSizes[$l[0]][1] : $hPt; - $annots .= sprintf('/Dest [%d 0 R /XYZ 0 %.2F null]>>',1+2*$l[0],$h-$l[1]*$this->k); - } - } - $this->_out($annots.']'); - } - if($this->PDFVersion>'1.3') - $this->_out('/Group <>'); - $this->_out('/Contents '.($this->n+1).' 0 R>>'); - $this->_out('endobj'); - // Page content - $p = ($this->compress) ? gzcompress($this->pages[$n]) : $this->pages[$n]; - $this->_newobj(); - $this->_out('<<'.$filter.'/Length '.strlen($p).'>>'); - $this->_putstream($p); - $this->_out('endobj'); - } - // Pages root - $this->offsets[1] = strlen($this->buffer); - $this->_out('1 0 obj'); - $this->_out('<_out($kids.']'); - $this->_out('/Count '.$nb); - $this->_out(sprintf('/MediaBox [0 0 %.2F %.2F]',$wPt,$hPt)); - $this->_out('>>'); - $this->_out('endobj'); -} - -function _putfonts() -{ - $nf = $this->n; - foreach($this->diffs as $diff) - { - // Encodings - $this->_newobj(); - $this->_out('<>'); - $this->_out('endobj'); - } - foreach($this->FontFiles as $file=>$info) - { - // Font file embedding - $this->_newobj(); - $this->FontFiles[$file]['n'] = $this->n; - $font = file_get_contents($this->fontpath.$file,true); - if(!$font) - $this->Error('Font file not found: '.$file); - $compressed = (substr($file,-2)=='.z'); - if(!$compressed && isset($info['length2'])) - $font = substr($font,6,$info['length1']).substr($font,6+$info['length1']+6,$info['length2']); - $this->_out('<_out('/Filter /FlateDecode'); - $this->_out('/Length1 '.$info['length1']); - if(isset($info['length2'])) - $this->_out('/Length2 '.$info['length2'].' /Length3 0'); - $this->_out('>>'); - $this->_putstream($font); - $this->_out('endobj'); - } - foreach($this->fonts as $k=>$font) - { - // Font objects - $this->fonts[$k]['n'] = $this->n+1; - $type = $font['type']; - $name = $font['name']; - if($type=='Core') - { - // Core font - $this->_newobj(); - $this->_out('<_out('/BaseFont /'.$name); - $this->_out('/Subtype /Type1'); - if($name!='Symbol' && $name!='ZapfDingbats') - $this->_out('/Encoding /WinAnsiEncoding'); - $this->_out('>>'); - $this->_out('endobj'); - } - elseif($type=='Type1' || $type=='TrueType') - { - // Additional Type1 or TrueType/OpenType font - $this->_newobj(); - $this->_out('<_out('/BaseFont /'.$name); - $this->_out('/Subtype /'.$type); - $this->_out('/FirstChar 32 /LastChar 255'); - $this->_out('/Widths '.($this->n+1).' 0 R'); - $this->_out('/FontDescriptor '.($this->n+2).' 0 R'); - if(isset($font['diffn'])) - $this->_out('/Encoding '.($nf+$font['diffn']).' 0 R'); - else - $this->_out('/Encoding /WinAnsiEncoding'); - $this->_out('>>'); - $this->_out('endobj'); - // Widths - $this->_newobj(); - $cw = &$font['cw']; - $s = '['; - for($i=32;$i<=255;$i++) - $s .= $cw[chr($i)].' '; - $this->_out($s.']'); - $this->_out('endobj'); - // Descriptor - $this->_newobj(); - $s = '<$v) - $s .= ' /'.$k.' '.$v; - if(!empty($font['file'])) - $s .= ' /FontFile'.($type=='Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R'; - $this->_out($s.'>>'); - $this->_out('endobj'); - } - else - { - // Allow for additional types - $mtd = '_put'.strtolower($type); - if(!method_exists($this,$mtd)) - $this->Error('Unsupported font type: '.$type); - $this->$mtd($font); - } - } -} - -function _putimages() -{ - foreach(array_keys($this->images) as $file) - { - $this->_putimage($this->images[$file]); - unset($this->images[$file]['data']); - unset($this->images[$file]['smask']); - } -} - -function _putimage(&$info) -{ - $this->_newobj(); - $info['n'] = $this->n; - $this->_out('<_out('/Subtype /Image'); - $this->_out('/Width '.$info['w']); - $this->_out('/Height '.$info['h']); - if($info['cs']=='Indexed') - $this->_out('/ColorSpace [/Indexed /DeviceRGB '.(strlen($info['pal'])/3-1).' '.($this->n+1).' 0 R]'); - else - { - $this->_out('/ColorSpace /'.$info['cs']); - if($info['cs']=='DeviceCMYK') - $this->_out('/Decode [1 0 1 0 1 0 1 0]'); - } - $this->_out('/BitsPerComponent '.$info['bpc']); - if(isset($info['f'])) - $this->_out('/Filter /'.$info['f']); - if(isset($info['dp'])) - $this->_out('/DecodeParms <<'.$info['dp'].'>>'); - if(isset($info['trns']) && is_array($info['trns'])) - { - $trns = ''; - for($i=0;$i_out('/Mask ['.$trns.']'); - } - if(isset($info['smask'])) - $this->_out('/SMask '.($this->n+1).' 0 R'); - $this->_out('/Length '.strlen($info['data']).'>>'); - $this->_putstream($info['data']); - $this->_out('endobj'); - // Soft mask - if(isset($info['smask'])) - { - $dp = '/Predictor 15 /Colors 1 /BitsPerComponent 8 /Columns '.$info['w']; - $smask = array('w'=>$info['w'], 'h'=>$info['h'], 'cs'=>'DeviceGray', 'bpc'=>8, 'f'=>$info['f'], 'dp'=>$dp, 'data'=>$info['smask']); - $this->_putimage($smask); - } - // Palette - if($info['cs']=='Indexed') - { - $filter = ($this->compress) ? '/Filter /FlateDecode ' : ''; - $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal']; - $this->_newobj(); - $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>'); - $this->_putstream($pal); - $this->_out('endobj'); - } -} - -function _putxobjectdict() -{ - foreach($this->images as $image) - $this->_out('/I'.$image['i'].' '.$image['n'].' 0 R'); -} - -function _putresourcedict() -{ - $this->_out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]'); - $this->_out('/Font <<'); - foreach($this->fonts as $font) - $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R'); - $this->_out('>>'); - $this->_out('/XObject <<'); - $this->_putxobjectdict(); - $this->_out('>>'); -} - -function _putresources() -{ - $this->_putfonts(); - $this->_putimages(); - // Resource dictionary - $this->offsets[2] = strlen($this->buffer); - $this->_out('2 0 obj'); - $this->_out('<<'); - $this->_putresourcedict(); - $this->_out('>>'); - $this->_out('endobj'); -} - -function _putinfo() -{ - $this->_out('/Producer '.$this->_textstring('FPDF '.FPDF_VERSION)); - if(!empty($this->title)) - $this->_out('/Title '.$this->_textstring($this->title)); - if(!empty($this->subject)) - $this->_out('/Subject '.$this->_textstring($this->subject)); - if(!empty($this->author)) - $this->_out('/Author '.$this->_textstring($this->author)); - if(!empty($this->keywords)) - $this->_out('/Keywords '.$this->_textstring($this->keywords)); - if(!empty($this->creator)) - $this->_out('/Creator '.$this->_textstring($this->creator)); - $this->_out('/CreationDate '.$this->_textstring('D:'.@date('YmdHis'))); -} - -function _putcatalog() -{ - $this->_out('/Type /Catalog'); - $this->_out('/Pages 1 0 R'); - if($this->ZoomMode=='fullpage') - $this->_out('/OpenAction [3 0 R /Fit]'); - elseif($this->ZoomMode=='fullwidth') - $this->_out('/OpenAction [3 0 R /FitH null]'); - elseif($this->ZoomMode=='real') - $this->_out('/OpenAction [3 0 R /XYZ null null 1]'); - elseif(!is_string($this->ZoomMode)) - $this->_out('/OpenAction [3 0 R /XYZ null null '.sprintf('%.2F',$this->ZoomMode/100).']'); - if($this->LayoutMode=='single') - $this->_out('/PageLayout /SinglePage'); - elseif($this->LayoutMode=='continuous') - $this->_out('/PageLayout /OneColumn'); - elseif($this->LayoutMode=='two') - $this->_out('/PageLayout /TwoColumnLeft'); -} - -function _putheader() -{ - $this->_out('%PDF-'.$this->PDFVersion); -} - -function _puttrailer() -{ - $this->_out('/Size '.($this->n+1)); - $this->_out('/Root '.$this->n.' 0 R'); - $this->_out('/Info '.($this->n-1).' 0 R'); -} - -function _enddoc() -{ - $this->_putheader(); - $this->_putpages(); - $this->_putresources(); - // Info - $this->_newobj(); - $this->_out('<<'); - $this->_putinfo(); - $this->_out('>>'); - $this->_out('endobj'); - // Catalog - $this->_newobj(); - $this->_out('<<'); - $this->_putcatalog(); - $this->_out('>>'); - $this->_out('endobj'); - // Cross-ref - $o = strlen($this->buffer); - $this->_out('xref'); - $this->_out('0 '.($this->n+1)); - $this->_out('0000000000 65535 f '); - for($i=1;$i<=$this->n;$i++) - $this->_out(sprintf('%010d 00000 n ',$this->offsets[$i])); - // Trailer - $this->_out('trailer'); - $this->_out('<<'); - $this->_puttrailer(); - $this->_out('>>'); - $this->_out('startxref'); - $this->_out($o); - $this->_out('%%EOF'); - $this->state = 3; -} -// End of class + public function FPDF($orientation = 'P', $unit = 'mm', $size = 'A4') + { + // Some checks + $this->_dochecks(); + // Initialization of properties + $this->page = 0; + $this->n = 2; + $this->buffer = ''; + $this->pages = []; + $this->PageSizes = []; + $this->state = 0; + $this->fonts = []; + $this->FontFiles = []; + $this->diffs = []; + $this->images = []; + $this->links = []; + $this->InHeader = false; + $this->InFooter = false; + $this->lasth = 0; + $this->FontFamily = ''; + $this->FontStyle = ''; + $this->FontSizePt = 12; + $this->underline = false; + $this->DrawColor = '0 G'; + $this->FillColor = '0 g'; + $this->TextColor = '0 g'; + $this->ColorFlag = false; + $this->ws = 0; + // Font path + if (defined('FPDF_FONTPATH')) { + $this->fontpath = FPDF_FONTPATH; + if (substr($this->fontpath, -1) != '/' && substr($this->fontpath, -1) != '\\') { + $this->fontpath .= '/'; + } + } elseif (is_dir(dirname(__FILE__).'/font')) { + $this->fontpath = dirname(__FILE__).'/font/'; + } else { + $this->fontpath = ''; + } + // Core fonts + $this->CoreFonts = ['courier', 'helvetica', 'times', 'symbol', 'zapfdingbats']; + // Scale factor + if ($unit == 'pt') { + $this->k = 1; + } elseif ($unit == 'mm') { + $this->k = 72 / 25.4; + } elseif ($unit == 'cm') { + $this->k = 72 / 2.54; + } elseif ($unit == 'in') { + $this->k = 72; + } else { + $this->Error('Incorrect unit: '.$unit); + } + // Page sizes + $this->StdPageSizes = ['a3'=> [841.89, 1190.55], 'a4'=>[595.28, 841.89], 'a5'=>[420.94, 595.28], + 'letter' => [612, 792], 'legal'=>[612, 1008]]; + $size = $this->_getpagesize($size); + $this->DefPageSize = $size; + $this->CurPageSize = $size; + // Page orientation + $orientation = strtolower($orientation); + if ($orientation == 'p' || $orientation == 'portrait') { + $this->DefOrientation = 'P'; + $this->w = $size[0]; + $this->h = $size[1]; + } elseif ($orientation == 'l' || $orientation == 'landscape') { + $this->DefOrientation = 'L'; + $this->w = $size[1]; + $this->h = $size[0]; + } else { + $this->Error('Incorrect orientation: '.$orientation); + } + $this->CurOrientation = $this->DefOrientation; + $this->wPt = $this->w * $this->k; + $this->hPt = $this->h * $this->k; + // Page margins (1 cm) + $margin = 28.35 / $this->k; + $this->SetMargins($margin, $margin); + // Interior cell margin (1 mm) + $this->cMargin = $margin / 10; + // Line width (0.2 mm) + $this->LineWidth = .567 / $this->k; + // Automatic page break + $this->SetAutoPageBreak(true, 2 * $margin); + // Default display mode + $this->SetDisplayMode('default'); + // Enable compression + $this->SetCompression(true); + // Set default PDF version number + $this->PDFVersion = '1.3'; + } + + public function SetMargins($left, $top, $right = null) + { + // Set left, top and right margins + $this->lMargin = $left; + $this->tMargin = $top; + if ($right === null) { + $right = $left; + } + $this->rMargin = $right; + } + + public function SetLeftMargin($margin) + { + // Set left margin + $this->lMargin = $margin; + if ($this->page > 0 && $this->x < $margin) { + $this->x = $margin; + } + } + + public function SetTopMargin($margin) + { + // Set top margin + $this->tMargin = $margin; + } + + public function SetRightMargin($margin) + { + // Set right margin + $this->rMargin = $margin; + } + + public function SetAutoPageBreak($auto, $margin = 0) + { + // Set auto page break mode and triggering margin + $this->AutoPageBreak = $auto; + $this->bMargin = $margin; + $this->PageBreakTrigger = $this->h - $margin; + } + + public function SetDisplayMode($zoom, $layout = 'default') + { + // Set display mode in viewer + if ($zoom == 'fullpage' || $zoom == 'fullwidth' || $zoom == 'real' || $zoom == 'default' || !is_string($zoom)) { + $this->ZoomMode = $zoom; + } else { + $this->Error('Incorrect zoom display mode: '.$zoom); + } + if ($layout == 'single' || $layout == 'continuous' || $layout == 'two' || $layout == 'default') { + $this->LayoutMode = $layout; + } else { + $this->Error('Incorrect layout display mode: '.$layout); + } + } + + public function SetCompression($compress) + { + // Set page compression + if (function_exists('gzcompress')) { + $this->compress = $compress; + } else { + $this->compress = false; + } + } + + public function SetTitle($title, $isUTF8 = false) + { + // Title of document + if ($isUTF8) { + $title = $this->_UTF8toUTF16($title); + } + $this->title = $title; + } + + public function SetSubject($subject, $isUTF8 = false) + { + // Subject of document + if ($isUTF8) { + $subject = $this->_UTF8toUTF16($subject); + } + $this->subject = $subject; + } + + public function SetAuthor($author, $isUTF8 = false) + { + // Author of document + if ($isUTF8) { + $author = $this->_UTF8toUTF16($author); + } + $this->author = $author; + } + + public function SetKeywords($keywords, $isUTF8 = false) + { + // Keywords of document + if ($isUTF8) { + $keywords = $this->_UTF8toUTF16($keywords); + } + $this->keywords = $keywords; + } + + public function SetCreator($creator, $isUTF8 = false) + { + // Creator of document + if ($isUTF8) { + $creator = $this->_UTF8toUTF16($creator); + } + $this->creator = $creator; + } + + public function AliasNbPages($alias = '{nb}') + { + // Define an alias for total number of pages + $this->AliasNbPages = $alias; + } + + public function Error($msg) + { + // Fatal error + die('FPDF error: '.$msg); + } + + public function Open() + { + // Begin document + $this->state = 1; + } + + public function Close() + { + // Terminate document + if ($this->state == 3) { + return; + } + if ($this->page == 0) { + $this->AddPage(); + } + // Page footer + $this->InFooter = true; + $this->Footer(); + $this->InFooter = false; + // Close page + $this->_endpage(); + // Close document + $this->_enddoc(); + } + + public function AddPage($orientation = '', $size = '') + { + // Start a new page + if ($this->state == 0) { + $this->Open(); + } + $family = $this->FontFamily; + $style = $this->FontStyle.($this->underline ? 'U' : ''); + $fontsize = $this->FontSizePt; + $lw = $this->LineWidth; + $dc = $this->DrawColor; + $fc = $this->FillColor; + $tc = $this->TextColor; + $cf = $this->ColorFlag; + if ($this->page > 0) { + // Page footer + $this->InFooter = true; + $this->Footer(); + $this->InFooter = false; + // Close page + $this->_endpage(); + } + // Start new page + $this->_beginpage($orientation, $size); + // Set line cap style to square + $this->_out('2 J'); + // Set line width + $this->LineWidth = $lw; + $this->_out(sprintf('%.2F w', $lw * $this->k)); + // Set font + if ($family) { + $this->SetFont($family, $style, $fontsize); + } + // Set colors + $this->DrawColor = $dc; + if ($dc != '0 G') { + $this->_out($dc); + } + $this->FillColor = $fc; + if ($fc != '0 g') { + $this->_out($fc); + } + $this->TextColor = $tc; + $this->ColorFlag = $cf; + // Page header + $this->InHeader = true; + $this->Header(); + $this->InHeader = false; + // Restore line width + if ($this->LineWidth != $lw) { + $this->LineWidth = $lw; + $this->_out(sprintf('%.2F w', $lw * $this->k)); + } + // Restore font + if ($family) { + $this->SetFont($family, $style, $fontsize); + } + // Restore colors + if ($this->DrawColor != $dc) { + $this->DrawColor = $dc; + $this->_out($dc); + } + if ($this->FillColor != $fc) { + $this->FillColor = $fc; + $this->_out($fc); + } + $this->TextColor = $tc; + $this->ColorFlag = $cf; + } + + public function Header() + { + // To be implemented in your own inherited class + } + + public function Footer() + { + // To be implemented in your own inherited class + } + + public function PageNo() + { + // Get current page number + return $this->page; + } + + public function SetDrawColor($r, $g = null, $b = null) + { + // Set color for all stroking operations + if (($r == 0 && $g == 0 && $b == 0) || $g === null) { + $this->DrawColor = sprintf('%.3F G', $r / 255); + } else { + $this->DrawColor = sprintf('%.3F %.3F %.3F RG', $r / 255, $g / 255, $b / 255); + } + if ($this->page > 0) { + $this->_out($this->DrawColor); + } + } + + public function SetFillColor($r, $g = null, $b = null) + { + // Set color for all filling operations + if (($r == 0 && $g == 0 && $b == 0) || $g === null) { + $this->FillColor = sprintf('%.3F g', $r / 255); + } else { + $this->FillColor = sprintf('%.3F %.3F %.3F rg', $r / 255, $g / 255, $b / 255); + } + $this->ColorFlag = ($this->FillColor != $this->TextColor); + if ($this->page > 0) { + $this->_out($this->FillColor); + } + } + + public function SetTextColor($r, $g = null, $b = null) + { + // Set color for text + if (($r == 0 && $g == 0 && $b == 0) || $g === null) { + $this->TextColor = sprintf('%.3F g', $r / 255); + } else { + $this->TextColor = sprintf('%.3F %.3F %.3F rg', $r / 255, $g / 255, $b / 255); + } + $this->ColorFlag = ($this->FillColor != $this->TextColor); + } + + public function GetStringWidth($s) + { + // Get width of a string in the current font + $s = (string) $s; + $cw = &$this->CurrentFont['cw']; + $w = 0; + $l = strlen($s); + for ($i = 0; $i < $l; $i++) { + $w += $cw[$s[$i]]; + } + + return $w * $this->FontSize / 1000; + } + + public function SetLineWidth($width) + { + // Set line width + $this->LineWidth = $width; + if ($this->page > 0) { + $this->_out(sprintf('%.2F w', $width * $this->k)); + } + } + + public function Line($x1, $y1, $x2, $y2) + { + // Draw a line + $this->_out(sprintf('%.2F %.2F m %.2F %.2F l S', $x1 * $this->k, ($this->h - $y1) * $this->k, $x2 * $this->k, ($this->h - $y2) * $this->k)); + } + + public function Rect($x, $y, $w, $h, $style = '') + { + // Draw a rectangle + if ($style == 'F') { + $op = 'f'; + } elseif ($style == 'FD' || $style == 'DF') { + $op = 'B'; + } else { + $op = 'S'; + } + $this->_out(sprintf('%.2F %.2F %.2F %.2F re %s', $x * $this->k, ($this->h - $y) * $this->k, $w * $this->k, -$h * $this->k, $op)); + } + + public function AddFont($family, $style = '', $file = '') + { + // Add a TrueType, OpenType or Type1 font + $family = strtolower($family); + if ($file == '') { + $file = str_replace(' ', '', $family).strtolower($style).'.php'; + } + $style = strtoupper($style); + if ($style == 'IB') { + $style = 'BI'; + } + $fontkey = $family.$style; + if (isset($this->fonts[$fontkey])) { + return; + } + $info = $this->_loadfont($file); + $info['i'] = count($this->fonts) + 1; + if (!empty($info['diff'])) { + // Search existing encodings + $n = array_search($info['diff'], $this->diffs); + if (!$n) { + $n = count($this->diffs) + 1; + $this->diffs[$n] = $info['diff']; + } + $info['diffn'] = $n; + } + if (!empty($info['file'])) { + // Embedded font + if ($info['type'] == 'TrueType') { + $this->FontFiles[$info['file']] = ['length1'=>$info['originalsize']]; + } else { + $this->FontFiles[$info['file']] = ['length1'=>$info['size1'], 'length2'=>$info['size2']]; + } + } + $this->fonts[$fontkey] = $info; + } + + public function SetFont($family, $style = '', $size = 0) + { + // Select a font; size given in points + if ($family == '') { + $family = $this->FontFamily; + } else { + $family = strtolower($family); + } + $style = strtoupper($style); + if (strpos($style, 'U') !== false) { + $this->underline = true; + $style = str_replace('U', '', $style); + } else { + $this->underline = false; + } + if ($style == 'IB') { + $style = 'BI'; + } + if ($size == 0) { + $size = $this->FontSizePt; + } + // Test if font is already selected + if ($this->FontFamily == $family && $this->FontStyle == $style && $this->FontSizePt == $size) { + return; + } + // Test if font is already loaded + $fontkey = $family.$style; + if (!isset($this->fonts[$fontkey])) { + // Test if one of the core fonts + if ($family == 'arial') { + $family = 'helvetica'; + } + if (in_array($family, $this->CoreFonts)) { + if ($family == 'symbol' || $family == 'zapfdingbats') { + $style = ''; + } + $fontkey = $family.$style; + if (!isset($this->fonts[$fontkey])) { + $this->AddFont($family, $style); + } + } else { + $this->Error('Undefined font: '.$family.' '.$style); + } + } + // Select it + $this->FontFamily = $family; + $this->FontStyle = $style; + $this->FontSizePt = $size; + $this->FontSize = $size / $this->k; + $this->CurrentFont = &$this->fonts[$fontkey]; + if ($this->page > 0) { + $this->_out(sprintf('BT /F%d %.2F Tf ET', $this->CurrentFont['i'], $this->FontSizePt)); + } + } + + public function SetFontSize($size) + { + // Set font size in points + if ($this->FontSizePt == $size) { + return; + } + $this->FontSizePt = $size; + $this->FontSize = $size / $this->k; + if ($this->page > 0) { + $this->_out(sprintf('BT /F%d %.2F Tf ET', $this->CurrentFont['i'], $this->FontSizePt)); + } + } + + public function AddLink() + { + // Create a new internal link + $n = count($this->links) + 1; + $this->links[$n] = [0, 0]; + + return $n; + } + + public function SetLink($link, $y = 0, $page = -1) + { + // Set destination of internal link + if ($y == -1) { + $y = $this->y; + } + if ($page == -1) { + $page = $this->page; + } + $this->links[$link] = [$page, $y]; + } + + public function Link($x, $y, $w, $h, $link) + { + // Put a link on the page + $this->PageLinks[$this->page][] = [$x * $this->k, $this->hPt - $y * $this->k, $w * $this->k, $h * $this->k, $link]; + } + + public function Text($x, $y, $txt) + { + // Output a string + $s = sprintf('BT %.2F %.2F Td (%s) Tj ET', $x * $this->k, ($this->h - $y) * $this->k, $this->_escape($txt)); + if ($this->underline && $txt != '') { + $s .= ' '.$this->_dounderline($x, $y, $txt); + } + if ($this->ColorFlag) { + $s = 'q '.$this->TextColor.' '.$s.' Q'; + } + $this->_out($s); + } + + public function AcceptPageBreak() + { + // Accept automatic page break or not + return $this->AutoPageBreak; + } + + public function Cell($w, $h = 0, $txt = '', $border = 0, $ln = 0, $align = '', $fill = false, $link = '') + { + // Output a cell + $k = $this->k; + if ($this->y + $h > $this->PageBreakTrigger && !$this->InHeader && !$this->InFooter && $this->AcceptPageBreak()) { + // Automatic page break + $x = $this->x; + $ws = $this->ws; + if ($ws > 0) { + $this->ws = 0; + $this->_out('0 Tw'); + } + $this->AddPage($this->CurOrientation, $this->CurPageSize); + $this->x = $x; + if ($ws > 0) { + $this->ws = $ws; + $this->_out(sprintf('%.3F Tw', $ws * $k)); + } + } + if ($w == 0) { + $w = $this->w - $this->rMargin - $this->x; + } + $s = ''; + if ($fill || $border == 1) { + if ($fill) { + $op = ($border == 1) ? 'B' : 'f'; + } else { + $op = 'S'; + } + $s = sprintf('%.2F %.2F %.2F %.2F re %s ', $this->x * $k, ($this->h - $this->y) * $k, $w * $k, -$h * $k, $op); + } + if (is_string($border)) { + $x = $this->x; + $y = $this->y; + if (strpos($border, 'L') !== false) { + $s .= sprintf('%.2F %.2F m %.2F %.2F l S ', $x * $k, ($this->h - $y) * $k, $x * $k, ($this->h - ($y + $h)) * $k); + } + if (strpos($border, 'T') !== false) { + $s .= sprintf('%.2F %.2F m %.2F %.2F l S ', $x * $k, ($this->h - $y) * $k, ($x + $w) * $k, ($this->h - $y) * $k); + } + if (strpos($border, 'R') !== false) { + $s .= sprintf('%.2F %.2F m %.2F %.2F l S ', ($x + $w) * $k, ($this->h - $y) * $k, ($x + $w) * $k, ($this->h - ($y + $h)) * $k); + } + if (strpos($border, 'B') !== false) { + $s .= sprintf('%.2F %.2F m %.2F %.2F l S ', $x * $k, ($this->h - ($y + $h)) * $k, ($x + $w) * $k, ($this->h - ($y + $h)) * $k); + } + } + if ($txt !== '') { + if ($align == 'R') { + $dx = $w - $this->cMargin - $this->GetStringWidth($txt); + } elseif ($align == 'C') { + $dx = ($w - $this->GetStringWidth($txt)) / 2; + } else { + $dx = $this->cMargin; + } + if ($this->ColorFlag) { + $s .= 'q '.$this->TextColor.' '; + } + $txt2 = str_replace(')', '\\)', str_replace('(', '\\(', str_replace('\\', '\\\\', $txt))); + $s .= sprintf('BT %.2F %.2F Td (%s) Tj ET', ($this->x + $dx) * $k, ($this->h - ($this->y + .5 * $h + .3 * $this->FontSize)) * $k, $txt2); + if ($this->underline) { + $s .= ' '.$this->_dounderline($this->x + $dx, $this->y + .5 * $h + .3 * $this->FontSize, $txt); + } + if ($this->ColorFlag) { + $s .= ' Q'; + } + if ($link) { + $this->Link($this->x + $dx, $this->y + .5 * $h - .5 * $this->FontSize, $this->GetStringWidth($txt), $this->FontSize, $link); + } + } + if ($s) { + $this->_out($s); + } + $this->lasth = $h; + if ($ln > 0) { + // Go to next line + $this->y += $h; + if ($ln == 1) { + $this->x = $this->lMargin; + } + } else { + $this->x += $w; + } + } + + public function MultiCell($w, $h, $txt, $border = 0, $align = 'J', $fill = false) + { + // Output text with automatic or explicit line breaks + $cw = &$this->CurrentFont['cw']; + if ($w == 0) { + $w = $this->w - $this->rMargin - $this->x; + } + $wmax = ($w - 2 * $this->cMargin) * 1000 / $this->FontSize; + $s = str_replace("\r", '', $txt); + $nb = strlen($s); + if ($nb > 0 && $s[$nb - 1] == "\n") { + $nb--; + } + $b = 0; + if ($border) { + if ($border == 1) { + $border = 'LTRB'; + $b = 'LRT'; + $b2 = 'LR'; + } else { + $b2 = ''; + if (strpos($border, 'L') !== false) { + $b2 .= 'L'; + } + if (strpos($border, 'R') !== false) { + $b2 .= 'R'; + } + $b = (strpos($border, 'T') !== false) ? $b2.'T' : $b2; + } + } + $sep = -1; + $i = 0; + $j = 0; + $l = 0; + $ns = 0; + $nl = 1; + while ($i < $nb) { + // Get next character + $c = $s[$i]; + if ($c == "\n") { + // Explicit line break + if ($this->ws > 0) { + $this->ws = 0; + $this->_out('0 Tw'); + } + $this->Cell($w, $h, substr($s, $j, $i - $j), $b, 2, $align, $fill); + $i++; + $sep = -1; + $j = $i; + $l = 0; + $ns = 0; + $nl++; + if ($border && $nl == 2) { + $b = $b2; + } + continue; + } + if ($c == ' ') { + $sep = $i; + $ls = $l; + $ns++; + } + $l += $cw[$c]; + if ($l > $wmax) { + // Automatic line break + if ($sep == -1) { + if ($i == $j) { + $i++; + } + if ($this->ws > 0) { + $this->ws = 0; + $this->_out('0 Tw'); + } + $this->Cell($w, $h, substr($s, $j, $i - $j), $b, 2, $align, $fill); + } else { + if ($align == 'J') { + $this->ws = ($ns > 1) ? ($wmax - $ls) / 1000 * $this->FontSize / ($ns - 1) : 0; + $this->_out(sprintf('%.3F Tw', $this->ws * $this->k)); + } + $this->Cell($w, $h, substr($s, $j, $sep - $j), $b, 2, $align, $fill); + $i = $sep + 1; + } + $sep = -1; + $j = $i; + $l = 0; + $ns = 0; + $nl++; + if ($border && $nl == 2) { + $b = $b2; + } + } else { + $i++; + } + } + // Last chunk + if ($this->ws > 0) { + $this->ws = 0; + $this->_out('0 Tw'); + } + if ($border && strpos($border, 'B') !== false) { + $b .= 'B'; + } + $this->Cell($w, $h, substr($s, $j, $i - $j), $b, 2, $align, $fill); + $this->x = $this->lMargin; + } + + public function Write($h, $txt, $link = '') + { + // Output text in flowing mode + $cw = &$this->CurrentFont['cw']; + $w = $this->w - $this->rMargin - $this->x; + $wmax = ($w - 2 * $this->cMargin) * 1000 / $this->FontSize; + $s = str_replace("\r", '', $txt); + $nb = strlen($s); + $sep = -1; + $i = 0; + $j = 0; + $l = 0; + $nl = 1; + while ($i < $nb) { + // Get next character + $c = $s[$i]; + if ($c == "\n") { + // Explicit line break + $this->Cell($w, $h, substr($s, $j, $i - $j), 0, 2, '', 0, $link); + $i++; + $sep = -1; + $j = $i; + $l = 0; + if ($nl == 1) { + $this->x = $this->lMargin; + $w = $this->w - $this->rMargin - $this->x; + $wmax = ($w - 2 * $this->cMargin) * 1000 / $this->FontSize; + } + $nl++; + continue; + } + if ($c == ' ') { + $sep = $i; + } + $l += $cw[$c]; + if ($l > $wmax) { + // Automatic line break + if ($sep == -1) { + if ($this->x > $this->lMargin) { + // Move to next line + $this->x = $this->lMargin; + $this->y += $h; + $w = $this->w - $this->rMargin - $this->x; + $wmax = ($w - 2 * $this->cMargin) * 1000 / $this->FontSize; + $i++; + $nl++; + continue; + } + if ($i == $j) { + $i++; + } + $this->Cell($w, $h, substr($s, $j, $i - $j), 0, 2, '', 0, $link); + } else { + $this->Cell($w, $h, substr($s, $j, $sep - $j), 0, 2, '', 0, $link); + $i = $sep + 1; + } + $sep = -1; + $j = $i; + $l = 0; + if ($nl == 1) { + $this->x = $this->lMargin; + $w = $this->w - $this->rMargin - $this->x; + $wmax = ($w - 2 * $this->cMargin) * 1000 / $this->FontSize; + } + $nl++; + } else { + $i++; + } + } + // Last chunk + if ($i != $j) { + $this->Cell($l / 1000 * $this->FontSize, $h, substr($s, $j), 0, 0, '', 0, $link); + } + } + + public function Ln($h = null) + { + // Line feed; default value is last cell height + $this->x = $this->lMargin; + if ($h === null) { + $this->y += $this->lasth; + } else { + $this->y += $h; + } + } + + public function Image($file, $x = null, $y = null, $w = 0, $h = 0, $type = '', $link = '') + { + // Put an image on the page + if (!isset($this->images[$file])) { + // First use of this image, get info + if ($type == '') { + $pos = strrpos($file, '.'); + if (!$pos) { + $this->Error('Image file has no extension and no type was specified: '.$file); + } + $type = substr($file, $pos + 1); + } + $type = strtolower($type); + if ($type == 'jpeg') { + $type = 'jpg'; + } + $mtd = '_parse'.$type; + if (!method_exists($this, $mtd)) { + $this->Error('Unsupported image type: '.$type); + } + $info = $this->$mtd($file); + $info['i'] = count($this->images) + 1; + $this->images[$file] = $info; + } else { + $info = $this->images[$file]; + } + + // Automatic width and height calculation if needed + if ($w == 0 && $h == 0) { + // Put image at 96 dpi + $w = -96; + $h = -96; + } + if ($w < 0) { + $w = -$info['w'] * 72 / $w / $this->k; + } + if ($h < 0) { + $h = -$info['h'] * 72 / $h / $this->k; + } + if ($w == 0) { + $w = $h * $info['w'] / $info['h']; + } + if ($h == 0) { + $h = $w * $info['h'] / $info['w']; + } + + // Flowing mode + if ($y === null) { + if ($this->y + $h > $this->PageBreakTrigger && !$this->InHeader && !$this->InFooter && $this->AcceptPageBreak()) { + // Automatic page break + $x2 = $this->x; + $this->AddPage($this->CurOrientation, $this->CurPageSize); + $this->x = $x2; + } + $y = $this->y; + $this->y += $h; + } + + if ($x === null) { + $x = $this->x; + } + $this->_out(sprintf('q %.2F 0 0 %.2F %.2F %.2F cm /I%d Do Q', $w * $this->k, $h * $this->k, $x * $this->k, ($this->h - ($y + $h)) * $this->k, $info['i'])); + if ($link) { + $this->Link($x, $y, $w, $h, $link); + } + } + + public function GetX() + { + // Get x position + return $this->x; + } + + public function SetX($x) + { + // Set x position + if ($x >= 0) { + $this->x = $x; + } else { + $this->x = $this->w + $x; + } + } + + public function GetY() + { + // Get y position + return $this->y; + } + + public function SetY($y) + { + // Set y position and reset x + $this->x = $this->lMargin; + if ($y >= 0) { + $this->y = $y; + } else { + $this->y = $this->h + $y; + } + } + + public function SetXY($x, $y) + { + // Set x and y positions + $this->SetY($y); + $this->SetX($x); + } + + public function Output($name = '', $dest = '') + { + // Output PDF to some destination + if ($this->state < 3) { + $this->Close(); + } + $dest = strtoupper($dest); + if ($dest == '') { + if ($name == '') { + $name = 'doc.pdf'; + $dest = 'I'; + } else { + $dest = 'F'; + } + } + switch ($dest) { + case 'I': + // Send to standard output + $this->_checkoutput(); + if (PHP_SAPI != 'cli') { + // We send to a browser + header('Content-Type: application/pdf'); + header('Content-Disposition: inline; filename="'.$name.'"'); + header('Cache-Control: private, max-age=0, must-revalidate'); + header('Pragma: public'); + } + echo $this->buffer; + break; + case 'D': + // Download file + $this->_checkoutput(); + header('Content-Type: application/x-download'); + header('Content-Disposition: attachment; filename="'.$name.'"'); + header('Cache-Control: private, max-age=0, must-revalidate'); + header('Pragma: public'); + echo $this->buffer; + break; + case 'F': + // Save to local file + $f = fopen($name, 'wb'); + if (!$f) { + $this->Error('Unable to create output file: '.$name); + } + fwrite($f, $this->buffer, strlen($this->buffer)); + fclose($f); + break; + case 'S': + // Return as a string + return $this->buffer; + default: + $this->Error('Incorrect output destination: '.$dest); + } + + return ''; + } + + /******************************************************************************* + * * + * Protected methods * + * * + *******************************************************************************/ + public function _dochecks() + { + // Check availability of %F + if (sprintf('%.1F', 1.0) != '1.0') { + $this->Error('This version of PHP is not supported'); + } + // Check mbstring overloading + if (ini_get('mbstring.func_overload') & 2) { + $this->Error('mbstring overloading must be disabled'); + } + // Ensure runtime magic quotes are disabled + if (get_magic_quotes_runtime()) { + @set_magic_quotes_runtime(0); + } + } + + public function _checkoutput() + { + if (PHP_SAPI != 'cli') { + if (headers_sent($file, $line)) { + $this->Error("Some data has already been output, can't send PDF file (output started at $file:$line)"); + } + } + if (ob_get_length()) { + // The output buffer is not empty + if (preg_match('/^(\xEF\xBB\xBF)?\s*$/', ob_get_contents())) { + // It contains only a UTF-8 BOM and/or whitespace, let's clean it + ob_clean(); + } else { + $this->Error("Some data has already been output, can't send PDF file"); + } + } + } + + public function _getpagesize($size) + { + if (is_string($size)) { + $size = strtolower($size); + if (!isset($this->StdPageSizes[$size])) { + $this->Error('Unknown page size: '.$size); + } + $a = $this->StdPageSizes[$size]; + + return [$a[0] / $this->k, $a[1] / $this->k]; + } else { + if ($size[0] > $size[1]) { + return [$size[1], $size[0]]; + } else { + return $size; + } + } + } + + public function _beginpage($orientation, $size) + { + $this->page++; + $this->pages[$this->page] = ''; + $this->state = 2; + $this->x = $this->lMargin; + $this->y = $this->tMargin; + $this->FontFamily = ''; + // Check page size and orientation + if ($orientation == '') { + $orientation = $this->DefOrientation; + } else { + $orientation = strtoupper($orientation[0]); + } + if ($size == '') { + $size = $this->DefPageSize; + } else { + $size = $this->_getpagesize($size); + } + if ($orientation != $this->CurOrientation || $size[0] != $this->CurPageSize[0] || $size[1] != $this->CurPageSize[1]) { + // New size or orientation + if ($orientation == 'P') { + $this->w = $size[0]; + $this->h = $size[1]; + } else { + $this->w = $size[1]; + $this->h = $size[0]; + } + $this->wPt = $this->w * $this->k; + $this->hPt = $this->h * $this->k; + $this->PageBreakTrigger = $this->h - $this->bMargin; + $this->CurOrientation = $orientation; + $this->CurPageSize = $size; + } + if ($orientation != $this->DefOrientation || $size[0] != $this->DefPageSize[0] || $size[1] != $this->DefPageSize[1]) { + $this->PageSizes[$this->page] = [$this->wPt, $this->hPt]; + } + } + + public function _endpage() + { + $this->state = 1; + } + + public function _loadfont($font) + { + // Load a font definition file from the font directory + include $this->fontpath.$font; + $a = get_defined_vars(); + if (!isset($a['name'])) { + $this->Error('Could not include font definition file'); + } + + return $a; + } + + public function _escape($s) + { + // Escape special characters in strings + $s = str_replace('\\', '\\\\', $s); + $s = str_replace('(', '\\(', $s); + $s = str_replace(')', '\\)', $s); + $s = str_replace("\r", '\\r', $s); + + return $s; + } + + public function _textstring($s) + { + // Format a text string + return '('.$this->_escape($s).')'; + } + + public function _UTF8toUTF16($s) + { + // Convert UTF-8 to UTF-16BE with BOM + $res = "\xFE\xFF"; + $nb = strlen($s); + $i = 0; + while ($i < $nb) { + $c1 = ord($s[$i++]); + if ($c1 >= 224) { + // 3-byte character + $c2 = ord($s[$i++]); + $c3 = ord($s[$i++]); + $res .= chr((($c1 & 0x0F) << 4) + (($c2 & 0x3C) >> 2)); + $res .= chr((($c2 & 0x03) << 6) + ($c3 & 0x3F)); + } elseif ($c1 >= 192) { + // 2-byte character + $c2 = ord($s[$i++]); + $res .= chr(($c1 & 0x1C) >> 2); + $res .= chr((($c1 & 0x03) << 6) + ($c2 & 0x3F)); + } else { + // Single-byte character + $res .= "\0".chr($c1); + } + } + + return $res; + } + + public function _dounderline($x, $y, $txt) + { + // Underline text + $up = $this->CurrentFont['up']; + $ut = $this->CurrentFont['ut']; + $w = $this->GetStringWidth($txt) + $this->ws * substr_count($txt, ' '); + + return sprintf('%.2F %.2F %.2F %.2F re f', $x * $this->k, ($this->h - ($y - $up / 1000 * $this->FontSize)) * $this->k, $w * $this->k, -$ut / 1000 * $this->FontSizePt); + } + + public function _parsejpg($file) + { + // Extract info from a JPEG file + $a = getimagesize($file); + if (!$a) { + $this->Error('Missing or incorrect image file: '.$file); + } + if ($a[2] != 2) { + $this->Error('Not a JPEG file: '.$file); + } + if (!isset($a['channels']) || $a['channels'] == 3) { + $colspace = 'DeviceRGB'; + } elseif ($a['channels'] == 4) { + $colspace = 'DeviceCMYK'; + } else { + $colspace = 'DeviceGray'; + } + $bpc = isset($a['bits']) ? $a['bits'] : 8; + $data = file_get_contents($file); + + return ['w'=>$a[0], 'h'=>$a[1], 'cs'=>$colspace, 'bpc'=>$bpc, 'f'=>'DCTDecode', 'data'=>$data]; + } + + public function _parsepng($file) + { + // Extract info from a PNG file + $f = fopen($file, 'rb'); + if (!$f) { + $this->Error('Can\'t open image file: '.$file); + } + $info = $this->_parsepngstream($f, $file); + fclose($f); + + return $info; + } + + public function _parsepngstream($f, $file) + { + // Check signature + if ($this->_readstream($f, 8) != chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) { + $this->Error('Not a PNG file: '.$file); + } + + // Read header chunk + $this->_readstream($f, 4); + if ($this->_readstream($f, 4) != 'IHDR') { + $this->Error('Incorrect PNG file: '.$file); + } + $w = $this->_readint($f); + $h = $this->_readint($f); + $bpc = ord($this->_readstream($f, 1)); + if ($bpc > 8) { + $this->Error('16-bit depth not supported: '.$file); + } + $ct = ord($this->_readstream($f, 1)); + if ($ct == 0 || $ct == 4) { + $colspace = 'DeviceGray'; + } elseif ($ct == 2 || $ct == 6) { + $colspace = 'DeviceRGB'; + } elseif ($ct == 3) { + $colspace = 'Indexed'; + } else { + $this->Error('Unknown color type: '.$file); + } + if (ord($this->_readstream($f, 1)) != 0) { + $this->Error('Unknown compression method: '.$file); + } + if (ord($this->_readstream($f, 1)) != 0) { + $this->Error('Unknown filter method: '.$file); + } + if (ord($this->_readstream($f, 1)) != 0) { + $this->Error('Interlacing not supported: '.$file); + } + $this->_readstream($f, 4); + $dp = '/Predictor 15 /Colors '.($colspace == 'DeviceRGB' ? 3 : 1).' /BitsPerComponent '.$bpc.' /Columns '.$w; + + // Scan chunks looking for palette, transparency and image data + $pal = ''; + $trns = ''; + $data = ''; + do { + $n = $this->_readint($f); + $type = $this->_readstream($f, 4); + if ($type == 'PLTE') { + // Read palette + $pal = $this->_readstream($f, $n); + $this->_readstream($f, 4); + } elseif ($type == 'tRNS') { + // Read transparency info + $t = $this->_readstream($f, $n); + if ($ct == 0) { + $trns = [ord(substr($t, 1, 1))]; + } elseif ($ct == 2) { + $trns = [ord(substr($t, 1, 1)), ord(substr($t, 3, 1)), ord(substr($t, 5, 1))]; + } else { + $pos = strpos($t, chr(0)); + if ($pos !== false) { + $trns = [$pos]; + } + } + $this->_readstream($f, 4); + } elseif ($type == 'IDAT') { + // Read image data block + $data .= $this->_readstream($f, $n); + $this->_readstream($f, 4); + } elseif ($type == 'IEND') { + break; + } else { + $this->_readstream($f, $n + 4); + } + } while ($n); + + if ($colspace == 'Indexed' && empty($pal)) { + $this->Error('Missing palette in '.$file); + } + $info = ['w'=>$w, 'h'=>$h, 'cs'=>$colspace, 'bpc'=>$bpc, 'f'=>'FlateDecode', 'dp'=>$dp, 'pal'=>$pal, 'trns'=>$trns]; + if ($ct >= 4) { + // Extract alpha channel + if (!function_exists('gzuncompress')) { + $this->Error('Zlib not available, can\'t handle alpha channel: '.$file); + } + $data = gzuncompress($data); + $color = ''; + $alpha = ''; + if ($ct == 4) { + // Gray image + $len = 2 * $w; + for ($i = 0; $i < $h; $i++) { + $pos = (1 + $len) * $i; + $color .= $data[$pos]; + $alpha .= $data[$pos]; + $line = substr($data, $pos + 1, $len); + $color .= preg_replace('/(.)./s', '$1', $line); + $alpha .= preg_replace('/.(.)/s', '$1', $line); + } + } else { + // RGB image + $len = 4 * $w; + for ($i = 0; $i < $h; $i++) { + $pos = (1 + $len) * $i; + $color .= $data[$pos]; + $alpha .= $data[$pos]; + $line = substr($data, $pos + 1, $len); + $color .= preg_replace('/(.{3})./s', '$1', $line); + $alpha .= preg_replace('/.{3}(.)/s', '$1', $line); + } + } + unset($data); + $data = gzcompress($color); + $info['smask'] = gzcompress($alpha); + if ($this->PDFVersion < '1.4') { + $this->PDFVersion = '1.4'; + } + } + $info['data'] = $data; + + return $info; + } + + public function _readstream($f, $n) + { + // Read n bytes from stream + $res = ''; + while ($n > 0 && !feof($f)) { + $s = fread($f, $n); + if ($s === false) { + $this->Error('Error while reading stream'); + } + $n -= strlen($s); + $res .= $s; + } + if ($n > 0) { + $this->Error('Unexpected end of stream'); + } + + return $res; + } + + public function _readint($f) + { + // Read a 4-byte integer from stream + $a = unpack('Ni', $this->_readstream($f, 4)); + + return $a['i']; + } + + public function _parsegif($file) + { + // Extract info from a GIF file (via PNG conversion) + if (!function_exists('imagepng')) { + $this->Error('GD extension is required for GIF support'); + } + if (!function_exists('imagecreatefromgif')) { + $this->Error('GD has no GIF read support'); + } + $im = imagecreatefromgif($file); + if (!$im) { + $this->Error('Missing or incorrect image file: '.$file); + } + imageinterlace($im, 0); + $f = @fopen('php://temp', 'rb+'); + if ($f) { + // Perform conversion in memory + ob_start(); + imagepng($im); + $data = ob_get_clean(); + imagedestroy($im); + fwrite($f, $data); + rewind($f); + $info = $this->_parsepngstream($f, $file); + fclose($f); + } else { + // Use temporary file + $tmp = tempnam('.', 'gif'); + if (!$tmp) { + $this->Error('Unable to create a temporary file'); + } + if (!imagepng($im, $tmp)) { + $this->Error('Error while saving to temporary file'); + } + imagedestroy($im); + $info = $this->_parsepng($tmp); + unlink($tmp); + } + + return $info; + } + + public function _newobj() + { + // Begin a new object + $this->n++; + $this->offsets[$this->n] = strlen($this->buffer); + $this->_out($this->n.' 0 obj'); + } + + public function _putstream($s) + { + $this->_out('stream'); + $this->_out($s); + $this->_out('endstream'); + } + + public function _out($s) + { + // Add a line to the document + if ($this->state == 2) { + $this->pages[$this->page] .= $s."\n"; + } else { + $this->buffer .= $s."\n"; + } + } + + public function _putpages() + { + $nb = $this->page; + if (!empty($this->AliasNbPages)) { + // Replace number of pages + for ($n = 1; $n <= $nb; $n++) { + $this->pages[$n] = str_replace($this->AliasNbPages, $nb, $this->pages[$n]); + } + } + if ($this->DefOrientation == 'P') { + $wPt = $this->DefPageSize[0] * $this->k; + $hPt = $this->DefPageSize[1] * $this->k; + } else { + $wPt = $this->DefPageSize[1] * $this->k; + $hPt = $this->DefPageSize[0] * $this->k; + } + $filter = ($this->compress) ? '/Filter /FlateDecode ' : ''; + for ($n = 1; $n <= $nb; $n++) { + // Page + $this->_newobj(); + $this->_out('<_out('/Parent 1 0 R'); + if (isset($this->PageSizes[$n])) { + $this->_out(sprintf('/MediaBox [0 0 %.2F %.2F]', $this->PageSizes[$n][0], $this->PageSizes[$n][1])); + } + $this->_out('/Resources 2 0 R'); + if (isset($this->PageLinks[$n])) { + // Links + $annots = '/Annots ['; + foreach ($this->PageLinks[$n] as $pl) { + $rect = sprintf('%.2F %.2F %.2F %.2F', $pl[0], $pl[1], $pl[0] + $pl[2], $pl[1] - $pl[3]); + $annots .= '<_textstring($pl[4]).'>>>>'; + } else { + $l = $this->links[$pl[4]]; + $h = isset($this->PageSizes[$l[0]]) ? $this->PageSizes[$l[0]][1] : $hPt; + $annots .= sprintf('/Dest [%d 0 R /XYZ 0 %.2F null]>>', 1 + 2 * $l[0], $h - $l[1] * $this->k); + } + } + $this->_out($annots.']'); + } + if ($this->PDFVersion > '1.3') { + $this->_out('/Group <>'); + } + $this->_out('/Contents '.($this->n + 1).' 0 R>>'); + $this->_out('endobj'); + // Page content + $p = ($this->compress) ? gzcompress($this->pages[$n]) : $this->pages[$n]; + $this->_newobj(); + $this->_out('<<'.$filter.'/Length '.strlen($p).'>>'); + $this->_putstream($p); + $this->_out('endobj'); + } + // Pages root + $this->offsets[1] = strlen($this->buffer); + $this->_out('1 0 obj'); + $this->_out('<_out($kids.']'); + $this->_out('/Count '.$nb); + $this->_out(sprintf('/MediaBox [0 0 %.2F %.2F]', $wPt, $hPt)); + $this->_out('>>'); + $this->_out('endobj'); + } + + public function _putfonts() + { + $nf = $this->n; + foreach ($this->diffs as $diff) { + // Encodings + $this->_newobj(); + $this->_out('<>'); + $this->_out('endobj'); + } + foreach ($this->FontFiles as $file=>$info) { + // Font file embedding + $this->_newobj(); + $this->FontFiles[$file]['n'] = $this->n; + $font = file_get_contents($this->fontpath.$file, true); + if (!$font) { + $this->Error('Font file not found: '.$file); + } + $compressed = (substr($file, -2) == '.z'); + if (!$compressed && isset($info['length2'])) { + $font = substr($font, 6, $info['length1']).substr($font, 6 + $info['length1'] + 6, $info['length2']); + } + $this->_out('<_out('/Filter /FlateDecode'); + } + $this->_out('/Length1 '.$info['length1']); + if (isset($info['length2'])) { + $this->_out('/Length2 '.$info['length2'].' /Length3 0'); + } + $this->_out('>>'); + $this->_putstream($font); + $this->_out('endobj'); + } + foreach ($this->fonts as $k=>$font) { + // Font objects + $this->fonts[$k]['n'] = $this->n + 1; + $type = $font['type']; + $name = $font['name']; + if ($type == 'Core') { + // Core font + $this->_newobj(); + $this->_out('<_out('/BaseFont /'.$name); + $this->_out('/Subtype /Type1'); + if ($name != 'Symbol' && $name != 'ZapfDingbats') { + $this->_out('/Encoding /WinAnsiEncoding'); + } + $this->_out('>>'); + $this->_out('endobj'); + } elseif ($type == 'Type1' || $type == 'TrueType') { + // Additional Type1 or TrueType/OpenType font + $this->_newobj(); + $this->_out('<_out('/BaseFont /'.$name); + $this->_out('/Subtype /'.$type); + $this->_out('/FirstChar 32 /LastChar 255'); + $this->_out('/Widths '.($this->n + 1).' 0 R'); + $this->_out('/FontDescriptor '.($this->n + 2).' 0 R'); + if (isset($font['diffn'])) { + $this->_out('/Encoding '.($nf + $font['diffn']).' 0 R'); + } else { + $this->_out('/Encoding /WinAnsiEncoding'); + } + $this->_out('>>'); + $this->_out('endobj'); + // Widths + $this->_newobj(); + $cw = &$font['cw']; + $s = '['; + for ($i = 32; $i <= 255; $i++) { + $s .= $cw[chr($i)].' '; + } + $this->_out($s.']'); + $this->_out('endobj'); + // Descriptor + $this->_newobj(); + $s = '<$v) { + $s .= ' /'.$k.' '.$v; + } + if (!empty($font['file'])) { + $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R'; + } + $this->_out($s.'>>'); + $this->_out('endobj'); + } else { + // Allow for additional types + $mtd = '_put'.strtolower($type); + if (!method_exists($this, $mtd)) { + $this->Error('Unsupported font type: '.$type); + } + $this->$mtd($font); + } + } + } + + public function _putimages() + { + foreach (array_keys($this->images) as $file) { + $this->_putimage($this->images[$file]); + unset($this->images[$file]['data']); + unset($this->images[$file]['smask']); + } + } + + public function _putimage(&$info) + { + $this->_newobj(); + $info['n'] = $this->n; + $this->_out('<_out('/Subtype /Image'); + $this->_out('/Width '.$info['w']); + $this->_out('/Height '.$info['h']); + if ($info['cs'] == 'Indexed') { + $this->_out('/ColorSpace [/Indexed /DeviceRGB '.(strlen($info['pal']) / 3 - 1).' '.($this->n + 1).' 0 R]'); + } else { + $this->_out('/ColorSpace /'.$info['cs']); + if ($info['cs'] == 'DeviceCMYK') { + $this->_out('/Decode [1 0 1 0 1 0 1 0]'); + } + } + $this->_out('/BitsPerComponent '.$info['bpc']); + if (isset($info['f'])) { + $this->_out('/Filter /'.$info['f']); + } + if (isset($info['dp'])) { + $this->_out('/DecodeParms <<'.$info['dp'].'>>'); + } + if (isset($info['trns']) && is_array($info['trns'])) { + $trns = ''; + for ($i = 0; $i < count($info['trns']); $i++) { + $trns .= $info['trns'][$i].' '.$info['trns'][$i].' '; + } + $this->_out('/Mask ['.$trns.']'); + } + if (isset($info['smask'])) { + $this->_out('/SMask '.($this->n + 1).' 0 R'); + } + $this->_out('/Length '.strlen($info['data']).'>>'); + $this->_putstream($info['data']); + $this->_out('endobj'); + // Soft mask + if (isset($info['smask'])) { + $dp = '/Predictor 15 /Colors 1 /BitsPerComponent 8 /Columns '.$info['w']; + $smask = ['w'=>$info['w'], 'h'=>$info['h'], 'cs'=>'DeviceGray', 'bpc'=>8, 'f'=>$info['f'], 'dp'=>$dp, 'data'=>$info['smask']]; + $this->_putimage($smask); + } + // Palette + if ($info['cs'] == 'Indexed') { + $filter = ($this->compress) ? '/Filter /FlateDecode ' : ''; + $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal']; + $this->_newobj(); + $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>'); + $this->_putstream($pal); + $this->_out('endobj'); + } + } + + public function _putxobjectdict() + { + foreach ($this->images as $image) { + $this->_out('/I'.$image['i'].' '.$image['n'].' 0 R'); + } + } + + public function _putresourcedict() + { + $this->_out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]'); + $this->_out('/Font <<'); + foreach ($this->fonts as $font) { + $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R'); + } + $this->_out('>>'); + $this->_out('/XObject <<'); + $this->_putxobjectdict(); + $this->_out('>>'); + } + + public function _putresources() + { + $this->_putfonts(); + $this->_putimages(); + // Resource dictionary + $this->offsets[2] = strlen($this->buffer); + $this->_out('2 0 obj'); + $this->_out('<<'); + $this->_putresourcedict(); + $this->_out('>>'); + $this->_out('endobj'); + } + + public function _putinfo() + { + $this->_out('/Producer '.$this->_textstring('FPDF '.FPDF_VERSION)); + if (!empty($this->title)) { + $this->_out('/Title '.$this->_textstring($this->title)); + } + if (!empty($this->subject)) { + $this->_out('/Subject '.$this->_textstring($this->subject)); + } + if (!empty($this->author)) { + $this->_out('/Author '.$this->_textstring($this->author)); + } + if (!empty($this->keywords)) { + $this->_out('/Keywords '.$this->_textstring($this->keywords)); + } + if (!empty($this->creator)) { + $this->_out('/Creator '.$this->_textstring($this->creator)); + } + $this->_out('/CreationDate '.$this->_textstring('D:'.@date('YmdHis'))); + } + + public function _putcatalog() + { + $this->_out('/Type /Catalog'); + $this->_out('/Pages 1 0 R'); + if ($this->ZoomMode == 'fullpage') { + $this->_out('/OpenAction [3 0 R /Fit]'); + } elseif ($this->ZoomMode == 'fullwidth') { + $this->_out('/OpenAction [3 0 R /FitH null]'); + } elseif ($this->ZoomMode == 'real') { + $this->_out('/OpenAction [3 0 R /XYZ null null 1]'); + } elseif (!is_string($this->ZoomMode)) { + $this->_out('/OpenAction [3 0 R /XYZ null null '.sprintf('%.2F', $this->ZoomMode / 100).']'); + } + if ($this->LayoutMode == 'single') { + $this->_out('/PageLayout /SinglePage'); + } elseif ($this->LayoutMode == 'continuous') { + $this->_out('/PageLayout /OneColumn'); + } elseif ($this->LayoutMode == 'two') { + $this->_out('/PageLayout /TwoColumnLeft'); + } + } + + public function _putheader() + { + $this->_out('%PDF-'.$this->PDFVersion); + } + + public function _puttrailer() + { + $this->_out('/Size '.($this->n + 1)); + $this->_out('/Root '.$this->n.' 0 R'); + $this->_out('/Info '.($this->n - 1).' 0 R'); + } + + public function _enddoc() + { + $this->_putheader(); + $this->_putpages(); + $this->_putresources(); + // Info + $this->_newobj(); + $this->_out('<<'); + $this->_putinfo(); + $this->_out('>>'); + $this->_out('endobj'); + // Catalog + $this->_newobj(); + $this->_out('<<'); + $this->_putcatalog(); + $this->_out('>>'); + $this->_out('endobj'); + // Cross-ref + $o = strlen($this->buffer); + $this->_out('xref'); + $this->_out('0 '.($this->n + 1)); + $this->_out('0000000000 65535 f '); + for ($i = 1; $i <= $this->n; $i++) { + $this->_out(sprintf('%010d 00000 n ', $this->offsets[$i])); + } + // Trailer + $this->_out('trailer'); + $this->_out('<<'); + $this->_puttrailer(); + $this->_out('>>'); + $this->_out('startxref'); + $this->_out($o); + $this->_out('%%EOF'); + $this->state = 3; + } + + // End of class } // Handle special IE contype request -if(isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT']=='contype') -{ - header('Content-Type: application/pdf'); - exit; +if (isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'contype') { + header('Content-Type: application/pdf'); + exit; } - -?> diff --git a/Imagen.php b/Imagen.php index 1b18ffb..0f831e8 100644 --- a/Imagen.php +++ b/Imagen.php @@ -1,6 +1,5 @@ . - * */ //Para comprimir las imágenes -require_once('Zebra_Image.php'); -define("HAYQUEGRABAR", 1); -define("HAYQUEBORRAR", 2); -define("NOHACERNADA", 3); +require_once 'Zebra_Image.php'; +define('HAYQUEGRABAR', 1); +define('HAYQUEBORRAR', 2); +define('NOHACERNADA', 3); -class Imagen { +class Imagen +{ private $archivoSubido; public $archivoComprimido; private $extension; private $dirData; public $archivoCopiado; - + public function __construct() { $this->dirData = IMAGEDATA; } - + public function determinaAccion($campo) { - if (isset($_POST[$campo]) && $_POST[$campo] == "") { + if (isset($_POST[$campo]) && $_POST[$campo] == '') { return HAYQUEBORRAR; //Hay que borrar el archivo de imagen } elseif (isset($_FILES[$campo]['error']) && $_FILES[$campo]['error'] == 0) { return HAYQUEGRABAR; //Hay que guardar el archivo de imagen enviado @@ -46,7 +45,7 @@ class Imagen { return NOHACERNADA; //No hay que hacer nada } } - + public function procesaEnvio($campo, &$mensaje) { try { @@ -77,11 +76,11 @@ class Imagen { $finfo = new finfo(FILEINFO_MIME_TYPE); if (false === $ext = array_search( $finfo->file($_FILES[$campo]['tmp_name']), - array( + [ 'jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif', - ), + ], true )) { throw new RuntimeException('Formato de imagen inválido, no es {jpg, png, gif}'); @@ -98,47 +97,51 @@ class Imagen { return true; } catch (RuntimeException $e) { $mensaje = $e->getMessage(); + return false; } } - + public static function borraImagenId($tabla, $id) { - $extensiones = array ("png", "gif", "jpg"); + $extensiones = ['png', 'gif', 'jpg']; foreach ($extensiones as $extension) { - $archivo = IMAGEDATA . "/" . $tabla . "_" . $id . "." . $extension; + $archivo = IMAGEDATA.'/'.$tabla.'_'.$id.'.'.$extension; if (file_exists($archivo)) { - unlink ($archivo); + unlink($archivo); } } } + public function copiaImagenId($valorImagen, $tabla, $id, &$mensaje) { - $extension = strrchr($valorImagen, "."); - $nombre = $this->dirData . "/" . $tabla . "_" . $id . $extension; + $extension = strrchr($valorImagen, '.'); + $nombre = $this->dirData.'/'.$tabla.'_'.$id.$extension; if (!@copy($valorImagen, $nombre)) { - $errors= error_get_last(); - $mensaje = "No pudo copiar el archivo " . $valorImagen . " en " . $nombre . " Error = [" . $errors['message'] . "]"; + $errors = error_get_last(); + $mensaje = 'No pudo copiar el archivo '.$valorImagen.' en '.$nombre.' Error = ['.$errors['message'].']'; + return false; } $this->archivoCopiado = $nombre; + return true; } - + public function mueveImagenId($tabla, $id, &$mensaje) { - if (!$this->comprimeArchivo($tabla . "_" . $id, $mensaje)) { + if (!$this->comprimeArchivo($tabla.'_'.$id, $mensaje)) { return false; } else { return true; - } + } } - - private function comprimeArchivo($id, &$mensaje) + + private function comprimeArchivo($id, &$mensaje) { $zebra = new Zebra_Image(); $zebra->source_path = $this->archivoSubido; - $this->archivoComprimido = $this->dirData . "/" . $id . "." . $this->extension; + $this->archivoComprimido = $this->dirData.'/'.$id.'.'.$this->extension; $zebra->target_path = $this->archivoComprimido; $zebra->jpeg_quality = 100; @@ -156,28 +159,28 @@ class Imagen { switch ($zebra->error) { case 1: $mensaje = 'El fichero origen no se ha encontrado!'; break; - case 2: $mensaje = 'No se puede leer el archivo origen ' . $this->archivoSubido; + case 2: $mensaje = 'No se puede leer el archivo origen '.$this->archivoSubido; break; - case 3: $mensaje = 'No se pudo escribir el archivo destino ' . $this->archivoComprimido; + case 3: $mensaje = 'No se pudo escribir el archivo destino '.$this->archivoComprimido; break; - case 4: $mensaje = 'Formato de fichero origen no soportado ' . $this->archivoSubido; + case 4: $mensaje = 'Formato de fichero origen no soportado '.$this->archivoSubido; break; - case 5: $mensaje = 'Formato de fichero destino no soportado ' . $this->archivoComprimido; + case 5: $mensaje = 'Formato de fichero destino no soportado '.$this->archivoComprimido; break; - case 6: $mensaje = 'La versión de la biblioteca GD no soporta el formato de destino ' . $this->archivoComprimido; + case 6: $mensaje = 'La versión de la biblioteca GD no soporta el formato de destino '.$this->archivoComprimido; break; case 7: $mensaje = 'La biblioteca GD no está instalada'; break; case 8: $mensaje = 'el comando "chmod" está deshabilitado por configuración'; break; } + return false; } else { //Borra el archivo subido unlink($this->archivoSubido); + return true; } - } + } } - -?> diff --git a/Importacion.php b/Importacion.php index a0adce6..d4aa52d 100644 --- a/Importacion.php +++ b/Importacion.php @@ -1,7 +1,6 @@ . - * */ -class Importacion { - +class Importacion +{ private $bdd; - public function __construct($baseDatos, $registrado) { - if (!$registrado) { + public function __construct($baseDatos, $registrado) + { + if (!$registrado) { return 'Debe registrarse para acceder a este apartado'; } $this->bdd = $baseDatos; } - public function ejecuta() { + public function ejecuta() + { $opc = ''; if (isset($_GET['opc'])) { $opc = $_GET['opc']; @@ -39,26 +39,29 @@ class Importacion { case 'form':return $this->formulario(); case 'importar':return $this->importarFichero(); case 'ejecutar':return $this->ejecutaFichero(); - default: return "Importacion: No entiendo qué me has pedido."; + default: return 'Importacion: No entiendo qué me has pedido.'; } } - private function importarFichero() { - $uploadfile = TMP."/" . basename($_FILES['fichero']['name']); + private function importarFichero() + { + $uploadfile = TMP.'/'.basename($_FILES['fichero']['name']); if (!move_uploaded_file($_FILES['fichero']['tmp_name'], $uploadfile)) { - die('No se pudo subir el fichero ' . $_FILES['userfile']['tmp_name']); + die('No se pudo subir el fichero '.$_FILES['userfile']['tmp_name']); } $csv = new Csv($this->bdd); $csv->cargaCSV($uploadfile); + return $csv->resumen(); } - private function formulario() { - $accion = "index.php?importacion&opc=importar"; - $salida = ""; + private function formulario() + { + $accion = 'index.php?importacion&opc=importar'; + $salida = ''; //$salida .= ''; - $salida .='
'; - $salida .= '
' . "\n"; + $salida .= '
'; + $salida .= ''."\n"; $salida .= "

Elige Archivo

\n"; //$salida .= ''; //$salida .= ''; @@ -76,7 +79,7 @@ class Importacion { Eliminar
'; - $salida .= '


' . "\n"; + $salida .= '


'."\n"; $salida .= '
'; $mensaje = 'Sólo se permiten archivos con extensión CSV'; $salida .= ""; + return $salida; } - private function ejecutaFichero() { + + private function ejecutaFichero() + { $archivo = $_POST['ficheroCSV']; $csv = new Csv($this->bdd); $csv->cargaCSV($archivo); + return $csv->ejecutaFichero(); } } - -?> diff --git a/InformeInventario.php b/InformeInventario.php index 29502a4..1b03d1a 100644 --- a/InformeInventario.php +++ b/InformeInventario.php @@ -1,7 +1,6 @@ . - * */ -class InformeInventario { - +class InformeInventario +{ private $bdd; public function __construct($baseDatos) @@ -48,67 +46,71 @@ class InformeInventario { $informe = new InformePDF($this->bdd, $enlace, true); $informe->crea($enlace); $informe->cierraPDF(); + return $this->devuelveInforme($informe); } private function devuelveInforme($informe) { - $letras = "abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; - $nombre = TMP."/informe" . substr(str_shuffle($letras), 0, 10) . ".pdf"; + $letras = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; + $nombre = TMP.'/informe'.substr(str_shuffle($letras), 0, 10).'.pdf'; $informe->guardaArchivo($nombre); + return '
- - + + '; } - + private function listarUbicacion() { $salidaInforme = isset($_POST['salida']) ? $_POST['salida'] : 'pantalla'; switch ($salidaInforme) { - case "pantalla": - $fichero = "xml/inventarioUbicacion.xml"; - $salida = TMP."/inventarioUbicacion.xml"; + case 'pantalla': + $fichero = 'xml/inventarioUbicacion.xml'; + $salida = TMP.'/inventarioUbicacion.xml'; break; - case "csv": - $fichero = "xml/inventarioUbicacionCSV.xml"; - $salida = TMP."/inventarioUbicacionCSV.xml"; + case 'csv': + $fichero = 'xml/inventarioUbicacionCSV.xml'; + $salida = TMP.'/inventarioUbicacionCSV.xml'; break; - case "etiquetas": - $fichero = "xml/inventarioUbicacionEtiquetas.xml"; - $salida = TMP."/inventarioUbicacionEtiquetas.xml"; + case 'etiquetas': + $fichero = 'xml/inventarioUbicacionEtiquetas.xml'; + $salida = TMP.'/inventarioUbicacionEtiquetas.xml'; break; } - $plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla ' . $fichero); - $id = $_POST['id'] == NULL ? $_GET['id'] : $_POST['id']; - $comando = "select * from Ubicaciones where id='" . $id . "';"; + $plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla '.$fichero); + $id = $_POST['id'] == null ? $_GET['id'] : $_POST['id']; + $comando = "select * from Ubicaciones where id='".$id."';"; $resultado = $this->bdd->ejecuta($comando); if (!$resultado) { return $this->bdd->mensajeError($comando); } $fila = $this->bdd->procesaResultado(); - $plantilla = str_replace("{id}", $id, $plantilla); - $plantilla = str_replace("{Descripcion}", $fila['Descripcion'], $plantilla); - file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida); + $plantilla = str_replace('{id}', $id, $plantilla); + $plantilla = str_replace('{Descripcion}', $fila['Descripcion'], $plantilla); + file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla '.$salida); switch ($salidaInforme) { - case "pantalla": + case 'pantalla': $informe = new InformePDF($this->bdd, $salida, true); $informe->crea($salida); $informe->cierraPDF(); + return $this->devuelveInforme($informe); - case "csv": + case 'csv': //Genera una hoja de cálculo en formato csv - $nombre = TMP."/Ubicacion" . strftime("%Y%m%d") . rand(100, 999) . ".csv"; + $nombre = TMP.'/Ubicacion'.strftime('%Y%m%d').rand(100, 999).'.csv'; $hoja = new Csv($this->bdd); $hoja->crea($nombre); $hoja->ejecutaConsulta($salida); - echo ''; + echo ''; break; - case "etiquetas": + case 'etiquetas': $etiquetas = new EtiquetasPDF($this->bdd, $salida, true); $etiquetas->crea($salida); $etiquetas->cierraPDF(); + return $this->devuelveInforme($etiquetas); } } @@ -117,50 +119,52 @@ class InformeInventario { { $salidaInforme = isset($_POST['salida']) ? $_POST['salida'] : 'pantalla'; switch ($salidaInforme) { - case "pantalla": - $fichero = "xml/inventarioArticulo.xml"; - $salida = TMP."/inventarioArticulo.xml"; + case 'pantalla': + $fichero = 'xml/inventarioArticulo.xml'; + $salida = TMP.'/inventarioArticulo.xml'; break; - case "csv": - $fichero = "xml/inventarioArticuloCSV.xml"; - $salida = TMP."/inventarioArticuloCSV.xml"; + case 'csv': + $fichero = 'xml/inventarioArticuloCSV.xml'; + $salida = TMP.'/inventarioArticuloCSV.xml'; break; - case "etiquetas": - $fichero = "xml/inventarioArticuloEtiquetas.xml"; - $salida = TMP."/inventarioArticuloEtiquetas.xml"; + case 'etiquetas': + $fichero = 'xml/inventarioArticuloEtiquetas.xml'; + $salida = TMP.'/inventarioArticuloEtiquetas.xml'; break; } - $plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla ' . $fichero); - $id = $_POST['id'] == NULL ? $_GET['id'] : $_POST['id']; - $comando = "select * from Articulos where id='" . $id . "';"; + $plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla '.$fichero); + $id = $_POST['id'] == null ? $_GET['id'] : $_POST['id']; + $comando = "select * from Articulos where id='".$id."';"; $resultado = $this->bdd->ejecuta($comando); if (!$resultado) { return $this->bdd->mensajeError($comando); } $fila = $this->bdd->procesaResultado(); - $plantilla = str_replace("{id}", $id, $plantilla); - $plantilla = str_replace("{Descripcion}", $fila['descripcion'], $plantilla); - $plantilla = str_replace("{Marca}", $fila['marca'], $plantilla); - $plantilla = str_replace("{Modelo}", $fila['modelo'], $plantilla); - file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida); + $plantilla = str_replace('{id}', $id, $plantilla); + $plantilla = str_replace('{Descripcion}', $fila['descripcion'], $plantilla); + $plantilla = str_replace('{Marca}', $fila['marca'], $plantilla); + $plantilla = str_replace('{Modelo}', $fila['modelo'], $plantilla); + file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla '.$salida); switch ($salidaInforme) { - case "pantalla": + case 'pantalla': $informe = new InformePDF($this->bdd, $salida, true); $informe->crea($salida); $informe->cierraPDF(); + return $this->devuelveInforme($informe); - case "csv": + case 'csv': //Genera una hoja de cálculo en formato csv - $nombre = TMP."/Articulo" . strftime("%Y%m%d") . rand(100, 999) . ".csv"; + $nombre = TMP.'/Articulo'.strftime('%Y%m%d').rand(100, 999).'.csv'; $hoja = new Csv($this->bdd); $hoja->crea($nombre); $hoja->ejecutaConsulta($salida); - echo ''; + echo ''; break; - case "etiquetas": + case 'etiquetas': $etiquetas = new EtiquetasPDF($this->bdd, $salida, true); $etiquetas->crea($salida); $etiquetas->cierraPDF(); + return $this->devuelveInforme($etiquetas); } } @@ -168,63 +172,68 @@ class InformeInventario { private function listaUbicaciones() { $salida = "\n"; + $salida .= "\n"; + return $salida; } private function listaArticulos() { $salida = "\n"; + $salida .= "\n"; + return $salida; } private function formulario($accion, $etiqueta, $lista) { - $salida = '
' . "\n"; - $salida.="

Elige $etiqueta\n"; - $salida.="

"; - $salida.=$lista; - $salida.="

+ $salida = '

'."\n"; + $salida .= "

Elige $etiqueta\n"; + $salida .= "

"; + $salida .= $lista; + $salida .= "

"; - $salida.='

'; - $salida.='
'; - $salida.='
'; - $salida.="

"; - $salida.='


' . "\n"; - $salida.=""; + $salida .= '
'; + $salida .= '
'; + $salida .= '
'; + $salida .= '

'; + $salida .= '


'."\n"; + $salida .= ""; + return $salida; } private function formularioUbicacion() { //Genera un formulario con las ubicaciones disponibles. - $accion = "index.php?informeInventario&opc=listarUbicacion"; + $accion = 'index.php?informeInventario&opc=listarUbicacion'; + return $this->formulario($accion, 'Ubicación', $this->listaUbicaciones()); } private function formularioArticulo() { - $accion = "index.php?informeInventario&opc=listarArticulo"; + $accion = 'index.php?informeInventario&opc=listarArticulo'; + return $this->formulario($accion, 'Artículo', $this->listaArticulos()); } - + private function inventarioTotal() { return $this->dialogo(); @@ -235,18 +244,19 @@ class InformeInventario { $dialogo = '

Inventario Total

¿Desea obtener el inventario de todo el centro?

-

Volver - +

Volver + Continuar

'; + return $dialogo; } - + private function listarTotal() { - $fichero = "xml/inventarioUbicacion.xml"; - $salida = TMP."/inventarioUbicacion.xml"; - $comando = "select * from Ubicaciones ;"; + $fichero = 'xml/inventarioUbicacion.xml'; + $salida = TMP.'/inventarioUbicacion.xml'; + $comando = 'select * from Ubicaciones ;'; $resultado = $this->bdd->ejecuta($comando); if (!$resultado) { return $this->bdd->mensajeError($comando); @@ -255,10 +265,10 @@ class InformeInventario { $bdatos = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS); $primero = true; while ($fila = $this->bdd->procesaResultado()) { - $plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla ' . $fichero); - $plantilla = str_replace("{id}", $fila['id'], $plantilla); - $plantilla = str_replace("{Descripcion}", $fila['Descripcion'], $plantilla); - file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida); + $plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla '.$fichero); + $plantilla = str_replace('{id}', $fila['id'], $plantilla); + $plantilla = str_replace('{Descripcion}', $fila['Descripcion'], $plantilla); + file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla '.$salida); if ($primero) { $primero = false; $informe = new InformePDF($bdatos, $salida, true); @@ -266,9 +276,7 @@ class InformeInventario { $informe->crea($salida); } $informe->cierraPDF(); + return $this->devuelveInforme($informe); } - } - -?> diff --git a/InformePDF.php b/InformePDF.php index d56feaf..99c494d 100644 --- a/InformePDF.php +++ b/InformePDF.php @@ -1,12 +1,13 @@ + * * @version 1.0 - * @package Inventario + * * @copyright Copyright (c) 2008, Ricardo Montañana - * @package Inventario * @copyright Copyright (c) 2008, Ricardo Montañana Gómez * @license http://www.gnu.org/licenses/gpl-3.0.txt * This file is part of Inventario. @@ -14,20 +15,18 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. - * + * * Inventario is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with Inventario. If not, see . - * */ -class InformePDF { - +class InformePDF +{ /** - * * @var basedatos Controlador de la base de datos */ private $bdd; @@ -36,14 +35,17 @@ class InformePDF { private $def; /** - * El constructor recibe como argumento el nombre del archivo XML con la definición, encargándose de recuperarla y guardar toda la información localmente - * @param basedatos $bdd manejador de la base de datos - * @param string $definicion fichero con la definición del informe en XML - * @param boolean $registrado usuario registrado si/no + * El constructor recibe como argumento el nombre del archivo XML con la definición, encargándose de recuperarla y guardar toda la información localmente. + * + * @param basedatos $bdd manejador de la base de datos + * @param string $definicion fichero con la definición del informe en XML + * @param bool $registrado usuario registrado si/no + * * @return ficheroPDF - * todo: cambiar este comentario + * todo: cambiar este comentario */ - public function __construct($bdd, $definicion, $registrado) { + public function __construct($bdd, $definicion, $registrado) + { if (!$registrado) { return 'Debe registrarse para acceder a este apartado'; } @@ -53,15 +55,16 @@ class InformePDF { $this->pdf = new Pdf_mysql_table($this->bdd->obtieneManejador(), (string) $this->def->Pagina['Orientacion'], (string) $this->def->Pagina['Formato'], (string) utf8_decode($this->def->Titulo['Texto']), (string) $this->def->Pagina->Cabecera); //echo $def->Titulo.$def->Cabecera; $this->pdf->Open(); - $this->pdf->setAuthor(AUTOR,true); - $creador = CENTRO . " " . PROGRAMA . " v" . VERSION; - $this->pdf->setCreator(html_entity_decode($creador),true); - $this->pdf->setSubject($this->def->Titulo,true); + $this->pdf->setAuthor(AUTOR, true); + $creador = CENTRO.' '.PROGRAMA.' v'.VERSION; + $this->pdf->setCreator(html_entity_decode($creador), true); + $this->pdf->setSubject($this->def->Titulo, true); $this->pdf->setAutoPageBreak(true, 10); } - public function crea($definicion) { - + public function crea($definicion) + { + //print_r($def);echo $bdd;die(); // Iniciamos la creación del documento $this->def = simplexml_load_file($definicion); @@ -74,50 +77,55 @@ class InformePDF { foreach ($this->def->Pagina->Cuerpo->Col as $columna) { $this->pdf->AddCol((string) $columna['Nombre'], (string) $columna['Ancho'], (string) $columna['Titulo'], (string) $columna['Ajuste'], (string) $columna['Total']); } - $prop = array('HeaderColor' => array(255, 150, 100), - 'color1' => array(210, 245, 255), - 'color2' => array(255, 255, 210), - 'padding' => 2); + $prop = ['HeaderColor' => [255, 150, 100], + 'color1' => [210, 245, 255], + 'color2' => [255, 255, 210], + 'padding' => 2]; $this->pdf->Table($this->def->Datos->Consulta, $prop); } - public function cierraPDF() { + public function cierraPDF() + { $this->pdf->Close(); $this->docu = $this->pdf->Output('', 'S'); } - public function getContenido() { + public function getContenido() + { return $this->docu; } - public function getCabecera() { - $cabecera = "Content-type: application/pdf"; - $cabecera = $cabecera . "Content-length: " . strlen($this->docu); - $cabecera = $cabecera . "Content-Disposition: inline; filename=".TMP."/Informe.pdf"; + public function getCabecera() + { + $cabecera = 'Content-type: application/pdf'; + $cabecera = $cabecera.'Content-length: '.strlen($this->docu); + $cabecera = $cabecera.'Content-Disposition: inline; filename='.TMP.'/Informe.pdf'; + return $cabecera; } - public function guardaArchivo($nombre) { - if (!isset($nombre)) - $nombre = TMP . "/Informe.pdf"; - $fichero = fopen($nombre, "w"); + public function guardaArchivo($nombre) + { + if (!isset($nombre)) { + $nombre = TMP.'/Informe.pdf'; + } + $fichero = fopen($nombre, 'w'); fwrite($fichero, $this->getCabecera()); fwrite($fichero, $this->getContenido(), strlen($this->getContenido())); fclose($fichero); } - public function enviaCabecera() { - header("Content-type: application/pdf"); + public function enviaCabecera() + { + header('Content-type: application/pdf'); $longitud = strlen($this->docu); header("Content-length: $longitud"); - header("Content-Disposition: inline; filename=".TMP."/Informe.pdf"); + header('Content-Disposition: inline; filename='.TMP.'/Informe.pdf'); } - public function imprimeInforme() { + public function imprimeInforme() + { $this->enviaCabecera(); echo $this->docu; } - } - -?> diff --git a/Instalar.php b/Instalar.php index afe4f52..5586545 100644 --- a/Instalar.php +++ b/Instalar.php @@ -1,8 +1,8 @@ . - * */ //Se incluyen los módulos necesarios -function __autoload($class_name) { - require_once $class_name . '.php'; +function __autoload($class_name) +{ + require_once $class_name.'.php'; } require_once 'inc/configuracion.inc'; @@ -37,22 +37,24 @@ define('INC', './inc'); $instalar = new Instalar(); if ($instalar->error) { echo $instalar->panelError(); + return; } echo $instalar->ejecuta(); -class Instalar { +class Instalar +{ private $contenido; private $plant; public $error; - public $error_msj; - + public $error_msj; + public function __construct() { //Selecciona la plantilla a utilizar - $this->plant='plant/'; - $this->plant.=PLANTILLA; - $this->plant.='.html'; + $this->plant = 'plant/'; + $this->plant .= PLANTILLA; + $this->plant .= '.html'; $this->error = false; $this->eror_msj = ''; if (INSTALADO != 'no') { @@ -64,34 +66,38 @@ class Instalar { $this->error_msj = "El indicador de instalación tiene 'no' pero la base de datos " . BASEDATOS . " contiene la tabla Articulos."; }*/ } - + private function existenDatos() { //Comprueba si existe la tabla Articulos $sql = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS); - if ($sql->error()) + if ($sql->error()) { return false; + } $sql->ejecuta('select * from Articulos;'); - if ($sql->error()) + if ($sql->error()) { return false; + } + return true; } - + public function ejecuta() { $paso = isset($_GET['paso']) ? $_GET['paso'] : 0; $paso = $paso > NUMPASOS ? '0' : $paso; - $i=0; + $i = 0; //Si quiere ir a un determinado paso se asegura que estén completos los anteriores for ($i = 0; $i < $paso; $i++) { - $funcion = "validaPaso" . $i; + $funcion = 'validaPaso'.$i; if (!$this->$funcion()) { break; } } - $funcion = "paso" . $i; + $funcion = 'paso'.$i; $this->contenido = $this->$funcion(); $salida = new Distribucion($this->plant, $this); + return $salida->procesaPlantilla(); } @@ -102,100 +108,107 @@ class Instalar { $info .= '
  • Configuración de PHP (php.ini)
  • '; // display_errors $displayErr = ini_get('display_errors'); - $displayErr = $displayErr == "1" || $displayErr == "on" ? "on" : "off"; - $mensaje = $displayErr == "off" ? $this->retornaLabel(false,'Se debe deshabilitar la impresión de errores') : - $this->retornaLabel(true, 'Se debe deshabilitar la impresión de errores', "warning"); + $displayErr = $displayErr == '1' || $displayErr == 'on' ? 'on' : 'off'; + $mensaje = $displayErr == 'off' ? $this->retornaLabel(false, 'Se debe deshabilitar la impresión de errores') : + $this->retornaLabel(true, 'Se debe deshabilitar la impresión de errores', 'warning'); $info .= $this->retornaElemento($mensaje, 'display_errors', $displayErr); // post_max_size $postMax = ini_get('post_max_size'); - $mensaje = $this->retornaBytes($postMax) >= MINBYTES ? $this->retornaLabel(false, 'Mínimo: ' . CADENAMINBYTES) : - $this->retornaLabel(true, 'Mínimo: ' . CADENAMINBYTES); + $mensaje = $this->retornaBytes($postMax) >= MINBYTES ? $this->retornaLabel(false, 'Mínimo: '.CADENAMINBYTES) : + $this->retornaLabel(true, 'Mínimo: '.CADENAMINBYTES); $info .= $this->retornaElemento($mensaje, 'post_max_size', $postMax); // upload_max_filesize $uploadMax = ini_get('upload_max_filesize'); - $mensaje = $this->retornaBytes($uploadMax) >= MINBYTES ? $this->retornaLabel(false, 'Mínimo: ' . CADENAMINBYTES) : - $this->retornaLabel(true, 'Mínimo: ' . CADENAMINBYTES); + $mensaje = $this->retornaBytes($uploadMax) >= MINBYTES ? $this->retornaLabel(false, 'Mínimo: '.CADENAMINBYTES) : + $this->retornaLabel(true, 'Mínimo: '.CADENAMINBYTES); $info .= $this->retornaElemento($mensaje, 'upload_max_filesize', $uploadMax); // mysqli $mysql = extension_loaded('mysqli'); - $mysql = $mysql ? "on" : "off"; + $mysql = $mysql ? 'on' : 'off'; $mensaje = $mysql ? $this->retornaLabel(false, 'Tiene que estar cargada la extensión MySQLi para poder funcionar') : $this->retornaLabel(true, 'Tiene que estar cargada la extensión MySQLi para poder funcionar'); $info .= $this->retornaElemento($mensaje, 'extensión MySQLi', $mysql); $info .= '
  • Configuración de la Aplicación
  • '; // img.dat - $mensaje = is_writable(IMAGEDATA) ? $this->retornaLabel(false, "Se debe poder escribir en el directorio " . IMAGEDATA) : - $this->retornaLabel(true, "Se debe poder escribir en el directorio " . IMAGEDATA); - $valor = is_writable(IMAGEDATA) ? "Sí" : "No"; - $info .= $this->retornaElemento($mensaje, 'Se puede escribir en ' . IMAGEDATA, $valor); - + $mensaje = is_writable(IMAGEDATA) ? $this->retornaLabel(false, 'Se debe poder escribir en el directorio '.IMAGEDATA) : + $this->retornaLabel(true, 'Se debe poder escribir en el directorio '.IMAGEDATA); + $valor = is_writable(IMAGEDATA) ? 'Sí' : 'No'; + $info .= $this->retornaElemento($mensaje, 'Se puede escribir en '.IMAGEDATA, $valor); + // tmp - $mensaje = is_writable(TMP) ? $this->retornaLabel(false, "Se debe poder escribir en el directorio " . TMP) : - $this->retornaLabel(true, "Se debe poder escribir en el directorio " . TMP); - $valor = is_writable(TMP) ? "Sí" : "No"; - $info .= $this->retornaElemento($mensaje, 'Se puede escribir en ' . TMP, $valor); - + $mensaje = is_writable(TMP) ? $this->retornaLabel(false, 'Se debe poder escribir en el directorio '.TMP) : + $this->retornaLabel(true, 'Se debe poder escribir en el directorio '.TMP); + $valor = is_writable(TMP) ? 'Sí' : 'No'; + $info .= $this->retornaElemento($mensaje, 'Se puede escribir en '.TMP, $valor); + // inc - $mensaje = is_writable(INC) ? $this->retornaLabel(false, "Se debe poder escribir en el directorio " . INC) : - $this->retornaLabel(true, "Se debe poder escribir en el directorio " . INC); - $valor = is_writable(INC) ? "Sí" : "No"; - $info .= $this->retornaElemento($mensaje, 'Se puede escribir en ' . INC, $valor); - + $mensaje = is_writable(INC) ? $this->retornaLabel(false, 'Se debe poder escribir en el directorio '.INC) : + $this->retornaLabel(true, 'Se debe poder escribir en el directorio '.INC); + $valor = is_writable(INC) ? 'Sí' : 'No'; + $info .= $this->retornaElemento($mensaje, 'Se puede escribir en '.INC, $valor); + // configuracion.inc - $mensaje = is_writable(CONFIGURACION) ? $this->retornaLabel(false, "Se debe poder escribir en el fichero de configuración ". CONFIGURACION) : - $this->retornaLabel(true, "Se debe poder escribir en el fichero de configuración ". CONFIGURACION); - $valor = is_writable(CONFIGURACION) ? "Sí" : "No"; - $info .= $this->retornaElemento($mensaje, 'Se puede escribir en ' . CONFIGURACION, $valor); - + $mensaje = is_writable(CONFIGURACION) ? $this->retornaLabel(false, 'Se debe poder escribir en el fichero de configuración '.CONFIGURACION) : + $this->retornaLabel(true, 'Se debe poder escribir en el fichero de configuración '.CONFIGURACION); + $valor = is_writable(CONFIGURACION) ? 'Sí' : 'No'; + $info .= $this->retornaElemento($mensaje, 'Se puede escribir en '.CONFIGURACION, $valor); + // Final del paso - $info .=''; - $info .= $this->validaPaso0() ? $this->retornaBoton(false, "Instalar.php?paso=1") : $this->retornaBoton(true, "Instalar.php"); + $info .= ''; + $info .= $this->validaPaso0() ? $this->retornaBoton(false, 'Instalar.php?paso=1') : $this->retornaBoton(true, 'Instalar.php'); $panel = $this->panelMensaje($info, 'primary', 'PASO 1: Configuración del servidor y la aplicación'); + return $panel; } + private function retornaElemento($validacion, $mensaje, $valor) { $info = '
  • '; - $info .= $validacion . ' ' . $mensaje . ': ' . $valor . ''; + $info .= $validacion.' '.$mensaje.': '.$valor.''; $info .= '
  • '; + return $info; } - + private function retornaBoton($error, $paso, $javascript = true) { - $anadido = $javascript ? 'onclick="location.href=' . "'" . $paso . "'". '"' : ''; + $anadido = $javascript ? 'onclick="location.href='."'".$paso."'".'"' : ''; if (!$error) { - return ''; + return ''; } else { - return ''; + return ''; } } - + private function botonVolver($enlace) { - $boton = ''; + $boton = ''; + return $boton; } - - private function retornaLabel($error, $mensaje, $tipo = "danger") + + private function retornaLabel($error, $mensaje, $tipo = 'danger') { if ($error) { - $nombre1 = $tipo; $nombre2 = "remove"; + $nombre1 = $tipo; + $nombre2 = 'remove'; } else { - $nombre1 = "success"; $nombre2 = "ok"; + $nombre1 = 'success'; + $nombre2 = 'ok'; } - $mensaje = ''; - $mensaje .=''; + $mensaje .= ''; + return $mensaje; } - - private function retornaBytes($val) + + private function retornaBytes($val) { $val = trim($val); - $last = strtolower($val[strlen($val)-1]); - switch($last) { + $last = strtolower($val[strlen($val) - 1]); + switch ($last) { // El modificador 'G' está disponble desde PHP 5.1.0 case 'g': $val *= 1024; @@ -204,12 +217,13 @@ class Instalar { case 'k': $val *= 1024; } + return $val; } - + private function validaPaso0() { - $validar = true; + $validar = true; $postMax = ini_get('post_max_size'); $uploadMax = ini_get('upload_max_filesize'); $mysql = extension_loaded('mysqli'); @@ -217,33 +231,41 @@ class Instalar { $escInc = is_writable(INC); $escTMP = is_writable(TMP); $escIMG = is_writable(IMAGEDATA); - if ($this->retornaBytes($postMax) < MINBYTES) + if ($this->retornaBytes($postMax) < MINBYTES) { $validar = false; - if ($this->retornaBytes($uploadMax) < MINBYTES) + } + if ($this->retornaBytes($uploadMax) < MINBYTES) { $validar = false; - if (!$mysql) + } + if (!$mysql) { $validar = false; - if (!$escConfig) + } + if (!$escConfig) { $validar = false; - if (!$escTMP) + } + if (!$escTMP) { $validar = false; - if (!$escIMG) + } + if (!$escIMG) { $validar = false; - if (!$escInc) + } + if (!$escInc) { $validar = false; + } + return $validar; } - + private function actualizaConfiguracion($grabar, $campos, &$datos) { $conf = new Configuracion(); $fichero = $conf->obtieneFichero(); $datosFichero = explode("\n", $fichero); if ($grabar) { - $fsalida = @fopen(CONFIGTMP, "wb"); + $fsalida = @fopen(CONFIGTMP, 'wb'); } foreach ($datosFichero as $linea) { - if (stripos($linea, "DEFINE") !== false) { + if (stripos($linea, 'DEFINE') !== false) { $conf->obtieneDatos($linea, $clave, $valor); if (stripos($campos, $clave) !== false) { if ($grabar) { @@ -253,7 +275,7 @@ class Instalar { } $datos[$clave] = $valor; } - $registro = substr($linea, 0, 2) == "?>" ? $linea : $linea . "\n"; + $registro = substr($linea, 0, 2) == '?>' ? $linea : $linea."\n"; if ($grabar) { fwrite($fsalida, $registro); } @@ -261,10 +283,10 @@ class Instalar { if ($grabar) { fclose($fsalida); unlink(CONFIGURACION); - rename(CONFIGTMP, CONFIGURACION); + rename(CONFIGTMP, CONFIGURACION); } } - + // Cuestiones de la base de datos private function paso1() { @@ -276,35 +298,37 @@ class Instalar { $datos[$clave] = $valor; } } else { - $datos = array(); + $datos = []; } $this->actualizaConfiguracion($grabar, $campos, $datos); if ($grabar && $this->validaPaso1()) { - //Pasa al paso siguiente - return $this->paso2(); + //Pasa al paso siguiente + return $this->paso2(); } - - $info = ''; + + $info = ''; $info .= '
      '; $info .= '
    • Datos de configuración
    • '; - $info .= '
    • Servidor
    • '; - $info .= '
    • Puerto
    • '; - $info .= '
    • Base de Datos
    • '; - $info .= '
    • Usuario
    • '; - $info .= '
    • Contraseña
    • '; + $info .= '
    • Servidor
    • '; + $info .= '
    • Puerto
    • '; + $info .= '
    • Base de Datos
    • '; + $info .= '
    • Usuario
    • '; + $info .= '
    • Contraseña
    • '; $info .= '
    '; - $info .= $this->botonVolver("Instalar.php"); - $info .= $this->validaPaso1() ? $this->retornaBoton(false, "Instalar.php?paso=1", false) : $this->retornaBoton(true, "Instalar.php?paso=1", false); + $info .= $this->botonVolver('Instalar.php'); + $info .= $this->validaPaso1() ? $this->retornaBoton(false, 'Instalar.php?paso=1', false) : $this->retornaBoton(true, 'Instalar.php?paso=1', false); $info .= ''; $panel = $this->panelMensaje($info, 'primary', 'PASO 2: Configuración de la Base de Datos.'); + return $panel; } - + private function validaPaso1() { $sql = new Sql(SERVIDOR, USUARIO, CLAVE, ''); - if ($sql->error()) + if ($sql->error()) { return false; + } $sql = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS); if ($sql->error()) { return false; @@ -319,17 +343,18 @@ class Instalar { if ($sql->error()) { return false; } - return true; + + return true; } - + // Usuario administrador private function paso2() { if (isset($_POST['usuario'])) { //ha enviado el formulario. //Crea la base de datos - $borra_database = "DROP DATABASE " . BASEDATOS . " ;"; - $database = "CREATE DATABASE " . BASEDATOS . " DEFAULT CHARACTER SET utf8;"; + $borra_database = 'DROP DATABASE '.BASEDATOS.' ;'; + $database = 'CREATE DATABASE '.BASEDATOS.' DEFAULT CHARACTER SET utf8;'; $articulos = "CREATE TABLE `Articulos` ( `id` smallint(6) NOT NULL auto_increment COMMENT 'ordenable,link/Articulo', `descripcion` varchar(60) NOT NULL COMMENT 'ordenable,ajax/text', @@ -379,41 +404,42 @@ class Instalar { KEY `nombre` (`nombre`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; "; - $letras = "abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; + $letras = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; $sesion = substr(str_shuffle($letras), 0, 8); $usuario = $_POST['usuario']; $clave = $_POST['clave']; $administrador = "insert into Usuarios values (null,'$usuario','$clave','$sesion','1','1','1','1','1','1','1');"; - + @mysqli_query($borra_database); @mysqli_query($database); $sql = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS); $sql->ejecuta($ubicaciones); if ($sql->error()) { - return $this->panelMensaje($sql->mensajeError(), "danger", "ERROR"); + return $this->panelMensaje($sql->mensajeError(), 'danger', 'ERROR'); } $sql->ejecuta($articulos); if ($sql->error()) { - return $this->panelMensaje($sql->mensajeError(), "danger", "ERROR"); + return $this->panelMensaje($sql->mensajeError(), 'danger', 'ERROR'); } $sql->ejecuta($elementos); if ($sql->error()) { - return $this->panelMensaje($sql->mensajeError(), "danger", "ERROR"); + return $this->panelMensaje($sql->mensajeError(), 'danger', 'ERROR'); } $sql->ejecuta($usuarios); if ($sql->error()) { - return $this->panelMensaje($sql->mensajeError(), "danger", "ERROR"); + return $this->panelMensaje($sql->mensajeError(), 'danger', 'ERROR'); } $sql->ejecuta($administrador); - if ($sql->error()) { - return $this->panelMensaje($sql->mensajeError(), "danger", "ERROR"); + if ($sql->error()) { + return $this->panelMensaje($sql->mensajeError(), 'danger', 'ERROR'); } - $campos="INSTALADO"; - $datos['INSTALADO'] = "sí"; + $campos = 'INSTALADO'; + $datos['INSTALADO'] = 'sí'; $this->actualizaConfiguracion(true, $campos, $datos); + return $this->resumen(); } - + $info = '
    @@ -435,69 +461,74 @@ class Instalar {
    - ' . $this->botonVolver("Instalar.php?paso=1") . ' + '.$this->botonVolver('Instalar.php?paso=1').'
    '; $panel = $this->panelMensaje($info, 'primary', 'PASO 3: Creación de la base de datos y el usuario administrador.'); - return $panel; + + return $panel; } - + private function validaPaso2() { //La validación de este paso se hace con la del formulario en javascript return true; } - - public function panelMensaje($info, $tipo = "info", $cabecera = "¡Atención!") { - $mensaje = '
    '; - $mensaje .= '

    ' . $cabecera . '

    '; + + public function panelMensaje($info, $tipo = 'info', $cabecera = '¡Atención!') + { + $mensaje = '
    '; + $mensaje .= '

    '.$cabecera.'

    '; $mensaje .= '
    '; $mensaje .= $info; $mensaje .= '
    '; $mensaje .= '
    '; + return $mensaje; } - + public function contenido() { return $this->contenido; } - + public function menu() { return ''; } - + public function opcion() { return 'INSTALACIÓN'; } - + public function control() { return ''; } - + public function aplicacion() { - return PROGRAMA . ' v' . VERSION; + return PROGRAMA.' v'.VERSION; } - + public function usuario() { return ''; } - + public function fecha() { $idioma = 'es_ES'; - $formato = "%d-%b-%y"; + $formato = '%d-%b-%y'; setlocale(LC_TIME, $idioma); + return strftime($formato); } + public function cabecera() { return ' @@ -527,32 +558,31 @@ class Instalar { '; } - + public function panelError() { $mensaje = $this->cabecera(); - $mensaje .= $this->panelMensaje($this->error_msj, "danger", "¡ERROR!"); - $mensaje .= ""; + $mensaje .= $this->panelMensaje($this->error_msj, 'danger', '¡ERROR!'); + $mensaje .= ''; + return $mensaje; } - + private function resumen() { $info = '
      '; $info .= '
    • Paso 1
    • '; - $info .= $this->retornaElemento($this->retornaLabel(false, ""), "Configuración de PHP"); - $info .= $this->retornaElemento($this->retornaLabel(false, ""), "Configuración de la aplicación"); + $info .= $this->retornaElemento($this->retornaLabel(false, ''), 'Configuración de PHP'); + $info .= $this->retornaElemento($this->retornaLabel(false, ''), 'Configuración de la aplicación'); $info .= '
    • Paso 2
    • '; - $info .= $this->retornaElemento($this->retornaLabel(false, ""), "Configuración de la base de datos"); + $info .= $this->retornaElemento($this->retornaLabel(false, ''), 'Configuración de la base de datos'); $info .= '
    • Paso 3
    • '; - $info .= $this->retornaElemento($this->retornaLabel(false, ""), "Creación de Base de datos"); - $info .= $this->retornaElemento($this->retornaLabel(false, ""), "Creación del usuario administrador"); + $info .= $this->retornaElemento($this->retornaLabel(false, ''), 'Creación de Base de datos'); + $info .= $this->retornaElemento($this->retornaLabel(false, ''), 'Creación del usuario administrador'); $info .= '
    '; - $info .= $this->retornaBoton(false, "index.php", true); + $info .= $this->retornaBoton(false, 'index.php', true); $panel = $this->panelMensaje($info, 'success', 'Instalación finalizada.'); + return $panel; - } } - -?> \ No newline at end of file diff --git a/Inventario.php b/Inventario.php index 404d5bd..ef4a1c3 100644 --- a/Inventario.php +++ b/Inventario.php @@ -2,9 +2,11 @@ /** * Clase Inventario que controla la ejecución principal del programa. + * * @author Ricardo Montañana Gómez + * * @version 1.0 - * @package Inventario + * * @copyright Copyright (c) 2008, Ricardo Montañana Gómez * @license http://www.gnu.org/licenses/gpl-3.0.txt * This file is part of Inventario. @@ -12,23 +14,22 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. - * + * * Inventario is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with Inventario. If not, see . - * */ // Clase del objeto principal de la aplicación -class Inventario { - +class Inventario +{ // Declaración de miembros private $bdd; // Enlace con el SGBD private $registrado; // Usuario registrado s/n - private $usuario = NULL; // Nombre del usuario + private $usuario = null; // Nombre del usuario private $clave; //contraseña del usuario private $opcActual; // Opción elegida por el usuario private $perfil; //Permisos del usuario. @@ -36,13 +37,15 @@ class Inventario { private $plant; // Constructor - public function __construct() { + public function __construct() + { // Analizamos la cadena de solicitud para saber // qué opción es la actual $this->opcActual = $_SERVER['QUERY_STRING'] == '' ? 'principal' : $_SERVER['QUERY_STRING']; //Si el programa no está instalado, llama al instalador. - if (INSTALADO == "no") { + if (INSTALADO == 'no') { header('location: Instalar.php'); + return; } // Iniciamos una sesión @@ -50,25 +53,25 @@ class Inventario { //Conexión con la base de datos. $this->bdd = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS); if ($this->bdd->error()) { - echo '

    Fallo al conectar con el servidor MySQL.

    '; - echo "Servidor [ " . SERVIDOR . " ] base de datos [" . BASEDATOS . "]"; + echo 'Servidor [ '.SERVIDOR.' ] base de datos ['.BASEDATOS.']'; $this->estado = false; + return; } else { $this->estado = true; } //Selecciona la plantilla a utilizar - $this->plant='plant/'; - $this->plant.=PLANTILLA; - $this->plant.='.html'; + $this->plant = 'plant/'; + $this->plant .= PLANTILLA; + $this->plant .= '.html'; // Comprobamos si el usuario ya está registrado en esta sesión $this->registrado = isset($_SESSION['Registrado']); if ($this->registrado) {// si está... // recuperamos el nombre del usuario $this->usuario = $_SESSION['Usuario']; $this->perfil = $_SESSION['Perfil']; - // en caso contrario comprobamos si tiene la cookie que le identifica como usuario + // en caso contrario comprobamos si tiene la cookie que le identifica como usuario } elseif (isset($_COOKIE['InventarioId'])) { // y usamos el Id para recuperar el nombre de la base de ddtos $this->recuperaNombreConId($_COOKIE['InventarioId']); @@ -77,14 +80,16 @@ class Inventario { } } - public function estado() { + public function estado() + { return $this->estado; } // Esta función pondrá en marcha la aplicación ocupándose // de las acciones que no generan contenido, esto es // iniciar sesión, cerrarla, etc. - public function Ejecuta() { + public function Ejecuta() + { // Dependiendo de la opción a procesar switch ($this->opcActual) { // El usuario quiere cerrar la sesión actual @@ -118,7 +123,7 @@ class Inventario { header('location:index.php?usuario_incorrecto'); exit; case 'usuario_incorrecto': - $this->opcActual = "principal"; + $this->opcActual = 'principal'; $contenido = $this->creaContenido(); $contenido->usuario_incorrecto(); $salida = new Distribucion($this->plant, $contenido); @@ -132,18 +137,20 @@ class Inventario { $salida = new Distribucion($this->plant, $this->creaContenido()); echo $salida->procesaPlantilla(); break; - + } } - private function creaContenido() { + private function creaContenido() + { return new AportaContenido($this->bdd, $this->registrado, $this->usuario, $this->perfil, $this->opcActual); } // Esta función comprueba si el usuario está o no registrado, // devolviendo su IdSesion en caso afirmativo o false // en caso contrario - private function usuarioRegistrado() { + private function usuarioRegistrado() + { $this->usuario = $_POST['usuario']; $this->clave = $_POST['clave']; // ejecuta la consulta para buscar el usuario @@ -167,10 +174,11 @@ class Inventario { return false; } - private function creaPerfil($fila) { - return array("Consulta" => $fila['consulta'], "Modificacion" => $fila['modificacion'], - "Alta" => $fila['alta'], "Borrado" => $fila['borrado'], "Informe" => $fila['informe'], - "Usuarios" => $fila['usuarios'], "Config" => $fila['config']); + private function creaPerfil($fila) + { + return ['Consulta' => $fila['consulta'], 'Modificacion' => $fila['modificacion'], + 'Alta' => $fila['alta'], 'Borrado' => $fila['borrado'], 'Informe' => $fila['informe'], + 'Usuarios' => $fila['usuarios'], 'Config' => $fila['config']]; } // Esta función intenta recuperar el nombre del usuario @@ -178,7 +186,8 @@ class Inventario { // dejando las variables Registrado y Usuario con // los valores apropiados // @param String Identificador de sesión del usuario actual - private function recuperaNombreConId($idSesion) { + private function recuperaNombreConId($idSesion) + { // para ejecutar la consulta para buscar el Id de sesión $res = $this->bdd->ejecuta("SELECT * FROM Usuarios WHERE idSesion='$idSesion'"); // Si no hemos encontrado el ID @@ -204,5 +213,3 @@ class Inventario { } } } - -?> diff --git a/Mantenimiento.php b/Mantenimiento.php index bd6e894..7b5e478 100644 --- a/Mantenimiento.php +++ b/Mantenimiento.php @@ -1,7 +1,6 @@ . - * */ //Clase que se encargará de manejar los elementos del modelo de datos. define('EDICION', 'Edición'); @@ -25,20 +23,20 @@ define('BORRADO', 'Borrado'); define('ANADIR', 'Inserción'); define('CLONAR', 'Clonar'); -class Mantenimiento { - +class Mantenimiento +{ private $descripcion; protected $bdd; protected $url; protected $tabla; protected $cadenaBusqueda; - protected $campos = array(); - protected $foraneas = array(); - protected $campoBusca = "Descripcion"; - protected $comandoConsulta = ""; + protected $campos = []; + protected $foraneas = []; + protected $campoBusca = 'Descripcion'; + protected $comandoConsulta = ''; protected $perfil; - protected $datosURL = array(); - protected $datosURLb = array(); //para hacer una copia + protected $datosURL = []; + protected $datosURLb = []; //para hacer una copia public function __construct($baseDatos, $perfil, $nombre) { @@ -59,7 +57,7 @@ class Mantenimiento { * - pag = nº página 0, 1, 2, ... * Los datos opcionales de la URL son: * - buscar = cadena de búsqueda - * - id = nº de la clave necesario para la edición o el borrado + * - id = nº de la clave necesario para la edición o el borrado. */ public function cargaDatosURL() { @@ -72,32 +70,33 @@ class Mantenimiento { $this->datosURL['buscar'] = $this->cadenaBusqueda; $this->datosURL['id'] = isset($_GET['id']) ? $_GET['id'] : null; } - + public function backupURL() { $this->datosURLb = $this->datosURL; } - + public function restoreURL() { $this->datosURL = $this->datosURLb; } - + //Monta una URL con los datos cargados en los atributos de la clase private function montaURL() { //Primero los datos obligatorios - $opc = "&opc=" . $this->datosURL['opc']; - $orden = "&orden=" . $this->datosURL['orden']; - $sentido = "&sentido=" . $this->datosURL['sentido']; - $pag = "&pag=" . $this->datosURL['pag']; + $opc = '&opc='.$this->datosURL['opc']; + $orden = '&orden='.$this->datosURL['orden']; + $sentido = '&sentido='.$this->datosURL['sentido']; + $pag = '&pag='.$this->datosURL['pag']; //Ahora los datos opcionales //$buscar = isset($this->cadenaBusqueda) ? '&buscar="'.$this->cadenaBusqueda.'"' : null; //$buscar = isset($this->cadenaBusqueda) ? "&buscar='$this->cadenaBusqueda'" : null; //$buscar = isset($this->cadenaBusqueda) ? "&buscar=$this->cadenaBusqueda" : null; - $buscar = isset($this->cadenaBusqueda) ? "&buscar=" . urlencode($this->cadenaBusqueda) : null; - $id = isset($this->datosURL['id']) ? "&id=" . $this->datosURL['id'] : null; - $enlace = $this->url . $opc . $orden . $sentido . $pag . $buscar . $id; + $buscar = isset($this->cadenaBusqueda) ? '&buscar='.urlencode($this->cadenaBusqueda) : null; + $id = isset($this->datosURL['id']) ? '&id='.$this->datosURL['id'] : null; + $enlace = $this->url.$opc.$orden.$sentido.$pag.$buscar.$id; + return $enlace; } @@ -114,27 +113,27 @@ class Mantenimiento { case 'modificar':return $this->modificar(); case 'borrar':return $this->borrar(); case 'clonar': return $this->muestra(CLONAR); - default: return "La clase Mantenimiento No entiende lo solicitado [" . $this->datosURL['opc'] . "]"; + default: return 'La clase Mantenimiento No entiende lo solicitado ['.$this->datosURL['opc'].']'; } } private function clonar() { - } + protected function obtieneClavesForaneas() { $salida = null; foreach ($this->campos as $clave => $valor) { - $trozos = explode(",", $valor["Comment"]); + $trozos = explode(',', $valor['Comment']); foreach ($trozos as $trozo) { - if (strstr($trozo, "foreign")) { + if (strstr($trozo, 'foreign')) { $temp = substr($trozo, 8, -1); - list($tabla, $atributos) = explode("->", $temp); - list($clave, $resto) = explode(";", $atributos); + list($tabla, $atributos) = explode('->', $temp); + list($clave, $resto) = explode(';', $atributos); //Quita el paréntesis final $atributos = substr($atributos, 0, -1); - $salida[$valor['Campo']] = $tabla . "," . $resto; + $salida[$valor['Campo']] = $tabla.','.$resto; } } } @@ -148,28 +147,28 @@ class Mantenimiento { //Calcula los números de página anterior y siguiente. $pagina = $this->datosURL['pag']; $pagSigte = $pagina <= 0 ? 1 : $pagina + 1; - $pagAnt = $pagSigte - 2 < 0 ? 0 : $pagSigte -2; + $pagAnt = $pagSigte - 2 < 0 ? 0 : $pagSigte - 2; $pagFwd = $pagSigte + 3; $pagRew = $pagAnt - 3 < 0 ? 0 : $pagAnt - 3; //Tengo que procesar la cabecera antes de lo de la cadena de búsqueda por el tema de las búsquedas $cabecera = $this->cabeceraTabla(); //Trata con la cadena de búsqueda si viene del post debe quedarse con ella sino con la del get y si no está definida => vacía if (isset($this->cadenaBusqueda) && strlen($this->cadenaBusqueda)) { - $sufijo = " where $this->campoBusca like '%" . $this->bdd->filtra(urldecode($this->cadenaBusqueda)) . "%'"; + $sufijo = " where $this->campoBusca like '%".$this->bdd->filtra(urldecode($this->cadenaBusqueda))."%'"; $comando = str_replace('{buscar}', $sufijo, $this->comandoConsulta); } else { $comando = str_replace('{buscar}', '', $this->comandoConsulta); } //Trata con el orden de mostrar los datos if (strlen($orden) > 0) { - $comando = str_replace('{orden}', "order by " . $orden . " " . $sentido, $comando); - $sufijoOrden = "&orden=" . $orden . "&sentido=" . $sentido; + $comando = str_replace('{orden}', 'order by '.$orden.' '.$sentido, $comando); + $sufijoOrden = '&orden='.$orden.'&sentido='.$sentido; } else { $comando = str_replace('{orden}', ' ', $comando); } $salida = $this->cargaComplementos(); //Introduce un botón para hacer búsquedas y el número de la página - $salida.= $this->enlaceBusqueda($pagSigte); + $salida .= $this->enlaceBusqueda($pagSigte); //Consulta paginada de todas las tuplas $comando = str_replace('{inferior}', $pagina * NUMFILAS, $comando); $comando = str_replace('{superior}', NUMFILAS, $comando); @@ -188,54 +187,54 @@ class Mantenimiento { $pagFwd = $pagFwd > $totalPags ? $totalPags : $pagFwd; if ($this->bdd->numeroTuplas() == 0) { if ($pagSigte > 1) { - // Si no hay datos en la consulta y no es la primera página, + // Si no hay datos en la consulta y no es la primera página, // carga la página final $this->datosURL['pag'] = $totalPags; - header('Location: ' . $this->montaURL()); + header('Location: '.$this->montaURL()); } else { $salida .= '

    No hay registros
    '; } } else { - $salida.= $cabecera; + $salida .= $cabecera; } //$salida.=$comando; //$salida.=var_export($this->campos,true); $cant = 0; while ($fila = $this->bdd->procesaResultado()) { - $salida.=''; + $salida .= ''; foreach ($fila as $clave => $valor) { - if ($clave == "id") { + if ($clave == 'id') { $id = $valor; } - if ($this->campos[$clave]['Visible'] == "no") { + if ($this->campos[$clave]['Visible'] == 'no') { continue; } // Comprueba si tiene que añadir el enlace de inventario - if (strstr($this->campos[$clave]['Comment'], "link")) { - $comen = explode(",", $this->campos[$clave]['Comment']); + if (strstr($this->campos[$clave]['Comment'], 'link')) { + $comen = explode(',', $this->campos[$clave]['Comment']); foreach ($comen as $co) { - if (strstr($co, "link")) { - $tmpco = explode("/", $co); + if (strstr($co, 'link')) { + $tmpco = explode('/', $co); $datoEnlace = $tmpco[1]; } } - $this->campoBusca = isset($dato[1]) ? $dato[1] : ""; - $valor = '' . $valor; + $this->campoBusca = isset($dato[1]) ? $dato[1] : ''; + $valor = ''.$valor; } - if (strstr($this->campos[$clave]['Comment'], "imagen") && isset($valor)) { - $msj = ''; + if (strstr($this->campos[$clave]['Comment'], 'imagen') && isset($valor)) { + $msj = ''; $msj .= $this->creaModal($valor, $id); $valor = $msj; } - if ($this->campos[$clave]['Type'] == "Boolean(1)") { + if ($this->campos[$clave]['Type'] == 'Boolean(1)') { $checked = $valor == '1' ? 'checked' : ''; - $valor = ''; + $valor = ''; } - if (strstr($this->campos[$clave]['Comment'], "ajax") && $this->perfil['Modificacion']) { - $comen = explode(",", $this->campos[$clave]['Comment']); + if (strstr($this->campos[$clave]['Comment'], 'ajax') && $this->perfil['Modificacion']) { + $comen = explode(',', $this->campos[$clave]['Comment']); foreach ($comen as $co) { - if (strstr($co, "ajax")) { - $tmpco = explode("/", $co); + if (strstr($co, 'ajax')) { + $tmpco = explode('/', $co); $tipo = $tmpco[1]; } } @@ -250,51 +249,57 @@ class Mantenimiento { case 'C': $alineacion = 'align="center"'; break; } } - $salida.="$valor\n"; + $salida .= "$valor\n"; } //Añade los botones de acciones $salida .= ''; //Añade el icono de clonar if ($this->perfil['Alta']) { //$salida.='datosURL['id'] = $id; + $this->backupURL(); + $this->datosURL['opc'] = 'clonar'; + $this->datosURL['id'] = $id; if (ESTILO == 'bootstrap') { - $salida.='  '; + $salida .= '  '; } else { - $salida.='clonar  '; - } + $salida .= 'clonar  '; + } $this->restoreURL(); } //Añade el icono de editar if ($this->perfil['Modificacion']) { //$salida.='datosURL['id'] = $id; + $this->backupURL(); + $this->datosURL['opc'] = 'editar'; + $this->datosURL['id'] = $id; if (ESTILO == 'bootstrap') { - $salida.=''; + $salida .= ''; } else { - $salida.='editar'; - } + $salida .= 'editar'; + } $this->restoreURL(); } //Añade el icono de eliminar if ($this->perfil['Borrado']) { //$salida.='  datosURL['id'] = $id; + $this->backupURL(); + $this->datosURL['opc'] = 'eliminar'; + $this->datosURL['id'] = $id; if (ESTILO == 'bootstrap') { - $salida.='  '; + $salida .= '  '; } else { - $salida.='  eliminar' . "\n"; - } + $salida .= '  eliminar'."\n"; + } $this->restoreURL(); } - $salida .= ""; + $salida .= ''; } - $salida.="

    "; + $salida .= '

    '; //Añade botones de comandos - + if ($numRegistros) { $this->backupURL(); $this->datosURL['pag'] = $pagAnt; @@ -304,13 +309,13 @@ class Mantenimiento { $this->datosURL['pag'] = $pagFwd; $fwd = $this->montaURL(); $this->datosURL['pag'] = $pagRew; - $rew = $this->montaURL(); + $rew = $this->montaURL(); $this->restoreURL(); - $this->datosURL['sentido'] = "asc"; + $this->datosURL['sentido'] = 'asc'; $az = $this->montaURL(); // //$az = '

    '; - $this->datosURL['sentido'] = "desc"; + $this->datosURL['sentido'] = 'desc'; $za = $this->montaURL(); // //$za = '

    '; @@ -320,60 +325,62 @@ class Mantenimiento { $fwd = ''; $rew = ''; $az = ''; - $za = ''; + $za = ''; } else { - $anterior = '\"anterior\"\n"; - $siguiente = '\"siguiente\"\n"; - $fwd = '\"mas4pags\"\n"; - $rew = '\"menos4pags\"\n"; - $az = 'asc'; - $za = 'desc'; + $anterior = 'anterior\n"; + $siguiente = 'siguiente\n"; + $fwd = 'mas4pags\n"; + $rew = 'menos4pags\n"; + $az = 'asc'; + $za = 'desc'; } $this->restoreURL(); if ($this->perfil['Informe']) { - $this->datosURL['opc'] = "informe"; + $this->datosURL['opc'] = 'informe'; $inf = $this->montaURL(); if (ESTILO == 'bootstrap') { $informe = ''; } else { - $informe = 'informe'; + $informe = 'informe'; } // - + //$informe = '

    '; } else { - $informe = ""; + $informe = ''; } $this->restoreURL(); } else { - $anterior = $rew = $az = $informe = $za = $siguiente = $fwd = ""; + $anterior = $rew = $az = $informe = $za = $siguiente = $fwd = ''; } if ($this->perfil['Alta']) { $this->datosURL['opc'] = 'nuevo'; if (ESTILO == 'bootstrap') { - $anadir = ''; + $anadir = ''; } else { - $anadir = '' . - 'nuevo'; - } - //$anadir = '

    '; + $anadir = ''. + 'nuevo'; + } + //$anadir = '

    '; } else { - $anadir = ""; + $anadir = ''; } - $salida .= '

    ' . - "$rew  $anterior  $az  $anadir  $informe  $za  $siguiente  $fwd

    "; + $salida .= '

    '. + "$rew  $anterior  $az  $anadir  $informe  $za  $siguiente  $fwd

    "; + return $salida; } private function enlaceBusqueda($pagina) { - $valor = isset($this->cadenaBusqueda) ? 'value="' . $this->cadenaBusqueda . '"' : ''; + $valor = isset($this->cadenaBusqueda) ? 'value="'.$this->cadenaBusqueda.'"' : ''; $salida = '
    - +
    '; $salida .= ''; + .$pagina.''; + return $salida; } @@ -381,7 +388,7 @@ class Mantenimiento { { //@todo hay que tener en cuenta aquí la cadena de búsqueda y la página en la url $id = $this->datosURL['id']; - $comando = "delete from " . $this->tabla . " where id=\"$id\""; + $comando = 'delete from '.$this->tabla." where id=\"$id\""; if (!$this->bdd->ejecuta($comando)) { return $this->errorBD($comando); } @@ -390,56 +397,56 @@ class Mantenimiento { //Comprueba si existe la imagen en datos para borrarla. Imagen::borraImagenId($this->tabla, $id); $url = $this->montaURL(); - header('Location: ' . $url); - return; + header('Location: '.$url); } protected function insertar() { - $comando = "insert into " . $this->tabla . " ("; - $lista = explode("&", $_POST['listacampos']); + $comando = 'insert into '.$this->tabla.' ('; + $lista = explode('&', $_POST['listacampos']); $primero = true; $hayImagen = false; //Añade la lista de campos foreach ($lista as $campo) { - if ($campo == "") { + if ($campo == '') { continue; } if ($primero) { $primero = false; - $coma = " "; + $coma = ' '; } else { - $coma = ","; + $coma = ','; } - $comando.="$coma $campo"; + $comando .= "$coma $campo"; } - $comando.=") values ("; + $comando .= ') values ('; //Añade la lista de valores $primero = true; foreach ($lista as $campo) { - if ($campo == "") + if ($campo == '') { continue; + } if ($primero) { $primero = false; - $coma = " "; + $coma = ' '; } else { - $coma = ","; + $coma = ','; } if (isset($this->campos[$campo]['Type']) && $this->campos[$campo]['Type'] == 'Boolean(1)') { - $valor = ""; + $valor = ''; if (empty($_POST[$campo])) { - $valor = "0"; + $valor = '0'; } - $valor = $_POST[$campo] == "on" ? '1' : $valor; + $valor = $_POST[$campo] == 'on' ? '1' : $valor; } else { - if (isset($this->campos[$campo]['Comment']) && stristr($this->campos[$campo]['Comment'], "imagen")) { + if (isset($this->campos[$campo]['Comment']) && stristr($this->campos[$campo]['Comment'], 'imagen')) { //procesa el envío de la imagen $imagen = new Imagen(); $accion = $imagen->determinaAccion($campo); if ($accion != NOHACERNADA) { // && $_POST['tipoOperacion'] != CLONAR) { - $mensaje = ""; + $mensaje = ''; if (!$imagen->procesaEnvio($campo, $mensaje)) { - return $this->panelMensaje($mensaje, "danger", "ERROR PROCESANDO IMAGEN"); + return $this->panelMensaje($mensaje, 'danger', 'ERROR PROCESANDO IMAGEN'); } $hayImagen = true; $campoImagen = $campo; @@ -448,57 +455,58 @@ class Mantenimiento { if (isset($_POST[$campo])) { $valor = $_POST[$campo]; } else { - $valor = ""; + $valor = ''; } if ($_POST['tipoOperacion'] == CLONAR && file_exists($valor)) { $hayImagen = true; $campoImagen = $campo; $valorImagen = $valor; - $valor = "null"; + $valor = 'null'; } else { - $valor = "null"; + $valor = 'null'; } } } else { - $valor = $_POST[$campo] == "" ? "null" : '"' . $this->bdd->filtra($_POST[$campo]) . '"'; + $valor = $_POST[$campo] == '' ? 'null' : '"'.$this->bdd->filtra($_POST[$campo]).'"'; } } - $comando.="$coma " . $valor; + $comando .= "$coma ".$valor; } - $comando.=")"; + $comando .= ')'; if (!$this->bdd->ejecuta($comando)) { return $this->errorBD($comando); } $id = $this->bdd->ultimoId(); if ($hayImagen) { - $mensaje = " "; + $mensaje = ' '; //Tiene que recuperar el id del registro insertado y actualizar el archivo de imagen if ($_POST['tipoOperacion'] == CLONAR) { //Tiene que copiar el archivo original. if (!$imagen->copiaImagenId($valorImagen, $this->tabla, $id, $mensaje)) { - return $this->panelMensaje($mensaje, "danger", "ERROR COPIANDO IMAGEN"); + return $this->panelMensaje($mensaje, 'danger', 'ERROR COPIANDO IMAGEN'); } $archivoImagen = $imagen->archivoCopiado; } else { //Crea el archivo de imagen if (!$imagen->mueveImagenId($this->tabla, $id, $mensaje)) { - return $this->panelMensaje($mensaje, "danger", "ERROR COMPRIMIENDO IMAGEN"); + return $this->panelMensaje($mensaje, 'danger', 'ERROR COMPRIMIENDO IMAGEN'); } $archivoImagen = $imagen->archivoComprimido; } - $comando = "update " . $this->tabla . " set " . $campoImagen . "='" . $archivoImagen . "' where id='" . $id ."';"; + $comando = 'update '.$this->tabla.' set '.$campoImagen."='".$archivoImagen."' where id='".$id."';"; if (!$this->bdd->ejecuta($comando)) { return $this->errorBD($comando); } } $this->datosURL['opc'] = 'inicial'; $this->datosURL['id'] = null; - $cabecera = "refresh:".PAUSA.";url=".$this->montaURL(); + $cabecera = 'refresh:'.PAUSA.';url='.$this->montaURL(); header($cabecera); - return $this->panelMensaje("Se ha insertado el registro con la clave " . $id, "info", "Información"); + + return $this->panelMensaje('Se ha insertado el registro con la clave '.$id, 'info', 'Información'); //return "

    montaURL()."\">Se ha insertado el registro con la clave " . $this->bdd->ultimoId() . "

    "; } - + protected function modificar() { //Los datos a utilizar para actualizar la tupla vienen en $_POST. @@ -506,75 +514,75 @@ class Mantenimiento { //print_r($_GET); //echo "id=$id pag=$pag orden=$orden sentido=$sentido";die(); //@todo hay que tener en cuenta aquí la página en la que se encuentra y la cadena de búsqueda - $comando = "update " . $this->tabla . " set "; - $lista = explode("&", $_POST['listacampos']); + $comando = 'update '.$this->tabla.' set '; + $lista = explode('&', $_POST['listacampos']); $primero = true; foreach ($lista as $campo) { - if ($campo == "id" || $campo == "") + if ($campo == 'id' || $campo == '') { continue; + } if ($primero) { $primero = false; - $coma = " "; + $coma = ' '; } else { - $coma = ","; + $coma = ','; } if ($this->campos[$campo]['Type'] == 'Boolean(1)') { - $valor = ""; + $valor = ''; if (empty($_POST[$campo])) { - $valor = "0"; + $valor = '0'; } - $valor = $_POST[$campo] == "on" ? '1' : $valor; - $comando.=$coma . ' ' . $campo . '="' . $valor . '"'; + $valor = $_POST[$campo] == 'on' ? '1' : $valor; + $comando .= $coma.' '.$campo.'="'.$valor.'"'; } else { - if (stristr($this->campos[$campo]['Comment'], "imagen")) { + if (stristr($this->campos[$campo]['Comment'], 'imagen')) { $valor = $_POST[$campo]; $imagen = new Imagen(); $accion = $imagen->determinaAccion($campo); if ($accion != NOHACERNADA) { if ($accion == HAYQUEGRABAR) { - $mensaje = ""; + $mensaje = ''; if (!$imagen->procesaEnvio($campo, $mensaje)) { - return $this->panelMensaje($mensaje, "danger", "ERROR PROCESANDO IMAGEN"); + return $this->panelMensaje($mensaje, 'danger', 'ERROR PROCESANDO IMAGEN'); } - $mensaje = ""; + $mensaje = ''; if (!$imagen->mueveImagenId($this->tabla, $this->datosURL['id'], $mensaje)) { - return $this->panelMensaje($mensaje, "danger", "ERROR COMPRIMIENDO IMAGEN"); - } - $comando .= "$coma $campo='" . $imagen->archivoComprimido . "'"; + return $this->panelMensaje($mensaje, 'danger', 'ERROR COMPRIMIENDO IMAGEN'); + } + $comando .= "$coma $campo='".$imagen->archivoComprimido."'"; } else { //Hay que borrar Imagen::borraImagenId($this->tabla, $this->datosURL['id']); - $extensiones = array("png", "jpg", "gif"); + $extensiones = ['png', 'jpg', 'gif']; $comando .= "$coma $campo=null"; } } } else { if (strlen(trim($_POST[$campo])) == 0) { - $comando.="$coma $campo=null"; + $comando .= "$coma $campo=null"; } else { - $comando.=$coma . ' ' . $campo . '="' . $this->bdd->filtra($_POST[$campo]) . '"'; + $comando .= $coma.' '.$campo.'="'.$this->bdd->filtra($_POST[$campo]).'"'; } } } } - $comando.=" where id=\"" . $this->datosURL['id'] . "\""; + $comando .= ' where id="'.$this->datosURL['id'].'"'; if (!$this->bdd->ejecuta($comando)) { return $this->errorBD($comando); } $this->datosURL['id'] = null; $this->datosURL['opc'] = inicial; - header('Location: ' . $this->montaURL()); - return; + header('Location: '.$this->montaURL()); } protected function muestra($tipoAccion) { $id = $this->datosURL['id']; if ($tipoAccion != ANADIR) { - $comando = "select * from " . $this->tabla . " where id='$id'"; + $comando = 'select * from '.$this->tabla." where id='$id'"; $resultado = $this->bdd->ejecuta($comando); if (!$resultado) { - return $this->errorBD("", "No se han podido encontrar datos del identificador $id"); + return $this->errorBD('', "No se han podido encontrar datos del identificador $id"); } $fila = $this->bdd->procesaResultado(); } else { @@ -588,10 +596,10 @@ class Mantenimiento { //tabla a la cual pertenece la clave foránea. protected function generaLista($datos, $campo, $valorInicial, $modo) { - $modoEfectivo = $modo == "readonly" ? "disabled" : ""; + $modoEfectivo = $modo == 'readonly' ? 'disabled' : ''; $salida = "\n

    "; - $salida.=""; + $salida .= "\n

    "; + $salida .= ""; + return $salida; } private function obtenerCampos() { //Si hay un fichero de descripción xml lo utiliza. - $nombre = "xml/mantenimiento" . $this->tabla . ".xml"; + $nombre = 'xml/mantenimiento'.$this->tabla.'.xml'; if (file_exists($nombre)) { $def = simplexml_load_file($nombre); foreach ($def->Campos->Col as $columna) { - $this->campos[(string) $columna['Nombre']] = array("Field" => (string) $columna['Titulo'], "Comment" => (string) $columna['Varios'], - "Type" => (string) $columna['Tipo'] . "(" . $columna['Ancho'] . ")", "Editable" => (string) $columna['Editable'], - "Campo" => (string) $columna['Campo'], "Visible" => (string) $columna['Visible'], "Ajuste" => (string) $columna['Ajuste'], - "Titulo" => (string) $columna['Titulo']); + $this->campos[(string) $columna['Nombre']] = ['Field' => (string) $columna['Titulo'], 'Comment' => (string) $columna['Varios'], + 'Type' => (string) $columna['Tipo'].'('.$columna['Ancho'].')', 'Editable' => (string) $columna['Editable'], + 'Campo' => (string) $columna['Campo'], 'Visible' => (string) $columna['Visible'], 'Ajuste' => (string) $columna['Ajuste'], + 'Titulo' => (string) $columna['Titulo']]; } $this->comandoConsulta = $def->Consulta; } else { //Toma los datos de la tabla. $datos = $this->bdd->estructura($this->tabla); for ($i = 0; $i < count($datos); $i++) { - $this->campos[$datos[$i]["Field"]][] = $datos[$i]; - $this->campos[$datos[$i]["Field"]] = $this->campos[$datos[$i]["Field"]][0]; - $this->campos[$datos[$i]["Field"]]["Campo"] = $datos[$i]["Field"]; - $this->campos[$datos[$i]["Field"]]["Editable"] = "si"; - if (strstr($datos[$i]["Type"],"int")) { - $ajuste = "D"; - } else if (strstr($datos[$i]["Type"],"char")) { - $ajuste = "L"; + $this->campos[$datos[$i]['Field']][] = $datos[$i]; + $this->campos[$datos[$i]['Field']] = $this->campos[$datos[$i]['Field']][0]; + $this->campos[$datos[$i]['Field']]['Campo'] = $datos[$i]['Field']; + $this->campos[$datos[$i]['Field']]['Editable'] = 'si'; + if (strstr($datos[$i]['Type'], 'int')) { + $ajuste = 'D'; + } elseif (strstr($datos[$i]['Type'], 'char')) { + $ajuste = 'L'; } - if (strstr($datos[$i]["Comment"],"imagen")) { - $ajuste = "C"; + if (strstr($datos[$i]['Comment'], 'imagen')) { + $ajuste = 'C'; } - $this->campos[$datos[$i]["Field"]]["Ajuste"] = $ajuste; + $this->campos[$datos[$i]['Field']]['Ajuste'] = $ajuste; } - $this->comandoConsulta = "select SQL_CALC_FOUND_ROWS * from " . $this->tabla . " {buscar} {orden} limit {inferior},{superior}"; + $this->comandoConsulta = 'select SQL_CALC_FOUND_ROWS * from '.$this->tabla.' {buscar} {orden} limit {inferior},{superior}'; } } @@ -667,17 +676,17 @@ class Mantenimiento { } $flecha = ''; foreach ($this->campos as $clave => $datos) { - if ($this->campos[$clave]['Visible'] == "no") { + if ($this->campos[$clave]['Visible'] == 'no') { continue; } - $comen = explode(",", $datos["Comment"]); + $comen = explode(',', $datos['Comment']); $ordenable = false; foreach ($comen as $co) { - if (strstr($co, "ordenable")) { + if (strstr($co, 'ordenable')) { $ordenable = true; } - if (strstr($co, "buscable")) { - $dato = explode("/", $co); + if (strstr($co, 'buscable')) { + $dato = explode('/', $co); $this->campoBusca = $dato[1]; } } @@ -690,61 +699,62 @@ class Mantenimiento { $this->backupURL(); $this->datosURL['orden'] = $clave2; $resFlecha = $clave2 == $ordenActual ? $flecha : ''; - $salida.="montaURL() . "\"> " . $datos["Titulo"] . $resFlecha . " \n"; + $salida .= "montaURL().'"> '.$datos['Titulo'].$resFlecha." \n"; //$salida.="montaURL() . "\"> " . ucfirst($clave) . $resFlecha . " \n"; $this->restoreURL(); } else { - $salida.='' . $datos["Titulo"] . '' . "\n"; + $salida .= ''.$datos['Titulo'].''."\n"; //$salida.='' . ucfirst($clave) . '' . "\n"; } } - $salida.="Acción\n"; + $salida .= "Acción\n"; + return $salida; } /** - * - * @param string $tipo ANADIR,EDICION,BORRADO,CLONAR - * @param array $datos Vector con los datos del registro + * @param string $tipo ANADIR,EDICION,BORRADO,CLONAR + * @param array $datos Vector con los datos del registro + * * @return array lista de campos y formulario de entrada */ private function formularioCampos($tipo, $datos) { - $modo = $tipo == BORRADO ? "readonly" : ""; + $modo = $tipo == BORRADO ? 'readonly' : ''; $nfechas = 0; switch ($tipo) { case CLONAR: case ANADIR: - $this->datosURL['opc'] = "insertar"; $this->datosURL['id'] = null; + $this->datosURL['opc'] = 'insertar'; $this->datosURL['id'] = null; break; case EDICION: - $this->datosURL['opc'] = "modificar"; + $this->datosURL['opc'] = 'modificar'; break; case BORRADO: - $this->datosURL['opc'] = "borrar"; + $this->datosURL['opc'] = 'borrar'; break; } $accion = $this->montaURL(); - $salida = '
    ' . "\n"; + $salida = '
    '."\n"; $salida .= "

    $tipo\n"; //$salida.= var_export($datos,true); - $campos = ""; + $campos = ''; foreach ($this->campos as $clave => $valor) { - if ($valor["Editable"] == "no") { + if ($valor['Editable'] == 'no') { //Se salta los campos que no deben aparecer continue; } //Genera una lista con los campos que intervienen en el formulario. - $salida .='

    '; + $salida .= '
    '; $campo = $valor['Campo']; - $campos.="$campo&"; - $salida.=' "; + $campos .= "$campo&"; + $salida .= ' '; //$salida.=' "; - $salida.='
    '; + $salida .= '
    '; //Se asegura que el id no se pueda modificar. - $modoEfectivo = $clave == 'id' ? "readonly" : $modo; - $valorDato = $datos == null ? "" : $datos[$campo]; + $modoEfectivo = $clave == 'id' ? 'readonly' : $modo; + $valorDato = $datos == null ? '' : $datos[$campo]; if ($clave == 'id' && ($tipo == ANADIR || $tipo == CLONAR)) { $valorDato = null; } @@ -752,24 +762,24 @@ class Mantenimiento { $tipoCampo = $valor['Type']; //Si es un campo fecha u hora y está insertando pone la fecha actual o la hora actual if ($tipo == ANADIR) { - if (stripos($tipoCampo, "echa") <> 0 || stripos($tipoCampo, "ate") <> 0) { - $valorDato = strftime("%Y/%m/%d"); + if (stripos($tipoCampo, 'echa') != 0 || stripos($tipoCampo, 'ate') != 0) { + $valorDato = strftime('%Y/%m/%d'); } } // Calcula el tamaño y el tipo - $tipo_campo = "text"; - if (stripos($tipoCampo, "echa") || stripos($tipoCampo, "ate")) { - $tamano = "19"; - $tipo_campo = "datetime"; + $tipo_campo = 'text'; + if (stripos($tipoCampo, 'echa') || stripos($tipoCampo, 'ate')) { + $tamano = '19'; + $tipo_campo = 'datetime'; $nfechas++; - $salida .= '
    - + $salida .= '
    +
    '; - if ($modo != "readonly") { + if ($modo != 'readonly') { $salida .= '"; } - $salida .= "
    "; + $salida .= '
    '; continue; } else { - list($resto, $tamano) = explode("(", $tipoCampo); + list($resto, $tamano) = explode('(', $tipoCampo); $tamano = substr($tamano, 0, -1); } - if ($tipoCampo == "Password") { - $tipo_campo = "password"; + if ($tipoCampo == 'Password') { + $tipo_campo = 'password'; } - if ($tipoCampo == "Boolean(1)") { + if ($tipoCampo == 'Boolean(1)') { $checked = $valorDato == '1' ? 'checked' : ''; - $modocheck = $modoEfectivo == "readonly" ? 'onclick="javascript: return false;" readonly ' : ''; - $salida .= ''; + $modocheck = $modoEfectivo == 'readonly' ? 'onclick="javascript: return false;" readonly ' : ''; + $salida .= ''; $salida .= '
    '; continue; } - if (stristr($this->campos[$campo]['Comment'], "imagen")) { + if (stristr($this->campos[$campo]['Comment'], 'imagen')) { /*if ($tipo == CLONAR) { // De momento no deja clonar las imágenes $valorDato = null; @@ -801,51 +811,51 @@ class Mantenimiento { $salida .= $this->creaCampoImagen($campo, $valorDato, $tipo); continue; } - if (stristr($this->campos[$campo]['Type'], "int")) { - $tipo_campo = "number"; + if (stristr($this->campos[$campo]['Type'], 'int')) { + $tipo_campo = 'number'; $modoEfectivo .= ' onkeypress = "if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;" '; } //Si no es una clave foránea añade un campo de texto normal - $salida.='

    \n"; - $salida.='
    '; + $salida .= '

    \n"; + $salida .= ''; } else { - $salida.=$this->generaLista($this->foraneas[$campo], $campo, $valorDato, $modoEfectivo); - $salida.=""; + $salida .= $this->generaLista($this->foraneas[$campo], $campo, $valorDato, $modoEfectivo); + $salida .= ''; } } //genera un campo oculto con la lista de campos a modificar. - $salida .= '\n"; + $salida .= '\n"; //genera un campo oculto con el tipo de operación asociado al formulario - $salida .= '\n"; - $salida .= "

    "; + $salida .= '\n"; + $salida .= '

    '; $salida .= '

    '; $this->datosURL['opc'] = 'inicial'; - $salida .= ''; + $salida .= ''; $salida .= '  '; $salida .= '  '; $salida .= '
    '; + return $salida; } - + protected function creaCampoImagen($campo, $valor, $tipoAccion) { - if (file_exists($valor)) { //El fichero existe. $existe = true; - $tipo = "fileinput-exists"; + $tipo = 'fileinput-exists'; } else { - $tipo = "fileinput-new"; + $tipo = 'fileinput-new'; $existe = false; } $mensaje = ' -
    +
    '; if ($existe) { - $mensaje .= ''; + $mensaje .= ''; } $mensaje .= '
    '; if ($tipoAccion == ANADIR || $tipoAccion == EDICION) { @@ -854,84 +864,89 @@ class Mantenimiento { Eliminar'; } if ($existe) { - $mensaje .=''; + $mensaje .= ''; } - $mensaje .='
    '; - if ($tipoAccion == ANADIR || $tipoAccion == EDICION) { + $mensaje .= '
    '; + if ($tipoAccion == ANADIR || $tipoAccion == EDICION) { $mensaje .= ''; } $mensaje .= $this->creaModal($valor, 1); + return $mensaje; - } - + private function creaModal($valor, $id) { $mensaje = ' '; + return $mensaje; } - protected function errorBD($comando, $texto = "") + protected function errorBD($comando, $texto = '') { if (!$texto) { - $texto = "No pudo ejecutar correctamente el comando $comando error=" . $this->bdd->mensajeError(); + $texto = "No pudo ejecutar correctamente el comando $comando error=".$this->bdd->mensajeError(); } else { - $texto = "$texto error=" . $this->bdd->mensajeError(); + $texto = "$texto error=".$this->bdd->mensajeError(); } - $cabecera="¡Error!"; - return $this->panelMensaje($texto, "danger", $cabecera); + $cabecera = '¡Error!'; + + return $this->panelMensaje($texto, 'danger', $cabecera); } - - private function panelMensaje($info, $tipo = "danger", $cabecera = "¡Atención!") { - $mensaje = '
    '; - $mensaje .= '

    ' . $cabecera . '

    '; + + private function panelMensaje($info, $tipo = 'danger', $cabecera = '¡Atención!') + { + $mensaje = '
    '; + $mensaje .= '

    '.$cabecera.'

    '; $mensaje .= '
    '; $mensaje .= $info; $mensaje .= '
    '; $mensaje .= '
    '; + return $mensaje; } - + private function cargaComplementos() { - $mensaje = ''; + $mensaje = ''; //$mensaje .= ''; return $mensaje; } - + private function campoAjax($id, $clave, $tipo, $valor, $num, $datosFila) { //url: 'ajax.php?tabla=". $this->tabla . "', //url: '" . $this->montaURL() . "&tabla=" . $this->tabla "', - $formato = $tipo == "combodate" ? 'data-format="YYYY-MM-DD" data-viewformat="DD/MM/YYYY"' : ''; - $remoto = ""; $select2 = ""; + $formato = $tipo == 'combodate' ? 'data-format="YYYY-MM-DD" data-viewformat="DD/MM/YYYY"' : ''; + $remoto = ''; + $select2 = ''; $titulo = $clave; - if (strstr($tipo, "select")) { - $datos = explode("-", $tipo); + if (strstr($tipo, 'select')) { + $datos = explode('-', $tipo); $tipo = $datos[0]; $tabla2 = $datos[1]; - $clave = "id_".$clave; - $indice = "id".$tabla2; + $clave = 'id_'.$clave; + $indice = 'id'.$tabla2; $valorDato = $datosFila[$indice]; $valorSelect = 'data-value="'.$valorDato.'" '; - $remoto = $valorSelect . ' data-sourceCache="true" data-sourceError="Error cargando datos" data-source="Ajax.php?opc=get&tabla='.$tabla2.'"'; - } + $remoto = $valorSelect.' data-sourceCache="true" data-sourceError="Error cargando datos" data-source="Ajax.php?opc=get&tabla='.$tabla2.'"'; + } $mensaje = ''. - '
    ' . $valor . '
    + '
    '.$valor.'
    "; + return $mensaje; } } - -?> \ No newline at end of file diff --git a/Menu.php b/Menu.php index 84235e4..9b1a9bf 100644 --- a/Menu.php +++ b/Menu.php @@ -1,54 +1,57 @@ . - * - */ +/** + * @copyright Copyright (c) 2008, Ricardo Montañana Gómez + * @license http://www.gnu.org/licenses/gpl-3.0.txt + * This file is part of Inventario. + * Inventario is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Inventario is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Inventario. If not, see . + */ // // Esta clase generará el menú de la aplicación. -class Menu { +class Menu +{ private $opciones; + public function __construct($fichero) { - $contenido=@file_get_contents($fichero) or + $contenido = @file_get_contents($fichero) or die("

    No puedo generar el menú. No puedo acceder al fichero $fichero

    "); // Obtenemos la lista de pares Opción|Enlace - $elementos=explode("\n", $contenido); - foreach($elementos as $elemento) { - list($tipo, $opcion, $enlace, $destino, $titulo)=explode('|', $elemento); + $elementos = explode("\n", $contenido); + foreach ($elementos as $elemento) { + list($tipo, $opcion, $enlace, $destino, $titulo) = explode('|', $elemento); // Los guardamos en la matriz de opciones - if ($tipo) - $this->opciones[]=$tipo.",".$opcion.",".$enlace.",".$destino.",".$titulo; + if ($tipo) { + $this->opciones[] = $tipo.','.$opcion.','.$enlace.','.$destino.','.$titulo; + } } } + public function insertaMenu() { - $salida=""; + $salida = ''; reset($this->opciones); - foreach($this->opciones as $opcion) { - list($tipo,$opcion,$enlace,$destino,$titulo)=explode(",",$opcion); - if ($tipo==2) - $salida.='
  • '.$opcion.'
  • '; - else - $salida.= + foreach ($this->opciones as $opcion) { + list($tipo, $opcion, $enlace, $destino, $titulo) = explode(',', $opcion); + if ($tipo == 2) { + $salida .= '
  • '.$opcion.'
  • '; + } else { + $salida .= //''.$opcion.'
    '; '
    '; + } } + return $salida; } } -?> diff --git a/Pdf_mysql_table.php b/Pdf_mysql_table.php index 955949c..b375275 100644 --- a/Pdf_mysql_table.php +++ b/Pdf_mysql_table.php @@ -9,236 +9,259 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. - * + * * Inventario is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with Inventario. If not, see . - * */ - class Pdf_mysql_table extends FPDF { /** - * Modificado por Ricardo Montañana 05/2008 para añadir la posibilidad de cálculo de totales - * @var $totales float[] Vector de totales de las columnas que lo necesiten + * Modificado por Ricardo Montañana 05/2008 para añadir la posibilidad de cálculo de totales. + * + * @var float[] Vector de totales de las columnas que lo necesiten */ - private $ProcessingTable=false,$aCols=array(),$TableX,$HeaderColor; - private $RowColors,$ColorIndex; - private $bdd,$titulo,$cabecera; - private $totales=array(),$procesandoTotales=false; - /** - * - * @param mixed $bdd Controlador de la base de datos - * @param string $orientacion Orientación de la página P/L - * @param string $formato Tamaño de la página p. ej. A4 - * @param string $titulo Título del informe - * @param string $cabecera Texto para la cabecera - */ - + private $ProcessingTable = false; + private $aCols = []; + private $TableX; + private $HeaderColor; + private $RowColors; + private $ColorIndex; + private $bdd; + private $titulo; + private $cabecera; + private $totales = []; + private $procesandoTotales = false; - public function __construct($bdd,$orientacion,$formato,$titulo='',$cabecera='') + /** + * @param mixed $bdd Controlador de la base de datos + * @param string $orientacion Orientación de la página P/L + * @param string $formato Tamaño de la página p. ej. A4 + * @param string $titulo Título del informe + * @param string $cabecera Texto para la cabecera + */ + public function __construct($bdd, $orientacion, $formato, $titulo = '', $cabecera = '') { - $this->bdd=$bdd; - $this->titulo=$titulo; - $this->cabecera=$cabecera; - parent::__construct($orientacion,'mm',$formato); + $this->bdd = $bdd; + $this->titulo = $titulo; + $this->cabecera = $cabecera; + parent::__construct($orientacion, 'mm', $formato); } + public function setTitulo($titulo) { - $this->titulo=$titulo; - } - public function iniciaTotales() - { - $this->totales = array(); - } - function Header() - { - //Modficada por Ricardo Montañana - //Titulo - $fecha=strftime("%d-%b-%Y %H:%M"); - $this->SetFont('Arial','',8); - $this->Cell(0,4,html_entity_decode(CENTRO . " " . PROGRAMA . " v" . VERSION,ENT_COMPAT | ENT_HTML401,'ISO-8859-1'),0,1,'L'); - $this->SetFont('Arial','',18); - $this->Cell(0,6,utf8_decode($this->titulo),0,1,'C'); - $this->SetFont('Arial','',8); - $this->Cell(0,3,$fecha,0,1,'R'); - $this->Cell(0,5,utf8_decode($this->cabecera),0,1,'C'); - $this->Ln(10); - //Print the table header if necessary - if($this->ProcessingTable) - $this->TableHeader(); - //Ensure table header is output - parent::Header(); - } - public function Footer() - { - $this->SetFont('Arial','',8); - $this->setY($this->h-10); - $this->Cell(0,6,'-'.$this->PageNo().'-',0,1,'C'); - parent::Footer(); + $this->titulo = $titulo; } - function TableHeader() + public function iniciaTotales() { - $this->SetFont('Arial','B',12); + $this->totales = []; + } + + public function Header() + { + //Modficada por Ricardo Montañana + //Titulo + $fecha = strftime('%d-%b-%Y %H:%M'); + $this->SetFont('Arial', '', 8); + $this->Cell(0, 4, html_entity_decode(CENTRO.' '.PROGRAMA.' v'.VERSION, ENT_COMPAT | ENT_HTML401, 'ISO-8859-1'), 0, 1, 'L'); + $this->SetFont('Arial', '', 18); + $this->Cell(0, 6, utf8_decode($this->titulo), 0, 1, 'C'); + $this->SetFont('Arial', '', 8); + $this->Cell(0, 3, $fecha, 0, 1, 'R'); + $this->Cell(0, 5, utf8_decode($this->cabecera), 0, 1, 'C'); + $this->Ln(10); + //Print the table header if necessary + if ($this->ProcessingTable) { + $this->TableHeader(); + } + //Ensure table header is output + parent::Header(); + } + + public function Footer() + { + $this->SetFont('Arial', '', 8); + $this->setY($this->h - 10); + $this->Cell(0, 6, '-'.$this->PageNo().'-', 0, 1, 'C'); + parent::Footer(); + } + + public function TableHeader() + { + $this->SetFont('Arial', 'B', 12); $this->SetX($this->TableX); - $fill=!empty($this->HeaderColor); - if($fill) - $this->SetFillColor($this->HeaderColor[0],$this->HeaderColor[1],$this->HeaderColor[2]); - foreach($this->aCols as $col) - $this->Cell($col['w'],6,utf8_decode($col['c']),1,0,'C',$fill); + $fill = !empty($this->HeaderColor); + if ($fill) { + $this->SetFillColor($this->HeaderColor[0], $this->HeaderColor[1], $this->HeaderColor[2]); + } + foreach ($this->aCols as $col) { + $this->Cell($col['w'], 6, utf8_decode($col['c']), 1, 0, 'C', $fill); + } $this->Ln(); } - function Row($data) + public function Row($data) { $this->SetX($this->TableX); - $ci=$this->ColorIndex; - $fill=!empty($this->RowColors[$ci]); - if($fill) - $this->SetFillColor($this->RowColors[$ci][0],$this->RowColors[$ci][1],$this->RowColors[$ci][2]); - foreach($this->aCols as $col) { + $ci = $this->ColorIndex; + $fill = !empty($this->RowColors[$ci]); + if ($fill) { + $this->SetFillColor($this->RowColors[$ci][0], $this->RowColors[$ci][1], $this->RowColors[$ci][2]); + } + foreach ($this->aCols as $col) { switch ($col['a']) { - case 'D':$alin='R';break; - case 'I':$alin='L';break; - case 'C':$alin='C';break; - default:$alin='L';break; + case 'D':$alin = 'R'; break; + case 'I':$alin = 'L'; break; + case 'C':$alin = 'C'; break; + default:$alin = 'L'; break; } if ($this->procesandoTotales) { - $this->SetFont('Arial','B',12); + $this->SetFont('Arial', 'B', 12); } - $dato = isset($data[$col['f']]) ? $data[$col['f']] : ""; - $this->Cell($col['w'],5,utf8_decode($dato),1,0,$alin,$fill); + $dato = isset($data[$col['f']]) ? $data[$col['f']] : ''; + $this->Cell($col['w'], 5, utf8_decode($dato), 1, 0, $alin, $fill); //$this->Cell($col['w'],5,utf8_decode($data[$col['f']]),1,0,$alin,$fill); //$this->Cell($col['w'],5,utf8_decode($data['proveedor']),1,0,$alin,$fill); //$this->Write(5,"nombre=".$col['f'].",titulo=".$col['c'].",ancho=".$col['w'].",alin=".$col['a']); //$this->Write(5,$data[$col['f']].$col['f']); //print_r($data); //print_r($this->aCols); - if ($col['t']=='S' && !$this->procesandoTotales) { - if (isset($this->totales[$col['f']])) + if ($col['t'] == 'S' && !$this->procesandoTotales) { + if (isset($this->totales[$col['f']])) { $this->totales[$col['f']] += $data[$col['f']]; - else + } else { $this->totales[$col['f']] = $data[$col['f']]; + } } - } $this->Ln(); - $this->ColorIndex=1-$ci; + $this->ColorIndex = 1 - $ci; } - function CalcWidths($width,$align) + public function CalcWidths($width, $align) { //Compute the widths of the columns - $TableWidth=0; - foreach($this->aCols as $i=>$col) - { - $w=$col['w']; - if($w==-1) - $w=$width/count($this->aCols); - elseif(substr($w,-1)=='%') - $w=$w/100*$width; - $this->aCols[$i]['w']=$w; - $TableWidth+=$w; + $TableWidth = 0; + foreach ($this->aCols as $i=>$col) { + $w = $col['w']; + if ($w == -1) { + $w = $width / count($this->aCols); + } elseif (substr($w, -1) == '%') { + $w = $w / 100 * $width; + } + $this->aCols[$i]['w'] = $w; + $TableWidth += $w; } //Compute the abscissa of the table - if($align=='C') - $this->TableX=max(($this->w-$TableWidth)/2,0); - elseif($align=='R') - $this->TableX=max($this->w-$this->rMargin-$TableWidth,0); - else - $this->TableX=$this->lMargin; + if ($align == 'C') { + $this->TableX = max(($this->w - $TableWidth) / 2, 0); + } elseif ($align == 'R') { + $this->TableX = max($this->w - $this->rMargin - $TableWidth, 0); + } else { + $this->TableX = $this->lMargin; + } } - function AddCol($field=-1,$width=-1,$caption='',$align='I',$total='N') + public function AddCol($field = -1, $width = -1, $caption = '', $align = 'I', $total = 'N') { //Add a column to the table - if($field==-1) - $field=count($this->aCols); - $this->aCols[]=array('f'=>$field,'c'=>$caption,'w'=>$width,'a'=>$align,'t'=>$total); + if ($field == -1) { + $field = count($this->aCols); + } + $this->aCols[] = ['f'=>$field, 'c'=>$caption, 'w'=>$width, 'a'=>$align, 't'=>$total]; } - function Table($query,$prop=array()) + public function Table($query, $prop = []) { //Issue query - $res=$this->bdd->query($query) or die('Error: '.$this->bdd->error."
    Query: $query"); + $res = $this->bdd->query($query) or die('Error: '.$this->bdd->error."
    Query: $query"); //Add all columns if none was specified - if(count($this->aCols)==0) - { - $nb=$res->field_count; - for($i=0;$i<$nb;$i++) + if (count($this->aCols) == 0) { + $nb = $res->field_count; + for ($i = 0; $i < $nb; $i++) { $this->AddCol(); + } } //Retrieve column names when not specified - $i=0; - foreach($this->aCols as $i=>$col) - { - if($col['c']=='') - { - if(is_string($col['f'])) - $this->aCols[$i]['c']=ucfirst($col['f']); - else - $this->aCols[$i]['c']=ucfirst($res->field_seek($i)); + $i = 0; + foreach ($this->aCols as $i=>$col) { + if ($col['c'] == '') { + if (is_string($col['f'])) { + $this->aCols[$i]['c'] = ucfirst($col['f']); + } else { + $this->aCols[$i]['c'] = ucfirst($res->field_seek($i)); + } } $i++; } //Handle properties - if(!isset($prop['width'])) - $prop['width']=0; - if($prop['width']==0) - $prop['width']=$this->w-$this->lMargin-$this->rMargin; - if(!isset($prop['align'])) - $prop['align']='C'; - if(!isset($prop['padding'])) - $prop['padding']=$this->cMargin; - $cMargin=$this->cMargin; - $this->cMargin=$prop['padding']; - if(!isset($prop['HeaderColor'])) - $prop['HeaderColor']=array(); - $this->HeaderColor=$prop['HeaderColor']; - if(!isset($prop['color1'])) - $prop['color1']=array(); - if(!isset($prop['color2'])) - $prop['color2']=array(); - $this->RowColors=array($prop['color1'],$prop['color2']); + if (!isset($prop['width'])) { + $prop['width'] = 0; + } + if ($prop['width'] == 0) { + $prop['width'] = $this->w - $this->lMargin - $this->rMargin; + } + if (!isset($prop['align'])) { + $prop['align'] = 'C'; + } + if (!isset($prop['padding'])) { + $prop['padding'] = $this->cMargin; + } + $cMargin = $this->cMargin; + $this->cMargin = $prop['padding']; + if (!isset($prop['HeaderColor'])) { + $prop['HeaderColor'] = []; + } + $this->HeaderColor = $prop['HeaderColor']; + if (!isset($prop['color1'])) { + $prop['color1'] = []; + } + if (!isset($prop['color2'])) { + $prop['color2'] = []; + } + $this->RowColors = [$prop['color1'], $prop['color2']]; //Compute column widths - $this->CalcWidths($prop['width'],$prop['align']); + $this->CalcWidths($prop['width'], $prop['align']); //Print header $this->TableHeader(); //Print rows - $this->SetFont('Arial','',11); - $this->ColorIndex=0; - $this->ProcessingTable=true; - $this->procesandoTotales=false; - while($row=$res->fetch_assoc()) { + $this->SetFont('Arial', '', 11); + $this->ColorIndex = 0; + $this->ProcessingTable = true; + $this->procesandoTotales = false; + while ($row = $res->fetch_assoc()) { $this->Row($row); } - $this->procesandoTotales=true; + $this->procesandoTotales = true; // Procesa los totales if ($this->procesaTotales()) { $this->Row($this->totales); } - $this->ProcessingTable=false; - $this->cMargin=$cMargin; - $this->aCols=array(); + $this->ProcessingTable = false; + $this->cMargin = $cMargin; + $this->aCols = []; } + /** - * Se encarga de generar una línea de totalización si es necesario + * Se encarga de generar una línea de totalización si es necesario. + * * @param array $datos Línea con los totales a imprimir o NULL - * @return boolean Si hay que generar la línea o no + * + * @return bool Si hay que generar la línea o no */ private function procesaTotales() { - foreach($this->aCols as $col) { - if ($col['t']=='S') { + foreach ($this->aCols as $col) { + if ($col['t'] == 'S') { return true; } } + return false; } } -?> \ No newline at end of file diff --git a/Sql.php b/Sql.php index 63e60fd..05918b7 100644 --- a/Sql.php +++ b/Sql.php @@ -1,82 +1,89 @@ - * @version 1.0 - * @package Inventario - * @copyright Copyright (c) 2008, Ricardo Montañana Gómez - * @license http://www.gnu.org/licenses/gpl-3.0.txt - * This file is part of Inventario. - * Inventario is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Inventario is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Inventario. If not, see . - * - */ -class Sql { +/** + * Gestión de una base de datos MySQL. + * + * @author Ricardo Montañana + * + * @version 1.0 + * + * @copyright Copyright (c) 2008, Ricardo Montañana Gómez + * @license http://www.gnu.org/licenses/gpl-3.0.txt + * This file is part of Inventario. + * Inventario is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Inventario is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Inventario. If not, see . + */ +class Sql +{ /** * @var mixed Manejador de la base de datos. */ - private $bdd=NULL; + private $bdd = null; /** * @var string Mensaje del último mensaje de error generado */ - private $mensajeError=''; + private $mensajeError = ''; /** - * @var boolean Almacena el estado de error o no de la última acción. + * @var bool Almacena el estado de error o no de la última acción. */ - private $error=false; + private $error = false; /** - * @var boolean Estado de la conexión con la base de datos. + * @var bool Estado de la conexión con la base de datos. */ - private $estado=false; + private $estado = false; /** * @var mixed Objeto que alberga la última consulta ejecutada. */ - private $peticion=NULL; + private $peticion = null; /** - * @var integer Número de tuplas afectadas en la última consulta. + * @var int Número de tuplas afectadas en la última consulta. */ - private $numero=0; + private $numero = 0; /** * @var string vector de cadenas con los resultados de la petición. */ - private $datos=array(); + private $datos = []; /** - * Id del último registro insertado - * @var integer mysql_ + * Id del último registro insertado. + * + * @var int mysql_ */ private $id; + /** * Crea un objeto Sql y conecta con la Base de Datos. + * * @param string $servidor * @param string $usuario * @param string $baseDatos */ - public function __construct($servidor,$usuario,$clave,$baseDatos) + public function __construct($servidor, $usuario, $clave, $baseDatos) { - $this->bdd = @new mysqli($servidor,$usuario,$clave,$baseDatos); + $this->bdd = @new mysqli($servidor, $usuario, $clave, $baseDatos); if (mysqli_connect_errno()) { - $this->mensajeError='

    Fallo al conectar con el servidor MySQL.

    '; - $this->mensajeError.="Servidor [".$servidor ."] base de datos [".$baseDatos."]"; - $this->error=true; - $this->estado=false; + $this->mensajeError = '

    Fallo al conectar con el servidor MySQL.

    '; + $this->mensajeError .= 'Servidor ['.$servidor.'] base de datos ['.$baseDatos.']'; + $this->error = true; + $this->estado = false; } else { - $this->mensajeError=''; - $this->error=false; - $this->estado=true; + $this->mensajeError = ''; + $this->error = false; + $this->estado = true; } - $this->peticion=NULL; + $this->peticion = null; + return $this; } + public function __destruct() { //Libera la memoria de una posible consulta. @@ -88,103 +95,132 @@ class Sql { $this->bdd->close(); } } - public function filtra($cadena) + + public function filtra($cadena) { - return $this->bdd->real_escape_string($cadena); + return $this->bdd->real_escape_string($cadena); } + public function ejecuta($comando) { if (!$this->estado) { - $this->error=true; - $this->mensajeError='No está conectado'; + $this->error = true; + $this->mensajeError = 'No está conectado'; + return false; } - - if (!$this->peticion=$this->bdd->query($comando)) { - $this->error=true; - $this->mensajeError='No pudo ejecutar la petición: '.$comando; + + if (!$this->peticion = $this->bdd->query($comando)) { + $this->error = true; + $this->mensajeError = 'No pudo ejecutar la petición: '.$comando; + return false; } - $this->numero=$this->bdd->affected_rows; - $this->id=$this->bdd->insert_id; - $this->error=false; - $this->mensajeError=''; + $this->numero = $this->bdd->affected_rows; + $this->id = $this->bdd->insert_id; + $this->error = false; + $this->mensajeError = ''; + return true; } + public function procesaResultado() { if (!$this->estado) { - $this->error=true; - $this->mensajeError='No está conectado a una base de datos'; - return NULL; + $this->error = true; + $this->mensajeError = 'No está conectado a una base de datos'; + + return; } if (!$this->peticion) { - $this->error=true; - $this->mensajeError='No hay un resultado disponible'; - return NULL; + $this->error = true; + $this->mensajeError = 'No hay un resultado disponible'; + + return; } - $datos=$this->peticion->fetch_assoc(); - $this->error=false; - $this->mensajeError=''; - return ($datos); + $datos = $this->peticion->fetch_assoc(); + $this->error = false; + $this->mensajeError = ''; + + return $datos; } - public function camposResultado() + + public function camposResultado() { if (!$this->estado) { - $this->error=true; - $this->mensajeError='No está conectado a una base de datos'; - return NULL; + $this->error = true; + $this->mensajeError = 'No está conectado a una base de datos'; + + return; } if (!$this->peticion) { - $this->error=true; - $this->mensajeError='No hay un resultado disponible'; - return NULL; + $this->error = true; + $this->mensajeError = 'No hay un resultado disponible'; + + return; } - $datos=$this->peticion->fetch_field(); - $this->error=false; - $this->mensajeError=''; - return ($datos); + $datos = $this->peticion->fetch_field(); + $this->error = false; + $this->mensajeError = ''; + + return $datos; } - /** + + /** * Devuelve el número de tuplas afectadas en la última petición. - * @return integer Número de tuplas. + * + * @return int Número de tuplas. */ - public function numeroTuplas() { + public function numeroTuplas() + { return $this->numero; } + /** * Devuelve el número de tuplas total si se ha hecho una consulta select * con SELECT SQL_CALC_FOUND_ROWS * ... - * @return integer Número de tuplas. + * + * @return int Número de tuplas. */ - public function numeroTotalTuplas() + public function numeroTotalTuplas() { - $comando = "select found_rows();"; - if (!$peticion=$this->bdd->query($comando)) { - $this->error=true; - $this->mensajeError='No pudo ejecutar la petición: '.$comando; + $comando = 'select found_rows();'; + if (!$peticion = $this->bdd->query($comando)) { + $this->error = true; + $this->mensajeError = 'No pudo ejecutar la petición: '.$comando; + return false; } $numero = $peticion->fetch_row(); - return $numero[0] ; + + return $numero[0]; } + /** - * Devuelve la condición de error de la última petición - * @return boolean condición de error. + * Devuelve la condición de error de la última petición. + * + * @return bool condición de error. */ - public function error() { + public function error() + { return $this->error; } + /** - * Devuelve el mensaje de error de la última petición + * Devuelve el mensaje de error de la última petición. + * * @return */ - public function mensajeError() { + public function mensajeError() + { return $this->mensajeError.$this->bdd->error; } + /** * Devuelve la estructura de campos de una tabla. + * * @param string $tabla Nombre de la tabla. + * * @return string vector asociativo con la descripción de la tabla [campo]->valor */ public function estructura($tabla) @@ -192,40 +228,46 @@ class Sql { if ($this->peticion) { $this->peticion->free_result(); } - $comando="show full columns from $tabla"; + $comando = "show full columns from $tabla"; if (!$this->ejecuta($comando)) { return false; } - while ($dato=$this->procesaResultado()) { - $salida[]=$dato; + while ($dato = $this->procesaResultado()) { + $salida[] = $dato; } + return $salida; } + public function ultimoId() { return $this->id; } + public function obtieneManejador() { return $this->bdd; } + public function comienzaTransaccion() { return $this->bdd->autocommit(false); } + public function abortaTransaccion() { $codigo = $this->bdd->rollback(); $this->bdd->autocommit(true); - return $codigo; + + return $codigo; } + public function confirmaTransaccion() { $codigo = $this->bdd->commit(); $this->bdd->autocommit(true); $this->peticion = null; + return $codigo; } } - -?> diff --git a/Zebra_Image.php b/Zebra_Image.php index ba59a2a..ce4d055 100644 --- a/Zebra_Image.php +++ b/Zebra_Image.php @@ -37,14 +37,14 @@ ini_set('gd.jpeg_ignore_warning', true); * For more resources visit {@link http://stefangabos.ro/} * * @author Stefan Gabos + * * @version 2.2.3 (last revision: July 14, 2013) + * * @copyright (c) 2006 - 2013 Stefan Gabos * @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU LESSER GENERAL PUBLIC LICENSE - * @package Zebra_Image */ class Zebra_Image { - /** * Indicates the file system permissions to be set for newly created images. * @@ -64,9 +64,9 @@ class Zebra_Image * * Default is 0755 * - * @var integer + * @var int */ - var $chmod_value; + public $chmod_value; /** * If set to FALSE, images having both width and height smaller than the required width and height, will be left @@ -76,9 +76,9 @@ class Zebra_Image * * Default is TRUE * - * @var boolean + * @var bool */ - var $enlarge_smaller_images; + public $enlarge_smaller_images; /** * In case of an error read this property's value to see the error's code. @@ -96,9 +96,9 @@ class Zebra_Image * * Default is 0 (no error). * - * @var integer + * @var int */ - var $error; + public $error; /** * Indicates the quality of the output image (better quality means bigger file size). @@ -109,9 +109,9 @@ class Zebra_Image * * Default is 85 * - * @var integer + * @var int */ - var $jpeg_quality; + public $jpeg_quality; /** * Indicates the compression level of the output image (lower compression means bigger file size). @@ -125,9 +125,9 @@ class Zebra_Image * * @since 2.2 * - * @var integer + * @var int */ - var $png_compression; + public $png_compression; /** * Specifies whether, upon resizing, images should preserve their aspect ratio. @@ -136,9 +136,9 @@ class Zebra_Image * * Default is TRUE * - * @var boolean + * @var bool */ - var $preserve_aspect_ratio; + public $preserve_aspect_ratio; /** * Indicates whether a target files should preserve the source file's date/time. @@ -147,9 +147,9 @@ class Zebra_Image * * @since 1.0.4 * - * @var boolean + * @var bool */ - var $preserve_time; + public $preserve_time; /** * Indicates whether the target image should have a "sharpen" filter applied to it. @@ -163,9 +163,9 @@ class Zebra_Image * * @since 2.2 * - * @var boolean + * @var bool */ - var $sharpen_images; + public $sharpen_images; /** * Path to an image file to apply the transformations to. @@ -174,7 +174,7 @@ class Zebra_Image * * @var string */ - var $source_path; + public $source_path; /** * Path (including file name) to where to save the transformed image. @@ -184,7 +184,7 @@ class Zebra_Image * * @var string */ - var $target_path; + public $target_path; /** * Constructor of the class. @@ -193,7 +193,7 @@ class Zebra_Image * * @return void */ - function Zebra_Image() + public function Zebra_Image() { // set default values for properties @@ -210,7 +210,6 @@ class Zebra_Image $this->sharpen_images = false; $this->source_path = $this->target_path = ''; - } /** @@ -292,21 +291,17 @@ class Zebra_Image * others weight of 1.0. the result is normalized by dividing * the sum with arg1 + 8.0 (sum of the matrix). * any float is accepted; - * * @param mixed $arg1 Used by the following filters: * - brightness - sets the brightness level (-255 to 255) * - contrast - sets the contrast level (-100 to 100) * - colorize - sets the value of the red component (-255 to 255) * - smooth - sets the smoothness level * - pixelate - sets the block size, in pixels - * * @param mixed $arg2 Used by the following filters: * - colorize - sets the value of the green component (-255 to 255) * - pixelate - whether to use advanced pixelation effect or not (defaults to FALSE). - * * @param mixed $arg3 Used by the following filters: * - colorize - sets the value of the blue component (-255 to 255) - * * @param mixed $arg4 Used by the following filters: * - colorize - alpha channel; a value between 0 and 127. 0 indicates * completely opaque while 127 indicates completely @@ -314,7 +309,7 @@ class Zebra_Image * * @since 2.2.2 * - * @return boolean Returns TRUE on success or FALSE on error. + * @return bool Returns TRUE on success or FALSE on error. * * If {@link http://php.net/manual/en/function.imagefilter.php imagefilter} is not * available the method will return FALSE without setting an {@link error} code. @@ -326,11 +321,11 @@ class Zebra_Image * {@link http://php.net/manual/en/function.imagefilter.php imagefilter} exists and that * the requested filter is valid, check the {@link error} property to see the error code. */ - function apply_filter($filter, $arg1 = '', $arg2 = '', $arg3 = '', $arg4 = '') + public function apply_filter($filter, $arg1 = '', $arg2 = '', $arg3 = '', $arg4 = '') { // if "imagefilter" function exists and the requested filter exists - if (function_exists('imagefilter')) + if (function_exists('imagefilter')) { // if image resource was successfully created if ($this->_create_from_source()) { @@ -358,45 +353,51 @@ class Zebra_Image if (is_array($filter)) { // iterate through the filters - foreach ($filter as $arguments) + foreach ($filter as $arguments) { // if filter exists - if (defined('IMG_FILTER_' . strtoupper($arguments[0]))) { + if (defined('IMG_FILTER_'.strtoupper($arguments[0]))) { // try to apply the filter... - if (!@call_user_func_array('imagefilter', array_merge(array($target_identifier, constant('IMG_FILTER_' . strtoupper($arguments[0]))), array_slice($arguments, 1)))) + if (!@call_user_func_array('imagefilter', array_merge([$target_identifier, constant('IMG_FILTER_'.strtoupper($arguments[0]))], array_slice($arguments, 1)))) { // ...and trigger an error if the filter could not be applied - trigger_error('Invalid arguments used for "' . strtoupper($arguments[0]) . '" filter', E_USER_WARNING); + trigger_error('Invalid arguments used for "'.strtoupper($arguments[0]).'" filter', E_USER_WARNING); + } - // if filter doesn't exists, trigger an error - } else trigger_error('Filter "' . strtoupper($arguments[0]) . '" is not available', E_USER_WARNING); + // if filter doesn't exists, trigger an error + } else { + trigger_error('Filter "'.strtoupper($arguments[0]).'" is not available', E_USER_WARNING); + } + } - // if a single filter is to be applied and it is available - } elseif (defined('IMG_FILTER_' . strtoupper($filter))) { + // if a single filter is to be applied and it is available + } elseif (defined('IMG_FILTER_'.strtoupper($filter))) { // get all the arguments passed to the method $arguments = func_get_args(); // try to apply the filter... - if (!@call_user_func_array('imagefilter', array_merge(array($target_identifier, constant('IMG_FILTER_' . strtoupper($filter))), array_slice($arguments, 1)))) + if (!@call_user_func_array('imagefilter', array_merge([$target_identifier, constant('IMG_FILTER_'.strtoupper($filter))], array_slice($arguments, 1)))) { // ...and trigger an error if the filter could not be applied - trigger_error('Invalid arguments used for "' . strtoupper($arguments[0]) . '" filter', E_USER_WARNING); + trigger_error('Invalid arguments used for "'.strtoupper($arguments[0]).'" filter', E_USER_WARNING); + } - // if filter doesn't exists, trigger an error - } else trigger_error('Filter "' . strtoupper($arguments[0]) . '" is not available', E_USER_WARNING); + // if filter doesn't exists, trigger an error + } else { + trigger_error('Filter "'.strtoupper($arguments[0]).'" is not available', E_USER_WARNING); + } // write image return $this->_write_image($target_identifier); - } + } // if script gets this far, return false // note that we do not set the error level as it has been already set // by the _create_from_source() method earlier, if the case return false; - } /** @@ -421,21 +422,18 @@ class Zebra_Image * $img->crop(0, 0, 100, 100); * * - * @param integer $start_x x coordinate to start cropping from - * - * @param integer $start_y y coordinate to start cropping from - * - * @param integer $end_x x coordinate where to end the cropping - * - * @param integer $end_y y coordinate where to end the cropping + * @param int $start_x x coordinate to start cropping from + * @param int $start_y y coordinate to start cropping from + * @param int $end_x x coordinate where to end the cropping + * @param int $end_y y coordinate where to end the cropping * * @since 1.0.4 * - * @return boolean Returns TRUE on success or FALSE on error. + * @return bool Returns TRUE on success or FALSE on error. * * If FALSE is returned, check the {@link error} property to see the error code. */ - function crop($start_x, $start_y, $end_x, $end_y) + public function crop($start_x, $start_y, $end_x, $end_y) { // this method might be also called internally @@ -453,7 +451,9 @@ class Zebra_Image // if method is called as usually // try to create an image resource from source path - } else $result = $this->_create_from_source(); + } else { + $result = $this->_create_from_source(); + } // if image resource was successfully created if ($result !== false) { @@ -479,19 +479,17 @@ class Zebra_Image // write image return $this->_write_image($target_identifier); - } // if script gets this far, return false // note that we do not set the error level as it has been already set // by the _create_from_source() method earlier return false; - } /** * Flips both horizontally and vertically the image given as {@link source_path} and outputs the resulted image as - * {@link target_path} + * {@link target_path}. * * * // include the Zebra_Image library @@ -514,19 +512,17 @@ class Zebra_Image * * @since 2.1 * - * @return boolean Returns TRUE on success or FALSE on error. + * @return bool Returns TRUE on success or FALSE on error. * * If FALSE is returned, check the {@link error} property to see the error code. */ - function flip_both() + public function flip_both() { - return $this->_flip('both'); - } /** - * Flips horizontally the image given as {@link source_path} and outputs the resulted image as {@link target_path} + * Flips horizontally the image given as {@link source_path} and outputs the resulted image as {@link target_path}. * * * // include the Zebra_Image library @@ -547,19 +543,17 @@ class Zebra_Image * $img->flip_horizontal(); * * - * @return boolean Returns TRUE on success or FALSE on error. + * @return bool Returns TRUE on success or FALSE on error. * * If FALSE is returned, check the {@link error} property to see the error code. */ - function flip_horizontal() + public function flip_horizontal() { - return $this->_flip('horizontal'); - } /** - * Flips vertically the image given as {@link source_path} and outputs the resulted image as {@link target_path} + * Flips vertically the image given as {@link source_path} and outputs the resulted image as {@link target_path}. * * * // include the Zebra_Image library @@ -580,15 +574,13 @@ class Zebra_Image * $img->flip_vertical(); * * - * @return boolean Returns TRUE on success or FALSE on error. + * @return bool Returns TRUE on success or FALSE on error. * * If FALSE is returned, check the {@link error} property to see the error code. */ - function flip_vertical() + public function flip_vertical() { - return $this->_flip('vertical'); - } /** @@ -616,7 +608,7 @@ class Zebra_Image * $img->resize(150, 150, ZEBRA_IMAGE_CROP_CENTER); * * - * @param integer $width The width to resize the image to. + * @param int $width The width to resize the image to. * * If set to 0, the width will be automatically adjusted, depending * on the value of the height argument so that the image preserves @@ -638,8 +630,7 @@ class Zebra_Image * If either width or height are set to 0, the script * will consider the value of the {@link preserve_aspect_ratio} to bet set * to TRUE regardless of its actual value! - * - * @param integer $height The height to resize the image to. + * @param int $height The height to resize the image to. * * If set to 0, the height will be automatically adjusted, depending * on the value of the width argument so that the image preserves @@ -661,7 +652,6 @@ class Zebra_Image * If either height or width are set to 0, the script * will consider the value of the {@link preserve_aspect_ratio} to bet set * to TRUE regardless of its actual value! - * * @param int $method (Optional) Method to use when resizing images to exact width and height * while preserving aspect ratio. * @@ -698,7 +688,6 @@ class Zebra_Image * indicated region of the resulted image. * * Default is ZEBRA_IMAGE_CROP_CENTER - * * @param hexadecimal $background_color (Optional) The hexadecimal color (like "#FFFFFF" or "#FFF") of the * blank area. See the method argument. * @@ -708,12 +697,12 @@ class Zebra_Image * * Default is #FFFFFF. * - * @return boolean Returns TRUE on success or FALSE on error. + * @return bool Returns TRUE on success or FALSE on error. * * If FALSE is returned, check the {@link error} property to see what went * wrong */ - function resize($width = 0, $height = 0, $method = ZEBRA_IMAGE_CROP_CENTER, $background_color = '#FFFFFF') + public function resize($width = 0, $height = 0, $method = ZEBRA_IMAGE_CROP_CENTER, $background_color = '#FFFFFF') { // if image resource was successfully created @@ -722,7 +711,9 @@ class Zebra_Image // if either width or height is to be adjusted automatically // set a flag telling the script that, even if $preserve_aspect_ratio is set to false // treat everything as if it was set to true - if ($width == 0 || $height == 0) $auto_preserve_aspect_ratio = true; + if ($width == 0 || $height == 0) { + $auto_preserve_aspect_ratio = true; + } // if aspect ratio needs to be preserved if ($this->preserve_aspect_ratio || isset($auto_preserve_aspect_ratio)) { @@ -775,15 +766,14 @@ class Zebra_Image // compute the target image's width so that the image will stay inside the bounding box $target_width = round($vertical_aspect_ratio * $this->source_width); - } - // if both width and height are given and image is to be cropped in order to get to the required size + // if both width and height are given and image is to be cropped in order to get to the required size } elseif ($width > 0 && $height > 0 && $method > 1 && $method < 11) { // compute the horizontal and vertical aspect ratios $vertical_aspect_ratio = $this->source_height / $height; - $horizontal_aspect_ratio = $this->source_width / $width; + $horizontal_aspect_ratio = $this->source_width / $width; // we'll use one of the two $aspect_ratio = @@ -806,10 +796,9 @@ class Zebra_Image // we will create a copy of the source image $target_width = $this->source_width; $target_height = $this->source_height; - } - // if aspect ratio does not need to be preserved + // if aspect ratio does not need to be preserved } else { // compute the target image's width @@ -817,7 +806,6 @@ class Zebra_Image // compute the target image's height $target_height = ($height > 0 ? $height : $this->source_height); - } // if @@ -1013,7 +1001,7 @@ class Zebra_Image } - // if aspect ratio doesn't need to be preserved or + // if aspect ratio doesn't need to be preserved or // it needs to be preserved and method is ZEBRA_IMAGE_BOXED or ZEBRA_IMAGE_NOT_BOXED } else { @@ -1041,21 +1029,20 @@ class Zebra_Image // if script gets this far, write the image to disk return $this->_write_image($target_identifier); - } - // if we get here it means that + // if we get here it means that // smaller images than the given width/height are to be left untouched // therefore, we save the image as it is - } else return $this->_write_image($this->source_identifier); - + } else { + return $this->_write_image($this->source_identifier); + } } // if script gets this far return false // note that we do not set the error level as it has been already set // by the _create_from_source() method earlier return false; - } /** @@ -1080,10 +1067,9 @@ class Zebra_Image * $img->rotate(45); * * - * @param double $angle Angle by which to rotate the image clockwise. + * @param float $angle Angle by which to rotate the image clockwise. * * Between 0 and 360. - * * @param mixed $background_color (Optional) The hexadecimal color (like "#FFFFFF" or "#FFF") of the * uncovered zone after the rotation. * @@ -1093,12 +1079,12 @@ class Zebra_Image * * Default is -1. * - * @return boolean Returns TRUE on success or FALSE on error. + * @return bool Returns TRUE on success or FALSE on error. * * If FALSE is returned, check the {@link error} property to see the error * code. */ - function rotate($angle, $background_color = -1) + public function rotate($angle, $background_color = -1) { // if image resource was successfully created @@ -1119,10 +1105,9 @@ class Zebra_Image // rotate the image $target_identifier = imagerotate($this->source_identifier, $angle, $background_color); - } - // if source image is a transparent GIF + // if source image is a transparent GIF } elseif ($this->source_type == IMAGETYPE_GIF && $this->source_transparent_color_index >= 0) { // convert the background color to RGB values @@ -1172,28 +1157,23 @@ class Zebra_Image // rotate the image $target_identifier = imagerotate($this->source_identifier, $angle, $background_color); - } // write image $this->_write_image($target_identifier); - } // if script gets this far return false // note that we do not set the error level as it has been already set // by the _create_from_source() method earlier - return false; - + return false; } /** * Returns an array containing the image identifier representing the image obtained from {@link $source_path}, the - * image's width and height and the image's type - * - * @access private + * image's width and height and the image's type. */ - function _create_from_source() + public function _create_from_source() { // perform some error checking first @@ -1255,13 +1235,14 @@ class Zebra_Image $identifier = imagecreatefromgif($this->source_path); // get the index of the transparent color (if any) - if (($this->source_transparent_color_index = imagecolortransparent($identifier)) >= 0) + if (($this->source_transparent_color_index = imagecolortransparent($identifier)) >= 0) { // get the transparent color's RGB values // we have to mute errors because there are GIF images which *are* transparent and everything // works as expected, but imagecolortransparent() returns a color that is outside the range of // colors in the image's pallette... $this->source_transparent_color = @imagecolorsforindex($identifier, $this->source_transparent_color_index); + } break; @@ -1294,18 +1275,18 @@ class Zebra_Image return false; } - } // if target file has to have the same timestamp as the source image // save it as a global property of the class - if ($this->preserve_time) $this->source_image_time = filemtime($this->source_path); + if ($this->preserve_time) { + $this->source_image_time = filemtime($this->source_path); + } // make available the source image's identifier $this->source_identifier = $identifier; return true; - } /** @@ -1314,50 +1295,48 @@ class Zebra_Image * The RGB values will be a value between 0 and 255 each. * * @param string $color Hexadecimal representation of a color (i.e. #123456 or #AAA). - * * @param string $default_on_error Hexadecimal representation of a color to be used in case $color is not * recognized as a hexadecimal color. * * @return array Returns an associative array with the values of (R)ed, (G)reen and (B)lue - * - * @access private */ - function _hex2rgb($color, $default_on_error = '#FFFFFF') + public function _hex2rgb($color, $default_on_error = '#FFFFFF') { // if color is not formatted correctly // use the default color - if (preg_match('/^#?([a-f]|[0-9]){3}(([a-f]|[0-9]){3})?$/i', $color) == 0) $color = $default_on_error; + if (preg_match('/^#?([a-f]|[0-9]){3}(([a-f]|[0-9]){3})?$/i', $color) == 0) { + $color = $default_on_error; + } // trim off the "#" prefix from $background_color $color = ltrim($color, '#'); // if color is given using the shorthand (i.e. "FFF" instead of "FFFFFF") if (strlen($color) == 3) { - $tmp = ''; // take each value // and duplicate it - for ($i = 0; $i < 3; $i++) $tmp .= str_repeat($color[$i], 2); + for ($i = 0; $i < 3; $i++) { + $tmp .= str_repeat($color[$i], 2); + } // the color in it's full, 6 characters length notation $color = $tmp; - } // decimal representation of the color $int = hexdec($color); // extract and return the RGB values - return array( + return [ - 'r' => 0xFF & ($int >> 0x10), - 'g' => 0xFF & ($int >> 0x8), - 'b' => 0xFF & $int - - ); + 'r' => 0xFF & ($int >> 0x10), + 'g' => 0xFF & ($int >> 0x8), + 'b' => 0xFF & $int + ]; } /** @@ -1365,13 +1344,11 @@ class Zebra_Image * * @since 2.1 * - * @access private - * - * @return boolean Returns TRUE on success or FALSE on error. + * @return bool Returns TRUE on success or FALSE on error. * * If FALSE is returned, check the {@link error} property to see the error code. */ - function _flip($orientation) + public function _flip($orientation) { // if image resource was successfully created @@ -1444,23 +1421,19 @@ class Zebra_Image // write image return $this->_write_image($target_identifier); - } // if script gets this far, return false // note that we do not set the error level as it has been already set // by the _create_from_source() method earlier return false; - } /** * Creates a blank image of given width, height and background color. * - * @param integer $width Width of the new image. - * - * @param integer $height Height of the new image. - * + * @param int $width Width of the new image. + * @param int $height Height of the new image. * @param string $background_color (Optional) The hexadecimal color of the background. * * Can also be -1 case in which the script will try to create a transparent @@ -1469,14 +1442,12 @@ class Zebra_Image * Default is "#FFFFFF". * * @return Returns the identifier of the newly created image. - * - * @access private */ - function _prepare_image($width, $height, $background_color = '#FFFFFF') + public function _prepare_image($width, $height, $background_color = '#FFFFFF') { // create a blank image - $identifier = imagecreatetruecolor((int)$width <= 0 ? 1 : (int)$width, (int)$height <= 0 ? 1 : (int)$height); + $identifier = imagecreatetruecolor((int) $width <= 0 ? 1 : (int) $width, (int) $height <= 0 ? 1 : (int) $height); // if we are creating a PNG image if ($this->target_type == 'png' && $background_color == -1) { @@ -1488,10 +1459,10 @@ class Zebra_Image $transparent_color = imagecolorallocatealpha($identifier, 0, 0, 0, 127); // fill the image with the transparent color - imagefill($identifier, 0, 0, $transparent_color); + imagefill($identifier, 0, 0, $transparent_color); //save full alpha channel information - imagesavealpha($identifier, true); + imagesavealpha($identifier, true); // if source image is a transparent GIF } elseif ($this->target_type == 'gif' && $background_color == -1 && $this->source_transparent_color_index >= 0) { @@ -1514,7 +1485,9 @@ class Zebra_Image } else { // if transparent background color specified, revert to white - if ($background_color == -1) $background_color = '#FFFFFF'; + if ($background_color == -1) { + $background_color = '#FFFFFF'; + } // convert hex color to rgb $background_color = $this->_hex2rgb($background_color); @@ -1524,12 +1497,10 @@ class Zebra_Image // fill the image with the background color imagefill($identifier, 0, 0, $background_color); - } // return the image's identifier return $identifier; - } /** @@ -1541,10 +1512,8 @@ class Zebra_Image * versions! * * @param $identifier identifier An image identifier - * - * @access private */ - function _sharpen_image($image) + public function _sharpen_image($image) { // if the "sharpen_images" is set to true and we're running an appropriate version of PHP @@ -1552,11 +1521,11 @@ class Zebra_Image if ($this->sharpen_images && version_compare(PHP_VERSION, '5.1.0') >= 0) { // the convolution matrix as an array of three arrays of three floats - $matrix = array( - array(-1.2, -1, -1.2), - array(-1, 20, -1), - array(-1.2, -1, -1.2), - ); + $matrix = [ + [-1.2, -1, -1.2], + [-1, 20, -1], + [-1.2, -1, -1.2], + ]; // the divisor of the matrix $divisor = array_sum(array_map('array_sum', $matrix)); @@ -1566,12 +1535,10 @@ class Zebra_Image // sharpen image imageconvolution($image, $matrix, $divisor, $offset); - } // return the image's identifier return $image; - } /** @@ -1579,13 +1546,11 @@ class Zebra_Image * * @param $identifier identifier An image identifier * - * @return boolean Returns TRUE on success or FALSE on error. + * @return bool Returns TRUE on success or FALSE on error. * * If FALSE is returned, check the {@link error} property to see the error code. - * - * @access private */ - function _write_image($identifier) + public function _write_image($identifier) { // sharpen image if it's required @@ -1614,7 +1579,6 @@ class Zebra_Image $this->error = 3; return false; - } break; @@ -1638,7 +1602,6 @@ class Zebra_Image $this->error = 3; return false; - } break; @@ -1664,7 +1627,6 @@ class Zebra_Image $this->error = 3; return false; - } break; @@ -1689,19 +1651,18 @@ class Zebra_Image chmod($this->target_path, intval($this->chmod_value, 8)); // save the error level - } else $this->error = 8; + } else { + $this->error = 8; + } // if target file has to have the same timestamp as the source image if ($this->preserve_time && isset($this->source_image_time)) { // touch the newly created file @touch($this->target_path, $this->source_image_time); - } // return true return true; - } - } diff --git a/css/dashboard.php b/css/dashboard.php index c88a8f5..986fefc 100644 --- a/css/dashboard.php +++ b/css/dashboard.php @@ -1,6 +1,6 @@ /* * Base structure diff --git a/index.php b/index.php index ffc804d..241a095 100644 --- a/index.php +++ b/index.php @@ -1,9 +1,11 @@ + * * @version 1.0 - * @package Inventario + * * @copyright Copyright (c) 2008, Ricardo Montañana Gómez * @license http://www.gnu.org/licenses/gpl-3.0.txt * This file is part of Inventario. @@ -11,23 +13,23 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. - * + * * Inventario is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with Inventario. If not, see . - * */ //Se incluyen los módulos necesarios - function __autoload($class_name) { - require_once $class_name . '.php'; + function __autoload($class_name) + { + require_once $class_name.'.php'; } - include('inc/configuracion.inc'); + include 'inc/configuracion.inc'; - $aplicacion=new Inventario(); - if ($aplicacion->estado()) + $aplicacion = new Inventario(); + if ($aplicacion->estado()) { $aplicacion->Ejecuta(); -?> + } diff --git a/phpqrcode.php b/phpqrcode.php index ea8c08f..63781e5 100644 --- a/phpqrcode.php +++ b/phpqrcode.php @@ -32,22 +32,14 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - /* * Version: 1.1.4 * Build: 2010100721 */ - - //---- qrconst.php ----------------------------- - - - - /* * PHP QR Code encoder * @@ -73,65 +65,56 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - // Encoding modes - - define('QR_MODE_NUL', -1); - define('QR_MODE_NUM', 0); - define('QR_MODE_AN', 1); - define('QR_MODE_8', 2); - define('QR_MODE_KANJI', 3); - define('QR_MODE_STRUCTURE', 4); - // Levels of error correction. + // Encoding modes - define('QR_ECLEVEL_L', 0); - define('QR_ECLEVEL_M', 1); - define('QR_ECLEVEL_Q', 2); - define('QR_ECLEVEL_H', 3); - - // Supported output formats - - define('QR_FORMAT_TEXT', 0); - define('QR_FORMAT_PNG', 1); - - class qrstr { - public static function set(&$srctab, $x, $y, $repl, $replLen = false) { - $srctab[$y] = substr_replace($srctab[$y], ($replLen !== false)?substr($repl,0,$replLen):$repl, $x, ($replLen !== false)?$replLen:strlen($repl)); - } - } + define('QR_MODE_NUL', -1); + define('QR_MODE_NUM', 0); + define('QR_MODE_AN', 1); + define('QR_MODE_8', 2); + define('QR_MODE_KANJI', 3); + define('QR_MODE_STRUCTURE', 4); + // Levels of error correction. + define('QR_ECLEVEL_L', 0); + define('QR_ECLEVEL_M', 1); + define('QR_ECLEVEL_Q', 2); + define('QR_ECLEVEL_H', 3); + + // Supported output formats + + define('QR_FORMAT_TEXT', 0); + define('QR_FORMAT_PNG', 1); + + class qrstr + { + public static function set(&$srctab, $x, $y, $repl, $replLen = false) + { + $srctab[$y] = substr_replace($srctab[$y], ($replLen !== false) ? substr($repl, 0, $replLen) : $repl, $x, ($replLen !== false) ? $replLen : strlen($repl)); + } + } //---- merged_config.php ----------------------------- - - - /* * PHP QR Code encoder * * Config file, tuned-up for merged verion */ - + define('QR_CACHEABLE', false); // use cache - more disk reads but less CPU power, masks and format templates are stored there define('QR_CACHE_DIR', false); // used when QR_CACHEABLE === true - define('QR_LOG_DIR', false); // default error logs dir - + define('QR_LOG_DIR', false); // default error logs dir + define('QR_FIND_BEST_MASK', true); // if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code define('QR_FIND_FROM_RANDOM', 2); // if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly define('QR_DEFAULT_MASK', 2); // when QR_FIND_BEST_MASK === false - - define('QR_PNG_MAXIMUM_SIZE', 1024); // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images - - + define('QR_PNG_MAXIMUM_SIZE', 1024); // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images //---- qrtools.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -155,79 +138,81 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - class QRtools { - + class QRtools + { //---------------------------------------------------------------------- public static function binarize($frame) { $len = count($frame); foreach ($frame as &$frameLine) { - - for($i=0; $i<$len; $i++) { - $frameLine[$i] = (ord($frameLine[$i])&1)?'1':'0'; + for ($i = 0; $i < $len; $i++) { + $frameLine[$i] = (ord($frameLine[$i]) & 1) ? '1' : '0'; } } - + return $frame; } - + //---------------------------------------------------------------------- public static function tcpdfBarcodeArray($code, $mode = 'QR,L', $tcPdfVersion = '4.5.037') { - $barcode_array = array(); - - if (!is_array($mode)) + $barcode_array = []; + + if (!is_array($mode)) { $mode = explode(',', $mode); - + } + $eccLevel = 'L'; - + if (count($mode) > 1) { $eccLevel = $mode[1]; } - + $qrTab = QRcode::text($code, false, $eccLevel); $size = count($qrTab); - + $barcode_array['num_rows'] = $size; $barcode_array['num_cols'] = $size; - $barcode_array['bcode'] = array(); - + $barcode_array['bcode'] = []; + foreach ($qrTab as $line) { - $arrAdd = array(); - foreach(str_split($line) as $char) - $arrAdd[] = ($char=='1')?1:0; + $arrAdd = []; + foreach (str_split($line) as $char) { + $arrAdd[] = ($char == '1') ? 1 : 0; + } $barcode_array['bcode'][] = $arrAdd; } - + return $barcode_array; } - + //---------------------------------------------------------------------- public static function clearCache() { - self::$frames = array(); + self::$frames = []; } - + //---------------------------------------------------------------------- public static function buildCache() { - QRtools::markTime('before_build_cache'); - - $mask = new QRmask(); - for ($a=1; $a <= QRSPEC_VERSION_MAX; $a++) { + self::markTime('before_build_cache'); + + $mask = new QRmask(); + for ($a = 1; $a <= QRSPEC_VERSION_MAX; $a++) { $frame = QRspec::newFrame($a); if (QR_IMAGE) { $fileName = QR_CACHE_DIR.'frame_'.$a.'.png'; QRimage::png(self::binarize($frame), $fileName, 1, 0); } - - $width = count($frame); - $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); - for ($maskNo=0; $maskNo<8; $maskNo++) - $mask->makeMaskNo($maskNo, $width, $frame, $bitMask, true); + + $width = count($frame); + $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); + for ($maskNo = 0; $maskNo < 8; $maskNo++) { + $mask->makeMaskNo($maskNo, $width, $frame, $bitMask, true); + } } - - QRtools::markTime('after_build_cache'); + + self::markTime('after_build_cache'); } //---------------------------------------------------------------------- @@ -240,38 +225,39 @@ } else { file_put_contents(QR_LOG_DIR.'errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND); } - } + } } } - + //---------------------------------------------------------------------- - public static function dumpMask($frame) + public static function dumpMask($frame) { $width = count($frame); - for($y=0;$y<$width;$y++) { - for($x=0;$x<$width;$x++) { + for ($y = 0; $y < $width; $y++) { + for ($x = 0; $x < $width; $x++) { echo ord($frame[$y][$x]).','; } } } - + //---------------------------------------------------------------------- public static function markTime($markerId) { - list($usec, $sec) = explode(" ", microtime()); - $time = ((float)$usec + (float)$sec); - - if (!isset($GLOBALS['qr_time_bench'])) - $GLOBALS['qr_time_bench'] = array(); - + list($usec, $sec) = explode(' ', microtime()); + $time = ((float) $usec + (float) $sec); + + if (!isset($GLOBALS['qr_time_bench'])) { + $GLOBALS['qr_time_bench'] = []; + } + $GLOBALS['qr_time_bench'][$markerId] = $time; } - + //---------------------------------------------------------------------- public static function timeBenchmark() { self::markTime('finish'); - + $lastTime = 0; $startTime = 0; $p = 0; @@ -280,37 +266,30 @@ BENCHMARK '; - foreach($GLOBALS['qr_time_bench'] as $markerId=>$thisTime) { + foreach ($GLOBALS['qr_time_bench'] as $markerId=>$thisTime) { if ($p > 0) { - echo 'till '.$markerId.': '.number_format($thisTime-$lastTime, 6).'s'; + echo 'till '.$markerId.': '.number_format($thisTime - $lastTime, 6).'s'; } else { $startTime = $thisTime; } - + $p++; $lastTime = $thisTime; } - + echo ' - TOTAL: '.number_format($lastTime-$startTime, 6).'s + TOTAL: '.number_format($lastTime - $startTime, 6).'s '; } - } - + //########################################################################## - + QRtools::markTime('start'); - - - //---- qrspec.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -325,7 +304,7 @@ * The following data / specifications are taken from * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004) * or - * "Automatic identification and data capture techniques -- + * "Automatic identification and data capture techniques -- * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006) * * This library is free software; you can redistribute it and/or @@ -342,116 +321,117 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - + define('QRSPEC_VERSION_MAX', 40); - define('QRSPEC_WIDTH_MAX', 177); + define('QRSPEC_WIDTH_MAX', 177); - define('QRCAP_WIDTH', 0); - define('QRCAP_WORDS', 1); - define('QRCAP_REMINDER', 2); - define('QRCAP_EC', 3); + define('QRCAP_WIDTH', 0); + define('QRCAP_WORDS', 1); + define('QRCAP_REMINDER', 2); + define('QRCAP_EC', 3); + + class QRspec + { + public static $capacity = [ + [0, 0, 0, [0, 0, 0, 0]], + [21, 26, 0, [7, 10, 13, 17]], // 1 + [25, 44, 7, [10, 16, 22, 28]], + [29, 70, 7, [15, 26, 36, 44]], + [33, 100, 7, [20, 36, 52, 64]], + [37, 134, 7, [26, 48, 72, 88]], // 5 + [41, 172, 7, [36, 64, 96, 112]], + [45, 196, 0, [40, 72, 108, 130]], + [49, 242, 0, [48, 88, 132, 156]], + [53, 292, 0, [60, 110, 160, 192]], + [57, 346, 0, [72, 130, 192, 224]], //10 + [61, 404, 0, [80, 150, 224, 264]], + [65, 466, 0, [96, 176, 260, 308]], + [69, 532, 0, [104, 198, 288, 352]], + [73, 581, 3, [120, 216, 320, 384]], + [77, 655, 3, [132, 240, 360, 432]], //15 + [81, 733, 3, [144, 280, 408, 480]], + [85, 815, 3, [168, 308, 448, 532]], + [89, 901, 3, [180, 338, 504, 588]], + [93, 991, 3, [196, 364, 546, 650]], + [97, 1085, 3, [224, 416, 600, 700]], //20 + [101, 1156, 4, [224, 442, 644, 750]], + [105, 1258, 4, [252, 476, 690, 816]], + [109, 1364, 4, [270, 504, 750, 900]], + [113, 1474, 4, [300, 560, 810, 960]], + [117, 1588, 4, [312, 588, 870, 1050]], //25 + [121, 1706, 4, [336, 644, 952, 1110]], + [125, 1828, 4, [360, 700, 1020, 1200]], + [129, 1921, 3, [390, 728, 1050, 1260]], + [133, 2051, 3, [420, 784, 1140, 1350]], + [137, 2185, 3, [450, 812, 1200, 1440]], //30 + [141, 2323, 3, [480, 868, 1290, 1530]], + [145, 2465, 3, [510, 924, 1350, 1620]], + [149, 2611, 3, [540, 980, 1440, 1710]], + [153, 2761, 3, [570, 1036, 1530, 1800]], + [157, 2876, 0, [570, 1064, 1590, 1890]], //35 + [161, 3034, 0, [600, 1120, 1680, 1980]], + [165, 3196, 0, [630, 1204, 1770, 2100]], + [169, 3362, 0, [660, 1260, 1860, 2220]], + [173, 3532, 0, [720, 1316, 1950, 2310]], + [177, 3706, 0, [750, 1372, 2040, 2430]] //40 + ]; - class QRspec { - - public static $capacity = array( - array( 0, 0, 0, array( 0, 0, 0, 0)), - array( 21, 26, 0, array( 7, 10, 13, 17)), // 1 - array( 25, 44, 7, array( 10, 16, 22, 28)), - array( 29, 70, 7, array( 15, 26, 36, 44)), - array( 33, 100, 7, array( 20, 36, 52, 64)), - array( 37, 134, 7, array( 26, 48, 72, 88)), // 5 - array( 41, 172, 7, array( 36, 64, 96, 112)), - array( 45, 196, 0, array( 40, 72, 108, 130)), - array( 49, 242, 0, array( 48, 88, 132, 156)), - array( 53, 292, 0, array( 60, 110, 160, 192)), - array( 57, 346, 0, array( 72, 130, 192, 224)), //10 - array( 61, 404, 0, array( 80, 150, 224, 264)), - array( 65, 466, 0, array( 96, 176, 260, 308)), - array( 69, 532, 0, array( 104, 198, 288, 352)), - array( 73, 581, 3, array( 120, 216, 320, 384)), - array( 77, 655, 3, array( 132, 240, 360, 432)), //15 - array( 81, 733, 3, array( 144, 280, 408, 480)), - array( 85, 815, 3, array( 168, 308, 448, 532)), - array( 89, 901, 3, array( 180, 338, 504, 588)), - array( 93, 991, 3, array( 196, 364, 546, 650)), - array( 97, 1085, 3, array( 224, 416, 600, 700)), //20 - array(101, 1156, 4, array( 224, 442, 644, 750)), - array(105, 1258, 4, array( 252, 476, 690, 816)), - array(109, 1364, 4, array( 270, 504, 750, 900)), - array(113, 1474, 4, array( 300, 560, 810, 960)), - array(117, 1588, 4, array( 312, 588, 870, 1050)), //25 - array(121, 1706, 4, array( 336, 644, 952, 1110)), - array(125, 1828, 4, array( 360, 700, 1020, 1200)), - array(129, 1921, 3, array( 390, 728, 1050, 1260)), - array(133, 2051, 3, array( 420, 784, 1140, 1350)), - array(137, 2185, 3, array( 450, 812, 1200, 1440)), //30 - array(141, 2323, 3, array( 480, 868, 1290, 1530)), - array(145, 2465, 3, array( 510, 924, 1350, 1620)), - array(149, 2611, 3, array( 540, 980, 1440, 1710)), - array(153, 2761, 3, array( 570, 1036, 1530, 1800)), - array(157, 2876, 0, array( 570, 1064, 1590, 1890)), //35 - array(161, 3034, 0, array( 600, 1120, 1680, 1980)), - array(165, 3196, 0, array( 630, 1204, 1770, 2100)), - array(169, 3362, 0, array( 660, 1260, 1860, 2220)), - array(173, 3532, 0, array( 720, 1316, 1950, 2310)), - array(177, 3706, 0, array( 750, 1372, 2040, 2430)) //40 - ); - //---------------------------------------------------------------------- public static function getDataLength($version, $level) { return self::$capacity[$version][QRCAP_WORDS] - self::$capacity[$version][QRCAP_EC][$level]; } - + //---------------------------------------------------------------------- public static function getECCLength($version, $level) { return self::$capacity[$version][QRCAP_EC][$level]; } - + //---------------------------------------------------------------------- public static function getWidth($version) { return self::$capacity[$version][QRCAP_WIDTH]; } - + //---------------------------------------------------------------------- public static function getRemainder($version) { return self::$capacity[$version][QRCAP_REMINDER]; } - + //---------------------------------------------------------------------- public static function getMinimumVersion($size, $level) { - - for($i=1; $i<= QRSPEC_VERSION_MAX; $i++) { - $words = self::$capacity[$i][QRCAP_WORDS] - self::$capacity[$i][QRCAP_EC][$level]; - if($words >= $size) + for ($i = 1; $i <= QRSPEC_VERSION_MAX; $i++) { + $words = self::$capacity[$i][QRCAP_WORDS] - self::$capacity[$i][QRCAP_EC][$level]; + if ($words >= $size) { return $i; + } } return -1; } - + //###################################################################### - - public static $lengthTableBits = array( - array(10, 12, 14), - array( 9, 11, 13), - array( 8, 16, 16), - array( 8, 10, 12) - ); - + + public static $lengthTableBits = [ + [10, 12, 14], + [9, 11, 13], + [8, 16, 16], + [8, 10, 12] + ]; + //---------------------------------------------------------------------- public static function lengthIndicator($mode, $version) { - if ($mode == QR_MODE_STRUCTURE) + if ($mode == QR_MODE_STRUCTURE) { return 0; - + } + if ($version <= 9) { $l = 0; - } else if ($version <= 26) { + } elseif ($version <= 26) { $l = 1; } else { $l = 2; @@ -459,16 +439,17 @@ return self::$lengthTableBits[$mode][$l]; } - + //---------------------------------------------------------------------- public static function maximumWords($mode, $version) { - if($mode == QR_MODE_STRUCTURE) + if ($mode == QR_MODE_STRUCTURE) { return 3; - - if($version <= 9) { + } + + if ($version <= 9) { $l = 0; - } else if($version <= 26) { + } elseif ($version <= 26) { $l = 1; } else { $l = 2; @@ -476,8 +457,8 @@ $bits = self::$lengthTableBits[$mode][$l]; $words = (1 << $bits) - 1; - - if($mode == QR_MODE_KANJI) { + + if ($mode == QR_MODE_KANJI) { $words *= 2; // the number of bytes is required } @@ -488,74 +469,74 @@ // Table of the error correction code (Reed-Solomon block) // See Table 12-16 (pp.30-36), JIS X0510:2004. - public static $eccTable = array( - array(array( 0, 0), array( 0, 0), array( 0, 0), array( 0, 0)), - array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), // 1 - array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), - array(array( 1, 0), array( 1, 0), array( 2, 0), array( 2, 0)), - array(array( 1, 0), array( 2, 0), array( 2, 0), array( 4, 0)), - array(array( 1, 0), array( 2, 0), array( 2, 2), array( 2, 2)), // 5 - array(array( 2, 0), array( 4, 0), array( 4, 0), array( 4, 0)), - array(array( 2, 0), array( 4, 0), array( 2, 4), array( 4, 1)), - array(array( 2, 0), array( 2, 2), array( 4, 2), array( 4, 2)), - array(array( 2, 0), array( 3, 2), array( 4, 4), array( 4, 4)), - array(array( 2, 2), array( 4, 1), array( 6, 2), array( 6, 2)), //10 - array(array( 4, 0), array( 1, 4), array( 4, 4), array( 3, 8)), - array(array( 2, 2), array( 6, 2), array( 4, 6), array( 7, 4)), - array(array( 4, 0), array( 8, 1), array( 8, 4), array(12, 4)), - array(array( 3, 1), array( 4, 5), array(11, 5), array(11, 5)), - array(array( 5, 1), array( 5, 5), array( 5, 7), array(11, 7)), //15 - array(array( 5, 1), array( 7, 3), array(15, 2), array( 3, 13)), - array(array( 1, 5), array(10, 1), array( 1, 15), array( 2, 17)), - array(array( 5, 1), array( 9, 4), array(17, 1), array( 2, 19)), - array(array( 3, 4), array( 3, 11), array(17, 4), array( 9, 16)), - array(array( 3, 5), array( 3, 13), array(15, 5), array(15, 10)), //20 - array(array( 4, 4), array(17, 0), array(17, 6), array(19, 6)), - array(array( 2, 7), array(17, 0), array( 7, 16), array(34, 0)), - array(array( 4, 5), array( 4, 14), array(11, 14), array(16, 14)), - array(array( 6, 4), array( 6, 14), array(11, 16), array(30, 2)), - array(array( 8, 4), array( 8, 13), array( 7, 22), array(22, 13)), //25 - array(array(10, 2), array(19, 4), array(28, 6), array(33, 4)), - array(array( 8, 4), array(22, 3), array( 8, 26), array(12, 28)), - array(array( 3, 10), array( 3, 23), array( 4, 31), array(11, 31)), - array(array( 7, 7), array(21, 7), array( 1, 37), array(19, 26)), - array(array( 5, 10), array(19, 10), array(15, 25), array(23, 25)), //30 - array(array(13, 3), array( 2, 29), array(42, 1), array(23, 28)), - array(array(17, 0), array(10, 23), array(10, 35), array(19, 35)), - array(array(17, 1), array(14, 21), array(29, 19), array(11, 46)), - array(array(13, 6), array(14, 23), array(44, 7), array(59, 1)), - array(array(12, 7), array(12, 26), array(39, 14), array(22, 41)), //35 - array(array( 6, 14), array( 6, 34), array(46, 10), array( 2, 64)), - array(array(17, 4), array(29, 14), array(49, 10), array(24, 46)), - array(array( 4, 18), array(13, 32), array(48, 14), array(42, 32)), - array(array(20, 4), array(40, 7), array(43, 22), array(10, 67)), - array(array(19, 6), array(18, 31), array(34, 34), array(20, 61)),//40 - ); + public static $eccTable = [ + [[0, 0], [0, 0], [0, 0], [0, 0]], + [[1, 0], [1, 0], [1, 0], [1, 0]], // 1 + [[1, 0], [1, 0], [1, 0], [1, 0]], + [[1, 0], [1, 0], [2, 0], [2, 0]], + [[1, 0], [2, 0], [2, 0], [4, 0]], + [[1, 0], [2, 0], [2, 2], [2, 2]], // 5 + [[2, 0], [4, 0], [4, 0], [4, 0]], + [[2, 0], [4, 0], [2, 4], [4, 1]], + [[2, 0], [2, 2], [4, 2], [4, 2]], + [[2, 0], [3, 2], [4, 4], [4, 4]], + [[2, 2], [4, 1], [6, 2], [6, 2]], //10 + [[4, 0], [1, 4], [4, 4], [3, 8]], + [[2, 2], [6, 2], [4, 6], [7, 4]], + [[4, 0], [8, 1], [8, 4], [12, 4]], + [[3, 1], [4, 5], [11, 5], [11, 5]], + [[5, 1], [5, 5], [5, 7], [11, 7]], //15 + [[5, 1], [7, 3], [15, 2], [3, 13]], + [[1, 5], [10, 1], [1, 15], [2, 17]], + [[5, 1], [9, 4], [17, 1], [2, 19]], + [[3, 4], [3, 11], [17, 4], [9, 16]], + [[3, 5], [3, 13], [15, 5], [15, 10]], //20 + [[4, 4], [17, 0], [17, 6], [19, 6]], + [[2, 7], [17, 0], [7, 16], [34, 0]], + [[4, 5], [4, 14], [11, 14], [16, 14]], + [[6, 4], [6, 14], [11, 16], [30, 2]], + [[8, 4], [8, 13], [7, 22], [22, 13]], //25 + [[10, 2], [19, 4], [28, 6], [33, 4]], + [[8, 4], [22, 3], [8, 26], [12, 28]], + [[3, 10], [3, 23], [4, 31], [11, 31]], + [[7, 7], [21, 7], [1, 37], [19, 26]], + [[5, 10], [19, 10], [15, 25], [23, 25]], //30 + [[13, 3], [2, 29], [42, 1], [23, 28]], + [[17, 0], [10, 23], [10, 35], [19, 35]], + [[17, 1], [14, 21], [29, 19], [11, 46]], + [[13, 6], [14, 23], [44, 7], [59, 1]], + [[12, 7], [12, 26], [39, 14], [22, 41]], //35 + [[6, 14], [6, 34], [46, 10], [2, 64]], + [[17, 4], [29, 14], [49, 10], [24, 46]], + [[4, 18], [13, 32], [48, 14], [42, 32]], + [[20, 4], [40, 7], [43, 22], [10, 67]], + [[19, 6], [18, 31], [34, 34], [20, 61]], //40 + ]; //---------------------------------------------------------------------- // CACHEABLE!!! - + public static function getEccSpec($version, $level, array &$spec) { if (count($spec) < 5) { - $spec = array(0,0,0,0,0); + $spec = [0, 0, 0, 0, 0]; } - $b1 = self::$eccTable[$version][$level][0]; - $b2 = self::$eccTable[$version][$level][1]; + $b1 = self::$eccTable[$version][$level][0]; + $b2 = self::$eccTable[$version][$level][1]; $data = self::getDataLength($version, $level); - $ecc = self::getECCLength($version, $level); + $ecc = self::getECCLength($version, $level); - if($b2 == 0) { + if ($b2 == 0) { $spec[0] = $b1; - $spec[1] = (int)($data / $b1); - $spec[2] = (int)($ecc / $b1); - $spec[3] = 0; + $spec[1] = (int) ($data / $b1); + $spec[2] = (int) ($ecc / $b1); + $spec[3] = 0; $spec[4] = 0; } else { $spec[0] = $b1; - $spec[1] = (int)($data / ($b1 + $b2)); - $spec[2] = (int)($ecc / ($b1 + $b2)); + $spec[1] = (int) ($data / ($b1 + $b2)); + $spec[2] = (int) ($ecc / ($b1 + $b2)); $spec[3] = $b2; $spec[4] = $spec[1] + 1; } @@ -564,80 +545,82 @@ // Alignment pattern --------------------------------------------------- // Positions of alignment patterns. - // This array includes only the second and the third position of the - // alignment patterns. Rest of them can be calculated from the distance + // This array includes only the second and the third position of the + // alignment patterns. Rest of them can be calculated from the distance // between them. - - // See Table 1 in Appendix E (pp.71) of JIS X0510:2004. - - public static $alignmentPattern = array( - array( 0, 0), - array( 0, 0), array(18, 0), array(22, 0), array(26, 0), array(30, 0), // 1- 5 - array(34, 0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), // 6-10 - array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), //11-15 - array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), //16-20 - array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), //21-25 - array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), //26-30 - array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), //31-35 - array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58), //35-40 - ); - + // See Table 1 in Appendix E (pp.71) of JIS X0510:2004. + + public static $alignmentPattern = [ + [0, 0], + [0, 0], [18, 0], [22, 0], [26, 0], [30, 0], // 1- 5 + [34, 0], [22, 38], [24, 42], [26, 46], [28, 50], // 6-10 + [30, 54], [32, 58], [34, 62], [26, 46], [26, 48], //11-15 + [26, 50], [30, 54], [30, 56], [30, 58], [34, 62], //16-20 + [28, 50], [26, 50], [30, 54], [28, 54], [32, 58], //21-25 + [30, 58], [34, 62], [26, 50], [30, 54], [26, 52], //26-30 + [30, 56], [34, 60], [30, 58], [34, 62], [30, 54], //31-35 + [24, 50], [28, 54], [32, 58], [26, 54], [30, 58], //35-40 + ]; + /** -------------------------------------------------------------------- * Put an alignment marker. + * * @param frame * @param width * @param ox,oy center coordinate of the pattern */ public static function putAlignmentMarker(array &$frame, $ox, $oy) { - $finder = array( + $finder = [ "\xa1\xa1\xa1\xa1\xa1", "\xa1\xa0\xa0\xa0\xa1", "\xa1\xa0\xa1\xa0\xa1", "\xa1\xa0\xa0\xa0\xa1", "\xa1\xa1\xa1\xa1\xa1" - ); - - $yStart = $oy-2; - $xStart = $ox-2; - - for($y=0; $y<5; $y++) { - QRstr::set($frame, $xStart, $yStart+$y, $finder[$y]); + ]; + + $yStart = $oy - 2; + $xStart = $ox - 2; + + for ($y = 0; $y < 5; $y++) { + QRstr::set($frame, $xStart, $yStart + $y, $finder[$y]); } } //---------------------------------------------------------------------- public static function putAlignmentPattern($version, &$frame, $width) { - if($version < 2) + if ($version < 2) { return; - - $d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0]; - if($d < 0) { - $w = 2; - } else { - $w = (int)(($width - self::$alignmentPattern[$version][0]) / $d + 2); } - if($w * $w - 3 == 1) { + $d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0]; + if ($d < 0) { + $w = 2; + } else { + $w = (int) (($width - self::$alignmentPattern[$version][0]) / $d + 2); + } + + if ($w * $w - 3 == 1) { $x = self::$alignmentPattern[$version][0]; $y = self::$alignmentPattern[$version][0]; self::putAlignmentMarker($frame, $x, $y); + return; } $cx = self::$alignmentPattern[$version][0]; - for($x=1; $x<$w - 1; $x++) { + for ($x = 1; $x < $w - 1; $x++) { self::putAlignmentMarker($frame, 6, $cx); - self::putAlignmentMarker($frame, $cx, 6); + self::putAlignmentMarker($frame, $cx, 6); $cx += $d; } $cy = self::$alignmentPattern[$version][0]; - for($y=0; $y<$w-1; $y++) { + for ($y = 0; $y < $w - 1; $y++) { $cx = self::$alignmentPattern[$version][0]; - for($x=0; $x<$w-1; $x++) { + for ($x = 0; $x < $w - 1; $x++) { self::putAlignmentMarker($frame, $cx, $cy); $cx += $d; } @@ -647,63 +630,67 @@ // Version information pattern ----------------------------------------- - // Version information pattern (BCH coded). + // Version information pattern (BCH coded). // See Table 1 in Appendix D (pp.68) of JIS X0510:2004. - - // size: [QRSPEC_VERSION_MAX - 6] - - public static $versionPattern = array( + + // size: [QRSPEC_VERSION_MAX - 6] + + public static $versionPattern = [ 0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d, 0x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9, 0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75, 0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64, 0x27541, 0x28c69 - ); + ]; //---------------------------------------------------------------------- public static function getVersionPattern($version) { - if($version < 7 || $version > QRSPEC_VERSION_MAX) + if ($version < 7 || $version > QRSPEC_VERSION_MAX) { return 0; + } - return self::$versionPattern[$version -7]; + return self::$versionPattern[$version - 7]; } // Format information -------------------------------------------------- // See calcFormatInfo in tests/test_qrspec.c (orginal qrencode c lib) - - public static $formatInfo = array( - array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976), - array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0), - array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed), - array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b) - ); + + public static $formatInfo = [ + [0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976], + [0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0], + [0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed], + [0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b] + ]; public static function getFormatInfo($mask, $level) { - if($mask < 0 || $mask > 7) + if ($mask < 0 || $mask > 7) { return 0; - - if($level < 0 || $level > 3) - return 0; + } + + if ($level < 0 || $level > 3) { + return 0; + } return self::$formatInfo[$level][$mask]; } // Frame --------------------------------------------------------------- // Cache of initial frames. - - public static $frames = array(); + + public static $frames = []; /** -------------------------------------------------------------------- * Put a finder pattern. + * * @param frame * @param width * @param ox,oy upper-left coordinate of the pattern */ public static function putFinderPattern(&$frame, $ox, $oy) { - $finder = array( + $finder = [ "\xc1\xc1\xc1\xc1\xc1\xc1\xc1", "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", @@ -711,10 +698,10 @@ "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", "\xc1\xc1\xc1\xc1\xc1\xc1\xc1" - ); - - for($y=0; $y<7; $y++) { - QRstr::set($frame, $ox, $oy+$y, $finder[$y]); + ]; + + for ($y = 0; $y < 7; $y++) { + QRstr::set($frame, $ox, $oy + $y, $finder[$y]); } } @@ -722,77 +709,77 @@ public static function createFrame($version) { $width = self::$capacity[$version][QRCAP_WIDTH]; - $frameLine = str_repeat ("\0", $width); + $frameLine = str_repeat("\0", $width); $frame = array_fill(0, $width, $frameLine); // Finder pattern self::putFinderPattern($frame, 0, 0); self::putFinderPattern($frame, $width - 7, 0); self::putFinderPattern($frame, 0, $width - 7); - + // Separator $yOffset = $width - 7; - - for($y=0; $y<7; $y++) { + + for ($y = 0; $y < 7; $y++) { $frame[$y][7] = "\xc0"; $frame[$y][$width - 8] = "\xc0"; $frame[$yOffset][7] = "\xc0"; $yOffset++; } - + $setPattern = str_repeat("\xc0", 8); - + QRstr::set($frame, 0, 7, $setPattern); - QRstr::set($frame, $width-8, 7, $setPattern); + QRstr::set($frame, $width - 8, 7, $setPattern); QRstr::set($frame, 0, $width - 8, $setPattern); - + // Format info $setPattern = str_repeat("\x84", 9); QRstr::set($frame, 0, 8, $setPattern); QRstr::set($frame, $width - 8, 8, $setPattern, 8); - + $yOffset = $width - 8; - for($y=0; $y<8; $y++,$yOffset++) { + for ($y = 0; $y < 8; $y++,$yOffset++) { $frame[$y][8] = "\x84"; $frame[$yOffset][8] = "\x84"; } - // Timing pattern - - for($i=1; $i<$width-15; $i++) { - $frame[6][7+$i] = chr(0x90 | ($i & 1)); - $frame[7+$i][6] = chr(0x90 | ($i & 1)); + // Timing pattern + + for ($i = 1; $i < $width - 15; $i++) { + $frame[6][7 + $i] = chr(0x90 | ($i & 1)); + $frame[7 + $i][6] = chr(0x90 | ($i & 1)); } - - // Alignment pattern + + // Alignment pattern self::putAlignmentPattern($version, $frame, $width); - - // Version information - if($version >= 7) { + + // Version information + if ($version >= 7) { $vinf = self::getVersionPattern($version); $v = $vinf; - - for($x=0; $x<6; $x++) { - for($y=0; $y<3; $y++) { - $frame[($width - 11)+$y][$x] = chr(0x88 | ($v & 1)); + + for ($x = 0; $x < 6; $x++) { + for ($y = 0; $y < 3; $y++) { + $frame[($width - 11) + $y][$x] = chr(0x88 | ($v & 1)); $v = $v >> 1; } } $v = $vinf; - for($y=0; $y<6; $y++) { - for($x=0; $x<3; $x++) { - $frame[$y][$x+($width - 11)] = chr(0x88 | ($v & 1)); + for ($y = 0; $y < 6; $y++) { + for ($x = 0; $x < 3; $x++) { + $frame[$y][$x + ($width - 11)] = chr(0x88 | ($v & 1)); $v = $v >> 1; } } } - - // and a little bit... + + // and a little bit... $frame[$width - 8][8] = "\x81"; - + return $frame; } @@ -800,40 +787,33 @@ public static function debug($frame, $binary_mode = false) { if ($binary_mode) { - - foreach ($frame as &$frameLine) { - $frameLine = join('  ', explode('0', $frameLine)); - $frameLine = join('██', explode('1', $frameLine)); - } - - ?> + foreach ($frame as &$frameLine) { + $frameLine = implode('  ', explode('0', $frameLine)); + $frameLine = implode('██', explode('1', $frameLine)); + } ?>


            '; - echo join("
            ", $frame); - echo '






    '; - + echo implode('
            ', $frame); + echo '





    '; } else { - foreach ($frame as &$frameLine) { - $frameLine = join(' ', explode("\xc0", $frameLine)); - $frameLine = join('', explode("\xc1", $frameLine)); - $frameLine = join(' ', explode("\xa0", $frameLine)); - $frameLine = join('', explode("\xa1", $frameLine)); - $frameLine = join('', explode("\x84", $frameLine)); //format 0 - $frameLine = join('', explode("\x85", $frameLine)); //format 1 - $frameLine = join('', explode("\x81", $frameLine)); //special bit - $frameLine = join(' ', explode("\x90", $frameLine)); //clock 0 - $frameLine = join('', explode("\x91", $frameLine)); //clock 1 - $frameLine = join(' ', explode("\x88", $frameLine)); //version - $frameLine = join('', explode("\x89", $frameLine)); //version - $frameLine = join('♦', explode("\x01", $frameLine)); - $frameLine = join('⋅', explode("\0", $frameLine)); - } - - ?> + $frameLine = implode(' ', explode("\xc0", $frameLine)); + $frameLine = implode('', explode("\xc1", $frameLine)); + $frameLine = implode(' ', explode("\xa0", $frameLine)); + $frameLine = implode('', explode("\xa1", $frameLine)); + $frameLine = implode('', explode("\x84", $frameLine)); //format 0 + $frameLine = implode('', explode("\x85", $frameLine)); //format 1 + $frameLine = implode('', explode("\x81", $frameLine)); //special bit + $frameLine = implode(' ', explode("\x90", $frameLine)); //clock 0 + $frameLine = implode('', explode("\x91", $frameLine)); //clock 1 + $frameLine = implode(' ', explode("\x88", $frameLine)); //version + $frameLine = implode('', explode("\x89", $frameLine)); //version + $frameLine = implode('♦', explode("\x01", $frameLine)); + $frameLine = implode('⋅', explode("\0", $frameLine)); + } ?> "; - echo join("
    ", $frame); - echo "
    "; - + echo '
    ';
    +                echo implode('
    ', $frame); + echo '
    '; } } //---------------------------------------------------------------------- public static function serial($frame) { - return gzcompress(join("\n", $frame), 9); + return gzcompress(implode("\n", $frame), 9); } - + //---------------------------------------------------------------------- public static function unserial($code) { return explode("\n", gzuncompress($code)); } - + //---------------------------------------------------------------------- public static function newFrame($version) { - if($version < 1 || $version > QRSPEC_VERSION_MAX) - return null; + if ($version < 1 || $version > QRSPEC_VERSION_MAX) { + return; + } - if(!isset(self::$frames[$version])) { - + if (!isset(self::$frames[$version])) { $fileName = QR_CACHE_DIR.'frame_'.$version.'.dat'; - + if (QR_CACHEABLE) { if (file_exists($fileName)) { self::$frames[$version] = self::unserial(file_get_contents($fileName)); @@ -883,33 +862,63 @@ self::$frames[$version] = self::createFrame($version); } } - - if(is_null(self::$frames[$version])) - return null; + + if (is_null(self::$frames[$version])) { + return; + } return self::$frames[$version]; } //---------------------------------------------------------------------- - public static function rsBlockNum($spec) { return $spec[0] + $spec[3]; } - public static function rsBlockNum1($spec) { return $spec[0]; } - public static function rsDataCodes1($spec) { return $spec[1]; } - public static function rsEccCodes1($spec) { return $spec[2]; } - public static function rsBlockNum2($spec) { return $spec[3]; } - public static function rsDataCodes2($spec) { return $spec[4]; } - public static function rsEccCodes2($spec) { return $spec[2]; } - public static function rsDataLength($spec) { return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]); } - public static function rsEccLength($spec) { return ($spec[0] + $spec[3]) * $spec[2]; } - + public static function rsBlockNum($spec) + { + return $spec[0] + $spec[3]; + } + + public static function rsBlockNum1($spec) + { + return $spec[0]; + } + + public static function rsDataCodes1($spec) + { + return $spec[1]; + } + + public static function rsEccCodes1($spec) + { + return $spec[2]; + } + + public static function rsBlockNum2($spec) + { + return $spec[3]; + } + + public static function rsDataCodes2($spec) + { + return $spec[4]; + } + + public static function rsEccCodes2($spec) + { + return $spec[2]; + } + + public static function rsDataLength($spec) + { + return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]); + } + + public static function rsEccLength($spec) + { + return ($spec[0] + $spec[3]) * $spec[2]; + } } - - //---- qrimage.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -932,86 +941,81 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - + define('QR_IMAGE', true); - class QRimage { - + class QRimage + { //---------------------------------------------------------------------- - public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4,$saveandprint=FALSE) + public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4, $saveandprint = false) { $image = self::image($frame, $pixelPerPoint, $outerFrame); - + if ($filename === false) { - Header("Content-type: image/png"); - ImagePng($image); + header('Content-type: image/png'); + imagepng($image); } else { - if($saveandprint===TRUE){ - ImagePng($image, $filename); - header("Content-type: image/png"); - ImagePng($image); - }else{ - ImagePng($image, $filename); + if ($saveandprint === true) { + imagepng($image, $filename); + header('Content-type: image/png'); + imagepng($image); + } else { + imagepng($image, $filename); } } - - ImageDestroy($image); + + imagedestroy($image); } - + //---------------------------------------------------------------------- - public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85) + public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85) { $image = self::image($frame, $pixelPerPoint, $outerFrame); - + if ($filename === false) { - Header("Content-type: image/jpeg"); - ImageJpeg($image, null, $q); + header('Content-type: image/jpeg'); + imagejpeg($image, null, $q); } else { - ImageJpeg($image, $filename, $q); + imagejpeg($image, $filename, $q); } - - ImageDestroy($image); + + imagedestroy($image); } - + //---------------------------------------------------------------------- - private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4) + private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4) { $h = count($frame); $w = strlen($frame[0]); - - $imgW = $w + 2*$outerFrame; - $imgH = $h + 2*$outerFrame; - - $base_image =ImageCreate($imgW, $imgH); - - $col[0] = ImageColorAllocate($base_image,255,255,255); - $col[1] = ImageColorAllocate($base_image,0,0,0); + + $imgW = $w + 2 * $outerFrame; + $imgH = $h + 2 * $outerFrame; + + $base_image = imagecreate($imgW, $imgH); + + $col[0] = imagecolorallocate($base_image, 255, 255, 255); + $col[1] = imagecolorallocate($base_image, 0, 0, 0); imagefill($base_image, 0, 0, $col[0]); - for($y=0; $y<$h; $y++) { - for($x=0; $x<$w; $x++) { + for ($y = 0; $y < $h; $y++) { + for ($x = 0; $x < $w; $x++) { if ($frame[$y][$x] == '1') { - ImageSetPixel($base_image,$x+$outerFrame,$y+$outerFrame,$col[1]); + imagesetpixel($base_image, $x + $outerFrame, $y + $outerFrame, $col[1]); } } } - - $target_image =ImageCreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint); - ImageCopyResized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH); - ImageDestroy($base_image); - + + $target_image = imagecreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint); + imagecopyresized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH); + imagedestroy($base_image); + return $target_image; } } - - //---- qrinput.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -1037,102 +1041,101 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - define('STRUCTURE_HEADER_BITS', 20); + + define('STRUCTURE_HEADER_BITS', 20); define('MAX_STRUCTURED_SYMBOLS', 16); - class QRinputItem { - + class QRinputItem + { public $mode; public $size; public $data; public $bstream; - public function __construct($mode, $size, $data, $bstream = null) + public function __construct($mode, $size, $data, $bstream = null) { $setData = array_slice($data, 0, $size); - + if (count($setData) < $size) { - $setData = array_merge($setData, array_fill(0,$size-count($setData),0)); + $setData = array_merge($setData, array_fill(0, $size - count($setData), 0)); } - - if(!QRinput::check($mode, $size, $setData)) { - throw new Exception('Error m:'.$mode.',s:'.$size.',d:'.join(',',$setData)); - return null; + + if (!QRinput::check($mode, $size, $setData)) { + throw new Exception('Error m:'.$mode.',s:'.$size.',d:'.implode(',', $setData)); + return; } - + $this->mode = $mode; $this->size = $size; $this->data = $setData; $this->bstream = $bstream; } - + //---------------------------------------------------------------------- public function encodeModeNum($version) { try { - - $words = (int)($this->size / 3); + $words = (int) ($this->size / 3); $bs = new QRbitstream(); - + $val = 0x1; $bs->appendNum(4, $val); $bs->appendNum(QRspec::lengthIndicator(QR_MODE_NUM, $version), $this->size); - for($i=0; $i<$words; $i++) { - $val = (ord($this->data[$i*3 ]) - ord('0')) * 100; - $val += (ord($this->data[$i*3+1]) - ord('0')) * 10; - $val += (ord($this->data[$i*3+2]) - ord('0')); + for ($i = 0; $i < $words; $i++) { + $val = (ord($this->data[$i * 3]) - ord('0')) * 100; + $val += (ord($this->data[$i * 3 + 1]) - ord('0')) * 10; + $val += (ord($this->data[$i * 3 + 2]) - ord('0')); $bs->appendNum(10, $val); } - if($this->size - $words * 3 == 1) { - $val = ord($this->data[$words*3]) - ord('0'); + if ($this->size - $words * 3 == 1) { + $val = ord($this->data[$words * 3]) - ord('0'); $bs->appendNum(4, $val); - } else if($this->size - $words * 3 == 2) { - $val = (ord($this->data[$words*3 ]) - ord('0')) * 10; - $val += (ord($this->data[$words*3+1]) - ord('0')); + } elseif ($this->size - $words * 3 == 2) { + $val = (ord($this->data[$words * 3]) - ord('0')) * 10; + $val += (ord($this->data[$words * 3 + 1]) - ord('0')); $bs->appendNum(7, $val); } $this->bstream = $bs; + return 0; - } catch (Exception $e) { return -1; } } - + //---------------------------------------------------------------------- public function encodeModeAn($version) { try { - $words = (int)($this->size / 2); + $words = (int) ($this->size / 2); $bs = new QRbitstream(); - + $bs->appendNum(4, 0x02); $bs->appendNum(QRspec::lengthIndicator(QR_MODE_AN, $version), $this->size); - for($i=0; $i<$words; $i++) { - $val = (int)QRinput::lookAnTable(ord($this->data[$i*2 ])) * 45; - $val += (int)QRinput::lookAnTable(ord($this->data[$i*2+1])); + for ($i = 0; $i < $words; $i++) { + $val = (int) QRinput::lookAnTable(ord($this->data[$i * 2])) * 45; + $val += (int) QRinput::lookAnTable(ord($this->data[$i * 2 + 1])); $bs->appendNum(11, $val); } - if($this->size & 1) { + if ($this->size & 1) { $val = QRinput::lookAnTable(ord($this->data[$words * 2])); $bs->appendNum(6, $val); } - + $this->bstream = $bs; + return 0; - } catch (Exception $e) { return -1; } } - + //---------------------------------------------------------------------- public function encodeMode8($version) { @@ -1142,36 +1145,35 @@ $bs->appendNum(4, 0x4); $bs->appendNum(QRspec::lengthIndicator(QR_MODE_8, $version), $this->size); - for($i=0; $i<$this->size; $i++) { + for ($i = 0; $i < $this->size; $i++) { $bs->appendNum(8, ord($this->data[$i])); } $this->bstream = $bs; + return 0; - } catch (Exception $e) { return -1; } } - + //---------------------------------------------------------------------- public function encodeModeKanji($version) { try { - $bs = new QRbitrtream(); - - $bs->appendNum(4, 0x8); - $bs->appendNum(QRspec::lengthIndicator(QR_MODE_KANJI, $version), (int)($this->size / 2)); - for($i=0; $i<$this->size; $i+=2) { - $val = (ord($this->data[$i]) << 8) | ord($this->data[$i+1]); - if($val <= 0x9ffc) { + $bs->appendNum(4, 0x8); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_KANJI, $version), (int) ($this->size / 2)); + + for ($i = 0; $i < $this->size; $i += 2) { + $val = (ord($this->data[$i]) << 8) | ord($this->data[$i + 1]); + if ($val <= 0x9ffc) { $val -= 0x8140; } else { $val -= 0xc140; } - + $h = ($val >> 8) * 0xc0; $val = ($val & 0xff) + $h; @@ -1179,8 +1181,8 @@ } $this->bstream = $bs; + return 0; - } catch (Exception $e) { return -1; } @@ -1190,129 +1192,126 @@ public function encodeModeStructure() { try { - $bs = new QRbitstream(); - + $bs = new QRbitstream(); + $bs->appendNum(4, 0x03); $bs->appendNum(4, ord($this->data[1]) - 1); $bs->appendNum(4, ord($this->data[0]) - 1); $bs->appendNum(8, ord($this->data[2])); $this->bstream = $bs; + return 0; - } catch (Exception $e) { return -1; } } - + //---------------------------------------------------------------------- public function estimateBitStreamSizeOfEntry($version) { $bits = 0; - if($version == 0) + if ($version == 0) { $version = 1; + } - switch($this->mode) { - case QR_MODE_NUM: $bits = QRinput::estimateBitsModeNum($this->size); break; - case QR_MODE_AN: $bits = QRinput::estimateBitsModeAn($this->size); break; - case QR_MODE_8: $bits = QRinput::estimateBitsMode8($this->size); break; - case QR_MODE_KANJI: $bits = QRinput::estimateBitsModeKanji($this->size);break; - case QR_MODE_STRUCTURE: return STRUCTURE_HEADER_BITS; + switch ($this->mode) { + case QR_MODE_NUM: $bits = QRinput::estimateBitsModeNum($this->size); break; + case QR_MODE_AN: $bits = QRinput::estimateBitsModeAn($this->size); break; + case QR_MODE_8: $bits = QRinput::estimateBitsMode8($this->size); break; + case QR_MODE_KANJI: $bits = QRinput::estimateBitsModeKanji($this->size); break; + case QR_MODE_STRUCTURE: return STRUCTURE_HEADER_BITS; default: return 0; } $l = QRspec::lengthIndicator($this->mode, $version); $m = 1 << $l; - $num = (int)(($this->size + $m - 1) / $m); + $num = (int) (($this->size + $m - 1) / $m); $bits += $num * (4 + $l); return $bits; } - + //---------------------------------------------------------------------- public function encodeBitStream($version) { try { - unset($this->bstream); $words = QRspec::maximumWords($this->mode, $version); - - if($this->size > $words) { - - $st1 = new QRinputItem($this->mode, $words, $this->data); - $st2 = new QRinputItem($this->mode, $this->size - $words, array_slice($this->data, $words)); + + if ($this->size > $words) { + $st1 = new self($this->mode, $words, $this->data); + $st2 = new self($this->mode, $this->size - $words, array_slice($this->data, $words)); $st1->encodeBitStream($version); $st2->encodeBitStream($version); - + $this->bstream = new QRbitstream(); $this->bstream->append($st1->bstream); $this->bstream->append($st2->bstream); - + unset($st1); unset($st2); - } else { - $ret = 0; - - switch($this->mode) { - case QR_MODE_NUM: $ret = $this->encodeModeNum($version); break; - case QR_MODE_AN: $ret = $this->encodeModeAn($version); break; - case QR_MODE_8: $ret = $this->encodeMode8($version); break; - case QR_MODE_KANJI: $ret = $this->encodeModeKanji($version);break; - case QR_MODE_STRUCTURE: $ret = $this->encodeModeStructure(); break; - + + switch ($this->mode) { + case QR_MODE_NUM: $ret = $this->encodeModeNum($version); break; + case QR_MODE_AN: $ret = $this->encodeModeAn($version); break; + case QR_MODE_8: $ret = $this->encodeMode8($version); break; + case QR_MODE_KANJI: $ret = $this->encodeModeKanji($version); break; + case QR_MODE_STRUCTURE: $ret = $this->encodeModeStructure(); break; + default: break; } - - if($ret < 0) + + if ($ret < 0) { return -1; + } } return $this->bstream->size(); - } catch (Exception $e) { return -1; } } - }; - + } + //########################################################################## - class QRinput { - + class QRinput + { public $items; - + private $version; private $level; - + //---------------------------------------------------------------------- public function __construct($version = 0, $level = QR_ECLEVEL_L) { if ($version < 0 || $version > QRSPEC_VERSION_MAX || $level > QR_ECLEVEL_H) { throw new Exception('Invalid version no'); - return NULL; + return; } - + $this->version = $version; $this->level = $level; } - + //---------------------------------------------------------------------- public function getVersion() { return $this->version; } - + //---------------------------------------------------------------------- public function setVersion($version) { - if($version < 0 || $version > QRSPEC_VERSION_MAX) { + if ($version < 0 || $version > QRSPEC_VERSION_MAX) { throw new Exception('Invalid version no'); return -1; } @@ -1321,7 +1320,7 @@ return 0; } - + //---------------------------------------------------------------------- public function getErrorCorrectionLevel() { @@ -1331,7 +1330,7 @@ //---------------------------------------------------------------------- public function setErrorCorrectionLevel($level) { - if($level > QR_ECLEVEL_H) { + if ($level > QR_ECLEVEL_H) { throw new Exception('Invalid ECLEVEL'); return -1; } @@ -1340,42 +1339,44 @@ return 0; } - + //---------------------------------------------------------------------- public function appendEntry(QRinputItem $entry) { $this->items[] = $entry; } - + //---------------------------------------------------------------------- public function append($mode, $size, $data) { try { $entry = new QRinputItem($mode, $size, $data); $this->items[] = $entry; + return 0; } catch (Exception $e) { return -1; } } - + //---------------------------------------------------------------------- - + public function insertStructuredAppendHeader($size, $index, $parity) { - if( $size > MAX_STRUCTURED_SYMBOLS ) { + if ($size > MAX_STRUCTURED_SYMBOLS) { throw new Exception('insertStructuredAppendHeader wrong size'); } - - if( $index <= 0 || $index > MAX_STRUCTURED_SYMBOLS ) { + + if ($index <= 0 || $index > MAX_STRUCTURED_SYMBOLS) { throw new Exception('insertStructuredAppendHeader wrong index'); } - $buf = array($size, $index, $parity); - + $buf = [$size, $index, $parity]; + try { $entry = new QRinputItem(QR_MODE_STRUCTURE, 3, buf); array_unshift($this->items, $entry); + return 0; } catch (Exception $e) { return -1; @@ -1386,10 +1387,10 @@ public function calcParity() { $parity = 0; - - foreach($this->items as $item) { - if($item->mode != QR_MODE_STRUCTURE) { - for($i=$item->size-1; $i>=0; $i--) { + + foreach ($this->items as $item) { + if ($item->mode != QR_MODE_STRUCTURE) { + for ($i = $item->size - 1; $i >= 0; $i--) { $parity ^= $item->data[$i]; } } @@ -1397,12 +1398,12 @@ return $parity; } - + //---------------------------------------------------------------------- public static function checkModeNum($size, $data) { - for($i=0; $i<$size; $i++) { - if((ord($data[$i]) < ord('0')) || (ord($data[$i]) > ord('9'))){ + for ($i = 0; $i < $size; $i++) { + if ((ord($data[$i]) < ord('0')) || (ord($data[$i]) > ord('9'))) { return false; } } @@ -1413,10 +1414,10 @@ //---------------------------------------------------------------------- public static function estimateBitsModeNum($size) { - $w = (int)$size / 3; + $w = (int) $size / 3; $bits = $w * 10; - - switch($size - $w * 3) { + + switch ($size - $w * 3) { case 1: $bits += 4; break; @@ -1429,9 +1430,9 @@ return $bits; } - + //---------------------------------------------------------------------- - public static $anTable = array( + public static $anTable = [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, @@ -1440,18 +1441,18 @@ 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - ); - + ]; + //---------------------------------------------------------------------- public static function lookAnTable($c) { - return (($c > 127)?-1:self::$anTable[$c]); + return ($c > 127) ? -1 : self::$anTable[$c]; } - + //---------------------------------------------------------------------- public static function checkModeAn($size, $data) { - for($i=0; $i<$size; $i++) { + for ($i = 0; $i < $size; $i++) { if (self::lookAnTable(ord($data[$i])) == -1) { return false; } @@ -1459,42 +1460,43 @@ return true; } - + //---------------------------------------------------------------------- public static function estimateBitsModeAn($size) { - $w = (int)($size / 2); + $w = (int) ($size / 2); $bits = $w * 11; - - if($size & 1) { + + if ($size & 1) { $bits += 6; } return $bits; } - + //---------------------------------------------------------------------- public static function estimateBitsMode8($size) { return $size * 8; } - + //---------------------------------------------------------------------- public function estimateBitsModeKanji($size) { - return (int)(($size / 2) * 13); + return (int) (($size / 2) * 13); } - + //---------------------------------------------------------------------- public static function checkModeKanji($size, $data) { - if($size & 1) + if ($size & 1) { return false; + } - for($i=0; $i<$size; $i+=2) { - $val = (ord($data[$i]) << 8) | ord($data[$i+1]); - if( $val < 0x8140 - || ($val > 0x9ffc && $val < 0xe040) + for ($i = 0; $i < $size; $i += 2) { + $val = (ord($data[$i]) << 8) | ord($data[$i + 1]); + if ($val < 0x8140 + || ($val > 0x9ffc && $val < 0xe040) || $val > 0xebbf) { return false; } @@ -1509,36 +1511,36 @@ public static function check($mode, $size, $data) { - if($size <= 0) + if ($size <= 0) { return false; + } - switch($mode) { - case QR_MODE_NUM: return self::checkModeNum($size, $data); break; - case QR_MODE_AN: return self::checkModeAn($size, $data); break; + switch ($mode) { + case QR_MODE_NUM: return self::checkModeNum($size, $data); break; + case QR_MODE_AN: return self::checkModeAn($size, $data); break; case QR_MODE_KANJI: return self::checkModeKanji($size, $data); break; case QR_MODE_8: return true; break; case QR_MODE_STRUCTURE: return true; break; - + default: break; } return false; } - - + //---------------------------------------------------------------------- public function estimateBitStreamSize($version) { $bits = 0; - foreach($this->items as $item) { + foreach ($this->items as $item) { $bits += $item->estimateBitStreamSizeOfEntry($version); } return $bits; } - + //---------------------------------------------------------------------- public function estimateVersion() { @@ -1547,7 +1549,7 @@ do { $prev = $version; $bits = $this->estimateBitStreamSize($prev); - $version = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); + $version = QRspec::getMinimumVersion((int) (($bits + 7) / 8), $this->level); if ($version < 0) { return -1; } @@ -1555,86 +1557,93 @@ return $version; } - + //---------------------------------------------------------------------- public static function lengthOfCode($mode, $version, $bits) { $payload = $bits - 4 - QRspec::lengthIndicator($mode, $version); - switch($mode) { + switch ($mode) { case QR_MODE_NUM: - $chunks = (int)($payload / 10); + $chunks = (int) ($payload / 10); $remain = $payload - $chunks * 10; $size = $chunks * 3; - if($remain >= 7) { + if ($remain >= 7) { $size += 2; - } else if($remain >= 4) { + } elseif ($remain >= 4) { $size += 1; } break; case QR_MODE_AN: - $chunks = (int)($payload / 11); + $chunks = (int) ($payload / 11); $remain = $payload - $chunks * 11; $size = $chunks * 2; - if($remain >= 6) + if ($remain >= 6) { $size++; + } break; case QR_MODE_8: - $size = (int)($payload / 8); + $size = (int) ($payload / 8); break; case QR_MODE_KANJI: - $size = (int)(($payload / 13) * 2); + $size = (int) (($payload / 13) * 2); break; case QR_MODE_STRUCTURE: - $size = (int)($payload / 8); + $size = (int) ($payload / 8); break; default: $size = 0; break; } - + $maxsize = QRspec::maximumWords($mode, $version); - if($size < 0) $size = 0; - if($size > $maxsize) $size = $maxsize; + if ($size < 0) { + $size = 0; + } + if ($size > $maxsize) { + $size = $maxsize; + } return $size; } - + //---------------------------------------------------------------------- public function createBitStream() { $total = 0; - foreach($this->items as $item) { + foreach ($this->items as $item) { $bits = $item->encodeBitStream($this->version); - - if($bits < 0) + + if ($bits < 0) { return -1; - + } + $total += $bits; } return $total; } - + //---------------------------------------------------------------------- public function convertData() { $ver = $this->estimateVersion(); - if($ver > $this->getVersion()) { + if ($ver > $this->getVersion()) { $this->setVersion($ver); } - for(;;) { + for (; ;) { $bits = $this->createBitStream(); - - if($bits < 0) + + if ($bits < 0) { return -1; - - $ver = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); - if($ver < 0) { + } + + $ver = QRspec::getMinimumVersion((int) (($bits + 7) / 8), $this->level); + if ($ver < 0) { throw new Exception('WRONG VERSION'); return -1; - } else if($ver > $this->getVersion()) { + } elseif ($ver > $this->getVersion()) { $this->setVersion($ver); } else { break; @@ -1643,7 +1652,7 @@ return 0; } - + //---------------------------------------------------------------------- public function appendPaddingBit(&$bstream) { @@ -1660,48 +1669,48 @@ } $bits += 4; - $words = (int)(($bits + 7) / 8); + $words = (int) (($bits + 7) / 8); $padding = new QRbitstream(); $ret = $padding->appendNum($words * 8 - $bits + 4, 0); - - if($ret < 0) + + if ($ret < 0) { return $ret; + } $padlen = $maxwords - $words; - - if($padlen > 0) { - - $padbuf = array(); - for($i=0; $i<$padlen; $i++) { - $padbuf[$i] = ($i&1)?0x11:0xec; + + if ($padlen > 0) { + $padbuf = []; + for ($i = 0; $i < $padlen; $i++) { + $padbuf[$i] = ($i & 1) ? 0x11 : 0xec; } - + $ret = $padding->appendBytes($padlen, $padbuf); - - if($ret < 0) + + if ($ret < 0) { return $ret; - + } } $ret = $bstream->append($padding); - + return $ret; } //---------------------------------------------------------------------- public function mergeBitStream() { - if($this->convertData() < 0) { - return null; + if ($this->convertData() < 0) { + return; } $bstream = new QRbitstream(); - - foreach($this->items as $item) { + + foreach ($this->items as $item) { $ret = $bstream->append($item->bstream); - if($ret < 0) { - return null; + if ($ret < 0) { + return; } } @@ -1711,43 +1720,34 @@ //---------------------------------------------------------------------- public function getBitStream() { - $bstream = $this->mergeBitStream(); - - if($bstream == null) { - return null; + + if ($bstream == null) { + return; } - + $ret = $this->appendPaddingBit($bstream); - if($ret < 0) { - return null; + if ($ret < 0) { + return; } return $bstream; } - + //---------------------------------------------------------------------- public function getByteStream() { $bstream = $this->getBitStream(); - if($bstream == null) { - return null; + if ($bstream == null) { + return; } - + return $bstream->toByte(); } } - - - - - //---- qrbitstream.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -1773,33 +1773,34 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - class QRbitstream { - - public $data = array(); - + + class QRbitstream + { + public $data = []; + //---------------------------------------------------------------------- public function size() { return count($this->data); } - + //---------------------------------------------------------------------- public function allocate($setLength) { $this->data = array_fill(0, $setLength, 0); + return 0; } - + //---------------------------------------------------------------------- public static function newFromNum($bits, $num) { - $bstream = new QRbitstream(); + $bstream = new self(); $bstream->allocate($bits); - + $mask = 1 << ($bits - 1); - for($i=0; $i<$bits; $i++) { - if($num & $mask) { + for ($i = 0; $i < $bits; $i++) { + if ($num & $mask) { $bstream->data[$i] = 1; } else { $bstream->data[$i] = 0; @@ -1809,18 +1810,18 @@ return $bstream; } - + //---------------------------------------------------------------------- public static function newFromBytes($size, $data) { - $bstream = new QRbitstream(); + $bstream = new self(); $bstream->allocate($size * 8); - $p=0; + $p = 0; - for($i=0; $i<$size; $i++) { + for ($i = 0; $i < $size; $i++) { $mask = 0x80; - for($j=0; $j<8; $j++) { - if($data[$i] & $mask) { + for ($j = 0; $j < 8; $j++) { + if ($data[$i] & $mask) { $bstream->data[$p] = 1; } else { $bstream->data[$p] = 0; @@ -1832,38 +1833,41 @@ return $bstream; } - + //---------------------------------------------------------------------- - public function append(QRbitstream $arg) + public function append(self $arg) { if (is_null($arg)) { return -1; } - - if($arg->size() == 0) { + + if ($arg->size() == 0) { return 0; } - - if($this->size() == 0) { + + if ($this->size() == 0) { $this->data = $arg->data; + return 0; } - + $this->data = array_values(array_merge($this->data, $arg->data)); return 0; } - + //---------------------------------------------------------------------- public function appendNum($bits, $num) { - if ($bits == 0) + if ($bits == 0) { return 0; + } - $b = QRbitstream::newFromNum($bits, $num); - - if(is_null($b)) + $b = self::newFromNum($bits, $num); + + if (is_null($b)) { return -1; + } $ret = $this->append($b); unset($b); @@ -1874,48 +1878,49 @@ //---------------------------------------------------------------------- public function appendBytes($size, $data) { - if ($size == 0) + if ($size == 0) { return 0; + } - $b = QRbitstream::newFromBytes($size, $data); - - if(is_null($b)) + $b = self::newFromBytes($size, $data); + + if (is_null($b)) { return -1; + } $ret = $this->append($b); unset($b); return $ret; } - + //---------------------------------------------------------------------- public function toByte() { - $size = $this->size(); - if($size == 0) { - return array(); + if ($size == 0) { + return []; } - - $data = array_fill(0, (int)(($size + 7) / 8), 0); - $bytes = (int)($size / 8); + + $data = array_fill(0, (int) (($size + 7) / 8), 0); + $bytes = (int) ($size / 8); $p = 0; - - for($i=0; $i<$bytes; $i++) { + + for ($i = 0; $i < $bytes; $i++) { $v = 0; - for($j=0; $j<8; $j++) { + for ($j = 0; $j < 8; $j++) { $v = $v << 1; $v |= $this->data[$p]; $p++; } $data[$i] = $v; } - - if($size & 7) { + + if ($size & 7) { $v = 0; - for($j=0; $j<($size & 7); $j++) { + for ($j = 0; $j < ($size & 7); $j++) { $v = $v << 1; $v |= $this->data[$p]; $p++; @@ -1925,17 +1930,10 @@ return $data; } - } - - - //---- qrsplit.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -1950,7 +1948,7 @@ * The following data / specifications are taken from * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004) * or - * "Automatic identification and data capture techniques -- + * "Automatic identification and data capture techniques -- * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006) * * This library is free software; you can redistribute it and/or @@ -1967,122 +1965,124 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - class QRsplit { - + class QRsplit + { public $dataStr = ''; public $input; public $modeHint; //---------------------------------------------------------------------- - public function __construct($dataStr, $input, $modeHint) + public function __construct($dataStr, $input, $modeHint) { - $this->dataStr = $dataStr; - $this->input = $input; + $this->dataStr = $dataStr; + $this->input = $input; $this->modeHint = $modeHint; } - + //---------------------------------------------------------------------- public static function isdigitat($str, $pos) - { - if ($pos >= strlen($str)) + { + if ($pos >= strlen($str)) { return false; - - return ((ord($str[$pos]) >= ord('0'))&&(ord($str[$pos]) <= ord('9'))); + } + + return (ord($str[$pos]) >= ord('0')) && (ord($str[$pos]) <= ord('9')); } - + //---------------------------------------------------------------------- public static function isalnumat($str, $pos) { - if ($pos >= strlen($str)) + if ($pos >= strlen($str)) { return false; - - return (QRinput::lookAnTable(ord($str[$pos])) >= 0); + } + + return QRinput::lookAnTable(ord($str[$pos])) >= 0; } //---------------------------------------------------------------------- public function identifyMode($pos) { - if ($pos >= strlen($this->dataStr)) + if ($pos >= strlen($this->dataStr)) { return QR_MODE_NUL; - + } + $c = $this->dataStr[$pos]; - - if(self::isdigitat($this->dataStr, $pos)) { + + if (self::isdigitat($this->dataStr, $pos)) { return QR_MODE_NUM; - } else if(self::isalnumat($this->dataStr, $pos)) { + } elseif (self::isalnumat($this->dataStr, $pos)) { return QR_MODE_AN; - } else if($this->modeHint == QR_MODE_KANJI) { - - if ($pos+1 < strlen($this->dataStr)) - { - $d = $this->dataStr[$pos+1]; + } elseif ($this->modeHint == QR_MODE_KANJI) { + if ($pos + 1 < strlen($this->dataStr)) { + $d = $this->dataStr[$pos + 1]; $word = (ord($c) << 8) | ord($d); - if(($word >= 0x8140 && $word <= 0x9ffc) || ($word >= 0xe040 && $word <= 0xebbf)) { + if (($word >= 0x8140 && $word <= 0x9ffc) || ($word >= 0xe040 && $word <= 0xebbf)) { return QR_MODE_KANJI; } } } return QR_MODE_8; - } - + } + //---------------------------------------------------------------------- public function eatNum() { $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); $p = 0; - while(self::isdigitat($this->dataStr, $p)) { + while (self::isdigitat($this->dataStr, $p)) { $p++; } - + $run = $p; $mode = $this->identifyMode($p); - - if($mode == QR_MODE_8) { + + if ($mode == QR_MODE_8) { $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln + QRinput::estimateBitsMode8(1) // + 4 + l8 - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 - if($dif > 0) { + if ($dif > 0) { return $this->eat8(); } } - if($mode == QR_MODE_AN) { + if ($mode == QR_MODE_AN) { $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln + QRinput::estimateBitsModeAn(1) // + 4 + la - - QRinput::estimateBitsModeAn($run + 1);// - 4 - la - if($dif > 0) { + - QRinput::estimateBitsModeAn($run + 1); // - 4 - la + if ($dif > 0) { return $this->eatAn(); } } - + $ret = $this->input->append(QR_MODE_NUM, $run, str_split($this->dataStr)); - if($ret < 0) + if ($ret < 0) { return -1; + } return $run; } - + //---------------------------------------------------------------------- public function eatAn() { - $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); + $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); $p = 0; - - while(self::isalnumat($this->dataStr, $p)) { - if(self::isdigitat($this->dataStr, $p)) { + + while (self::isalnumat($this->dataStr, $p)) { + if (self::isdigitat($this->dataStr, $p)) { $q = $p; - while(self::isdigitat($this->dataStr, $q)) { + while (self::isdigitat($this->dataStr, $q)) { $q++; } - + $dif = QRinput::estimateBitsModeAn($p) // + 4 + la + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln - QRinput::estimateBitsModeAn($q); // - 4 - la - - if($dif < 0) { + + if ($dif < 0) { break; } else { $p = $q; @@ -2094,34 +2094,36 @@ $run = $p; - if(!self::isalnumat($this->dataStr, $p)) { + if (!self::isalnumat($this->dataStr, $p)) { $dif = QRinput::estimateBitsModeAn($run) + 4 + $la + QRinput::estimateBitsMode8(1) // + 4 + l8 - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 - if($dif > 0) { + if ($dif > 0) { return $this->eat8(); } } $ret = $this->input->append(QR_MODE_AN, $run, str_split($this->dataStr)); - if($ret < 0) + if ($ret < 0) { return -1; + } return $run; } - + //---------------------------------------------------------------------- public function eatKanji() { $p = 0; - - while($this->identifyMode($p) == QR_MODE_KANJI) { + + while ($this->identifyMode($p) == QR_MODE_KANJI) { $p += 2; } - + $ret = $this->input->append(QR_MODE_KANJI, $p, str_split($this->dataStr)); - if($ret < 0) + if ($ret < 0) { return -1; + } return $run; } @@ -2134,35 +2136,34 @@ $p = 1; $dataStrLen = strlen($this->dataStr); - - while($p < $dataStrLen) { - + + while ($p < $dataStrLen) { $mode = $this->identifyMode($p); - if($mode == QR_MODE_KANJI) { + if ($mode == QR_MODE_KANJI) { break; } - if($mode == QR_MODE_NUM) { + if ($mode == QR_MODE_NUM) { $q = $p; - while(self::isdigitat($this->dataStr, $q)) { + while (self::isdigitat($this->dataStr, $q)) { $q++; } $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln - QRinput::estimateBitsMode8($q); // - 4 - l8 - if($dif < 0) { + if ($dif < 0) { break; } else { $p = $q; } - } else if($mode == QR_MODE_AN) { + } elseif ($mode == QR_MODE_AN) { $q = $p; - while(self::isalnumat($this->dataStr, $q)) { + while (self::isalnumat($this->dataStr, $q)) { $q++; } $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 + QRinput::estimateBitsModeAn($q - $p) + 4 + $la - QRinput::estimateBitsMode8($q); // - 4 - l8 - if($dif < 0) { + if ($dif < 0) { break; } else { $p = $q; @@ -2174,9 +2175,10 @@ $run = $p; $ret = $this->input->append(QR_MODE_8, $run, str_split($this->dataStr)); - - if($ret < 0) + + if ($ret < 0) { return -1; + } return $run; } @@ -2184,28 +2186,34 @@ //---------------------------------------------------------------------- public function splitString() { - while (strlen($this->dataStr) > 0) - { - if($this->dataStr == '') + while (strlen($this->dataStr) > 0) { + if ($this->dataStr == '') { return 0; + } $mode = $this->identifyMode(0); - + switch ($mode) { case QR_MODE_NUM: $length = $this->eatNum(); break; case QR_MODE_AN: $length = $this->eatAn(); break; case QR_MODE_KANJI: - if ($hint == QR_MODE_KANJI) - $length = $this->eatKanji(); - else $length = $this->eat8(); + if ($hint == QR_MODE_KANJI) { + $length = $this->eatKanji(); + } else { + $length = $this->eat8(); + } break; default: $length = $this->eat8(); break; - + + } + + if ($length == 0) { + return 0; + } + if ($length < 0) { + return -1; } - if($length == 0) return 0; - if($length < 0) return -1; - $this->dataStr = substr($this->dataStr, $length); } } @@ -2215,10 +2223,10 @@ { $stringLen = strlen($this->dataStr); $p = 0; - - while ($p<$stringLen) { + + while ($p < $stringLen) { $mode = self::identifyMode(substr($this->dataStr, $p), $this->modeHint); - if($mode == QR_MODE_KANJI) { + if ($mode == QR_MODE_KANJI) { $p += 2; } else { if (ord($this->dataStr[$p]) >= ord('a') && ord($this->dataStr[$p]) <= ord('z')) { @@ -2234,31 +2242,27 @@ //---------------------------------------------------------------------- public static function splitStringToQRinput($string, QRinput $input, $modeHint, $casesensitive = true) { - if(is_null($string) || $string == '\0' || $string == '') { + if (is_null($string) || $string == '\0' || $string == '') { throw new Exception('empty string!!!'); } - $split = new QRsplit($string, $input, $modeHint); - - if(!$casesensitive) + $split = new self($string, $input, $modeHint); + + if (!$casesensitive) { $split->toUpper(); - + } + return $split->splitString(); } } - - //---- qrrscode.php ----------------------------- - - - /* * PHP QR Code encoder * * Reed-Solomon error correction support - * + * * Copyright (C) 2002, 2003, 2004, 2006 Phil Karn, KA9Q * (libfec is released under the GNU Lesser General Public License.) * @@ -2282,21 +2286,21 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - class QRrsItem { - - public $mm; // Bits per symbol - public $nn; // Symbols per block (= (1<nn; $x = ($x >> $this->mm) + ($x & $this->nn); } - + return $x; } - + //---------------------------------------------------------------------- public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) { @@ -2316,119 +2320,129 @@ // May be used under the terms of the GNU Lesser General Public License (LGPL) $rs = null; - - // Check parameter ranges - if($symsize < 0 || $symsize > 8) return $rs; - if($fcr < 0 || $fcr >= (1<<$symsize)) return $rs; - if($prim <= 0 || $prim >= (1<<$symsize)) return $rs; - if($nroots < 0 || $nroots >= (1<<$symsize)) return $rs; // Can't have more roots than symbol values! - if($pad < 0 || $pad >= ((1<<$symsize) -1 - $nroots)) return $rs; // Too much padding - $rs = new QRrsItem(); + // Check parameter ranges + if ($symsize < 0 || $symsize > 8) { + return $rs; + } + if ($fcr < 0 || $fcr >= (1 << $symsize)) { + return $rs; + } + if ($prim <= 0 || $prim >= (1 << $symsize)) { + return $rs; + } + if ($nroots < 0 || $nroots >= (1 << $symsize)) { + return $rs; + } // Can't have more roots than symbol values! + if ($pad < 0 || $pad >= ((1 << $symsize) - 1 - $nroots)) { + return $rs; + } // Too much padding + + $rs = new self(); $rs->mm = $symsize; - $rs->nn = (1<<$symsize)-1; + $rs->nn = (1 << $symsize) - 1; $rs->pad = $pad; - $rs->alpha_to = array_fill(0, $rs->nn+1, 0); - $rs->index_of = array_fill(0, $rs->nn+1, 0); - + $rs->alpha_to = array_fill(0, $rs->nn + 1, 0); + $rs->index_of = array_fill(0, $rs->nn + 1, 0); + // PHP style macro replacement ;) - $NN =& $rs->nn; - $A0 =& $NN; - + $NN = &$rs->nn; + $A0 = &$NN; + // Generate Galois field lookup tables $rs->index_of[0] = $A0; // log(zero) = -inf $rs->alpha_to[$A0] = 0; // alpha**-inf = 0 $sr = 1; - - for($i=0; $i<$rs->nn; $i++) { + + for ($i = 0; $i < $rs->nn; $i++) { $rs->index_of[$sr] = $i; $rs->alpha_to[$i] = $sr; $sr <<= 1; - if($sr & (1<<$symsize)) { + if ($sr & (1 << $symsize)) { $sr ^= $gfpoly; } $sr &= $rs->nn; } - - if($sr != 1){ + + if ($sr != 1) { // field generator polynomial is not primitive! - $rs = NULL; + $rs = null; + return $rs; } /* Form RS code generator polynomial from its roots */ - $rs->genpoly = array_fill(0, $nroots+1, 0); - + $rs->genpoly = array_fill(0, $nroots + 1, 0); + $rs->fcr = $fcr; $rs->prim = $prim; $rs->nroots = $nroots; $rs->gfpoly = $gfpoly; /* Find prim-th root of 1, used in decoding */ - for($iprim=1;($iprim % $prim) != 0;$iprim += $rs->nn) - ; // intentional empty-body loop! - - $rs->iprim = (int)($iprim / $prim); + for ($iprim = 1; ($iprim % $prim) != 0; $iprim += $rs->nn); // intentional empty-body loop! + + $rs->iprim = (int) ($iprim / $prim); $rs->genpoly[0] = 1; - - for ($i = 0,$root=$fcr*$prim; $i < $nroots; $i++, $root += $prim) { - $rs->genpoly[$i+1] = 1; + + for ($i = 0,$root = $fcr * $prim; $i < $nroots; $i++, $root += $prim) { + $rs->genpoly[$i + 1] = 1; // Multiply rs->genpoly[] by @**(root + x) for ($j = $i; $j > 0; $j--) { if ($rs->genpoly[$j] != 0) { - $rs->genpoly[$j] = $rs->genpoly[$j-1] ^ $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[$j]] + $root)]; + $rs->genpoly[$j] = $rs->genpoly[$j - 1] ^ $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[$j]] + $root)]; } else { - $rs->genpoly[$j] = $rs->genpoly[$j-1]; + $rs->genpoly[$j] = $rs->genpoly[$j - 1]; } } // rs->genpoly[0] can never be zero $rs->genpoly[0] = $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[0]] + $root)]; } - + // convert rs->genpoly[] to index form for quicker encoding - for ($i = 0; $i <= $nroots; $i++) + for ($i = 0; $i <= $nroots; $i++) { $rs->genpoly[$i] = $rs->index_of[$rs->genpoly[$i]]; + } return $rs; } - + //---------------------------------------------------------------------- public function encode_rs_char($data, &$parity) { - $MM =& $this->mm; - $NN =& $this->nn; - $ALPHA_TO =& $this->alpha_to; - $INDEX_OF =& $this->index_of; - $GENPOLY =& $this->genpoly; - $NROOTS =& $this->nroots; - $FCR =& $this->fcr; - $PRIM =& $this->prim; - $IPRIM =& $this->iprim; - $PAD =& $this->pad; - $A0 =& $NN; + $MM = &$this->mm; + $NN = &$this->nn; + $ALPHA_TO = &$this->alpha_to; + $INDEX_OF = &$this->index_of; + $GENPOLY = &$this->genpoly; + $NROOTS = &$this->nroots; + $FCR = &$this->fcr; + $PRIM = &$this->prim; + $IPRIM = &$this->iprim; + $PAD = &$this->pad; + $A0 = &$NN; $parity = array_fill(0, $NROOTS, 0); - for($i=0; $i< ($NN-$NROOTS-$PAD); $i++) { - + for ($i = 0; $i < ($NN - $NROOTS - $PAD); $i++) { $feedback = $INDEX_OF[$data[$i] ^ $parity[0]]; - if($feedback != $A0) { + if ($feedback != $A0) { // feedback term is non-zero - + // This line is unnecessary when GENPOLY[NROOTS] is unity, as it must // always be for the polynomials constructed by init_rs() $feedback = $this->modnn($NN - $GENPOLY[$NROOTS] + $feedback); - - for($j=1;$j<$NROOTS;$j++) { - $parity[$j] ^= $ALPHA_TO[$this->modnn($feedback + $GENPOLY[$NROOTS-$j])]; + + for ($j = 1; $j < $NROOTS; $j++) { + $parity[$j] ^= $ALPHA_TO[$this->modnn($feedback + $GENPOLY[$NROOTS - $j])]; } } - - // Shift + + // Shift array_shift($parity); - if($feedback != $A0) { + if ($feedback != $A0) { array_push($parity, $ALPHA_TO[$this->modnn($feedback + $GENPOLY[0])]); } else { array_push($parity, 0); @@ -2436,23 +2450,35 @@ } } } - + //########################################################################## - - class QRrs { - - public static $items = array(); - + + class QRrs + { + public static $items = []; + //---------------------------------------------------------------------- public static function init_rs($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) { - foreach(self::$items as $rs) { - if($rs->pad != $pad) continue; - if($rs->nroots != $nroots) continue; - if($rs->mm != $symsize) continue; - if($rs->gfpoly != $gfpoly) continue; - if($rs->fcr != $fcr) continue; - if($rs->prim != $prim) continue; + foreach (self::$items as $rs) { + if ($rs->pad != $pad) { + continue; + } + if ($rs->nroots != $nroots) { + continue; + } + if ($rs->mm != $symsize) { + continue; + } + if ($rs->gfpoly != $gfpoly) { + continue; + } + if ($rs->fcr != $fcr) { + continue; + } + if ($rs->prim != $prim) { + continue; + } return $rs; } @@ -2464,13 +2490,8 @@ } } - - //---- qrmask.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -2496,125 +2517,157 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - define('N1', 3); - define('N2', 3); - define('N3', 40); - define('N4', 10); - class QRmask { - - public $runLength = array(); - - //---------------------------------------------------------------------- - public function __construct() + define('N1', 3); + define('N2', 3); + define('N3', 40); + define('N4', 10); + + class QRmask + { + public $runLength = []; + + //---------------------------------------------------------------------- + public function __construct() { $this->runLength = array_fill(0, QRSPEC_WIDTH_MAX + 1, 0); } - + //---------------------------------------------------------------------- public function writeFormatInformation($width, &$frame, $mask, $level) { $blacks = 0; - $format = QRspec::getFormatInfo($mask, $level); + $format = QRspec::getFormatInfo($mask, $level); - for($i=0; $i<8; $i++) { - if($format & 1) { + for ($i = 0; $i < 8; $i++) { + if ($format & 1) { $blacks += 2; $v = 0x85; } else { $v = 0x84; } - + $frame[8][$width - 1 - $i] = chr($v); - if($i < 6) { + if ($i < 6) { $frame[$i][8] = chr($v); } else { $frame[$i + 1][8] = chr($v); } $format = $format >> 1; } - - for($i=0; $i<7; $i++) { - if($format & 1) { + + for ($i = 0; $i < 7; $i++) { + if ($format & 1) { $blacks += 2; $v = 0x85; } else { $v = 0x84; } - + $frame[$width - 7 + $i][8] = chr($v); - if($i == 0) { + if ($i == 0) { $frame[8][7] = chr($v); } else { $frame[8][6 - $i] = chr($v); } - + $format = $format >> 1; } return $blacks; } - + //---------------------------------------------------------------------- - public function mask0($x, $y) { return ($x+$y)&1; } - public function mask1($x, $y) { return ($y&1); } - public function mask2($x, $y) { return ($x%3); } - public function mask3($x, $y) { return ($x+$y)%3; } - public function mask4($x, $y) { return (((int)($y/2))+((int)($x/3)))&1; } - public function mask5($x, $y) { return (($x*$y)&1)+($x*$y)%3; } - public function mask6($x, $y) { return ((($x*$y)&1)+($x*$y)%3)&1; } - public function mask7($x, $y) { return ((($x*$y)%3)+(($x+$y)&1))&1; } - + public function mask0($x, $y) + { + return ($x + $y) & 1; + } + + public function mask1($x, $y) + { + return $y & 1; + } + + public function mask2($x, $y) + { + return $x % 3; + } + + public function mask3($x, $y) + { + return ($x + $y) % 3; + } + + public function mask4($x, $y) + { + return (((int) ($y / 2)) + ((int) ($x / 3))) & 1; + } + + public function mask5($x, $y) + { + return (($x * $y) & 1) + ($x * $y) % 3; + } + + public function mask6($x, $y) + { + return ((($x * $y) & 1) + ($x * $y) % 3) & 1; + } + + public function mask7($x, $y) + { + return ((($x * $y) % 3) + (($x + $y) & 1)) & 1; + } + //---------------------------------------------------------------------- private function generateMaskNo($maskNo, $width, $frame) { $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); - - for($y=0; $y<$width; $y++) { - for($x=0; $x<$width; $x++) { - if(ord($frame[$y][$x]) & 0x80) { + + for ($y = 0; $y < $width; $y++) { + for ($x = 0; $x < $width; $x++) { + if (ord($frame[$y][$x]) & 0x80) { $bitMask[$y][$x] = 0; } else { - $maskFunc = call_user_func(array($this, 'mask'.$maskNo), $x, $y); - $bitMask[$y][$x] = ($maskFunc == 0)?1:0; + $maskFunc = call_user_func([$this, 'mask'.$maskNo], $x, $y); + $bitMask[$y][$x] = ($maskFunc == 0) ? 1 : 0; } - } } - + return $bitMask; } - + //---------------------------------------------------------------------- public static function serial($bitFrame) { - $codeArr = array(); - - foreach ($bitFrame as $line) - $codeArr[] = join('', $line); - - return gzcompress(join("\n", $codeArr), 9); + $codeArr = []; + + foreach ($bitFrame as $line) { + $codeArr[] = implode('', $line); + } + + return gzcompress(implode("\n", $codeArr), 9); } - + //---------------------------------------------------------------------- public static function unserial($code) { - $codeArr = array(); - + $codeArr = []; + $codeLines = explode("\n", gzuncompress($code)); - foreach ($codeLines as $line) + foreach ($codeLines as $line) { $codeArr[] = str_split($line); - + } + return $codeArr; } - + //---------------------------------------------------------------------- - public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false) + public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false) { $b = 0; - $bitMask = array(); - + $bitMask = []; + $fileName = QR_CACHE_DIR.'mask_'.$maskNo.DIRECTORY_SEPARATOR.'mask_'.$width.'_'.$maskNo.'.dat'; if (QR_CACHEABLE) { @@ -2622,100 +2675,103 @@ $bitMask = self::unserial(file_get_contents($fileName)); } else { $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); - if (!file_exists(QR_CACHE_DIR.'mask_'.$maskNo)) + if (!file_exists(QR_CACHE_DIR.'mask_'.$maskNo)) { mkdir(QR_CACHE_DIR.'mask_'.$maskNo); + } file_put_contents($fileName, self::serial($bitMask)); } } else { $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); } - if ($maskGenOnly) + if ($maskGenOnly) { return; - + } + $d = $s; - for($y=0; $y<$width; $y++) { - for($x=0; $x<$width; $x++) { - if($bitMask[$y][$x] == 1) { - $d[$y][$x] = chr(ord($s[$y][$x]) ^ (int)$bitMask[$y][$x]); + for ($y = 0; $y < $width; $y++) { + for ($x = 0; $x < $width; $x++) { + if ($bitMask[$y][$x] == 1) { + $d[$y][$x] = chr(ord($s[$y][$x]) ^ (int) $bitMask[$y][$x]); } - $b += (int)(ord($d[$y][$x]) & 1); + $b += (int) (ord($d[$y][$x]) & 1); } } return $b; } - + //---------------------------------------------------------------------- public function makeMask($width, $frame, $maskNo, $level) { $masked = array_fill(0, $width, str_repeat("\0", $width)); $this->makeMaskNo($maskNo, $width, $frame, $masked); $this->writeFormatInformation($width, $masked, $maskNo, $level); - + return $masked; } - + //---------------------------------------------------------------------- public function calcN1N3($length) { $demerit = 0; - for($i=0; $i<$length; $i++) { - - if($this->runLength[$i] >= 5) { + for ($i = 0; $i < $length; $i++) { + if ($this->runLength[$i] >= 5) { $demerit += (N1 + ($this->runLength[$i] - 5)); } - if($i & 1) { - if(($i >= 3) && ($i < ($length-2)) && ($this->runLength[$i] % 3 == 0)) { - $fact = (int)($this->runLength[$i] / 3); - if(($this->runLength[$i-2] == $fact) && - ($this->runLength[$i-1] == $fact) && - ($this->runLength[$i+1] == $fact) && - ($this->runLength[$i+2] == $fact)) { - if(($this->runLength[$i-3] < 0) || ($this->runLength[$i-3] >= (4 * $fact))) { + if ($i & 1) { + if (($i >= 3) && ($i < ($length - 2)) && ($this->runLength[$i] % 3 == 0)) { + $fact = (int) ($this->runLength[$i] / 3); + if (($this->runLength[$i - 2] == $fact) && + ($this->runLength[$i - 1] == $fact) && + ($this->runLength[$i + 1] == $fact) && + ($this->runLength[$i + 2] == $fact)) { + if (($this->runLength[$i - 3] < 0) || ($this->runLength[$i - 3] >= (4 * $fact))) { $demerit += N3; - } else if((($i+3) >= $length) || ($this->runLength[$i+3] >= (4 * $fact))) { + } elseif ((($i + 3) >= $length) || ($this->runLength[$i + 3] >= (4 * $fact))) { $demerit += N3; } } } } } + return $demerit; } - + //---------------------------------------------------------------------- public function evaluateSymbol($width, $frame) { $head = 0; $demerit = 0; - for($y=0; $y<$width; $y++) { + for ($y = 0; $y < $width; $y++) { $head = 0; $this->runLength[0] = 1; - + $frameY = $frame[$y]; - - if ($y>0) - $frameYM = $frame[$y-1]; - - for($x=0; $x<$width; $x++) { - if(($x > 0) && ($y > 0)) { - $b22 = ord($frameY[$x]) & ord($frameY[$x-1]) & ord($frameYM[$x]) & ord($frameYM[$x-1]); - $w22 = ord($frameY[$x]) | ord($frameY[$x-1]) | ord($frameYM[$x]) | ord($frameYM[$x-1]); - - if(($b22 | ($w22 ^ 1))&1) { + + if ($y > 0) { + $frameYM = $frame[$y - 1]; + } + + for ($x = 0; $x < $width; $x++) { + if (($x > 0) && ($y > 0)) { + $b22 = ord($frameY[$x]) & ord($frameY[$x - 1]) & ord($frameYM[$x]) & ord($frameYM[$x - 1]); + $w22 = ord($frameY[$x]) | ord($frameY[$x - 1]) | ord($frameYM[$x]) | ord($frameYM[$x - 1]); + + if (($b22 | ($w22 ^ 1)) & 1) { $demerit += N2; } } - if(($x == 0) && (ord($frameY[$x]) & 1)) { + if (($x == 0) && (ord($frameY[$x]) & 1)) { $this->runLength[0] = -1; $head = 1; $this->runLength[$head] = 1; - } else if($x > 0) { - if((ord($frameY[$x]) ^ ord($frameY[$x-1])) & 1) { + } elseif ($x > 0) { + if ((ord($frameY[$x]) ^ ord($frameY[$x - 1])) & 1) { $head++; $this->runLength[$head] = 1; } else { @@ -2723,21 +2779,21 @@ } } } - - $demerit += $this->calcN1N3($head+1); + + $demerit += $this->calcN1N3($head + 1); } - for($x=0; $x<$width; $x++) { + for ($x = 0; $x < $width; $x++) { $head = 0; $this->runLength[0] = 1; - - for($y=0; $y<$width; $y++) { - if($y == 0 && (ord($frame[$y][$x]) & 1)) { + + for ($y = 0; $y < $width; $y++) { + if ($y == 0 && (ord($frame[$y][$x]) & 1)) { $this->runLength[0] = -1; $head = 1; $this->runLength[$head] = 1; - } else if($y > 0) { - if((ord($frame[$y][$x]) ^ ord($frame[$y-1][$x])) & 1) { + } elseif ($y > 0) { + if ((ord($frame[$y][$x]) ^ ord($frame[$y - 1][$x])) & 1) { $head++; $this->runLength[$head] = 1; } else { @@ -2745,68 +2801,59 @@ } } } - - $demerit += $this->calcN1N3($head+1); + + $demerit += $this->calcN1N3($head + 1); } return $demerit; } - - + //---------------------------------------------------------------------- public function mask($width, $frame, $level) { $minDemerit = PHP_INT_MAX; $bestMaskNum = 0; - $bestMask = array(); - - $checked_masks = array(0,1,2,3,4,5,6,7); - + $bestMask = []; + + $checked_masks = [0, 1, 2, 3, 4, 5, 6, 7]; + if (QR_FIND_FROM_RANDOM !== false) { - - $howManuOut = 8-(QR_FIND_FROM_RANDOM % 9); - for ($i = 0; $i < $howManuOut; $i++) { - $remPos = rand (0, count($checked_masks)-1); + $howManuOut = 8 - (QR_FIND_FROM_RANDOM % 9); + for ($i = 0; $i < $howManuOut; $i++) { + $remPos = rand(0, count($checked_masks) - 1); unset($checked_masks[$remPos]); $checked_masks = array_values($checked_masks); } - } - + $bestMask = $frame; - - foreach($checked_masks as $i) { + + foreach ($checked_masks as $i) { $mask = array_fill(0, $width, str_repeat("\0", $width)); $demerit = 0; $blacks = 0; - $blacks = $this->makeMaskNo($i, $width, $frame, $mask); + $blacks = $this->makeMaskNo($i, $width, $frame, $mask); $blacks += $this->writeFormatInformation($width, $mask, $i, $level); - $blacks = (int)(100 * $blacks / ($width * $width)); - $demerit = (int)((int)(abs($blacks - 50) / 5) * N4); + $blacks = (int) (100 * $blacks / ($width * $width)); + $demerit = (int) ((int) (abs($blacks - 50) / 5) * N4); $demerit += $this->evaluateSymbol($width, $mask); - - if($demerit < $minDemerit) { + + if ($demerit < $minDemerit) { $minDemerit = $demerit; $bestMask = $mask; $bestMaskNum = $i; } } - + return $bestMask; } - + //---------------------------------------------------------------------- } - - - //---- qrencode.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -2832,44 +2879,46 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - class QRrsblock { + + class QRrsblock + { public $dataLength; - public $data = array(); + public $data = []; public $eccLength; - public $ecc = array(); - + public $ecc = []; + public function __construct($dl, $data, $el, &$ecc, QRrsItem $rs) { $rs->encode_rs_char($data, $ecc); - + $this->dataLength = $dl; $this->data = $data; $this->eccLength = $el; $this->ecc = $ecc; } - }; - + } + //########################################################################## - class QRrawcode { + class QRrawcode + { public $version; - public $datacode = array(); - public $ecccode = array(); + public $datacode = []; + public $ecccode = []; public $blocks; - public $rsblocks = array(); //of RSblock + public $rsblocks = []; //of RSblock public $count; public $dataLength; public $eccLength; public $b1; - + //---------------------------------------------------------------------- public function __construct(QRinput $input) { - $spec = array(0,0,0,0,0); - + $spec = [0, 0, 0, 0, 0]; + $this->datacode = $input->getByteStream(); - if(is_null($this->datacode)) { + if (is_null($this->datacode)) { throw new Exception('null imput string'); } @@ -2881,51 +2930,53 @@ $this->eccLength = QRspec::rsEccLength($spec); $this->ecccode = array_fill(0, $this->eccLength, 0); $this->blocks = QRspec::rsBlockNum($spec); - + $ret = $this->init($spec); - if($ret < 0) { + if ($ret < 0) { throw new Exception('block alloc error'); - return null; + return; } $this->count = 0; } - + //---------------------------------------------------------------------- public function init(array $spec) { $dl = QRspec::rsDataCodes1($spec); $el = QRspec::rsEccCodes1($spec); $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); - $blockNo = 0; $dataPos = 0; $eccPos = 0; - for($i=0; $iecccode,$eccPos); - $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); - $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc); - + for ($i = 0; $i < QRspec::rsBlockNum1($spec); $i++) { + $ecc = array_slice($this->ecccode, $eccPos); + $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); + $this->ecccode = array_merge(array_slice($this->ecccode, 0, $eccPos), $ecc); + $dataPos += $dl; $eccPos += $el; $blockNo++; } - if(QRspec::rsBlockNum2($spec) == 0) + if (QRspec::rsBlockNum2($spec) == 0) { return 0; + } $dl = QRspec::rsDataCodes2($spec); $el = QRspec::rsEccCodes2($spec); $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); - - if($rs == NULL) return -1; - - for($i=0; $iecccode,$eccPos); + + if ($rs == null) { + return -1; + } + + for ($i = 0; $i < QRspec::rsBlockNum2($spec); $i++) { + $ecc = array_slice($this->ecccode, $eccPos); $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); - $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc); - + $this->ecccode = array_merge(array_slice($this->ecccode, 0, $eccPos), $ecc); + $dataPos += $dl; $eccPos += $el; $blockNo++; @@ -2933,20 +2984,20 @@ return 0; } - + //---------------------------------------------------------------------- public function getCode() { $ret; - if($this->count < $this->dataLength) { + if ($this->count < $this->dataLength) { $row = $this->count % $this->blocks; $col = $this->count / $this->blocks; - if($col >= $this->rsblocks[0]->dataLength) { + if ($col >= $this->rsblocks[0]->dataLength) { $row += $this->b1; } $ret = $this->rsblocks[$row]->data[$col]; - } else if($this->count < $this->dataLength + $this->eccLength) { + } elseif ($this->count < $this->dataLength + $this->eccLength) { $row = ($this->count - $this->dataLength) % $this->blocks; $col = ($this->count - $this->dataLength) / $this->blocks; $ret = $this->rsblocks[$row]->ecc[$col]; @@ -2954,72 +3005,70 @@ return 0; } $this->count++; - + return $ret; } } //########################################################################## - - class QRcode { - + + class QRcode + { public $version; public $width; - public $data; - + public $data; + //---------------------------------------------------------------------- public function encodeMask(QRinput $input, $mask) { - if($input->getVersion() < 0 || $input->getVersion() > QRSPEC_VERSION_MAX) { + if ($input->getVersion() < 0 || $input->getVersion() > QRSPEC_VERSION_MAX) { throw new Exception('wrong version'); } - if($input->getErrorCorrectionLevel() > QR_ECLEVEL_H) { + if ($input->getErrorCorrectionLevel() > QR_ECLEVEL_H) { throw new Exception('wrong level'); } $raw = new QRrawcode($input); - + QRtools::markTime('after_raw'); - + $version = $raw->version; $width = QRspec::getWidth($version); $frame = QRspec::newFrame($version); - + $filler = new FrameFiller($width, $frame); - if(is_null($filler)) { - return NULL; + if (is_null($filler)) { + return; } // inteleaved data and ecc codes - for($i=0; $i<$raw->dataLength + $raw->eccLength; $i++) { + for ($i = 0; $i < $raw->dataLength + $raw->eccLength; $i++) { $code = $raw->getCode(); $bit = 0x80; - for($j=0; $j<8; $j++) { + for ($j = 0; $j < 8; $j++) { $addr = $filler->next(); $filler->setFrameAt($addr, 0x02 | (($bit & $code) != 0)); $bit = $bit >> 1; } } - + QRtools::markTime('after_filler'); - + unset($raw); - + // remainder bits $j = QRspec::getRemainder($version); - for($i=0; $i<$j; $i++) { + for ($i = 0; $i < $j; $i++) { $addr = $filler->next(); $filler->setFrameAt($addr, 0x02); } - + $frame = $filler->frame; unset($filler); - - + // masking $maskObj = new QRmask(); - if($mask < 0) { - + if ($mask < 0) { if (QR_FIND_BEST_MASK) { $masked = $maskObj->mask($width, $frame, $input->getErrorCorrectionLevel()); } else { @@ -3028,98 +3077,106 @@ } else { $masked = $maskObj->makeMask($width, $frame, $mask, $input->getErrorCorrectionLevel()); } - - if($masked == NULL) { - return NULL; + + if ($masked == null) { + return; } - + QRtools::markTime('after_mask'); - + $this->version = $version; $this->width = $width; $this->data = $masked; - + return $this; } - + //---------------------------------------------------------------------- public function encodeInput(QRinput $input) { return $this->encodeMask($input, -1); } - + //---------------------------------------------------------------------- public function encodeString8bit($string, $version, $level) { - if(string == NULL) { + if (string == null) { throw new Exception('empty string!'); - return NULL; + return; } $input = new QRinput($version, $level); - if($input == NULL) return NULL; + if ($input == null) { + return; + } $ret = $input->append($input, QR_MODE_8, strlen($string), str_split($string)); - if($ret < 0) { + if ($ret < 0) { unset($input); - return NULL; + + return; } + return $this->encodeInput($input); } //---------------------------------------------------------------------- public function encodeString($string, $version, $level, $hint, $casesensitive) { - - if($hint != QR_MODE_8 && $hint != QR_MODE_KANJI) { + if ($hint != QR_MODE_8 && $hint != QR_MODE_KANJI) { throw new Exception('bad hint'); - return NULL; + return; } $input = new QRinput($version, $level); - if($input == NULL) return NULL; + if ($input == null) { + return; + } $ret = QRsplit::splitStringToQRinput($string, $input, $hint, $casesensitive); - if($ret < 0) { - return NULL; + if ($ret < 0) { + return; } return $this->encodeInput($input); } - + //---------------------------------------------------------------------- - public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false) + public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint = false) { $enc = QRencode::factory($level, $size, $margin); - return $enc->encodePNG($text, $outfile, $saveandprint=false); + + return $enc->encodePNG($text, $outfile, $saveandprint = false); } //---------------------------------------------------------------------- - public static function text($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) + public static function text($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) { $enc = QRencode::factory($level, $size, $margin); + return $enc->encode($text, $outfile); } //---------------------------------------------------------------------- - public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) + public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) { $enc = QRencode::factory($level, $size, $margin); + return $enc->encodeRAW($text, $outfile); } } - + //########################################################################## - - class FrameFiller { - + + class FrameFiller + { public $width; public $frame; public $x; public $y; public $dir; public $bit; - + //---------------------------------------------------------------------- public function __construct($width, &$frame) { @@ -3130,34 +3187,34 @@ $this->dir = -1; $this->bit = -1; } - + //---------------------------------------------------------------------- public function setFrameAt($at, $val) { $this->frame[$at['y']][$at['x']] = chr($val); } - + //---------------------------------------------------------------------- public function getFrameAt($at) { return ord($this->frame[$at['y']][$at['x']]); } - + //---------------------------------------------------------------------- public function next() { do { - - if($this->bit == -1) { + if ($this->bit == -1) { $this->bit = 0; - return array('x'=>$this->x, 'y'=>$this->y); + + return ['x'=>$this->x, 'y'=>$this->y]; } $x = $this->x; $y = $this->y; $w = $this->width; - if($this->bit == 0) { + if ($this->bit == 0) { $x--; $this->bit++; } else { @@ -3166,62 +3223,62 @@ $this->bit--; } - if($this->dir < 0) { - if($y < 0) { + if ($this->dir < 0) { + if ($y < 0) { $y = 0; $x -= 2; $this->dir = 1; - if($x == 6) { + if ($x == 6) { $x--; $y = 9; } } } else { - if($y == $w) { + if ($y == $w) { $y = $w - 1; $x -= 2; $this->dir = -1; - if($x == 6) { + if ($x == 6) { $x--; $y -= 8; } } } - if($x < 0 || $y < 0) return null; + if ($x < 0 || $y < 0) { + return; + } $this->x = $x; $this->y = $y; + } while (ord($this->frame[$y][$x]) & 0x80); - } while(ord($this->frame[$y][$x]) & 0x80); - - return array('x'=>$x, 'y'=>$y); + return ['x'=>$x, 'y'=>$y]; } - - } ; - - //########################################################################## - - class QRencode { - + } + + //########################################################################## + + class QRencode + { public $casesensitive = true; public $eightbit = false; - + public $version = 0; public $size = 3; public $margin = 4; - + public $structured = 0; // not supported yet - + public $level = QR_ECLEVEL_L; public $hint = QR_MODE_8; - + //---------------------------------------------------------------------- public static function factory($level = QR_ECLEVEL_L, $size = 3, $margin = 4) { - $enc = new QRencode(); + $enc = new self(); $enc->size = $size; $enc->margin = $margin; - + switch ($level.'') { case '0': case '1': @@ -3246,67 +3303,62 @@ $enc->level = QR_ECLEVEL_H; break; } - + return $enc; } - + //---------------------------------------------------------------------- - public function encodeRAW($intext, $outfile = false) + public function encodeRAW($intext, $outfile = false) { $code = new QRcode(); - if($this->eightbit) { + if ($this->eightbit) { $code->encodeString8bit($intext, $this->version, $this->level); } else { $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); } - + return $code->data; } //---------------------------------------------------------------------- - public function encode($intext, $outfile = false) + public function encode($intext, $outfile = false) { $code = new QRcode(); - if($this->eightbit) { + if ($this->eightbit) { $code->encodeString8bit($intext, $this->version, $this->level); } else { $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); } - + QRtools::markTime('after_encode'); - - if ($outfile!== false) { - file_put_contents($outfile, join("\n", QRtools::binarize($code->data))); + + if ($outfile !== false) { + file_put_contents($outfile, implode("\n", QRtools::binarize($code->data))); } else { return QRtools::binarize($code->data); } } - + //---------------------------------------------------------------------- - public function encodePNG($intext, $outfile = false,$saveandprint=false) + public function encodePNG($intext, $outfile = false, $saveandprint = false) { try { - ob_start(); $tab = $this->encode($intext); $err = ob_get_contents(); ob_end_clean(); - - if ($err != '') + + if ($err != '') { QRtools::log($outfile, $err); - - $maxSize = (int)(QR_PNG_MAXIMUM_SIZE / (count($tab)+2*$this->margin)); - - QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin,$saveandprint); - + } + + $maxSize = (int) (QR_PNG_MAXIMUM_SIZE / (count($tab) + 2 * $this->margin)); + + QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin, $saveandprint); } catch (Exception $e) { - QRtools::log($outfile, $e->getMessage()); - } } } - - diff --git a/sql/upgrade.php b/sql/upgrade.php index 7b8561c..7050da2 100644 --- a/sql/upgrade.php +++ b/sql/upgrade.php @@ -1,7 +1,7 @@ . - * */ -$host="localhost"; -$baseAnt="Inventario"; -$baseNueva="Inventario2"; -$usuario="test"; -$claveUsuario="tset"; -$probar=false; - +$host = 'localhost'; +$baseAnt = 'Inventario'; +$baseNueva = 'Inventario2'; +$usuario = 'test'; +$claveUsuario = 'tset'; +$probar = false; // No se debería modificar nada después de este comentario -function creaUbicacion($bd1,$bd2,$clave) +function creaUbicacion($bd1, $bd2, $clave) { global $probar; - $comando="select nombre from Ubicaciones where codigo=".$clave.";"; - $resultado=$bd1->query($comando); - if ($bd1->affected_rows==0) { + $comando = 'select nombre from Ubicaciones where codigo='.$clave.';'; + $resultado = $bd1->query($comando); + if ($bd1->affected_rows == 0) { echo $comando; - die("No encontró la ubicación ".$clave); + die('No encontró la ubicación '.$clave); } - $dato=$resultado->fetch_assoc(); - $valor=$dato['nombre']; - $comando="insert into Ubicaciones values (NULL,'".$valor."');"; + $dato = $resultado->fetch_assoc(); + $valor = $dato['nombre']; + $comando = "insert into Ubicaciones values (NULL,'".$valor."');"; if ($probar) { echo $comando; + return 1; } else { - $test=$bd2->query($comando); + $test = $bd2->query($comando); if (!$test) { - die("**No pudo insertar ubicacion.".$comando); + die('**No pudo insertar ubicacion.'.$comando); } + return $bd2->insert_id; - } + } } -function creaArticulo($bd1,$bd2,$clave) +function creaArticulo($bd1, $bd2, $clave) { global $probar; - $comando="select * from Articulos where codigo='".$clave."';"; - $resultado=$bd1->query($comando); - if ($bd1->affected_rows==0) { + $comando = "select * from Articulos where codigo='".$clave."';"; + $resultado = $bd1->query($comando); + if ($bd1->affected_rows == 0) { echo $comando; - die("No encontró el artículo ".$clave); + die('No encontró el artículo '.$clave); } - $dato=$resultado->fetch_assoc(); - $valor1=$dato['descripcion']; - $valor2=$dato['marca']; - $valor3=$dato['modelo']; - $valor4=$dato['cantidad']; - $comando="insert into Articulos values (NULL,'".$valor1."','".$valor2."','".$valor3."',".$valor4.");"; + $dato = $resultado->fetch_assoc(); + $valor1 = $dato['descripcion']; + $valor2 = $dato['marca']; + $valor3 = $dato['modelo']; + $valor4 = $dato['cantidad']; + $comando = "insert into Articulos values (NULL,'".$valor1."','".$valor2."','".$valor3."',".$valor4.');'; if ($probar) { echo $comando; + return 1; } else { - $test=$bd2->query($comando); + $test = $bd2->query($comando); if (!$test) { - die("**No pudo insertar artículo.".$comando); + die('**No pudo insertar artículo.'.$comando); } + return $bd2->insert_id; } } function generaSesion() { - $long=10; - $cadena=""; - for ($i=0;$i<$long;$i++) { - $cadena.=chr(rand(40,126)); + $long = 10; + $cadena = ''; + for ($i = 0; $i < $long; $i++) { + $cadena .= chr(rand(40, 126)); } + return $cadena; } /* @@ -91,64 +94,64 @@ function generaSesion() * Comienzo del programa principal. * */ -$bd1=new mysqli($host,$usuario,$claveUsuario,$baseAnt); -if(mysqli_connect_errno()) { - die("**Error conectando a la base de datos antigua.".$bd1->error); +$bd1 = new mysqli($host, $usuario, $claveUsuario, $baseAnt); +if (mysqli_connect_errno()) { + die('**Error conectando a la base de datos antigua.'.$bd1->error); } -$bd2=new mysqli($host,$usuario,$claveUsuario,$baseNueva); -if(mysqli_connect_errno()) { - die("**Error conectando a la base de datos nueva.".$bd2->error); +$bd2 = new mysqli($host, $usuario, $claveUsuario, $baseNueva); +if (mysqli_connect_errno()) { + die('**Error conectando a la base de datos nueva.'.$bd2->error); } $bd2->autocommit(false); -$datos=$bd1->query("select * from Elementos;"); +$datos = $bd1->query('select * from Elementos;'); if (!$datos) { - die("**No encontró datos en la tabla de elementos."); + die('**No encontró datos en la tabla de elementos.'); } -$numRegistros=$bd1->affected_rows; -$contador=0; -$ubicaciones=array(); -$articulos=array(); -echo "++Comenzando proceso de actualización de Elementos con ".$numRegistros." registros por procesar.
    \n"; -while($fila=$datos->fetch_assoc()) { +$numRegistros = $bd1->affected_rows; +$contador = 0; +$ubicaciones = []; +$articulos = []; +echo '++Comenzando proceso de actualización de Elementos con '.$numRegistros." registros por procesar.
    \n"; +while ($fila = $datos->fetch_assoc()) { $contador++; - echo "Procesando registro ".$contador." de ".$numRegistros."
    \n"; - if (!isset($ubicaciones[$fila['codUbicacion']])) { - $ubicaciones[$fila['codUbicacion']]=creaUbicacion($bd1,$bd2,$fila['codUbicacion']); + echo 'Procesando registro '.$contador.' de '.$numRegistros."
    \n"; + if (!isset($ubicaciones[$fila['codUbicacion']])) { + $ubicaciones[$fila['codUbicacion']] = creaUbicacion($bd1, $bd2, $fila['codUbicacion']); } if (!isset($articulos[$fila['codArticulo']])) { - $articulos[$fila['codArticulo']]=creaArticulo($bd1,$bd2,$fila['codArticulo']); + $articulos[$fila['codArticulo']] = creaArticulo($bd1, $bd2, $fila['codArticulo']); } - $comando="insert into Elementos values (NULL,".$articulos[$fila['codArticulo']].",".$ubicaciones[$fila['codUbicacion']]; - $comando.=",'".$fila['numserie']."',".$fila['cantidad'].",'".$fila['fechaCompra']."');"; + $comando = 'insert into Elementos values (NULL,'.$articulos[$fila['codArticulo']].','.$ubicaciones[$fila['codUbicacion']]; + $comando .= ",'".$fila['numserie']."',".$fila['cantidad'].",'".$fila['fechaCompra']."');"; if ($probar) { - echo $comando."
    "; + echo $comando.'
    '; } else { - $res=$bd2->query($comando); + $res = $bd2->query($comando); if (!$res) { - die("**Error ejecutando el comando de actualización. ".$comando." ".$bd2->error); + die('**Error ejecutando el comando de actualización. '.$comando.' '.$bd2->error); } } } //Traspasa los usuarios -$datos=$bd1->query("select * from Usuarios;"); +$datos = $bd1->query('select * from Usuarios;'); if (!$datos) { - die("**No encontró datos en la tabla de Usuarios."); + die('**No encontró datos en la tabla de Usuarios.'); } -$numRegistros=$bd1->affected_rows; -$contador=0; -while ($fila=$datos->fetch_assoc()) { +$numRegistros = $bd1->affected_rows; +$contador = 0; +while ($fila = $datos->fetch_assoc()) { $contador++; - echo "Procesando registro ".$contador." de ".$numRegistros."
    \n"; - $sesion=generaSesion(); - $comando="insert into Usuarios values (NULL,'".$fila['usuario']."','".$fila['usuario']."','".$sesion; - $comando.="',".$fila['altas'].",".$fila['modificaciones'].",".$fila['bajas'].",".$fila['consultas'].","; - $comando.=$fila['informes'].",".$fila['usuarios'].",1);"; + echo 'Procesando registro '.$contador.' de '.$numRegistros."
    \n"; + $sesion = generaSesion(); + $comando = "insert into Usuarios values (NULL,'".$fila['usuario']."','".$fila['usuario']."','".$sesion; + $comando .= "',".$fila['altas'].','.$fila['modificaciones'].','.$fila['bajas'].','.$fila['consultas'].','; + $comando .= $fila['informes'].','.$fila['usuarios'].',1);'; if ($probar) { - echo $comando."
    "; + echo $comando.'
    '; } else { - $res=$bd2->query($comando); + $res = $bd2->query($comando); if (!$res) { - die("**Error ejecutando el comando de actualización. ".$comando." ".$bd2->error); + die('**Error ejecutando el comando de actualización. '.$comando.' '.$bd2->error); } } } @@ -156,4 +159,3 @@ echo "++Fin del proceso.
    \n"; $bd2->commit(); $bd1->close(); $bd2->close(); -?>