kemamada@php-sandbox: ~/ejercicios

Ejercicios PHP

240 scripts en 13 carpetas · ejecutados en un contenedor Docker aislado (sin red, usuario no-root, recursos limitados). · ← Volver al portafolio

2026-07-29

Primer ejercicio: formulario y salida basica de datos.
Ejercicio.php
Script de practica.
Abrir
Ver codigo

<?php
function esPrimo($num) {
    if ($num < 2) return false;
    for ($i = 2; $i <= sqrt($num); $i++) {
        if ($num % $i == 0) return false;
    }
    return true;
}

echo "<h2>Generador de 20 numeros aleatorios</h2>";
echo "<p>Fecha: " . date('d/m/Y') . "</p>";
echo "<hr>";
echo "<table border='1' cellpadding='8' cellspacing='0'>
        <tr><th>#</th><th>Numero</th><th>Es primo?</th></tr>";

$numeros = [];
for ($i = 0; $i < 20; $i++) {
    $numeros[] = rand(1, 100);
}

$contadorPrimos = 0;
foreach ($numeros as $index => $num) {
    $primo = esPrimo($num);
    if ($primo) $contadorPrimos++;
    $resultado = $primo ? 'Si' : 'No';
    echo "<tr><td>" . ($index + 1) . "</td><td>$num</td><td>$resultado</td></tr>";
}

echo "</table>";
echo "<hr>";
echo "<h3>Cantidad de numeros primos: $contadorPrimos</h3>";
?>

2026-08-04

CRUD sobre archivo de texto: alta, baja y listado de clientes.
adicionar.phpArchivos de texto
Procesa el alta y guarda los datos.
Abrir
Ver codigo

<?php
  $carnet = $_POST["carnet"];
  $paterno = $_POST["paterno"];
  $materno = $_POST["materno"];
  $nombres = $_POST["nombres"];
  $celular = $_POST["celular"];
  $email = $_POST["email"];

  $nomArch = "clientes.txt";
  $recurso = fopen($nomArch,"a+") or die("NO se puede crear el recurso");
  $registro = $carnet."|".$paterno."|".$materno."|".$nombres."|".$celular."|".$email;
  fwrite($recurso,$registro."\n");

  fclose($recurso);

  echo "Se ha registrado exitosamente !";
?>
eliminar.phpArchivos de texto
Elimina o anula un registro.
Abrir
Ver codigo

<?php
 $carnet = $_POST["carnet"];
 $nomArch = "clientes.txt";
 $temporal ="clientes_temporal.txt";
 $recurso = fopen($nomArch,"r") or die("NO se puede crear el recurso");
 $recurso_tmp = fopen($temporal,"w") or die("NO se puede crear el recurso");
 while(!feof($recurso)){
    $linea = fgets($recurso);
    $registro = explode("|", $linea) ;
    if($registro[0]==trim($carnet)){
        echo "REGISTRO ENCONTRADO...!carnet: ".$carnet."<br>";
    }
    else{
        fwrite($recurso_tmp,$linea);
    }
 }
fclose($recurso_tmp);
fclose($recurso);
unlink($nomArch);
rename($temporal,$nomArch);

?>
formularioAdicionar.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <h3>AGREGAR CLIENTES</h3>
        <form action="adicionar.php" method="post">
            carnet:<input type="number" name="carnet" required><br>
            paterno:<input type="text" name="paterno"><br>
            materno:<input type="text" name="materno"><br>
            nombres:<input type="text" name="nombres" required><br>
            celular:<input type="number" name="celular" required><br>
            email:<input type="email" name="email" required><br>
            <input type="submit" value="Registrar Cliente">
        </form>
    </div>
</body>
</html>
formularioEliminar.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ELIMINAR CLIENTES</title>
</head>
<body>
    <div>
        <h3>ELIMINAR CLIENTES</h3>
        <form action="eliminar.php" method="post">
            Carnet:<input type="number" name="carnet" required><br>
            <input type="submit" value="Registrar Cliente">
        </form>
    </div>
</body>
</html>
inicio.php
Listado / indice del ejercicio.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>COOPERATIVA</title>
    <style>
        #principal{
            background-color:lightgray;
            width:100%;
            height:600px;
        }
        #principal div#menu{
            background-color:lightgreen;
            width:25%;
            float: left;
        }
        #principal div#conte{
            width:75%;
            float: right;
        }        
    </style>
</head>
<body>
    <h3>SISTEMA COOPERATIVA SISINFO</h3>
    <div id="principal">
        <div id="menu">
            <h3>MENU</h3>
            <nav>
                <ul>
                    <li><a href="formularioAdicionar.php" target="container">AGREGAR CLIENTE</a></li>
                    <li><a href="formularioEliminar.php" target="container">ELIMINAR CLIENTE</a></li>
                    <li><a>MODIFICAR CLIENTE</a></li>
                    <li><a>MOSTRAR CLIENTES</a></li>
                </ul>
            </nav>
        </div>
        <div id="conte">
            <iframe name="container" src="" frameborder="0" width="100%" height="600"></iframe>
        </div>
    </div>
</body>
</html>

2026-08-18

Variables, operadores y estructuras de control.
codigo1.phpArchivos de texto
Fragmento de practica de codigo.
Abrir
Ver codigo

<?php
$nomArch = "planilla.csv";
$recurso = fopen($nomArch,"r");
echo "<table border = '1'>";
while (!feof($recurso)) {
    $linea = fgets($recurso);
    $registro = explode(",",$linea);
if (trim($linea)!="") {
    echo "<tr>";
    echo "<td>".trim($registro[0])."</td>";
    echo "<td>".trim($registro[1])."</td>";
    echo "<td>".trim($registro[2])."</td>";
    echo "<td>".trim($registro[3])."</td>";
    echo "<td>".trim($registro[4])."</td>";
    echo "<td>".trim($registro[5])."</td>";
    echo "<td>".trim($registro[6])."</td>";
    echo "<td>".trim($registro[7])."</td>";
    echo "<td>".trim($registro[8])."</td>";
    echo "<td>".trim($registro[9])."</td>";
    echo "<td>".trim($registro[10])."</td>";
    echo "</tr>";
}
}
echo "</table>";
fclose($recurso);
?>
codigo2.phpError de sintaxisArchivos de texto
Fragmento de practica de codigo.
No ejecutable
Ver codigo

<?php
$nomArch = "planilla.csv";
$recurso = fopen($nomArch,"r");
$recursoProg = fopen("programacion.csv","r");
$recursoBdd = fopen("basedd.csv","r");
$recursoRedes = fopen("redes.csv","r");
echo "<table border = '1'>";
while (!feof($recurso)) {
    $linea = fgets($recurso);
    $registro = explode(",",$linea);

    if ($registro[4]=="Programación") {
        fwrite($recursoProg,$linea);
    } elseif ($registro[4]=="Base de Datos") {
        fwrite($recursoBdd,$linea);
    } elseif ($registro[4]=="Redes") {
        fwrite($recursoRedes,$linea);
    }


}
echo "</table>"
fclose($recurso);
?>

2026-09-01

Formularios y manejo de imagenes con PHP.
codigo.phpArchivos de texto
Fragmento de practica de codigo.
Abrir
Ver codigo

<?php
    $recurso = fopen("datos.txt","r");
    for ($i=1; $i < 10; $i++) { 
        $x = rand(1,100);
        echo $x . "<br>";
    }
    fclose($recurso);
?>

codigo1.php
Fragmento de practica de codigo.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <img src="imagen3.php" alt="" width="600">
</body>
</html>
imagen1.php
Trabajo con imagenes en el navegador.
Abrir
Ver codigo

<?php
    $imagen = imagecreatetruecolor(500, 400);
    $blanco = imagecolorallocate($imagen,255,255,255);
    $beige = imagecolorallocate($imagen,239,228,176);
    $rojo = imagecolorallocate($imagen,255,0,0);
    imagefill($imagen,0,0,$blanco);
    imagefill($imagen,0,0,$rojo);
    header("content-type: image/png");
    imagepng($imagen);
    imagedestroy($imagen);
?>

imagen2.php
Trabajo con imagenes en el navegador.
Abrir
Ver codigo

<?php
    $imagen = imagecreatetruecolor(500, 400);
    $color1= imagecolorallocate($imagen,255,255,255);
    $color2 = imagecolorallocate($imagen,0,162,232);
    imagefill($imagen,0,0,$color1);
    imagerectangle($imagen,89,134,319,235,$color2);
    header("content-type: image/png");
    imagepng($imagen);
    imagedestroy($imagen);
?>

imagen3.php
Trabajo con imagenes en el navegador.
Abrir
Ver codigo

<?php
    $imagen = imagecreatetruecolor(500, 400);
    $color1= imagecolorallocate($imagen,255,255,255);
    imagefill($imagen,0,0,$color1);
    for ($i=1; $i<=10 ; $i++) { 
        $color2 = imagecolorallocate($imagen,0,162,232);
        imagerectangle($imagen,10*$i,10*$i,210+(10*$i),60+(10*$i),$color2);
    }
    header("content-type: image/png");
    imagepng($imagen);
    imagedestroy($imagen);
?>

img.php
Trabajo con imagenes en el navegador.
Abrir
Ver codigo

<?php
    $imagen = imagecreatetruecolor(500, 400);
    $color1= imagecolorallocate($imagen,255,255,255);
    imagefill($imagen,0,0,$color1);
    for ($i=1; $i<=10 ; $i++) { 
        $color2 = imagecolorallocate($imagen,0,162,232);
        imagerectangle($imagen,10*$i,10*$i,210+(10*$i),60+(10*$i),$color2);
    }
    header("content-type: image/png");
    imagepng($imagen);
    imagedestroy($imagen);
?>

2026-09-08

Registro de estudiantes y notas: listado y grafico de barras.
barras.phpArchivos de texto
Grafico de barras con las notas.
Abrir
Ver codigo

<?php
  header("Content-Type: image/png");

  $carnet = $_GET["carnet"] ?? "";
  if($carnet == ""){
    echo "No se especifico carnet";
    exit;
  }

  if(!file_exists("estudiantes.txt")){
    echo "No hay registros";
    exit;
  }

  $encontrado = false;
  $recurso = fopen("estudiantes.txt","r");
  while(!feof($recurso)){
    $linea = fgets($recurso);
    if(trim($linea) != ""){
      $reg = explode("|", $linea);
      if(count($reg) == 7 && trim($reg[0]) == $carnet){
        $encontrado = true;
        break;
      }
    }
  }
  fclose($recurso);

  if(!$encontrado){
    echo "Estudiante no encontrado";
    exit;
  }

  $nombre = $reg[1];
  $notas = array(floatval($reg[2]), floatval($reg[3]), floatval($reg[4]), floatval($reg[5]), floatval($reg[6]));
  $promedio = array_sum($notas) / count($notas);

  $materias = array("Mat1", "Mat2", "Mat3", "Mat4", "Mat5", "Promedio");
  $valores = array_merge($notas, array(round($promedio, 2)));

  $ancho = 800;
  $alto = 500;
  $img = imagecreatetruecolor($ancho, $alto);

  $fondo = imagecolorallocate($img, 255, 255, 255);
  $negro = imagecolorallocate($img, 0, 0, 0);
  $gris = imagecolorallocate($img, 150, 150, 150);
  $rojo = imagecolorallocate($img, 220, 50, 50);
  $verde = imagecolorallocate($img, 50, 180, 50);

  imagefill($img, 0, 0, $fondo);

  $titulo = "Notas de: " . $nombre . " (Carnet: " . $carnet . ")";
  imagestring($img, 5, ($ancho - strlen($titulo) * imagefontwidth(5)) / 2, 10, $titulo, $negro);

  $inicioX = 80;
  $inicioY = 60;
  $anchoBarra = 70;
  $espacio = 25;
  $maxAltura = 350;
  $maxNota = 100;

  for($i = 0; $i < count($valores); $i++){
    $x = $inicioX + $i * ($anchoBarra + $espacio);
    $altura = ($valores[$i] / $maxNota) * $maxAltura;
    $y = $inicioY + ($maxAltura - $altura);

    if($valores[$i] >= 0 && $valores[$i] <= 39){
      $color = $gris;
    } elseif($valores[$i] >= 40 && $valores[$i] <= 60){
      $color = $rojo;
    } else {
      $color = $verde;
    }

    imagefilledrectangle($img, $x, $y, $x + $anchoBarra, $inicioY + $maxAltura, $color);
    imagerectangle($img, $x, $y, $x + $anchoBarra, $inicioY + $maxAltura, $negro);

    $textoNota = strval($valores[$i]);
    imagestring($img, 4, $x + ($anchoBarra - strlen($textoNota) * imagefontwidth(4)) / 2, $y - 15, $textoNota, $negro);

    $textoMateria = $materias[$i];
    imagestring($img, 4, $x + ($anchoBarra - strlen($textoMateria) * imagefontwidth(4)) / 2, $inicioY + $maxAltura + 8, $textoMateria, $negro);
  }

  imagestring($img, 3, 10, $inicioY + $maxAltura + 30, "Leyenda:", $negro);
  imagefilledrectangle($img, 10, $inicioY + $maxAltura + 50, 25, $inicioY + $maxAltura + 60, $gris);
  imagestring($img, 3, 30, $inicioY + $maxAltura + 50, "[0-39] Abandono", $negro);
  imagefilledrectangle($img, 160, $inicioY + $maxAltura + 50, 175, $inicioY + $maxAltura + 60, $rojo);
  imagestring($img, 3, 180, $inicioY + $maxAltura + 50, "[40-60] Reprobado", $negro);
  imagefilledrectangle($img, 320, $inicioY + $maxAltura + 50, 335, $inicioY + $maxAltura + 60, $verde);
  imagestring($img, 3, 340, $inicioY + $maxAltura + 50, "[61-100] Aprobado", $negro);

  imagepng($img);
  imagedestroy($img);
?>

formRegistro.php
Registro de usuario y guardado de credenciales.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Registro de Estudiantes</title>
    <style>
        body { font-family: Arial; padding: 10px; }
        input { margin: 5px 0; padding: 5px; width: 250px; }
        input[type=submit] { width: auto; background: #4CAF50; color: white; border: none; padding: 10px 20px; cursor: pointer; }
        input[type=submit]:hover { background: #45a049; }
    </style>
</head>
<body>
    <h3>Registrar Estudiante</h3>
    <form action="registrar.php" method="post">
        Carnet: <input type="text" name="carnet" required><br>
        Nombre completo: <input type="text" name="nombres" required><br>
        Nota Materia 1: <input type="number" name="nota1" min="0" max="100" required><br>
        Nota Materia 2: <input type="number" name="nota2" min="0" max="100" required><br>
        Nota Materia 3: <input type="number" name="nota3" min="0" max="100" required><br>
        Nota Materia 4: <input type="number" name="nota4" min="0" max="100" required><br>
        Nota Materia 5: <input type="number" name="nota5" min="0" max="100" required><br><br>
        <input type="submit" value="Registrar datos">
    </form>
</body>
</html>

indice.php
Listado / indice del ejercicio.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NOTAS GRAFICAS</title>
    <style>
        div{
            width: 100%;
            background-color: burlywood;
        }
    </style>
</head>
<body>
    <div>
       <a href="formRegistro.php" target="contenido">REGISTRAR</a>
       <a href="listado.php" target="contenido">MOSTRAR GRAFICO</a>
    </div>
    <div>
        <iframe name="contenido" src="" frameborder="0" width="100%" height="500"></iframe>
    </div>
</body>
</html>
listado.phpArchivos de texto
Listado / indice del ejercicio.
Abrir
Ver codigo

<?php
  if(!file_exists("estudiantes.txt")){
    echo "<p>No hay registros. Primero registra estudiantes.</p>";
    exit;
  }
  $recurso = fopen("estudiantes.txt","r");
  echo "<h3>Listado de Estudiantes</h3>";
  echo "<table border='1' cellpadding='5'>";
  echo "<tr><th>Carnet</th><th>Nombre</th><th>Mat1</th><th>Mat2</th><th>Mat3</th><th>Mat4</th><th>Mat5</th><th>Grafico</th></tr>";
  while(!feof($recurso)){
    $linea = fgets($recurso);
    if(trim($linea)!=""){
      $reg = explode("|",$linea);
      if(count($reg)==7){
        echo "<tr>";
        echo "<td>".htmlspecialchars($reg[0])."</td>";
        echo "<td>".htmlspecialchars($reg[1])."</td>";
        echo "<td>$reg[2]</td>";
        echo "<td>$reg[3]</td>";
        echo "<td>$reg[4]</td>";
        echo "<td>$reg[5]</td>";
        echo "<td>$reg[6]</td>";
        echo "<td><a href='barras.php?carnet=".urlencode(trim($reg[0]))."'>Ver grafico</a></td>";
        echo "</tr>";
      }
    }
  }
  echo "</table>";
  fclose($recurso);
?>

registrar.phpArchivos de texto
Procesa el alta y guarda los datos.
Abrir
Ver codigo

<?php
  $carnet = $_POST["carnet"] ?? "";
  $nombres = $_POST["nombres"] ?? "";
  $nota1 = $_POST["nota1"] ?? "";
  $nota2 = $_POST["nota2"] ?? "";
  $nota3 = $_POST["nota3"] ?? "";
  $nota4 = $_POST["nota4"] ?? "";
  $nota5 = $_POST["nota5"] ?? "";

  if($carnet == "" || $nombres == ""){
    echo "<p>Error: Carnet y Nombre son obligatorios</p>";
    echo "<a href='formRegistro.php'>Volver</a>";
    exit;
  }

  $registro = $carnet."|".$nombres."|".$nota1."|".$nota2."|".$nota3."|".$nota4."|".$nota5;

  $recurso = fopen("estudiantes.txt", "a");
  fwrite($recurso, $registro."\n");
  fclose($recurso);

  echo "<p>Estudiante registrado exitosamente!</p>";
  echo "<p><a href='formRegistro.php'>Registrar otro</a> | <a href='listado.php'>Ver listado</a></p>";
?>

2026-09-13

Login y registro de usuarios con MySQL (mysqli).
conexion.phpError de sintaxis
Conexion a la base de datos.
No ejecutable
Ver codigo

<?php
    $servidor ="localhost";
    $usuario ="dpw";
    $clave ="***";
    $
?>
inicio.php
Listado / indice del ejercicio.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
         #caja{
            width: 95%;
            height: 650px;

         };
         #menu{
            
         };

    </style>
</head>
<body>
    <div id="caja">
        <DIV id="menu">
            <ul>
                <li></li>
                <li></li>
                <li></li>
                <li></li>
            </ul>
        </DIV>
    </div>
</body>
</html>
login.php
Autenticacion de usuario.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <label for=""></label>
        <input type="text">
        <label for=""></label>
        <input type="text">
    </div>
</body>
</html>
registro_login.phpError de sintaxisMySQL
Autenticacion de usuario.
No ejecutable
Ver codigo

<?php
    include "conexion.php";
    if (isset($_REQUEST["usuario"]) && isset($_REQUEST["clave"])) {
        $sql = "SELECT * FROM usuarios";
        $resultado = mysqli_query($conexion,$sql);
        $usuario =  $_REQUEST 
        $verifica = 

        while ($registro = mysqli_fetch_array($resultado)) {
            if ($registro[0]==$usuario && $registro[1]==$clave) {
                $verifica=1;
            }
        }
    }
?>
sistema.php
Script de practica.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
</html>

2026-09-22

Generacion de codigos QR para estudiantes.
codigo1.phpQR
Fragmento de practica de codigo.
Abrir
Ver codigo

<?php 
    require 'phpqrcode/qrlib.php' ;
    $texto = "SISTEMAS IINFORMATICOS";
    QRcode:: png($texto,"qr_generado1.png") ;
?>

ejercicio1.phpQR
Script de practica.
Abrir
Ver codigo

Ejercicio
1 se tiene un archiuvo estudiantes.txt que contriene 10 registros, carnet, paterno, materno, email, celular 
2 leer el archivo estudiantes.txt y para cada registro generar el codigo QR,  asignando como nombre de archivo del codigo QR el carnet de identidad 5678912.png 
3 El codigo QR generado alamenar en el archivo codigoQR.txt
4 mostrar el archivo codigoQR.txt en una tabla y el usuario podra hacer un cick en el carnet y mostrara el QR
<?php 
    require 'phpqrcode/qrlib.php' ;
    $texto = "SISTEMAS IINFORMATICOS";
    QRcode:: png($texto,"qr_generado1.png") ;
?>

generarQR.phpArchivos de textoQR
Genera los codigos QR a partir de los registros.
Abrir
Ver codigo

<?php
  require 'phpqrcode/qrlib.php';

  if(!file_exists("estudiantes.txt")){
    echo "<p>No existe el archivo estudiantes.txt</p>";
    echo "<a href='inicio.php'>Volver</a>";
    exit;
  }

  $recurso = fopen("estudiantes.txt","r");
  $recursoQR = fopen("codigoQR.txt","w");

  $contador = 0;
  while(!feof($recurso)){
    $linea = fgets($recurso);
    if(trim($linea) != ""){
      $reg = explode("|",$linea);
      if(count($reg) >= 5){
        $carnet = trim($reg[0]);
        $paterno = trim($reg[1]);
        $materno = trim($reg[2]);
        $email = trim($reg[3]);
        $celular = trim($reg[4]);

        $textoQR = "CI: $carnet, $paterno $materno, Email: $email, Cel: $celular";
        $archivoQR = $carnet.".png";
        QRcode::png($textoQR, $archivoQR);

        $registro = $carnet."|".$paterno."|".$materno."|".$email."|".$celular."|".$archivoQR;
        fwrite($recursoQR, $registro."\n");
        $contador++;
      }
    }
  }
  fclose($recurso);
  fclose($recursoQR);

  echo "<h3>Codigos QR generados exitosamente!</h3>";
  echo "<p>Se generaron $contador codigos QR</p>";
  echo "<p><a href='inicio.php'>Ver tabla de codigos QR</a></p>";
?>
inicio.phpArchivos de texto
Listado / indice del ejercicio.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>CODIGOS QR ESTUDIANTES</title>
</head>
<body>
    <h3>CODIGOS QR - ESTUDIANTES</h3>
    <a href="generarQR.php">GENERAR CODIGOS QR</a>
    <?php
      if(!file_exists("codigoQR.txt")){
        echo "<p>Aun no se generaron los codigos QR. Haga clic en GENERAR CODIGOS QR.</p>";
        exit;
      }
      $recurso = fopen("codigoQR.txt","r");
      echo "<table border='1'>";
      echo "<tr><th>Carnet</th><th>Paterno</th><th>Materno</th><th>Email</th><th>Celular</th><th>Codigo QR</th></tr>";
      while(!feof($recurso)){
        $linea = fgets($recurso);
        if(trim($linea) != ""){
          $reg = explode("|",$linea);
          if(count($reg) >= 6){
            echo "<tr>";
            echo "<td><a href='".trim($reg[5])."' target='_blank'>".htmlspecialchars($reg[0])."</a></td>";
            echo "<td>".htmlspecialchars($reg[1])."</td>";
            echo "<td>".htmlspecialchars($reg[2])."</td>";
            echo "<td>".htmlspecialchars($reg[3])."</td>";
            echo "<td>".htmlspecialchars($reg[4])."</td>";
            $qrFile = trim($reg[5]);
$v = file_exists($qrFile) ? filemtime($qrFile) : time();
echo "<td><a href='$qrFile' target='_blank'><img src='".$qrFile."?v=$v' width='80'></a></td>";
            echo "</tr>";
          }
        }
      }
      echo "</table>";
      fclose($recurso);
    ?>
</body>
</html>

2026-09-29

Lectura de codigos QR desde una imagen subida (ZXing + ImageMagick).
autoload_qr.phpQR
Script de practica.
Abrir
Ver codigo

<?php
// autoload_qr.php
require_once __DIR__ . '/php-qrcode-detector-decoder/lib/Common/customFunctions.php';

spl_autoload_register(function ($clase) {
    $prefijo = 'Zxing\\';
    $directorioBase = __DIR__ . '/php-qrcode-detector-decoder/lib/';

    $largoPrefijo = strlen($prefijo);
    if (strncmp($prefijo, $clase, $largoPrefijo) !== 0) {
        return;
    }

    $claseRelativa = substr($clase, $largoPrefijo);
    $archivo = $directorioBase . str_replace('\\', '/', $claseRelativa) . '.php';

    if (file_exists($archivo)) {
        require $archivo;
    }
});
generar.phpQR
Genera los codigos QR a partir de los registros.
Abrir
Ver codigo

<?php
  require 'phpqrcode/qrlib.php';

  $texto = "";
  $archivo = "";
  if(isset($_POST["texto"])){
    $texto = trim($_POST["texto"]);
    if($texto == ""){
      $aviso = "Escriba un texto para generar el codigo QR";
    } else {
      $archivo = "qr_" . uniqid() . ".png";
      QRcode::png($texto, $archivo, QR_ECLEVEL_L, 6);
      if(!file_exists($archivo)){
        $archivo = "";
      }
    }
  }
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Generar QR</title>
</head>
<body>
    <h3>1. GENERAR CODIGO QR</h3>
    <form action="generar.php" method="post">
        Texto: <input type="text" name="texto" value="<?php echo htmlspecialchars($texto); ?>" size="40" required>
        <input type="submit" value="GENERAR QR">
    </form>

    <?php
      
      if($archivo != ""){
        echo "<p>Texto: <b>" . htmlspecialchars($texto) . "</b></p>";
        echo "<p><img src='" . $archivo . "' width='260'></p>";
        echo "<p><a href='" . $archivo . "' target='_blank'>Ver tamano completo</a></p>";
      }
      echo "<p><a href='indice.php'>Volver al inicio</a></p>";
      
    ?>
</body>
</html>

indice.php
Listado / indice del ejercicio.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>GENERAR Y LEER CODIGOS QR</title>
</head>
<body>
    <h3>GENERAR Y LEER CODIGOS QR</h3>
    <a href="generar.php" target="contenido"><b>1. GENERAR QR</b></a>
    &nbsp;&nbsp;
    <a href="leer.php" target="contenido"><b>2. LEER QR</b></a>
    <hr>
    <iframe name="contenido" src="generar.php" frameborder="0" width="100%" height="620"></iframe>
</body>
</html>

leer.phpSubida de archivosexec
Lee un codigo QR desde una imagen subida.
Abrir
Ver codigo

<?php
  require 'autoload_qr.php';

  use Zxing\QrReader;

  $archivo = "";
  $texto = "";
  $error = "";

  if(isset($_FILES["imagenQR"])){
    if($_FILES["imagenQR"]["error"] != UPLOAD_ERR_OK){
      $error = "No se pudo subir la imagen";
    } else {
      $info = @getimagesize($_FILES["imagenQR"]["tmp_name"]);
      if($info === false){
        $error = "El archivo no es una imagen valida";
      } else {
        if(!file_exists("uploads")){
          mkdir("uploads", 0777);
        }
        $archivo = "uploads/qr_" . uniqid() . ".png";
        $mime = strtolower($info["mime"]);
        if(in_array($mime, array("image/avif", "image/heic", "image/heif"))){
          exec("convert " . escapeshellarg($_FILES["imagenQR"]["tmp_name"]) . " " . escapeshellarg($archivo));
        } else {
          move_uploaded_file($_FILES["imagenQR"]["tmp_name"], $archivo);
        }

        if(!file_exists($archivo)){
          $error = "No se pudo guardar la imagen en uploads/";
        } else {
          try {
            $qr = new QrReader($archivo);
            $resultado = $qr->text();
          } catch (Throwable $e) {
            $resultado = false;
            $error = htmlspecialchars($e->getMessage());
          }

          if(is_string($resultado) && $resultado != ""){
            $texto = $resultado;
          } else if($error == ""){
            $error = "La imagen no contiene un codigo QR legible";
          }
        }
      }
    }
  }
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Leer QR</title>
</head>
<body>
    <h3>2. LEER CODIGO QR</h3>
    <form action="leer.php" method="post" enctype="multipart/form-data">
        Imagen con QR: <input type="file" name="imagenQR" accept="image/*" required>
        <input type="submit" value="LEER QR">
    </form>

    <?php
      if($archivo != ""){
        echo "<p><img src='" . $archivo . "' width='220'></p>";
      }
      if($texto != ""){
        echo "<p>Contenido del QR: <b>" . htmlspecialchars($texto) . "</b></p>";
      }
      if($error != ""){
        echo "<p>" . $error . "</p>";
      }
      echo "<p><a href='indice.php'>Volver al inicio</a></p>";
    ?>
</body>
</html>

ecs.php
Script de practica.
Abrir
Ver codigo

<?php

use Rector\Set\ValueObject\LevelSetList;
use PhpCsFixer\Fixer\Operator\ConcatSpaceFixer;
use Symplify\EasyCodingStandard\Config\ECSConfig;
use Symplify\EasyCodingStandard\ValueObject\Option;

use PhpCsFixer\Fixer\ArrayNotation\ArraySyntaxFixer;
use Symplify\EasyCodingStandard\ValueObject\Set\SetList;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ECSConfig $configurator): void {

  // alternative to CLI arguments, easier to maintain and extend
  $configurator->paths([__DIR__ . '/lib', __DIR__ . '/tests']);

  // choose 
  $configurator->sets([
    SetList::CLEAN_CODE, SetList::PSR_12//, LevelSetList::UP_TO_PHP_81 //, SymfonySetList::SYMFONY_60
  ]);

  $configurator->ruleWithConfiguration(ConcatSpaceFixer::class, [
    'spacing' => 'one'
  ]);

  // indent and tabs/spaces
  // [default: spaces]. BUT: tabs are superiour due to accessibility reasons
  $configurator->indentation('tab');
};

rector.php
Script de practica.
Abrir
Ver codigo

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Symfony\Set\SymfonySetList;
use Rector\Doctrine\Set\DoctrineSetList;
use Rector\Set\ValueObject\LevelSetList;
use Rector\DeadCode\Rector\ClassMethod\RemoveUselessParamTagRector;
use Rector\TypeDeclaration\Rector\Property\TypedPropertyFromAssignsRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnNewRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddReturnTypeDeclarationRector;
use Rector\CodeQuality\Rector\Class_\InlineConstructorDefaultToPropertyRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ParamTypeByParentCallTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictNewArrayRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddVoidReturnTypeWhereNoReturnRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddMethodCallBasedStrictParamTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictBoolReturnExprRector;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->paths([
        __DIR__ . '/lib'
    ]);

    $rectorConfig->symfonyContainerXml(__DIR__ . '/var/cache/dev/App_KernelDevDebugContainer.xml');

    $rectorConfig->sets([
        DoctrineSetList::ANNOTATIONS_TO_ATTRIBUTES,
        SymfonySetList::ANNOTATIONS_TO_ATTRIBUTES,
        SymfonySetList::SYMFONY_60,
        LevelSetList::UP_TO_PHP_81
    ]);

    // register a single rule
    $rectorConfig->rule(InlineConstructorDefaultToPropertyRector::class);
    $rectorConfig->rule(AddReturnTypeDeclarationRector::class);
    $rectorConfig->rules([
        AddMethodCallBasedStrictParamTypeRector::class,
        AddVoidReturnTypeWhereNoReturnRector::class,
        ParamTypeByMethodCallTypeRector::class,
        ParamTypeByParentCallTypeRector::class,
        RemoveUselessParamTagRector::class,
        ReturnTypeFromReturnNewRector::class,
        ReturnTypeFromStrictBoolReturnExprRector::class,
        ReturnTypeFromStrictNewArrayRector::class,
        TypedPropertyFromAssignsRector::class,
    ]);

    // define sets of rules
    //    $rectorConfig->sets([
    //        LevelSetList::UP_TO_PHP_80
    //    ]);
};

Binarizer.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing;

use Zxing\Common\BitArray;
use Zxing\Common\BitMatrix;

/**
 * This class hierarchy provides a set of methods to convert luminance data to 1 bit data.
 * It allows the algorithm to vary polymorphically, for example allowing a very expensive
 * thresholding technique for servers and a fast one for mobile. It also permits the implementation
 * to vary, e.g. a JNI version for Android and a Java fallback version for other platforms.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 */
abstract class Binarizer
{
	protected function __construct(private $source)
	{
	}

	/**
	 * @return LuminanceSource
	 */
	final public function getLuminanceSource()
	{
		return $this->source;
	}

	/**
	 * Converts one row of luminance data to 1 bit data. May actually do the conversion, or return
	 * cached data. Callers should assume this method is expensive and call it as seldom as possible.
	 * This method is intended for decoding 1D barcodes and may choose to apply sharpening.
	 * For callers which only examine one row of pixels at a time, the same BitArray should be reused
	 * and passed in with each call for performance. However it is legal to keep more than one row
	 * at a time if needed.
	 *
	 * @param int $y   The row to fetch, which must be in [0, bitmap height)
	 * @param BitArray|null $row An optional preallocated array. If null or too small, it will be ignored.
	 *            If used, the Binarizer will call BitArray.clear(). Always use the returned object.
	 *
	 * @return BitArray The array of bits for this row (true means black).
	 * @throws NotFoundException if row can't be binarized
	 */
	abstract public function getBlackRow(int $y, ?BitArray $row = null): BitArray;

	/**
	 * Converts a 2D array of luminance data to 1 bit data. As above, assume this method is expensive
	 * and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or
	 * may not apply sharpening. Therefore, a row from this matrix may not be identical to one
	 * fetched using getBlackRow(), so don't mix and match between them.
	 *
	 * @return BitMatrix The 2D array of bits for the image (true means black).
	 * @throws NotFoundException if image can't be binarized to make a matrix
	 */
	abstract public function getBlackMatrix();

	/**
	 * Creates a new object with the same type as this Binarizer implementation, but with pristine
	 * state. This is needed because Binarizer implementations may be stateful, e.g. keeping a cache
	 * of 1 bit data. See Effective Java for why we can't use Java's clone() method.
	 *
	 * @param $source The LuminanceSource this Binarizer will operate on.
	 *
	 * @return Binarizer A new concrete Binarizer implementation object.
	 */
	abstract public function createBinarizer($source);

	final public function getWidth()
	{
		return $this->source->getWidth();
	}

	final public function getHeight()
	{
		return $this->source->getHeight();
	}
}

BinaryBitmap.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing;

use Zxing\Common\BitMatrix;

/**
 * This class is the core bitmap class used by ZXing to represent 1 bit data. Reader objects
 * accept a BinaryBitmap and attempt to decode it.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 */
final class BinaryBitmap
{
	private readonly \Zxing\Binarizer $binarizer;
	private ?\Zxing\Common\BitMatrix $matrix = null;

	public function __construct(Binarizer $binarizer)
	{
		if ($binarizer === null) {
			throw new \InvalidArgumentException("Binarizer must be non-null.");
		}
		$this->binarizer = $binarizer;
	}

	/**
	 * @return int The width of the bitmap.
	 */
	public function getWidth()
	{
		return $this->binarizer->getWidth();
	}

	/**
	 * @return int The height of the bitmap.
	 */
	public function getHeight()
	{
		return $this->binarizer->getHeight();
	}

	/**
	 * Converts one row of luminance data to 1 bit data. May actually do the conversion, or return
	 * cached data. Callers should assume this method is expensive and call it as seldom as possible.
	 * This method is intended for decoding 1D barcodes and may choose to apply sharpening.
	 *
	 * @param $y   The row to fetch, which must be in [0, bitmap height)
	 * @param array|null $row An optional preallocated array. If null or too small, it will be ignored.
	 *            If used, the Binarizer will call BitArray.clear(). Always use the returned object.
	 *
	 * @return Common\BitArray The array of bits for this row (true means black).
	 *
	 * @throws NotFoundException if row can't be binarized
	 */
	public function getBlackRow($y, $row): Common\BitArray
	{
		return $this->binarizer->getBlackRow($y, $row);
	}

	/**
	 * @return bool Whether this bitmap can be cropped.
	 */
	public function isCropSupported()
	{
		return $this->binarizer->getLuminanceSource()->isCropSupported();
	}

	/**
	 * Returns a new object with cropped image data. Implementations may keep a reference to the
	 * original data rather than a copy. Only callable if isCropSupported() is true.
	 *
	 * @param $left   The left coordinate, which must be in [0,getWidth())
	 * @param $top    The top coordinate, which must be in [0,getHeight())
	 * @param $width  The width of the rectangle to crop.
	 * @param $height The height of the rectangle to crop.
	 *
	 * @return BinaryBitmap A cropped version of this object.
	 */
	public function crop($left, $top, $width, $height): \Zxing\BinaryBitmap
	{
		$newSource = $this->binarizer->getLuminanceSource()->crop($left, $top, $width, $height);

		return new BinaryBitmap($this->binarizer->createBinarizer($newSource));
	}

	/**
	 * @return bool this Whether bitmap supports counter-clockwise rotation.
	 */
	public function isRotateSupported()
	{
		return $this->binarizer->getLuminanceSource()->isRotateSupported();
	}

	/**
	 * Returns a new object with rotated image data by 90 degrees counterclockwise.
	 * Only callable if {@link #isRotateSupported()} is true.
	 *
	 * @return BinaryBitmap A rotated version of this object.
	 */
	public function rotateCounterClockwise(): \Zxing\BinaryBitmap
	{
		$newSource = $this->binarizer->getLuminanceSource()->rotateCounterClockwise();

		return new BinaryBitmap($this->binarizer->createBinarizer($newSource));
	}

	/**
	 * Returns a new object with rotated image data by 45 degrees counterclockwise.
	 * Only callable if {@link #isRotateSupported()} is true.
	 *
	 * @return BinaryBitmap A rotated version of this object.
	 */
	public function rotateCounterClockwise45(): \Zxing\BinaryBitmap
	{
		$newSource = $this->binarizer->getLuminanceSource()->rotateCounterClockwise45();

		return new BinaryBitmap($this->binarizer->createBinarizer($newSource));
	}

	public function toString(): string
	{
		try {
			return $this->getBlackMatrix()->toString();
		} catch (NotFoundException) {
		}

		return '';
	}

	/**
	 * Converts a 2D array of luminance data to 1 bit. As above, assume this method is expensive
	 * and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or
	 * may not apply sharpening. Therefore, a row from this matrix may not be identical to one
	 * fetched using getBlackRow(), so don't mix and match between them.
	 *
	 * @return BitMatrix The 2D array of bits for the image (true means black).
	 * @throws NotFoundException if image can't be binarized to make a matrix
	 */
	public function getBlackMatrix()
	{
		// The matrix is created on demand the first time it is requested, then cached. There are two
		// reasons for this:
		// 1. This work will never be done if the caller only installs 1D Reader objects, or if a
		//    1D Reader finds a barcode before the 2D Readers run.
		// 2. This work will only be done once even if the caller installs multiple 2D Readers.
		if ($this->matrix === null) {
			$this->matrix = $this->binarizer->getBlackMatrix();
		}

		return $this->matrix;
	}
}

ChecksumException.php
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing;

/**
 * Thrown when a barcode was successfully detected and decoded, but
 * was not returned because its checksum feature failed.
 *
 * @author Sean Owen
 */
final class ChecksumException extends ReaderException
{
	private static ?\Zxing\ChecksumException $instance = null;

	public static function getChecksumInstance($cause = ""): self
	{
		if (self::$isStackTrace) {
			return new ChecksumException($cause);
		} else {
			if (!self::$instance) {
				self::$instance = new ChecksumException($cause);
			}

			return self::$instance;
		}
	}
}

FormatException.php
Formulario de entrada de datos.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing;

/**
 * Thrown when a barcode was successfully detected, but some aspect of
 * the content did not conform to the barcode's format rules. This could have
 * been due to a mis-detection.
 *
 * @author Sean Owen
 */
final class FormatException extends ReaderException
{
	private static ?\Zxing\FormatException $instance = null;

	public function __construct($cause = null)
	{
		if ($cause) {
			parent::__construct($cause);
		}
	}

	public static function getFormatInstance($cause = null): self
	{
		if (!self::$instance) {
			self::$instance = new FormatException();
		}
		if (self::$isStackTrace) {
			return new FormatException($cause);
		} else {
			return self::$instance;
		}
	}
}

GDLuminanceSource.php
Script de practica.
Abrir
Ver codigo

<?php


namespace Zxing;

/**
 * This class is used to help decode images from files which arrive as GD Resource
 * It does not support rotation.
 *
 *
 *
 */
final class GDLuminanceSource extends LuminanceSource
{
	public $luminances;
	private $dataWidth;
	private $dataHeight;
	/**
  * @var mixed|int
  */
	private $left;
	/**
  * @var mixed|int
  */
	private $top;
	/**
  * @var mixed|null
  */
	private $gdImage;

	public function __construct(
		$gdImage,
		$dataWidth,
		$dataHeight,
		$left = null,
		$top = null,
		$width = null,
		$height = null
	) {
		if (!$left && !$top && !$width && !$height) {
			$this->GDLuminanceSource($gdImage, $dataWidth, $dataHeight);

			return;
		}
		parent::__construct($width, $height);
		if ($left + $width > $dataWidth || $top + $height > $dataHeight) {
			throw new \InvalidArgumentException("Crop rectangle does not fit within image data.");
		}
		$this->luminances = $gdImage;
		$this->dataWidth = $dataWidth;
		$this->dataHeight = $dataHeight;
		$this->left = $left;
		$this->top = $top;
	}

	public function GDLuminanceSource($gdImage, $width, $height): void
	{
		parent::__construct($width, $height);

		$this->dataWidth = $width;
		$this->dataHeight = $height;
		$this->left = 0;
		$this->top = 0;
		$this->gdImage = $gdImage;


		// In order to measure pure decoding speed, we convert the entire image to a greyscale array
		// up front, which is the same as the Y channel of the YUVLuminanceSource in the real app.
		$this->luminances = [];
		//$this->luminances = $this->grayScaleToBitmap($this->grayscale());

		$array = [];
		$rgb = [];

		for ($j = 0; $j < $height; $j++) {
			for ($i = 0; $i < $width; $i++) {
				$argb = imagecolorat($this->gdImage, $i, $j);
				$pixel = imagecolorsforindex($this->gdImage, $argb);
				$r = $pixel['red'];
				$g = $pixel['green'];
				$b = $pixel['blue'];
				if ($r == $g && $g == $b) {
					// Image is already greyscale, so pick any channel.

					$this->luminances[] = $r;//(($r + 128) % 256) - 128;
				} else {
					// Calculate luminance cheaply, favoring green.
					$this->luminances[] = ($r + 2 * $g + $b) / 4;//(((($r + 2 * $g + $b) / 4) + 128) % 256) - 128;
				}
			}
		}

		/*
		for ($y = 0; $y < $height; $y++) {
			$offset = $y * $width;
			for ($x = 0; $x < $width; $x++) {
				$pixel = $pixels[$offset + $x];
				$r = ($pixel >> 16) & 0xff;
				$g = ($pixel >> 8) & 0xff;
				$b = $pixel & 0xff;
				if ($r == $g && $g == $b) {
// Image is already greyscale, so pick any channel.

					$this->luminances[(int)($offset + $x)] = (($r+128) % 256) - 128;
				} else {
// Calculate luminance cheaply, favoring green.
					$this->luminances[(int)($offset + $x)] =  (((($r + 2 * $g + $b) / 4)+128)%256) - 128;
				}



			}
		*/
		//}
		//   $this->luminances = $this->grayScaleToBitmap($this->luminances);
	}

	
	public function getRow($y, $row = null)
	{
		if ($y < 0 || $y >= $this->getHeight()) {
			throw new \InvalidArgumentException('Requested row is outside the image: ' . $y);
		}
		$width = $this->getWidth();
		if ($row == null || (is_countable($row) ? count($row) : 0) < $width) {
			$row = [];
		}
		$offset = ($y + $this->top) * $this->dataWidth + $this->left;
		$row = arraycopy($this->luminances, $offset, $row, 0, $width);

		return $row;
	}

	
	public function getMatrix()
	{
		$width = $this->getWidth();
		$height = $this->getHeight();

		// If the caller asks for the entire underlying image, save the copy and give them the
		// original data. The docs specifically warn that result.length must be ignored.
		if ($width == $this->dataWidth && $height == $this->dataHeight) {
			return $this->luminances;
		}

		$area = $width * $height;
		$matrix = [];
		$inputOffset = $this->top * $this->dataWidth + $this->left;

		// If the width matches the full width of the underlying data, perform a single copy.
		if ($width == $this->dataWidth) {
			$matrix = arraycopy($this->luminances, $inputOffset, $matrix, 0, $area);

			return $matrix;
		}

		// Otherwise copy one cropped row at a time.
		$rgb = $this->luminances;
		for ($y = 0; $y < $height; $y++) {
			$outputOffset = $y * $width;
			$matrix = arraycopy($rgb, $inputOffset, $matrix, $outputOffset, $width);
			$inputOffset += $this->dataWidth;
		}

		return $matrix;
	}

	
	public function isCropSupported(): bool
	{
		return true;
	}

	
	public function crop($left, $top, $width, $height): \Zxing\GDLuminanceSource
	{
		return new GDLuminanceSource(
			$this->luminances,
			$this->dataWidth,
			$this->dataHeight,
			$this->left + $left,
			$this->top + $top,
			$width,
			$height
		);
	}

	public function rotateCounterClockwise(): void
	{
		throw new \RuntimeException("This LuminanceSource does not support rotateCounterClockwise");
	}

	public function rotateCounterClockwise45(): void
	{
		throw new \RuntimeException("This LuminanceSource does not support rotateCounterClockwise45");
	}
}

IMagickLuminanceSource.php
Script de practica.
Abrir
Ver codigo

<?php

namespace Zxing;

/**
 * This class is used to help decode images from files which arrive as GD Resource
 * It does not support rotation.
 */
final class IMagickLuminanceSource extends LuminanceSource
{
	public $luminances;
	private $dataWidth;
	private $dataHeight;
	/**
	 * @var mixed|int
	 */
	private $left;
	/**
	 * @var mixed|int
	 */
	private $top;
	private ?\Imagick $image = null;

	public function __construct(
		\Imagick $image,
		$dataWidth,
		$dataHeight,
		$left = null,
		$top = null,
		$width = null,
		$height = null
	) {
		if (!$left && !$top && !$width && !$height) {
			$this->_IMagickLuminanceSource($image, $dataWidth, $dataHeight);

			return;
		}
		parent::__construct($width, $height);
		if ($left + $width > $dataWidth || $top + $height > $dataHeight) {
			throw new \InvalidArgumentException("Crop rectangle does not fit within image data.");
		}
		$this->luminances = $image;
		$this->dataWidth = $dataWidth;
		$this->dataHeight = $dataHeight;
		$this->left = $left;
		$this->top = $top;
	}

	public function rotateCounterClockwise(): void
	{
		throw new \RuntimeException("This LuminanceSource does not support rotateCounterClockwise");
	}

	public function rotateCounterClockwise45(): void
	{
		throw new \RuntimeException("This LuminanceSource does not support rotateCounterClockwise45");
	}

	/**
	 * TODO: move to some utility class or something
	 * Converts shorthand memory notation value to bytes
	 * From http://php.net/manual/en/function.ini-get.php
	 *
	 * @param int $val Memory size shorthand notation string
	 */
	protected static function kmgStringToBytes(string $val)
	{
		$val = trim($val);
		$last = strtolower($val[strlen($val) - 1]);
		$val = substr($val, 0, -1);
		switch ($last) {
				// The 'G' modifier is available since PHP 5.1.0
			case 'g':
				$val *= 1024;
				// no break
			case 'm':
				$val *= 1024;
				// no break
			case 'k':
				$val *= 1024;
		}
		return $val;
	}

	public function _IMagickLuminanceSource(\Imagick $image, $width, $height): void
	{
		parent::__construct($width, $height);

		$this->dataWidth = $width;
		$this->dataHeight = $height;
		$this->left = 0;
		$this->top = 0;
		$this->image = $image;

		// In order to measure pure decoding speed, we convert the entire image to a greyscale array
		// up front, which is the same as the Y channel of the YUVLuminanceSource in the real app.
		$this->luminances = [];

		$image->setImageColorspace(\Imagick::COLORSPACE_GRAY);
		// Check that we actually have enough space to do it
		if (ini_get('memory_limit') != -1 && $width * $height * 16 * 3 > $this->kmgStringToBytes(ini_get('memory_limit'))) {
			throw new \RuntimeException("PHP Memory Limit does not allow pixel export.");
		}
		$pixels = $image->exportImagePixels(1, 1, $width, $height, "RGB", \Imagick::PIXEL_CHAR);

		$array = [];
		$rgb = [];

		$countPixels = count($pixels);
		for ($i = 0; $i < $countPixels; $i += 3) {
			$r = $pixels[$i] & 0xff;
			$g = $pixels[$i + 1] & 0xff;
			$b = $pixels[$i + 2] & 0xff;
			if ($r == $g && $g == $b) {
				// Image is already greyscale, so pick any channel.
				$this->luminances[] = $r; //(($r + 128) % 256) - 128;
			} else {
				// Calculate luminance cheaply, favoring green.
				$this->luminances[] = ($r + 2 * $g + $b) / 4; //(((($r + 2 * $g + $b) / 4) + 128) % 256) - 128;
			}
		}
	}


	public function getRow($y, $row = null)
	{
		if ($y < 0 || $y >= $this->getHeight()) {
			throw new \InvalidArgumentException('Requested row is outside the image: ' . $y);
		}
		$width = $this->getWidth();
		if ($row == null || (is_countable($row) ? count($row) : 0) < $width) {
			$row = [];
		}
		$offset = ($y + $this->top) * $this->dataWidth + $this->left;
		$row = arraycopy($this->luminances, $offset, $row, 0, $width);

		return $row;
	}


	public function getMatrix()
	{
		$width = $this->getWidth();
		$height = $this->getHeight();

		// If the caller asks for the entire underlying image, save the copy and give them the
		// original data. The docs specifically warn that result.length must be ignored.
		if ($width == $this->dataWidth && $height == $this->dataHeight) {
			return $this->luminances;
		}

		$area = $width * $height;
		$matrix = [];
		$inputOffset = $this->top * $this->dataWidth + $this->left;

		// If the width matches the full width of the underlying data, perform a single copy.
		if ($width == $this->dataWidth) {
			$matrix = arraycopy($this->luminances, $inputOffset, $matrix, 0, $area);

			return $matrix;
		}

		// Otherwise copy one cropped row at a time.
		$rgb = $this->luminances;
		for ($y = 0; $y < $height; $y++) {
			$outputOffset = $y * $width;
			$matrix = arraycopy($rgb, $inputOffset, $matrix, $outputOffset, $width);
			$inputOffset += $this->dataWidth;
		}

		return $matrix;
	}


	public function isCropSupported(): bool
	{
		return true;
	}


	public function crop($left, $top, $width, $height): LuminanceSource
	{
		return $this->luminances->cropImage($width, $height, $left, $top);

		return new GDLuminanceSource(
			$this->luminances,
			$this->dataWidth,
			$this->dataHeight,
			$this->left + $left,
			$this->top + $top,
			$width,
			$height
		);
	}
}

LuminanceSource.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing;

use Zxing\Common\BitMatrix;

/**
 * The purpose of this class hierarchy is to abstract different bitmap implementations across
 * platforms into a standard interface for requesting greyscale luminance values. The interface
 * only provides immutable methods; therefore crop and rotation create copies. This is to ensure
 * that one Reader does not modify the original luminance source and leave it in an unknown state
 * for other Readers in the chain.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 */
abstract class LuminanceSource
{
	public function __construct(private $width, private $height)
	{
	}

	/**
	 * Fetches luminance data for the underlying bitmap. Values should be fetched using:
	 * {@code int luminance = array[y * width + x] & 0xff}
	 *
	 * @return BitMatrix A row-major 2D array of luminance values. Do not use result.length as it may be
	 *         larger than width * height bytes on some platforms. Do not modify the contents
	 *         of the result.
	 */
	abstract public function getMatrix();

	/**
	 * @return float The width of the bitmap.
	 */
	final public function getWidth(): float
	{
		return $this->width;
	}

	/**
	 * @return float The height of the bitmap.
	 */
	final public function getHeight(): float
	{
		return $this->height;
	}

	/**
	 * @return bool Whether this subclass supports cropping.
	 */
	public function isCropSupported(): bool
	{
		return false;
	}

	/**
	 * Returns a new object with cropped image data. Implementations may keep a reference to the
	 * original data rather than a copy. Only callable if isCropSupported() is true.
	 *
	 * @param $left   The left coordinate, which must be in [0,getWidth())
	 * @param $top    The top coordinate, which must be in [0,getHeight())
	 * @param $width  The width of the rectangle to crop.
	 * @param $height The height of the rectangle to crop.
	 *
	 * @return mixed A cropped version of this object.
	 */
	abstract public function crop($left, $top, $width, $height): LuminanceSource;

	/**
	 * @return bool Whether this subclass supports counter-clockwise rotation.
	 */
	public function isRotateSupported(): bool
	{
		return false;
	}

	/**
	 * @return a wrapper of this {@code LuminanceSource} which inverts the luminances it returns -- black becomes
	 *  white and vice versa, and each value becomes (255-value).
	 */
	// public function invert()
	// {
	// 	return new InvertedLuminanceSource($this);
	// }

	/**
	 * Returns a new object with rotated image data by 90 degrees counterclockwise.
	 * Only callable if {@link #isRotateSupported()} is true.
	 *
	 * @return mixed A rotated version of this object.
	 */
	abstract public function rotateCounterClockwise(): void;

	/**
	 * Returns a new object with rotated image data by 45 degrees counterclockwise.
	 * Only callable if {@link #isRotateSupported()} is true.
	 *
	 * @return mixed A rotated version of this object.
	 */
	abstract public function rotateCounterClockwise45(): void;

	final public function toString(): string
	{
		$row = [];
		$result = '';
		for ($y = 0; $y < $this->height; $y++) {
			$row = $this->getRow($y, $row);
			for ($x = 0; $x < $this->width; $x++) {
				$luminance = $row[$x] & 0xFF;
				$c = '';
				if ($luminance < 0x40) {
					$c = '#';
				} elseif ($luminance < 0x80) {
					$c = '+';
				} elseif ($luminance < 0xC0) {
					$c = '.';
				} else {
					$c = ' ';
				}
				$result .= ($c);
			}
			$result .= ('\n');
		}

		return $result;
	}

	/**
	 * Fetches one row of luminance data from the underlying platform's bitmap. Values range from
	 * 0 (black) to 255 (white). Because Java does not have an unsigned byte type, callers will have
	 * to bitwise and with 0xff for each value. It is preferable for implementations of this method
	 * to only fetch this row rather than the whole image, since no 2D Readers may be installed and
	 * getMatrix() may never be called.
	 *
	 * @param $y   ; The row to fetch, which must be in [0,getHeight())
	 * @param $row ; An optional preallocated array. If null or too small, it will be ignored.
	 *             Always use the returned object, and ignore the .length of the array.
	 *
	 * @return array
	 * An array containing the luminance data.
	 */
	abstract public function getRow(int $y, array $row);
}

NotFoundException.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing;

/**
 * Thrown when a barcode was not found in the image. It might have been
 * partially detected but could not be confirmed.
 *
 * @author Sean Owen
 */
final class NotFoundException extends ReaderException
{
	private static ?\Zxing\NotFoundException $instance = null;

	public static function getNotFoundInstance(string $message = ""): self
	{
		if (!self::$instance) {
			self::$instance = new NotFoundException($message);
		}

		return self::$instance;
	}
}

PlanarYUVLuminanceSource.php
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2009 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing;

/**
 * This object extends LuminanceSource around an array of YUV data returned from the camera driver,
 * with the option to crop to a rectangle within the full data. This can be used to exclude
 * superfluous pixels around the perimeter and speed up decoding.
 *
 * It works for any pixel format where the Y channel is planar and appears first, including
 * YCbCr_420_SP and YCbCr_422_SP.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 */
final class PlanarYUVLuminanceSource extends LuminanceSource
{
	private static int $THUMBNAIL_SCALE_FACTOR = 2;
	private $dataWidth;
	private $dataHeight;
	private $left;
	private $top;

	public function __construct(
		private $yuvData,
		$dataWidth,
		$dataHeight,
		$left,
		$top,
		$width,
		$height,
		$reverseHorizontal
	) {
		parent::__construct($width, $height);

		if ($left + $width > $dataWidth || $top + $height > $dataHeight) {
			throw new \InvalidArgumentException("Crop rectangle does not fit within image data.");
		}
		$this->dataWidth = $dataWidth;
		$this->dataHeight = $dataHeight;
		$this->left = $left;
		$this->top = $top;
		if ($reverseHorizontal) {
			$this->reverseHorizontal($width, $height);
		}
	}

	public function rotateCounterClockwise(): void
	{
		throw new \RuntimeException("This LuminanceSource does not support rotateCounterClockwise");
	}

	public function rotateCounterClockwise45(): void
	{
		throw new \RuntimeException("This LuminanceSource does not support rotateCounterClockwise45");
	}

	public function getRow($y, $row = null)
	{
		if ($y < 0 || $y >= $this->getHeight()) {
			throw new \InvalidArgumentException("Requested row is outside the image: " + $y);
		}
		$width = $this->getWidth();
		if ($row == null || (is_countable($row) ? count($row) : 0) < $width) {
			$row = []; //new byte[width];
		}
		$offset = ($y + $this->top) * $this->dataWidth + $this->left;
		$row = arraycopy($this->yuvData, $offset, $row, 0, $width);

		return $row;
	}


	public function getMatrix()
	{
		$width = $this->getWidth();
		$height = $this->getHeight();

		// If the caller asks for the entire underlying image, save the copy and give them the
		// original data. The docs specifically warn that result.length must be ignored.
		if ($width == $this->dataWidth && $height == $this->dataHeight) {
			return $this->yuvData;
		}

		$area = $width * $height;
		$matrix = []; //new byte[area];
		$inputOffset = $this->top * $this->dataWidth + $this->left;

		// If the width matches the full width of the underlying data, perform a single copy.
		if ($width == $this->dataWidth) {
			$matrix = arraycopy($this->yuvData, $inputOffset, $matrix, 0, $area);

			return $matrix;
		}

		// Otherwise copy one cropped row at a time.
		$yuv = $this->yuvData;
		for ($y = 0; $y < $height; $y++) {
			$outputOffset = $y * $width;
			$matrix = arraycopy($this->yuvData, $inputOffset, $matrix, $outputOffset, $width);
			$inputOffset += $this->dataWidth;
		}

		return $matrix;
	}

	// @Override
	public function isCropSupported(): bool
	{
		return true;
	}

	// @Override
	public function crop($left, $top, $width, $height): \Zxing\PlanarYUVLuminanceSource
	{
		return new PlanarYUVLuminanceSource(
			$this->yuvData,
			$this->dataWidth,
			$this->dataHeight,
			$this->left + $left,
			$this->top + $top,
			$width,
			$height,
			false
		);
	}

	/**
	 * @return int[]
	 */
	public function renderThumbnail(): array
	{
		$width = (int)($this->getWidth() / self::$THUMBNAIL_SCALE_FACTOR);
		$height = (int)($this->getHeight() / self::$THUMBNAIL_SCALE_FACTOR);
		$pixels = []; //new int[width * height];
		$yuv = $this->yuvData;
		$inputOffset = $this->top * $this->dataWidth + $this->left;

		for ($y = 0; $y < $height; $y++) {
			$outputOffset = $y * $width;
			for ($x = 0; $x < $width; $x++) {
				$grey = ($yuv[$inputOffset + $x * self::$THUMBNAIL_SCALE_FACTOR] & 0xff);
				$pixels[$outputOffset + $x] = (0xFF000000 | ($grey * 0x00010101));
			}
			$inputOffset += $this->dataWidth * self::$THUMBNAIL_SCALE_FACTOR;
		}

		return $pixels;
	}

	/**
	 * @return width of image from {@link #renderThumbnail()}
	 */
	/*
  public int getThumbnailWidth() {
	return getWidth() / THUMBNAIL_SCALE_FACTOR;
  }*/

	/**
	 * @return height of image from {@link #renderThumbnail()}
	 */
	/**public function getThumbnailHeight(): int
	{
		return getHeight() / THUMBNAIL_SCALE_FACTOR;
	}*/

	/**
	 *
	 * @param int $width
	 * @param int $height
	 * @return void
	 */
	private function reverseHorizontal(int $width, int $height): void
	{
		$yuvData = $this->yuvData;
		for ($y = 0, $rowStart = $this->top * $this->dataWidth + $this->left; $y < $height; $y++, $rowStart += $this->dataWidth) {
			$middle = (int)round($rowStart + $width / 2);
			for ($x1 = $rowStart, $x2 = $rowStart + $width - 1; $x1 < $middle; $x1++, $x2--) {
				$temp = $yuvData[$x1];
				$yuvData[$x1] = $yuvData[$x2];
				$yuvData[$x2] = $temp;
			}
		}
	}
}

QrReader.phpArchivos de textoQR
Script de practica.
Abrir
Ver codigo

<?php

namespace Zxing;

use Exception;
use Zxing\Common\HybridBinarizer;
use Zxing\Qrcode\QRCodeReader;

final class QrReader
{
	/**
	 * @var string
	 */
	public const SOURCE_TYPE_FILE = 'file';
	/**
	 * @var string
	 */
	public const SOURCE_TYPE_BLOB = 'blob';
	/**
	 * @var string
	 */
	public const SOURCE_TYPE_RESOURCE = 'resource';

	private readonly \Zxing\BinaryBitmap $bitmap;
	private readonly \Zxing\Qrcode\QRCodeReader $reader;
	private \Zxing\Result|bool|null $result = null;
	private ?Exception $error = null;

	public function __construct($imgSource, $sourceType = QrReader::SOURCE_TYPE_FILE, $useImagickIfAvailable = true)
	{
		if (!in_array($sourceType, [
			self::SOURCE_TYPE_FILE,
			self::SOURCE_TYPE_BLOB,
			self::SOURCE_TYPE_RESOURCE,
		], true)) {
			throw new \InvalidArgumentException('Invalid image source.');
		}
		$im = null;
		switch ($sourceType) {
			case QrReader::SOURCE_TYPE_FILE:
				if ($useImagickIfAvailable && extension_loaded('imagick')) {
					$im = new \Imagick();
					$im->readImage($imgSource);
				} else {
					$image = file_get_contents($imgSource);
					$im = imagecreatefromstring($image);
				}
				break;

			case QrReader::SOURCE_TYPE_BLOB:
				if ($useImagickIfAvailable && extension_loaded('imagick')) {
					$im = new \Imagick();
					$im->readImageBlob($imgSource);
				} else {
					$im = imagecreatefromstring($imgSource);
				}
				break;

			case QrReader::SOURCE_TYPE_RESOURCE:
				$im = $imgSource;
				if ($useImagickIfAvailable && extension_loaded('imagick')) {
					$useImagickIfAvailable = true;
				} else {
					$useImagickIfAvailable = false;
				}
				break;
		}
		if ($useImagickIfAvailable && extension_loaded('imagick')) {
			if (!$im instanceof \Imagick) {
				throw new \InvalidArgumentException('Invalid image source.');
			}
			$width = $im->getImageWidth();
			$height = $im->getImageHeight();
			$source = new IMagickLuminanceSource($im, $width, $height);
		} else {
			if (!$im instanceof \GdImage && !is_object($im)) {
				throw new \InvalidArgumentException('Invalid image source.');
			}
			$width = imagesx($im);
			$height = imagesy($im);
			$source = new GDLuminanceSource($im, $width, $height);
		}
		$histo = new HybridBinarizer($source);
		$this->bitmap = new BinaryBitmap($histo);
		$this->reader = new QRCodeReader();
	}

	public function decode($hints = null): void
	{
		try {
			$this->result = $this->reader->decode($this->bitmap, $hints);
		} catch (NotFoundException | FormatException | ChecksumException $e) {
			$this->result = false;
			$this->error = $e;
		}
	}

	public function text($hints = null)
	{
		$this->decode($hints);

		if ($this->result !== false && method_exists($this->result, 'toString')) {
			return $this->result->toString();
		}

		return $this->result;
	}

	public function getResult(): bool|Result|null
	{
		return $this->result;
	}

	public function getError(): Exception|null
	{
		return $this->error;
	}
}

RGBLuminanceSource.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing;

/**
 * This class is used to help decode images from files which arrive as RGB data from
 * an ARGB pixel array. It does not support rotation.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 * @author Betaminos
 */
final class RGBLuminanceSource extends LuminanceSource
{
	public $luminances;
	private $dataWidth;
	private $dataHeight;
	/**
  * @var mixed|int
  */
	private $left;
	/**
  * @var mixed|int
  */
	private $top;
	/**
  * @var mixed|null
  */
	private $pixels;


	public function __construct(
		$pixels,
		$dataWidth,
		$dataHeight,
		$left = null,
		$top = null,
		$width = null,
		$height = null
	) {
		if (!$left && !$top && !$width && !$height) {
			$this->RGBLuminanceSource_($pixels, $dataWidth, $dataHeight);

			return;
		}
		parent::__construct($width, $height);
		if ($left + $width > $dataWidth || $top + $height > $dataHeight) {
			throw new \InvalidArgumentException("Crop rectangle does not fit within image data.");
		}
		$this->luminances = $pixels;
		$this->dataWidth = $dataWidth;
		$this->dataHeight = $dataHeight;
		$this->left = $left;
		$this->top = $top;
	}

	public function rotateCounterClockwise(): void
	{
		throw new \RuntimeException("This LuminanceSource does not support rotateCounterClockwise");
	}

	public function rotateCounterClockwise45(): void
	{
		throw new \RuntimeException("This LuminanceSource does not support rotateCounterClockwise45");
	}

	public function RGBLuminanceSource_($width, $height, $pixels): void
	{
		parent::__construct($width, $height);

		$this->dataWidth = $width;
		$this->dataHeight = $height;
		$this->left = 0;
		$this->top = 0;
		$this->pixels = $pixels;


		// In order to measure pure decoding speed, we convert the entire image to a greyscale array
		// up front, which is the same as the Y channel of the YUVLuminanceSource in the real app.
		$this->luminances = [];
		//$this->luminances = $this->grayScaleToBitmap($this->grayscale());

		foreach ($pixels as $key => $pixel) {
			$r = $pixel['red'];
			$g = $pixel['green'];
			$b = $pixel['blue'];

			/* if (($pixel & 0xFF000000) == 0) {
				 $pixel = 0xFFFFFFFF; // = white
			 }

			 // .229R + 0.587G + 0.114B (YUV/YIQ for PAL and NTSC)

			 $this->luminances[$key] =
				 (306 * (($pixel >> 16) & 0xFF) +
					 601 * (($pixel >> 8) & 0xFF) +
					 117 * ($pixel & 0xFF) +
					 0x200) >> 10;

			*/
			//$r = ($pixel >> 16) & 0xff;
			//$g = ($pixel >> 8) & 0xff;
			//$b = $pixel & 0xff;
			if ($r == $g && $g == $b) {
				// Image is already greyscale, so pick any channel.

				$this->luminances[$key] = $r;//(($r + 128) % 256) - 128;
			} else {
				// Calculate luminance cheaply, favoring green.
				$this->luminances[$key] = ($r + 2 * $g + $b) / 4;//(((($r + 2 * $g + $b) / 4) + 128) % 256) - 128;
			}
		}

		/*

		for ($y = 0; $y < $height; $y++) {
			$offset = $y * $width;
			for ($x = 0; $x < $width; $x++) {
				$pixel = $pixels[$offset + $x];
				$r = ($pixel >> 16) & 0xff;
				$g = ($pixel >> 8) & 0xff;
				$b = $pixel & 0xff;
				if ($r == $g && $g == $b) {
// Image is already greyscale, so pick any channel.

					$this->luminances[(int)($offset + $x)] = (($r+128) % 256) - 128;
				} else {
// Calculate luminance cheaply, favoring green.
					$this->luminances[(int)($offset + $x)] =  (((($r + 2 * $g + $b) / 4)+128)%256) - 128;
				}



			}
		*/
		//}
		//   $this->luminances = $this->grayScaleToBitmap($this->luminances);
	}

	/**
	 * @return (int|mixed)[]
	 *
	 * @psalm-return array<int|mixed>
	 */
	public function grayscale(): array
	{
		$width = $this->dataWidth;
		$height = $this->dataHeight;

		$ret = fill_array(0, $width * $height, 0);
		for ($y = 0; $y < $height; $y++) {
			for ($x = 0; $x < $width; $x++) {
				$gray = $this->getPixel($x, $y, $width, $height);

				$ret[$x + $y * $width] = $gray;
			}
		}

		return $ret;
	}

	public function getPixel(int $x, int $y, $width, $height): int
	{
		$image = $this->pixels;
		if ($width < $x) {
			die('error');
		}
		if ($height < $y) {
			die('error');
		}
		$point = ($x) + ($y * $width);

		$r = $image[$point]['red'];//($image[$point] >> 16) & 0xff;
		$g = $image[$point]['green'];//($image[$point] >> 8) & 0xff;
		$b = $image[$point]['blue'];//$image[$point] & 0xff;

		$p = (int)(($r * 33 + $g * 34 + $b * 33) / 100);


		return $p;
	}

	/**
	 * @return (int|mixed)[]
	 *
	 * @psalm-return array<int, 0|255|mixed>
	 */
	public function grayScaleToBitmap($grayScale): array
	{
		$middle = $this->getMiddleBrightnessPerArea($grayScale);
		$sqrtNumArea = is_countable($middle) ? count($middle) : 0;
		$areaWidth = floor($this->dataWidth / $sqrtNumArea);
		$areaHeight = floor($this->dataHeight / $sqrtNumArea);
		$bitmap = fill_array(0, $this->dataWidth * $this->dataHeight, 0);

		for ($ay = 0; $ay < $sqrtNumArea; $ay++) {
			for ($ax = 0; $ax < $sqrtNumArea; $ax++) {
				for ($dy = 0; $dy < $areaHeight; $dy++) {
					for ($dx = 0; $dx < $areaWidth; $dx++) {
						$bitmap[(int)($areaWidth * $ax + $dx + ($areaHeight * $ay + $dy) * $this->dataWidth)] = ($grayScale[(int)($areaWidth * $ax + $dx + ($areaHeight * $ay + $dy) * $this->dataWidth)] < $middle[$ax][$ay]) ? 0 : 255;
					}
				}
			}
		}

		return $bitmap;
	}

	/**
  * @return float[]&mixed[][]
  */
	public function getMiddleBrightnessPerArea($image): array
	{
		$numSqrtArea = 4;
		//obtain middle brightness((min + max) / 2) per area
		$areaWidth = floor($this->dataWidth / $numSqrtArea);
		$areaHeight = floor($this->dataHeight / $numSqrtArea);
		$minmax = fill_array(0, $numSqrtArea, 0);
		for ($i = 0; $i < $numSqrtArea; $i++) {
			$minmax[$i] = fill_array(0, $numSqrtArea, 0);
			for ($i2 = 0; $i2 < $numSqrtArea; $i2++) {
				$minmax[$i][$i2] = [0, 0];
			}
		}
		for ($ay = 0; $ay < $numSqrtArea; $ay++) {
			for ($ax = 0; $ax < $numSqrtArea; $ax++) {
				$minmax[$ax][$ay][0] = 0xFF;
				for ($dy = 0; $dy < $areaHeight; $dy++) {
					for ($dx = 0; $dx < $areaWidth; $dx++) {
						$target = $image[(int)($areaWidth * $ax + $dx + ($areaHeight * $ay + $dy) * $this->dataWidth)];
						if ($target < $minmax[$ax][$ay][0]) {
							$minmax[$ax][$ay][0] = $target;
						}
						if ($target > $minmax[$ax][$ay][1]) {
							$minmax[$ax][$ay][1] = $target;
						}
					}
				}
				//minmax[ax][ay][0] = (minmax[ax][ay][0] + minmax[ax][ay][1]) / 2;
			}
		}
		$middle = [];
		for ($i3 = 0; $i3 < $numSqrtArea; $i3++) {
			$middle[$i3] = [];
		}
		for ($ay = 0; $ay < $numSqrtArea; $ay++) {
			for ($ax = 0; $ax < $numSqrtArea; $ax++) {
				$middle[$ax][$ay] = floor(($minmax[$ax][$ay][0] + $minmax[$ax][$ay][1]) / 2);
				//Console.out.print(middle[ax][ay] + ",");
			}
			//Console.out.println("");
		}

		//Console.out.println("");

		return $middle;
	}

	
	public function getRow($y, $row = null)
	{
		if ($y < 0 || $y >= $this->getHeight()) {
			throw new \InvalidArgumentException("Requested row is outside the image: " + $y);
		}
		$width = $this->getWidth();
		if ($row == null || (is_countable($row) ? count($row) : 0) < $width) {
			$row = [];
		}
		$offset = ($y + $this->top) * $this->dataWidth + $this->left;
		$row = arraycopy($this->luminances, $offset, $row, 0, $width);

		return $row;
	}

	
	public function getMatrix()
	{
		$width = $this->getWidth();
		$height = $this->getHeight();

		// If the caller asks for the entire underlying image, save the copy and give them the
		// original data. The docs specifically warn that result.length must be ignored.
		if ($width == $this->dataWidth && $height == $this->dataHeight) {
			return $this->luminances;
		}

		$area = $width * $height;
		$matrix = [];
		$inputOffset = $this->top * $this->dataWidth + $this->left;

		// If the width matches the full width of the underlying data, perform a single copy.
		if ($width == $this->dataWidth) {
			$matrix = arraycopy($this->luminances, $inputOffset, $matrix, 0, $area);

			return $matrix;
		}

		// Otherwise copy one cropped row at a time.
		$rgb = $this->luminances;
		for ($y = 0; $y < $height; $y++) {
			$outputOffset = $y * $width;
			$matrix = arraycopy($rgb, $inputOffset, $matrix, $outputOffset, $width);
			$inputOffset += $this->dataWidth;
		}

		return $matrix;
	}

	
	public function isCropSupported(): bool
	{
		return true;
	}

	
	public function crop($left, $top, $width, $height): \Zxing\RGBLuminanceSource
	{
		return new RGBLuminanceSource(
			$this->luminances,
			$this->dataWidth,
			$this->dataHeight,
			$this->left + $left,
			$this->top + $top,
			$width,
			$height
		);
	}
}

Reader.php
Script de practica.
Abrir
Ver codigo

<?php

namespace Zxing;

interface Reader
{
	public function decode(BinaryBitmap $image);

	public function reset();
}

ReaderException.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing;

/**
 * The general exception class throw when something goes wrong during decoding of a barcode.
 * This includes, but is not limited to, failing checksums / error correction algorithms, being
 * unable to locate finder timing patterns, and so on.
 *
 * @author Sean Owen
 */
abstract class ReaderException extends \Exception
{
	// disable stack traces when not running inside test units
	//protected static  $isStackTrace = System.getProperty("surefire.test.class.path") != null;
	protected static bool $isStackTrace = false;

	public function ReaderException($cause = null): void
	{
		if ($cause) {
			parent::__construct($cause);
		}
	}


	// Prevent stack traces from being taken
	// srowen says: huh, my IDE is saying this is not an override. native methods can't be overridden?
	// This, at least, does not hurt. Because we use a singleton pattern here, it doesn't matter anyhow.

	final public function fillInStackTrace()
	{
		return null;
	}
}

Result.php
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing;

/**
 * <p>Encapsulates the result of decoding a barcode within an image.</p>
 *
 * @author Sean Owen
 */
final class Result
{
	/**
  * @var mixed[]|mixed
  */
	private $resultMetadata = null;
	private $timestamp;

	public function __construct(
		private $text,
		private $rawBytes,
		private $resultPoints,
		private $format,
		$timestamp = ''
	) {
		$this->timestamp = $timestamp ?: time();
	}

	/**
	 * @return string raw text encoded by the barcode
	 */
	public function getText()
	{
		return $this->text;
	}

	/**
	 * @return array|string raw bytes encoded by the barcode, if applicable, otherwise {@code null}
	 */
	public function getRawBytes()
	{
		return $this->rawBytes;
	}

	/**
	 * @return array points related to the barcode in the image. These are typically points
	 *         identifying finder patterns or the corners of the barcode. The exact meaning is
	 *         specific to the type of barcode that was decoded.
	 */
	public function getResultPoints()
	{
		return $this->resultPoints;
	}

	/**
	 * @return {@link BarcodeFormat} representing the format of the barcode that was decoded
	 */
	public function getBarcodeFormat()
	{
		return $this->format;
	}

	/**
	 * @return {@link Map} mapping {@link ResultMetadataType} keys to values. May be
	 *   {@code null}. This contains optional metadata about what was detected about the barcode,
	 *   like orientation.
	 */
	public function getResultMetadata()
	{
		return $this->resultMetadata;
	}

	public function putMetadata(string $type, $value): void
	{
		$resultMetadata = [];
		if ($this->resultMetadata === null) {
			$this->resultMetadata = [];
		}
		$resultMetadata[$type] = $value;
	}

	public function putAllMetadata($metadata): void
	{
		if ($metadata !== null) {
			if ($this->resultMetadata === null) {
				$this->resultMetadata = $metadata;
			} else {
				$this->resultMetadata = array_merge($this->resultMetadata, $metadata);
			}
		}
	}

	public function addResultPoints($newPoints): void
	{
		$oldPoints = $this->resultPoints;
		if ($oldPoints === null) {
			$this->resultPoints = $newPoints;
		} elseif ($newPoints !== null && (is_countable($newPoints) ? count($newPoints) : 0) > 0) {
			$allPoints = fill_array(0, (is_countable($oldPoints) ? count($oldPoints) : 0) + (is_countable($newPoints) ? count($newPoints) : 0), 0);
			$allPoints = arraycopy($oldPoints, 0, $allPoints, 0, is_countable($oldPoints) ? count($oldPoints) : 0);
			$allPoints = arraycopy($newPoints, 0, $allPoints, is_countable($oldPoints) ? count($oldPoints) : 0, is_countable($newPoints) ? count($newPoints) : 0);
			$this->resultPoints = $allPoints;
		}
	}

	public function getTimestamp()
	{
		return $this->timestamp;
	}

	public function toString()
	{
		return $this->text;
	}
}

ResultPoint.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing;

use Zxing\Common\Detector\MathUtils;

/**
 * <p>Encapsulates a point of interest in an image containing a barcode. Typically, this
 * would be the location of a finder pattern or the corner of the barcode, for example.</p>
 *
 * @author Sean Owen
 */
class ResultPoint
{
	private float $x;
	private float $y;

	public function __construct($x, $y)
	{
		$this->x = (float)($x);
		$this->y = (float)($y);
	}

	/**
	 * Orders an array of three ResultPoints in an order [A,B,C] such that AB is less than AC
	 * and BC is less than AC, and the angle between BC and BA is less than 180 degrees.
	 *
	 * @param array $patterns of three {@code ResultPoint} to order
	 */
	public static function orderBestPatterns(array $patterns): array
	{

// Find distances between pattern centers
		$zeroOneDistance = self::distance($patterns[0], $patterns[1]);
		$oneTwoDistance = self::distance($patterns[1], $patterns[2]);
		$zeroTwoDistance = self::distance($patterns[0], $patterns[2]);

		$pointA = '';
		$pointB = '';
		$pointC = '';
		// Assume one closest to other two is B; A and C will just be guesses at first
		if ($oneTwoDistance >= $zeroOneDistance && $oneTwoDistance >= $zeroTwoDistance) {
			$pointB = $patterns[0];
			$pointA = $patterns[1];
			$pointC = $patterns[2];
		} elseif ($zeroTwoDistance >= $oneTwoDistance && $zeroTwoDistance >= $zeroOneDistance) {
			$pointB = $patterns[1];
			$pointA = $patterns[0];
			$pointC = $patterns[2];
		} else {
			$pointB = $patterns[2];
			$pointA = $patterns[0];
			$pointC = $patterns[1];
		}

		// Use cross product to figure out whether A and C are correct or flipped.
		// This asks whether BC x BA has a positive z component, which is the arrangement
		// we want for A, B, C. If it's negative, then we've got it flipped around and
		// should swap A and C.
		if (self::crossProductZ($pointA, $pointB, $pointC) < 0.0) {
			$temp = $pointA;
			$pointA = $pointC;
			$pointC = $temp;
		}

		$patterns[0] = $pointA;
		$patterns[1] = $pointB;
		$patterns[2] = $pointC;

		return $patterns;
	}

	/**
	 * @param ResultPoint $pattern1 first pattern
	 * @param ResultPoint $pattern2 second pattern
	 *
	 * @return float distance between two points
	 */
	public static function distance($pattern1, $pattern2)
	{
		return MathUtils::distance($pattern1->x, $pattern1->y, $pattern2->x, $pattern2->y);
	}

	

	/**
	 * Returns the z component of the cross product between vectors BC and BA.
	 */
	private static function crossProductZ(
		$pointA,
		$pointB,
		$pointC
	) {
		$bX = $pointB->x;
		$bY = $pointB->y;

		return (($pointC->x - $bX) * ($pointA->y - $bY)) - (($pointC->y - $bY) * ($pointA->x - $bX));
	}

	

	final public function getX(): float
	{
		return (float)($this->x);
	}

	

	final public function getY(): float
	{
		return (float)($this->y);
	}

	final public function equals($other): bool
	{
		if ($other instanceof ResultPoint) {
			$otherPoint = $other;

			return $this->x == $otherPoint->x && $this->y == $otherPoint->y;
		}

		return false;
	}

	final public function hashCode()
	{
		return 31 * floatToIntBits($this->x) + floatToIntBits($this->y);
	}

	final public function toString(): string
	{
		$result = '';
		$result .= ('(');
		$result .= ($this->x);
		$result .= (',');
		$result .= ($this->y);
		$result .= (')');

		return $result;
	}
}

AbstractEnum.php
Script de practica.
Abrir
Ver codigo

<?php

namespace Zxing\Common;

use ReflectionClass;

/**
 * A general enum implementation until we got SplEnum.
 */
final class AbstractEnum implements \Stringable
{
	/**
  * Default value.
  * @var null
  */
	public const __default = null;
	/**
	 * Current value.
	 *
	 * @var mixed
	 */
	private $value;
	/**
  * Cache of constants.
  *
  * @var array<string, mixed>|null
  */
	private ?array $constants = null;

	/**
	 * Creates a new enum.
	 *
	 * @param mixed   $initialValue
	 * @param boolean $strict
	 */
	public function __construct($initialValue = null, private $strict = false)
	{
		$this->change($initialValue);
	}

	/**
	 * Changes the value of the enum.
	 *
	 * @param  mixed $value
	 *
	 * @return void
	 */
	public function change($value)
	{
		if (!in_array($value, $this->getConstList(), $this->strict)) {
			throw new \UnexpectedValueException('Value not a const in enum ' . $this::class);
		}
		$this->value = $value;
	}

	/**
  * Gets all constants (possible values) as an array.
  *
  *
  * @return array
  */
	public function getConstList(bool $includeDefault = true)
	{
		$constants = [];
		if ($this->constants === null) {
			$reflection = new ReflectionClass($this);
			$this->constants = $reflection->getConstants();
		}
		if ($includeDefault) {
			return $this->constants;
		}
		$constants = $this->constants;
		unset($constants['__default']);

		return $constants;
	}

	/**
	 * Gets current value.
	 *
	 * @return mixed
	 */
	public function get()
	{
		return $this->value;
	}

	/**
	 * Gets the name of the enum.
	 *
	 * @return string
	 */
	public function __toString(): string
	{
		return (string)array_search($this->value, $this->getConstList());
	}
}

BitArray.php
Script de practica.
Abrir
Ver codigo

<?php
/**
 * Created by PhpStorm.
 * User: Ashot
 * Date: 3/25/15
 * Time: 11:51
 */

/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Common;

/**
 * <p>A simple, fast array of bits, represented compactly by an array of ints internally.</p>
 *
 * @author Sean Owen
 */

final class BitArray
{
	/**
  * @var mixed[]|int[]|null
  */
	private $bits;
	/**
  * @var mixed|null
  */
	private $size;


	public function __construct($bits = [], $size = 0)
	{
		if (!$bits && !$size) {
			$this->$size = 0;
			$this->bits = [];
		} elseif ($bits && !$size) {
			$this->size = $bits;
			$this->bits = self::makeArray($bits);
		} else {
			$this->bits = $bits;
			$this->size = $size;
		}
	}

	/**
	 * @psalm-return array<empty, empty>
	 */
	private static function makeArray($size): array
	{
		return [];
	}

	public function getSize()
	{
		return $this->size;
	}

	public function getSizeInBytes()
	{
		return ($this->size + 7) / 8;
	}

	/**
	 * Sets bit i.
	 *
	 * @param int $i bit to set
	 */
	public function set($i): void
	{
		$this->bits[(int)($i / 32)] |= 1 << ($i & 0x1F);
		$this->bits[(int)($i / 32)] = ($this->bits[(int)($i / 32)]);
	}

	/**
	 * Flips bit i.
	 *
	 * @param int $i bit to set
	 */
	public function flip($i): void
	{
		$this->bits[(int)($i / 32)] ^= 1 << ($i & 0x1F);
		$this->bits[(int)($i / 32)] = ($this->bits[(int)($i / 32)]);
	}

	/**
	 * @param int $from first bit to check
	 *
	 * @return int index of first bit that is set, starting from the given index, or size if none are set
	 *  at or beyond this given index
	 * @see #getNextUnset(int)
	 */
	public function getNextSet($from)
	{
		if ($from >= $this->size) {
			return $this->size;
		}
		$bitsOffset = (int)($from / 32);
		$currentBits = (int)$this->bits[$bitsOffset];
		// mask off lesser bits first
		$currentBits &= ~((1 << ($from & 0x1F)) - 1);
		while ($currentBits == 0) {
			if (++$bitsOffset == (is_countable($this->bits) ? count($this->bits) : 0)) {
				return $this->size;
			}
			$currentBits = $this->bits[$bitsOffset];
		}
		$result = ($bitsOffset * 32) + numberOfTrailingZeros($currentBits); //numberOfTrailingZeros

		return $result > $this->size ? $this->size : $result;
	}

	/**
	 * @param int $from index to start looking for unset bit
	 *
	 * @return int index of next unset bit, or {@code size} if none are unset until the end
	 * @see #getNextSet(int)
	 */
	public function getNextUnset($from)
	{
		if ($from >= $this->size) {
			return $this->size;
		}
		$bitsOffset = (int)($from / 32);
		$currentBits = ~$this->bits[$bitsOffset];
		// mask off lesser bits first
		$currentBits &= ~((1 << ($from & 0x1F)) - 1);
		while ($currentBits == 0) {
			if (++$bitsOffset == (is_countable($this->bits) ? count($this->bits) : 0)) {
				return $this->size;
			}
			$currentBits = (~$this->bits[$bitsOffset]);
		}
		$result = ($bitsOffset * 32) + numberOfTrailingZeros($currentBits);

		return $result > $this->size ? $this->size : $result;
	}

	/**
	 * Sets a block of 32 bits, starting at bit i.
	 *
	 * @param int $i first  bit to set
	 * @param int $newBits the new value of the next 32 bits. Note again that the least-significant bit
	 *                corresponds to bit i, the next-least-significant to i+1, and so on.
	 */
	public function setBulk($i, $newBits): void
	{
		$this->bits[(int)($i / 32)] = $newBits;
	}

	/**
	 * Sets a range of bits.
	 *
	 * @param int $start start of range, inclusive.
	 * @param int $end end   of range, exclusive
	 *
	 * @return void
	 */
	public function setRange($start, $end)
	{
		if ($end < $start) {
			throw new \InvalidArgumentException();
		}
		if ($end == $start) {
			return;
		}
		$end--; // will be easier to treat this as the last actually set bit -- inclusive
		$firstInt = (int)($start / 32);
		$lastInt = (int)($end / 32);
		for ($i = $firstInt; $i <= $lastInt; $i++) {
			$firstBit = $i > $firstInt ? 0 : $start & 0x1F;
			$lastBit = $i < $lastInt ? 31 : $end & 0x1F;
			$mask = 0;
			if ($firstBit == 0 && $lastBit == 31) {
				$mask = -1;
			} else {
				$mask = 0;
				for ($j = $firstBit; $j <= $lastBit; $j++) {
					$mask |= 1 << $j;
				}
			}
			$this->bits[$i] = ($this->bits[$i] | $mask);
		}
	}

	/**
	 * Clears all bits (sets to false).
	 */
	public function clear(): void
	{
		$max = is_countable($this->bits) ? count($this->bits) : 0;
		for ($i = 0; $i < $max; $i++) {
			$this->bits[$i] = 0;
		}
	}

	/**
	 * Efficient method to check if a range of bits is set, or not set.
	 *
	 * @param int $start start of range, inclusive.
	 * @param int $end end   of range, exclusive
	 * @param bool $value if true, checks that bits in range are set, otherwise checks that they are not set
	 *
	 * @return bool iff all bits are set or not set in range, according to value argument
	 *
	 * @throws \InvalidArgumentException if end is less than or equal to start
	 */
	public function isRange($start, $end, $value): bool
	{
		if ($end < $start) {
			throw new \InvalidArgumentException();
		}
		if ($end == $start) {
			return true; // empty range matches
		}
		$end--; // will be easier to treat this as the last actually set bit -- inclusive
		$firstInt = (int)($start / 32);
		$lastInt = (int)($end / 32);
		for ($i = $firstInt; $i <= $lastInt; $i++) {
			$firstBit = $i > $firstInt ? 0 : $start & 0x1F;
			$lastBit = $i < $lastInt ? 31 : $end & 0x1F;
			$mask = 0;
			if ($firstBit == 0 && $lastBit == 31) {
				$mask = -1;
			} else {
				$mask = 0;
				for ($j = $firstBit; $j <= $lastBit; $j++) {
					$mask = ($mask | (1 << $j));
				}
			}

			// Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is,
			// equals the mask, or we're looking for 0s and the masked portion is not all 0s
			if (($this->bits[$i] & $mask) != ($value ? $mask : 0)) {
				return false;
			}
		}

		return true;
	}

	/**
	 * Appends the least-significant bits, from value, in order from most-significant to
	 * least-significant. For example, appending 6 bits from 0x000001E will append the bits
	 * 0, 1, 1, 1, 1, 0 in that order.
	 *
	 * @param int $value   {@code int} containing bits to append
	 * @param int $numBits bits from value to append
	 */
	public function appendBits($value, $numBits): void
	{
		if ($numBits < 0 || $numBits > 32) {
			throw new \InvalidArgumentException("Num bits must be between 0 and 32");
		}
		$this->ensureCapacity($this->size + $numBits);
		for ($numBitsLeft = $numBits; $numBitsLeft > 0; $numBitsLeft--) {
			$this->appendBit((($value >> ($numBitsLeft - 1)) & 0x01) == 1);
		}
	}

	private function ensureCapacity($size): void
	{
		if ($size > (is_countable($this->bits) ? count($this->bits) : 0) * 32) {
			$newBits = self::makeArray($size);
			$newBits = arraycopy($this->bits, 0, $newBits, 0, is_countable($this->bits) ? count($this->bits) : 0);
			$this->bits = $newBits;
		}
	}

	public function appendBit(bool $bit): void
	{
		$this->ensureCapacity($this->size + 1);
		if ($bit) {
			$this->bits[(int)($this->size / 32)] |= 1 << ($this->size & 0x1F);
		}
		$this->size++;
	}

	public function appendBitArray($other): void
	{
		$otherSize = $other->size;
		$this->ensureCapacity($this->size + $otherSize);
		for ($i = 0; $i < $otherSize; $i++) {
			$this->appendBit($other->get($i));
		}
	}

	public function _xor($other): void
	{
		if ((is_countable($this->bits) ? count($this->bits) : 0) !== (is_countable($other->bits) ? count($other->bits) : 0)) {
			throw new \InvalidArgumentException("Sizes don't match");
		}
		$count = is_countable($this->bits) ? count($this->bits) : 0;
		for ($i = 0; $i < $count; $i++) {
			// The last byte could be incomplete (i.e. not have 8 bits in
			// it) but there is no problem since 0 XOR 0 == 0.
			$this->bits[$i] ^= $other->bits[$i];
		}
	}

	/**
	 *
	 * @param int $bitOffset first bit to start writing
	 * @param array     $array to write into. Bytes are written most-significant byte first. This is the opposite
	 *                  of the internal representation, which is exposed by {@link #getBitArray()}
	 * @param int $offset position    in array to start writing
	 * @param int $numBytes how  many bytes to write
	 */
	public function toBytes($bitOffset, array &$array, $offset, $numBytes): void
	{
		for ($i = 0; $i < $numBytes; $i++) {
			$theByte = 0;
			for ($j = 0; $j < 8; $j++) {
				if ($this->get($bitOffset)) {
					$theByte |= 1 << (7 - $j);
				}
				$bitOffset++;
			}
			$array[(int)($offset + $i)] = $theByte;
		}
	}

	/**
	 * @param $i ; bit to get
	 * @param float|int first $i
	 *
	 * @return bool iff bit i is set
	 */
	public function get(int|float $i): bool
	{
		$key = (int)($i / 32);

		return ($this->bits[$key] & (1 << ($i & 0x1F))) != 0;
	}

	/**
	 * @return (int|mixed)[]|null underlying array of ints. The first element holds the first 32 bits, and the least significant bit is bit 0.
	 *
	 * @psalm-return array<int|mixed>|null
	 */
	public function getBitArray(): array|null
	{
		return $this->bits;
	}

	/**
	 * Reverses all bits in the array.
	 */
	public function reverse(): void
	{
		$newBits = [];
		// reverse all int's first
		$len = (($this->size - 1) / 32);
		$oldBitsLen = $len + 1;
		for ($i = 0; $i < $oldBitsLen; $i++) {
			$x = $this->bits[$i];/*
			 $x = (($x >>  1) & 0x55555555L) | (($x & 0x55555555L) <<  1);
				  $x = (($x >>  2) & 0x33333333L) | (($x & 0x33333333L) <<  2);
				  $x = (($x >>  4) & 0x0f0f0f0fL) | (($x & 0x0f0f0f0fL) <<  4);
				  $x = (($x >>  8) & 0x00ff00ffL) | (($x & 0x00ff00ffL) <<  8);
				  $x = (($x >> 16) & 0x0000ffffL) | (($x & 0x0000ffffL) << 16);*/
			$x = (($x >> 1) & 0x55555555) | (($x & 0x55555555) << 1);
			$x = (($x >> 2) & 0x33333333) | (($x & 0x33333333) << 2);
			$x = (($x >> 4) & 0x0f0f0f0f) | (($x & 0x0f0f0f0f) << 4);
			$x = (($x >> 8) & 0x00ff00ff) | (($x & 0x00ff00ff) << 8);
			$x = (($x >> 16) & 0x0000ffff) | (($x & 0x0000ffff) << 16);
			$newBits[(int)$len - $i] = (int)$x;
		}
		// now correct the int's if the bit size isn't a multiple of 32
		if ($this->size != $oldBitsLen * 32) {
			$leftOffset = $oldBitsLen * 32 - $this->size;
			$mask = 1;
			for ($i = 0; $i < 31 - $leftOffset; $i++) {
				$mask = ($mask << 1) | 1;
			}
			$currentInt = ($newBits[0] >> $leftOffset) & $mask;
			for ($i = 1; $i < $oldBitsLen; $i++) {
				$nextInt = $newBits[$i];
				$currentInt |= $nextInt << (32 - $leftOffset);
				$newBits[(int)($i) - 1] = $currentInt;
				$currentInt = ($nextInt >> $leftOffset) & $mask;
			}
			$newBits[(int)($oldBitsLen) - 1] = $currentInt;
		}
		//        $bits = $newBits;
	}

	public function equals($o): bool
	{
		if (!($o instanceof BitArray)) {
			return false;
		}
		$other = $o;

		return $this->size == $other->size && $this->bits === $other->bits;
	}

	public function hashCode()
	{
		return 31 * $this->size + hashCode($this->bits);
	}

	public function toString(): string
	{
		$result = '';
		for ($i = 0; $i < $this->size; $i++) {
			if (($i & 0x07) == 0) {
				$result .= ' ';
			}
			$result .= ($this->get($i) ? 'X' : '.');
		}

		return (string)$result;
	}

	public function _clone(): \Zxing\Common\BitArray
	{
		return new BitArray($this->bits, $this->size);
	}
}

BitMatrix.php
Script de practica.
Abrir
Ver codigo

<?php

namespace Zxing\Common;

final class BitMatrix
{
	private $width;
	private $height;
	private $rowSize;
	/**
  * @var mixed|int[]
  */
	private $bits;

	public function __construct($width, $height = false, $rowSize = false, $bits = false)
	{
		if (!$height) {
			$height = $width;
		}
		if (!$rowSize) {
			$rowSize = (int)(($width + 31) / 32);
		}
		if (!$bits) {
			$bits = fill_array(0, $rowSize * $height, 0);
			//            [];//new int[rowSize * height];
		}
		$this->width = $width;
		$this->height = $height;
		$this->rowSize = $rowSize;
		$this->bits = $bits;
	}

	public static function parse($stringRepresentation, $setString, $unsetString): self
	{
		if (!$stringRepresentation) {
			throw new \InvalidArgumentException();
		}
		$bits = [];
		$bitsPos = 0;
		$rowStartPos = 0;
		$rowLength = -1;
		$nRows = 0;
		$pos = 0;
		while ($pos < strlen((string) $stringRepresentation)) {
			if ($stringRepresentation[$pos] == '\n' ||
				$stringRepresentation->{$pos} == '\r') {
				if ($bitsPos > $rowStartPos) {
					if ($rowLength == -1) {
						$rowLength = $bitsPos - $rowStartPos;
					} elseif ($bitsPos - $rowStartPos != $rowLength) {
						throw new \InvalidArgumentException("row lengths do not match");
					}
					$rowStartPos = $bitsPos;
					$nRows++;
				}
				$pos++;
			} elseif (substr((string) $stringRepresentation, $pos, strlen((string) $setString)) == $setString) {
				$pos += strlen((string) $setString);
				$bits[$bitsPos] = true;
				$bitsPos++;
			} elseif (substr((string) $stringRepresentation, $pos + strlen((string) $unsetString)) == $unsetString) {
				$pos += strlen((string) $unsetString);
				$bits[$bitsPos] = false;
				$bitsPos++;
			} else {
				throw new \InvalidArgumentException(
					"illegal character encountered: " . substr((string) $stringRepresentation, $pos)
				);
			}
		}

		// no EOL at end?
		if ($bitsPos > $rowStartPos) {
			if ($rowLength == -1) {
				$rowLength = $bitsPos - $rowStartPos;
			} elseif ($bitsPos - $rowStartPos != $rowLength) {
				throw new \InvalidArgumentException("row lengths do not match");
			}
			$nRows++;
		}

		$matrix = new BitMatrix($rowLength, $nRows);
		for ($i = 0; $i < $bitsPos; $i++) {
			if ($bits[$i]) {
				$matrix->set($i % $rowLength, $i / $rowLength);
			}
		}

		return $matrix;
	}

	/**
	 * <p>Sets the given bit to true.</p>
	 *
	 * @param $x ;  The horizontal component (i.e. which column)
	 * @param $y ;   The vertical component (i.e. which row)
	 * @param float|int $x
	 * @param float|int $y
	 */
	public function set(int|float $x, int|float $y): void
	{
		$offset = (int)($y * $this->rowSize + ($x / 32));
		if (!isset($this->bits[$offset])) {
			$this->bits[$offset] = 0;
		}
		//$this->bits[$offset] = $this->bits[$offset];

		//  if($this->bits[$offset]>200748364){
		//$this->bits= array(0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-1090519040,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,1056964608,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-1358954496,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,117440512,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,50331648,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,33554432,-1,-1,536870911,-4096,65279,0,0,0,0,0,0,0,0,-1,-1,65535,-4096,65535,0,0,0,0,0,0,0,0,-193,536870911,0,-4096,65279,0,0,0,0,0,0,0,0,-254,32767,0,-4096,61951,0,0,0,0,0,0,0,0,20913920,0,0,-4096,50175,0,0,0,0,0,0,0,0,0,0,0,-4096,60159,0,0,0,0,0,0,0,0,0,0,0,-4096,64255,0,0,0,0,0,0,0,0,0,0,0,-8192,56319,0,0,0,0,0,0,0,0,0,0,0,-4096,16777215,0,0,0,0,0,0,0,0,0,0,0,-4096,16777215,0,0,0,0,0,0,0,0,0,0,0,-4096,16777215,0,0,0,0,0,0,0,0,0,0,0,-4096,16777215,0,0,0,0,0,0,0,0,0,0,0,-4096,16777215,0,0,0,0,0,0,0,0,0,0,0,-4096,16777215,0,0,0,0,0,0,0,0,0,0,0,-4096,16777215,0,0,0,0,0,0,0,0,0,0,0,-4096,16777215,0,0,0,0,0,0,0,251658240,0,0,0,-4096,-1,255,0,256,0,0,0,0,117440512,0,0,0,-4096,-1,255,0,512,0,0,0,0,117440512,0,0,0,-4096,-1,255,0,1024,0,0,0,0,117440512,0,0,0,-4096,-1,223,0,256,0,0,0,0,117440512,0,0,33030144,-4096,-1,191,0,256,0,0,0,0,117440512,0,0,33554428,-4096,-1,255,0,768,0,0,0,0,117440512,0,402849792,67108862,-8192,-1,255,0,768,0,0,0,0,117440512,0,470278396,63045630,-8192,-1,255,0,256,0,0,0,0,251658240,-8388608,470278399,58720286,-8192,-1,2686975,0,3842,0,0,0,0,251658240,-131072,1007149567,58720286,-8192,-1,2031615,0,3879,0,0,0,0,251658240,536739840,1007092192,58720286,-8192,-1,851967,0,3840,0,0,0,0,251658240,917504,1007092192,58720284,-8192,-1,2031615,0,3968,0,0,0,0,251658240,917504,1007092160,59244060,-8192,-1,65535,0,7936,0,0,0,0,251658240,917504,1009779136,59244060,-8192,-1,9371647,0,1792,0,0,0,0,251658240,917504,946921920,59244060,-8192,-1,8585215,0,1792,0,0,0,0,117440512,-15859712,477159875,59244060,-8192,-1,65535,0,12032,0,0,0,0,251658240,-15859712,52490691,59244060,-8192,-1,-1,0,65408,0,0,0,0,251658240,-15859712,58778051,59244060,-8192,-1,-1,0,65473,0,0,0,0,251658240,-15859712,125886915,59244060,-8192,-1,-1,0,65472,0,0,0,0,251658240,-15859712,58778051,59244060,-8192,-1,-1,0,65408,0,0,0,0,251658240,-15859712,8380867,59244060,-8192,-1,-1,0,65473,0,0,0,0,251658240,-15859712,8380867,59244060,-8192,-1,-1,0,131011,0,0,0,0,251658240,-15859712,8380867,58720284,-8192,-1,-1,0,130947,0,0,0,0,251658240,-15859712,2089411,58720284,-8192,-1,-1,0,130947,0,0,0,0,251658240,-32636928,449,58720284,-8192,-1,-1,33554431,131015,0,0,0,0,251658240,786432,448,62914588,-8192,-1,-1,16777215,131015,0,0,0,0,251658240,786432,448,67108860,-8192,-1,-1,553648127,131015,0,0,0,0,251658240,786432,946864576,67108860,-8192,-1,-1,32505855,131015,0,0,0,0,251658240,786432,946921976,8388604,-8192,-1,-1,8191999,131015,0,0,0,0,251658240,-262144,946921983,248,-8192,-1,-1,8126463,196551,0,0,0,0,251658240,-262144,7397887,0,-8192,-1,-1,16777215,262087,0,0,0,0,251658240,-262144,8257543,0,-8192,-1,-1,-2121269249,262095,0,0,0,0,520093696,0,8257536,0,-8192,-1,-1,-201326593,262095,0,0,0,0,520290304,0,8257536,117963776,-8192,-1,-1,-201326593,262095,0,0,0,0,520093696,0,-2140143616,118488579,-8192,-1,-1,-201326593,131023,0,0,0,0,520093696,0,-2131697280,118488579,-8192,-1,-1,-503316481,131023,0,0,0,0,520093696,2145386496,-2131631232,118484995,-16384,-1,-1,-469762049,262095,0,0,0,0,520093696,2147221504,552649600,118481344,-16384,-1,-1,-469762049,131023,0,0,0,0,520290304,2147221504,2029002240,118481344,-16384,-1,-1,-469762049,262031,0,0,0,0,520290304,-266600448,2029001791,125952960,-16384,-1,-1,-469762049,262031,0,0,0,0,1057423360,-266600448,2027953215,133177312,-16384,-1,-1,-134217729,262111,0,0,0,0,1058471936,-266600448,-119531393,133177343,-16384,-1,-1,-134217729,262111,0,0,0,0,1058471936,-2145648640,-253754369,66068479,-16384,-1,-1,-134217729,262111,0,0,0,0,1058471936,236716032,-253754369,15729663,-16384,-1,-1,-134217729,262095,0,0,0,0,1057947648,236716032,-253754369,6348807,-16384,-1,-1,-134217729,262095,0,0,0,0,524222464,236716032,-253690305,6348803,-16384,-1,-1,-134217729,262111,0,0,0,0,521076736,2115764224,-253625344,14737411,-16384,-1,-1,-134217729,262095,0,0,0,0,522125312,2115764224,-253625344,14743555,-16384,-1,-1,-134217729,262111,0,0,16772608,0,1073676288,-31719424,-2014283776,14810115,-16384,-1,-1,-1,262143,0,0,16776704,0,1065287680,-1642594304,-1879178880,14810115,-16384,-1,-1,-1,524287,0,0,16776192,0,2139029504,264241152,-2013396089,14809091,-16384,-1,-1,-1,262095,0,0,16776192,0,2139029504,264241152,-2080636025,14803335,-16384,-1,-1,-1,262087,0,0,16776192,0,2147418112,264241152,-2132803581,14803847,-16384,-1,-1,-402653185,524259,0,0,8386048,0,2147418112,0,-2132688896,123783,-16384,-1,-1,1207959551,262112,0,0,16775168,0,2147418112,0,14794752,1046535,-16384,-1,-1,268435455,262128,0,0,16775168,0,2147418112,0,14712832,1047615,-16384,-1,-1,536870911,524284,0,0,16776705,0,2147418112,0,14680832,1047615,-16384,-1,-1,-1,524287,0,0,16776704,0,2147418112,-1048576,14681087,1046591,-32768,-1,-1,-1,524287,0,0,16776704,0,2147418112,-524288,-2132802561,2080831,-32768,-1,-1,-1,524287,0,0,16776705,0,2147418112,-524288,-31718401,2080831,-32768,-1,-1,-1,1048575,0,0,16776193,0,2147418112,3670016,-31718528,2080831,-32768,-1,-1,-1,524287,0,0,16776195,0,2147418112,3670016,-31718528,134086719,-32768,-1,-1,-1,524287,0,0,16776195,0,2147418112,3670016,253494144,268173368,-32768,-1,-1,-1,524287,0,0,16775171,0,2147418112,3670016,268174208,268173368,-32768,-1,-1,-1,1048575,0,0,16771072,0,2147418112,-63438848,268174223,31457328,-32768,-1,-1,-1,1048575,0,0,10418176,0,-65536,-63438848,133957519,14807040,-32768,-1,-1,-1,2097151,0,0,15923200,0,2147418112,-63438848,1968015,14809095,-32768,-1,-1,-1,1048575,0,0,12808192,0,2147418112,-63438848,2082703,12711943,-32768,-1,-1,-1,2097151,0,0,6420480,0,2147418112,-63438848,2082703,14343,-32768,-1,-1,-1,2097151,0,0,15202304,0,-65536,-63438848,2082703,1849351,-32768,-1,-1,-1,2097151,0,0,15464448,0,-65536,-63438848,264472335,1849351,-32768,-1,-1,-1,4194303,0,0,16371712,0,-65536,-63438848,264472335,14343,-32768,-1,-1,-1,8388607,0,0,0,0,-65536,-63438848,532907791,235010048,-32768,-1,-1,-1,16777215,0,0,0,0,-65536,-63438848,-1603833,235010160,-32768,-1,-1,-1,16777215,0,0,0,0,-65536,3670016,-30976,67238000,-32768,-1,-1,-1,16777215,0,0,0,0,-65536,3670016,-30976,48,-32768,-1,-1,-1,16777215,0,0,0,0,-65536,3670016,-29391104,768,-32768,-1,-1,-1,16777215,0,0,0,0,-65536,3670016,-29391104,768,-32768,-1,-1,-1,16777215,0,0,0,0,-65536,-524287,-65042433,768,-32768,-1,-1,-1,16777215,0,0,0,0,-65536,-524287,2082441215,0,-65536,-1,-1,-1,16777215,0,0,0,0,-13697024,-524287,511,0,-65536,-1,-1,-1,16777215,0,0,0,0,-12648448,1,0,0,-65536,-1,-1,-1,14680063,0,0,0,0,-12648448,1,0,0,-65536,-1,-1,-1,16777215,0,0,0,0,-65536,1,0,0,-65536,-1,-1,-1,14680063,0,0,0,0,-8454144,1,0,0,-65536,-1,-1,-1,12582911,0,0,0,0,-12648448,1,0,0,-65536,-1,-1,-1,2097151,0,0,0,0,-12648448,1,0,0,-65536,-1,-1,-1,1048575,0,0,0,0,-14745600,1,0,0,-65536,-1,-1,-1,3145727,0,0,0,0,1056964608,1,0,0,-65536,-1,-1,-1,1048575,0,0,0,0,1056964608,1,0,0,-65536,-1,-1,-1,1048575,0,0,0,0,1056964608,1,0,0,-65536,-1,-1,-1,524287,0,0,0,0,2130706432,1,0,0,-65536,-1,-1,-1,1048575,0,0,0,0,1056964608,1,0,0,-65536,-1,-1,-1,524287,0,0,0,0,2130706432,1,0,0,-65536,-1,-1,-1,524287,0,0,0,0,2130706432,1,0,0,-65536,-1,-1,-1,1048575,0,0,0,0,2130706432,1,0,0,-65536,-1,-1,-1,1048575,0,0,0,0,50331648,1,0,0,-65536,-1,-1,-1,1048575,0,0,0,0,117440512,1,0,-268435456,-1,-1,-1,-1,524287,0,0,0,0,251658240,1,0,-320,-1,-1,-1,-1,262143,0,0,0,0,520093696,1,-2048,-1,-1,-1,-1,-1,262143,0,0,0,0,1056964608,-16777213,-1,-1,-1,-1,-1,-1,131071,0,0,0,0,-16777216,-121,-1,-1,-1,-1,-1,-1,131071,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,131071,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,131071,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,131071,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,65535,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,65535,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,131071,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,262143,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,524287,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,524287,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,589823,0,0,0,0,0,-1,-1,-1,-1,-1,-1,-1,8179,0,0,0,0,50331648,-1,-1,-1,-1,-1,-1,-1,4080,0,0,0,0,117440512,-1,-1,-1,-1,-1,-1,-1,1016,0,0,0,0,251658240,-1,-1,-1,-1,-1,-1,1073741823,1020,0,0,0,0,50331648,-1,-1,-1,-1,-1,-1,536870911,254,0,0,0,0,50331648,-1,-1,-1,-1,-1,-1,536870911,255,0,0,0,0,50331648,-1,-1,-1,-1,-1,-1,-1879048193,127,0,0,0,0,50331648,-1,-1,-1,-1,-1,-1,-469762049,63,0,0,0,0,1191182336,-1,-1,-1,-1,1023999,0,-520093712,15,0,0,0,0,-218103808,-1,-1,-1,-1,0,-8454144,-260046849,7,0,0,0,0,0,-193,-1,-1,-1057947649,-2147483648,-1,-58720257,1,0,0,0,0,0,-251,-1,-1,-1057423361,-2074,-1,-1,0,0,0,0,0,0,-59648,-1,-1,-1,-1,-1,1073741823,0,0,0,0,0,0,-65536,-1,-1,-1,-1,-1,268435455,0,0,0,0,0,0,-65536,-1,-1,-1,-1,-1,67108863,0,0,0,0,0,0,-65536,-1,-1,-1,-1,-1,8388607,0,0,0,0,0,0,0,-403603456,-1,-1,-1,-1,262143,0,0,0,8388656,0,0,0,-1891434496,-1,-1,-1,-1,16383,0,0,0,8388608,0,0,0,-1612513280,-1,-1,-1,-1,63,0,0,0,0,0,0,0,-24320,-1,-1,-1,8388607,0,0,0,0,0,0,0,0,-256,-1,-1,1073741823,1,0,0,0,0,0,0,0,1610612736,-15,-1,-1,16383,0,0,0,0,0,0,0,0,-16646144,-1,-1,251658239,0,0,0,0,0,0,0,0,0,-51200,-1,-1,40959,0,0,0,0,0,0,268419584,103809024,-12713984,-1,-2147483137,4194303,0,0,0,0,0,0,0,402620416,-2144010240,-13631487,-32513,3,20480,0,0,0,0,0,0,0,419299328,0,-262144,-1,0,0,0,0,0,0,0,0,0,0,0,-5832704,268049407,0,0,0,0,0,0,0,0,0,0,0,0,33030144,0,0,0,0,0,0,0,0,0,0,0,0,3670016,0,0,0,0,0,0,0,0,0,0,0,0,1572864,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,458752,0,0,0,0,0,0,0,0,0,0,0,0,229376,0,0,0,0,0,0,0,0,0,0,0,0,32768,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8192,0,0,0,0,0,0,0,0,0,0,0,0,8192,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,31744,0,0,0,0,0,0,0,0,0,0,0,0,31744,0,0,0,0,0,0,0,0,0,0,0,0,64512,0,0,0,0,0,0,0,0,0,0,0,0,15872,0,0,0,0,0,0,0,0,0,0,0,0,3584,0,0,0,0,0,0,0,0,0,0,0,0,7680,0,0,0,0,0,0,0,0,0,0,0,0,512,0,0,0,0,0,0,0,0,0,0,0,0,3968,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3840,0,0,0,0,0,0,0,0,0,0,0,0,1855,0,0,0,0,0,0,0,0,0,0,0,0,63,0,0,0,0,0,0,0,0,0,0,0,0,15,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,134217728,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,124,0,0,0,0,0,0,0,0,0,0,0,-260046848,63,0,0,0,0,0,0,0,0,0,0,0,-17301504,127,0,0,0,0,0,0,0,0,0,0,0,-524288,127,0,0,0,0,0,0,0,0,0,0,0,-262144,127,0,0,0,0,0,0,0,0,0,0,0,-262144,63,0,0,0,0,0,0,0,0,0,0,0,-262144,63,0,0,0,0,0,0,0,0,0,0,0,-262144,63,0,0,0,0,0,0,0,0,0,0,0,-262144,31,0,0,0,0,0,0,0,0,0,0,0,-262144,63,0,0,0,0,3,0,0,0,0,0,0,-262144,63,0,0,0,0,7,0,0,0,0,0,0,-262144,63,0,0,0,0,63,0,0,0,0,0,0,-262144,63,0,0,0,0,511,0,0,0,0,0,0,-524288,31,0,0,0,0,8191,0,0,0,0,0,0,-1048576,63,0,0,0,0,131071,0,0,0,0,0,0,-524288,63,0,0,0,0,262143,0,0,0,0,0,0,-524288,63,0,0,0,0,131071,0,0,0,0,0,0,-1048576,63,0,0,0,0,262143,0,0,0,0,0,0,-1048576,63,0,0,0,0,262143,0,0,0,0,0,0,-1048576,63,0,0,0,0,262143,0,0,0,0,0,0,-1048576,63,0,0,0,0,262143,0,0,0,0,0,0,-2097152,127,0,0,0,0,262143,0,0,0,0,0,0,-2097152,127,0,0,0,0,262143,0,0,0,0,0,0,-1048576,127,0,0,0,0,262143,0,0,0,0,0,0,-1048576,127,0,0,0,0,262143,0,0,0,0,0,0,-2097152,255,0,0,0,0,262143,0,0,0,0,0,0,-2097152,255,0,0,0,0,262142,0,0,0,0,0,0,-2097152,255,0,0,0,0,262142,0,0,0,0,0,0,-2097152,255,0,0,0,0,262142,0,0,0,0,0,0,-2097152,255,0,0,0,0,262140,0,0,0,0,0,0,-2097152,255,0,0,0,0,131068,0,0,0,0,0,0,-4194304,255,0,0,0,0,131068,0,0,0,0,0,0,-4194304,255,0,0,0,0,65528,0,0,0,0,0,0,-8388608,255,0,0,0,0,65528,0,0,0,0,0,0,-8388608,255,0,0,0,0,65528,0,0,0,0,0,0,-8388608,255,0,0,0,0,32760,0,0,0,0,0,0,-8388608,255,0,0,0,0,32760,0,0,0,0,0,0,-16777216,255,0,0,-2147483648,255,16368,0,0,0,0,0,0,-16777216,255,0,0,-536870912,1023,16368,0,0,0,0,0,0,-33554432,255,0,0,-16777216,4095,16352,0,0,0,0,0,0,-33554432,255,0,0,-8388608,262143,16352,0,0,0,0,0,0,-33554432,255,0,0,-1048576,2097151,16352,0,0,0,0,0,0,-67108864,255,0,0,-524288,8388607,16352,0,0,0,0,0,0,-67108864,255,0,0,-262144,16777215,16320,0,0,0,0,0,0,-67108864,255,0,0,-131072,16777215,100679648,0,0,0,0,0,0,-67108864,255,0,0,-16384,16776959,125861824,0,0,0,0,0,0,-134217728,255,0,0,-4096,16773121,62930880,0,0,0,0,0,0,-134217728,127,0,0,2147482624,16252928,32704,0,0,0,0,0,0,-134217728,127,0,0,268435200,14680064,16320,0,0,0,0,0,0,-134217728,127,0,0,134217600,0,32704,0,0,0,0,0,0,-33554432,127,0,1056964608,67108736,0,32704,0,0,0,0,0,0,-33554432,127,0,2130706432,33554368,0,65408,0,0,0,0,0,0,-33554432,127,0,-16777216,8388576,0,32640,0,0,0,0,0,0,-134217728,127,0,-16777216,2097136,0,32640,0,0,0,0,0,0,-134217728,63,0,-16776960,1048573,0,32640,0,0,0,0,0,0,-536870912,63,0,-16776448,1048575,0,32640,0,0,0,0,0,0,-536870912,63,0,-33553664,6291455,66752,32640,0,0,0,0,0,0,-536870912,63,0,2013266688,2097148,229376,32640,0,0,0,0,0,0,-536870912,63,0,256,4194300,229376,32640,0,0,0,0,0,0,-536870912,63,0,0,524280,196608,32512,0,0,8,0,0,0,-1073741824,63,0,0,-200,15,65280,0,0,24,0,0,0,-1073741824,63,0,0,-1867768,127,32512,0,0,56,0,0,0,-1073741824,63,0,0,-1056768,4095,32512,0,0,124,0,0,0,-1073741824,63,0,0,-1050624,8191,32512,0,0,508,0,0,0,-2147483648,31,0,0,-7866368,8191,32512,0,0,1020,0,0,0,-2147483648,31,0,0,-33030656,8095,32512,0,0,2046,0,0,0,-2147483648,63,0,0,-66586624,771,32512,0,0,4094,0,0,0,0,63,0,0,-134184960,1,32256,0,0,8190,0,0,0,0,63,0,0,1610612736,0,32256,0,0,16382,0,0,0,-2147483648,63,0,0,0,0,15872,0,0,32767,0,0,0,-2147483648,31,0,0,0,0,15872,0,-2147483648,65535,0,0,0,-2147483648,31,0,0,0,0,7680,0,0,65535,0,0,0,-2147483648,31,0,0,134217728,0,7680,0,-2147483648,65535,0,0,0,-2147483648,31,0,0,0,0,7680,0,-2147483648,65535,0,0,0,-2147483648,31,0,0,0,0,7680,0,-1073741824,65535,0,0,0,-2147483648,31,0,0,0,0,3072,0,-1073741824,65535,0,0,0,-2147483648,31,0,0,0,0,3072,0,-1073741824,65535,0,0,0,-2147483648,31,0,0,0,0,0,0,-2147483648,65535,0,0,0,-2147483648,31,0,0,0,0,0,0,-1073741824,65535,0,0,0,0,31,0,0,0,0,0,0,-1073741824,65535,0,0,0,0,31,0,0,0,0,0,0,-2147483648,65535,0,0,0,0,30,0,0,0,0,0,0,-1073741824,65535,0,0,0,0,30,0,0,0,0,0,0,-2147483648,65535,0,0,0,0,30,0,0,0,0,0,0,0,65535,0,0,0,0,28,0,0,0,0,0,0,0,65535,0,0,0,0,28,0,0,0,0,0,0,0,65535,0,0,0,0,28,0,0,0,0,0,0,0,65535,0,0,0,0,24,0,0,0,0,0,0,-2147483648,65535,0,0,0,0,0,0,0,0,0,0,0,-536870912,65535);//[$offset] |= intval32bits(1 << ($x & 0x1f));
		$bob = $this->bits[$offset];
		$bob |= 1 << ($x & 0x1f);
		$this->bits[$offset] |= ($bob);
		//$this->bits[$offset] = intval32bits($this->bits[$offset]);

		//}
//16777216
	}

	public function _unset($x, $y): void
	{//было unset, php не позволяет использовать unset
		$offset = (int)($y * $this->rowSize + ($x / 32));
		$this->bits[$offset] &= ~(1 << ($x & 0x1f));
	}

	/**1 << (249 & 0x1f)
	 * <p>Flips the given bit.</p>
	 *
	 * @param $x ;  The horizontal component (i.e. which column)
	 * @param $y ;  The vertical component (i.e. which row)
	 */
	/**
	 * @psalm-param 0|positive-int $x
	 * @psalm-param 0|positive-int $y
	 */
	public function flip(int $x, int $y): void
	{
		$offset = $y * $this->rowSize + (int)($x / 32);

		$this->bits[$offset] = ($this->bits[$offset] ^ (1 << ($x & 0x1f)));
	}

	/**
	 * Exclusive-or (XOR): Flip the bit in this {@code BitMatrix} if the corresponding
	 * mask bit is set.
	 *
	 * @param $mask ;  XOR mask
	 */
	public function _xor($mask): void
	{//было xor, php не позволяет использовать xor
		if ($this->width != $mask->getWidth() || $this->height != $mask->getHeight()
			|| $this->rowSize != $mask->getRowSize()) {
			throw new \InvalidArgumentException("input matrix dimensions do not match");
		}
		$rowArray = new BitArray($this->width / 32 + 1);
		for ($y = 0; $y < $this->height; $y++) {
			$offset = $y * $this->rowSize;
			$row = $mask->getRow($y, $rowArray)->getBitArray();
			for ($x = 0; $x < $this->rowSize; $x++) {
				$this->bits[$offset + $x] ^= $row[$x];
			}
		}
	}

	/**
	 * Clears all bits (sets to false).
	 */
	public function clear(): void
	{
		$max = is_countable($this->bits) ? count($this->bits) : 0;
		for ($i = 0; $i < $max; $i++) {
			$this->bits[$i] = 0;
		}
	}

	/**
	 * <p>Sets a square region of the bit matrix to true.</p>
	 *
	 * @param $left   ;  The horizontal position to begin at (inclusive)
	 * @param $top    ;  The vertical position to begin at (inclusive)
	 * @param $width  ;  The width of the region
	 * @param $height ;  The height of the region
	 *
	 * @psalm-param 0|6|9 $left
	 * @psalm-param 0|6|9 $top
	 */
	public function setRegion(int $left, int $top, int $width, int $height): void
	{
		if ($top < 0 || $left < 0) {
			throw new \InvalidArgumentException("Left and top must be nonnegative");
		}
		if ($height < 1 || $width < 1) {
			throw new \InvalidArgumentException("Height and width must be at least 1");
		}
		$right = $left + $width;
		$bottom = $top + $height;
		if ($bottom > $this->height || $right > $this->width) { //> this.height || right > this.width
			throw new \InvalidArgumentException("The region must fit inside the matrix");
		}
		for ($y = $top; $y < $bottom; $y++) {
			$offset = $y * $this->rowSize;
			for ($x = $left; $x < $right; $x++) {
				$this->bits[$offset + (int)($x / 32)] = ($this->bits[$offset + (int)($x / 32)] |= 1 << ($x & 0x1f));
			}
		}
	}

	/**
	 * Modifies this {@code BitMatrix} to represent the same but rotated 180 degrees
	 */
	public function rotate180(): void
	{
		$width = $this->getWidth();
		$height = $this->getHeight();
		$topRow = new BitArray($width);
		$bottomRow = new BitArray($width);
		for ($i = 0; $i < ($height + 1) / 2; $i++) {
			$topRow = $this->getRow($i, $topRow);
			$bottomRow = $this->getRow($height - 1 - $i, $bottomRow);
			$topRow->reverse();
			$bottomRow->reverse();
			$this->setRow($i, $bottomRow);
			$this->setRow($height - 1 - $i, $topRow);
		}
	}

	/**
	 * @return float The width of the matrix
	 */
	public function getWidth()
	{
		return $this->width;
	}

	/**
	 * A fast method to retrieve one row of data from the matrix as a BitArray.
	 *
	 * @param $y   ;  The row to retrieve
	 * @param $row ;  An optional caller-allocated BitArray, will be allocated if null or too small
	 * @param float|int $y
	 *
	 * @psalm-param 0|float|positive-int $y
	 */
	public function getRow(int|float $y, BitArray $row): BitArray
	{
		if ($row == null || $row->getSize() < $this->width) {
			$row = new BitArray($this->width);
		} else {
			$row->clear();
		}
		$offset = $y * $this->rowSize;
		for ($x = 0; $x < $this->rowSize; $x++) {
			$row->setBulk($x * 32, $this->bits[$offset + $x]);
		}

		return $row;
	}

	/**
	 * @param $y   ;  row to set
	 * @param $row ;  {@link BitArray} to copy from
	 * @param float|int $y
	 *
	 * @psalm-param 0|float|positive-int $y
	 */
	public function setRow(int|float $y, BitArray $row): void
	{
		$this->bits = arraycopy($row->getBitArray(), 0, $this->bits, $y * $this->rowSize, $this->rowSize);
	}

	/**
	 * This is useful in detecting the enclosing rectangle of a 'pure' barcode.
	 *
	 * @return (int|mixed)[]|null
	 *
	 * @psalm-return array{0: int|mixed, 1: 0|mixed|positive-int, 2: mixed, 3: mixed}|null
	 */
	public function getEnclosingRectangle(): array|null
	{
		$left = $this->width;
		$top = $this->height;
		$right = -1;
		$bottom = -1;

		for ($y = 0; $y < $this->height; $y++) {
			for ($x32 = 0; $x32 < $this->rowSize; $x32++) {
				$theBits = $this->bits[$y * $this->rowSize + $x32];
				if ($theBits != 0) {
					if ($y < $top) {
						$top = $y;
					}
					if ($y > $bottom) {
						$bottom = $y;
					}
					if ($x32 * 32 < $left) {
						$bit = 0;
						while (($theBits << (31 - $bit)) == 0) {
							$bit++;
						}
						if (($x32 * 32 + $bit) < $left) {
							$left = $x32 * 32 + $bit;
						}
					}
					if ($x32 * 32 + 31 > $right) {
						$bit = 31;
						while ((sdvig3($theBits, $bit)) == 0) {//>>>
							$bit--;
						}
						if (($x32 * 32 + $bit) > $right) {
							$right = $x32 * 32 + $bit;
						}
					}
				}
			}
		}

		$width = $right - $left;
		$height = $bottom - $top;

		if ($width < 0 || $height < 0) {
			return null;
		}

		return [$left, $top, $width, $height];
	}

	/**
	 * This is useful in detecting a corner of a 'pure' barcode.
	 *
	 * @psalm-return array{0: mixed, 1: mixed}|null
	 */
	public function getTopLeftOnBit(): array|null
	{
		$bitsOffset = 0;
		while ($bitsOffset < (is_countable($this->bits) ? count($this->bits) : 0) && $this->bits[$bitsOffset] == 0) {
			$bitsOffset++;
		}
		if ($bitsOffset == (is_countable($this->bits) ? count($this->bits) : 0)) {
			return null;
		}
		$y = $bitsOffset / $this->rowSize;
		$x = ($bitsOffset % $this->rowSize) * 32;

		$theBits = $this->bits[$bitsOffset];
		$bit = 0;
		while (($theBits << (31 - $bit)) == 0) {
			

... (vista previa truncada) ...
BitSource.php
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Common;

/**
 * <p>This provides an easy abstraction to read bits at a time from a sequence of bytes, where the
 * number of bits read is not often a multiple of 8.</p>
 *
 * <p>This class is thread-safe but not reentrant -- unless the caller modifies the bytes array
 * it passed in, in which case all bets are off.</p>
 *
 * @author Sean Owen
 */
final class BitSource
{
	private int $byteOffset = 0;
	private int $bitOffset = 0;

	/**
	 * @param array $bytes bytes from which this will read bits. Bits will be read from the first byte first.
	 *              Bits are read within a byte from most-significant to least-significant bit.
	 */
	public function __construct(private array $bytes)
	{
	}

	/**
	 * @return int of next bit in current byte which would be read by the next call to {@link #readBits(int)}.
	 */
	public function getBitOffset(): int
	{
		return $this->bitOffset;
	}

	/**
	 * @return int of next byte in input byte array which would be read by the next call to {@link #readBits(int)}.
	 */
	public function getByteOffset(): int
	{
		return $this->byteOffset;
	}

	/**
	 * @param int $numBits number of bits to read
	 *
	 * @return int representing the bits read. The bits will appear as the least-significant
	 *         bits of the int
	 * @throws \InvalidArgumentException if numBits isn't in [1,32] or more than is available
	 */
	public function readBits($numBits)
	{
		if ($numBits < 1 || $numBits > 32 || $numBits > $this->available()) {
			throw new \InvalidArgumentException(strval($numBits));
		}

		$result = 0;

		// First, read remainder from current byte
		if ($this->bitOffset > 0) {
			$bitsLeft = 8 - $this->bitOffset;
			$toRead = $numBits < $bitsLeft ? $numBits : $bitsLeft;
			$bitsToNotRead = $bitsLeft - $toRead;
			$mask = (0xFF >> (8 - $toRead)) << $bitsToNotRead;
			$result = ($this->bytes[$this->byteOffset] & $mask) >> $bitsToNotRead;
			$numBits -= $toRead;
			$this->bitOffset += $toRead;
			if ($this->bitOffset == 8) {
				$this->bitOffset = 0;
				$this->byteOffset++;
			}
		}

		// Next read whole bytes
		if ($numBits > 0) {
			while ($numBits >= 8) {
				$result = ($result << 8) | ($this->bytes[$this->byteOffset] & 0xFF);
				$this->byteOffset++;
				$numBits -= 8;
			}

			// Finally read a partial byte
			if ($numBits > 0) {
				$bitsToNotRead = 8 - $numBits;
				$mask = (0xFF >> $bitsToNotRead) << $bitsToNotRead;
				$result = ($result << $numBits) | (($this->bytes[$this->byteOffset] & $mask) >> $bitsToNotRead);
				$this->bitOffset += $numBits;
			}
		}

		return $result;
	}

	/**
	 * @return int of bits that can be read successfully
	 */
	public function available(): int
	{
		return 8 * ((is_countable($this->bytes) ? count($this->bytes) : 0) - $this->byteOffset) - $this->bitOffset;
	}
}

CharacterSetECI.php
Script de practica.
Abrir
Ver codigo

<?php

namespace Zxing\Common;

/**
 * Encapsulates a Character Set ECI, according to "Extended Channel
 * Interpretations" 5.3.1.1 of ISO 18004.
 */
final class CharacterSetECI
{
	/**#@+
  * Character set constants.
  */
	/**
	 * @var int
	 */
	public const CP437 = 0;
	/**
  * @var int
  */
	public const ISO8859_1 = 1;
	/**
  * @var int
  */
	public const ISO8859_2 = 4;
	/**
  * @var int
  */
	public const ISO8859_3 = 5;
	/**
  * @var int
  */
	public const ISO8859_4 = 6;
	/**
  * @var int
  */
	public const ISO8859_5 = 7;
	/**
  * @var int
  */
	public const ISO8859_6 = 8;
	/**
  * @var int
  */
	public const ISO8859_7 = 9;
	/**
  * @var int
  */
	public const ISO8859_8 = 10;
	/**
  * @var int
  */
	public const ISO8859_9 = 11;
	/**
  * @var int
  */
	public const ISO8859_10 = 12;
	/**
  * @var int
  */
	public const ISO8859_11 = 13;
	/**
  * @var int
  */
	public const ISO8859_12 = 14;
	/**
  * @var int
  */
	public const ISO8859_13 = 15;
	/**
  * @var int
  */
	public const ISO8859_14 = 16;
	/**
  * @var int
  */
	public const ISO8859_15 = 17;
	/**
  * @var int
  */
	public const ISO8859_16 = 18;
	/**
  * @var int
  */
	public const SJIS = 20;
	/**
  * @var int
  */
	public const CP1250 = 21;
	/**
  * @var int
  */
	public const CP1251 = 22;
	/**
  * @var int
  */
	public const CP1252 = 23;
	/**
  * @var int
  */
	public const CP1256 = 24;
	/**
  * @var int
  */
	public const UNICODE_BIG_UNMARKED = 25;
	/**
  * @var int
  */
	public const UTF8 = 26;
	/**
  * @var int
  */
	public const ASCII = 27;
	/**
  * @var int
  */
	public const BIG5 = 28;
	/**
  * @var int
  */
	public const GB18030 = 29;
	/**
  * @var int
  */
	public const EUC_KR = 30;
	/**
  * Map between character names and their ECI values.
  */
	private static array $nameToEci = [
		'ISO-8859-1' => self::ISO8859_1,
		'ISO-8859-2' => self::ISO8859_2,
		'ISO-8859-3' => self::ISO8859_3,
		'ISO-8859-4' => self::ISO8859_4,
		'ISO-8859-5' => self::ISO8859_5,
		'ISO-8859-6' => self::ISO8859_6,
		'ISO-8859-7' => self::ISO8859_7,
		'ISO-8859-8' => self::ISO8859_8,
		'ISO-8859-9' => self::ISO8859_9,
		'ISO-8859-10' => self::ISO8859_10,
		'ISO-8859-11' => self::ISO8859_11,
		'ISO-8859-12' => self::ISO8859_12,
		'ISO-8859-13' => self::ISO8859_13,
		'ISO-8859-14' => self::ISO8859_14,
		'ISO-8859-15' => self::ISO8859_15,
		'ISO-8859-16' => self::ISO8859_16,
		'SHIFT-JIS' => self::SJIS,
		'WINDOWS-1250' => self::CP1250,
		'WINDOWS-1251' => self::CP1251,
		'WINDOWS-1252' => self::CP1252,
		'WINDOWS-1256' => self::CP1256,
		'UTF-16BE' => self::UNICODE_BIG_UNMARKED,
		'UTF-8' => self::UTF8,
		'ASCII' => self::ASCII,
		'GBK' => self::GB18030,
		'EUC-KR' => self::EUC_KR,
	];
	/**#@-*/
	/**
	 * Additional possible values for character sets.
	 */
	private static array $additionalValues = [
		self::CP437 => 2,
		self::ASCII => 170,
	];
	private static int|string|null $name = null;

	/**
  * Gets character set ECI by value.
  *
  *
  * @return CharacterSetEci|null
  */
	public static function getCharacterSetECIByValue(string $value)
	{
		if ($value < 0 || $value >= 900) {
			throw new \InvalidArgumentException('Value must be between 0 and 900');
		}
		if (false !== ($key = array_search($value, self::$additionalValues))) {
			$value = $key;
		}
		array_search($value, self::$nameToEci);
		try {
			self::setName($value);

			return new self($value);
		} catch (\UnexpectedValueException) {
			return null;
		}
	}

	/**
	 * @param (int|string) $value
	 *
	 * @psalm-param array-key $value
	 *
	 * @return null|true
	 */
	private static function setName($value)
	{
		foreach (self::$nameToEci as $name => $key) {
			if ($key == $value) {
				self::$name = $name;

				return true;
			}
		}
		if (self::$name == null) {
			foreach (self::$additionalValues as $name => $key) {
				if ($key == $value) {
					self::$name = $name;

					return true;
				}
			}
		}
	}

	/**
	 * Gets character set ECI name.
	 *
	 * @return int|null|string set ECI name|null
	 */
	public static function name(): string|int|null
	{
		return self::$name;
	}

	/**
  * Gets character set ECI by name.
  *
  *
  * @return CharacterSetEci|null
  */
	public static function getCharacterSetECIByName(string $name)
	{
		$name = strtoupper($name);
		if (isset(self::$nameToEci[$name])) {
			return new self(self::$nameToEci[$name]);
		}

		return null;
	}
}

DecoderResult.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Common;

/**
 * <p>Encapsulates the result of decoding a matrix of bits. This typically
 * applies to 2D barcode formats. For now it contains the raw bytes obtained,
 * as well as a String interpretation of those bytes, if applicable.</p>
 *
 * @author Sean Owen
 */
final class DecoderResult
{
	/**
  * @var mixed|null
  */
	private $errorsCorrected;
	/**
  * @var mixed|null
  */
	private $erasures;
	/**
  * @var mixed|null
  */
	private $other;


	public function __construct(private $rawBytes, private $text, private $byteSegments, private $ecLevel, private $structuredAppendSequenceNumber = -1, private $structuredAppendParity = -1)
	{
	}

	public function getRawBytes()
	{
		return $this->rawBytes;
	}

	public function getText()
	{
		return $this->text;
	}

	public function getByteSegments()
	{
		return $this->byteSegments;
	}

	public function getECLevel()
	{
		return $this->ecLevel;
	}

	public function getErrorsCorrected()
	{
		return $this->errorsCorrected;
	}

	public function setErrorsCorrected($errorsCorrected): void
	{
		$this->errorsCorrected = $errorsCorrected;
	}

	public function getErasures()
	{
		return $this->erasures;
	}

	public function setErasures($erasures): void
	{
		$this->erasures = $erasures;
	}

	public function getOther()
	{
		return $this->other;
	}

	public function setOther(\Zxing\Qrcode\Decoder\QRCodeDecoderMetaData $other): void
	{
		$this->other = $other;
	}

	public function hasStructuredAppend(): bool
	{
		return $this->structuredAppendParity >= 0 && $this->structuredAppendSequenceNumber >= 0;
	}

	public function getStructuredAppendParity()
	{
		return $this->structuredAppendParity;
	}

	public function getStructuredAppendSequenceNumber()
	{
		return $this->structuredAppendSequenceNumber;
	}
}

DefaultGridSampler.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Common;

use Zxing\NotFoundException;

/**
 * @author Sean Owen
 */
final class DefaultGridSampler extends GridSampler
{
	/**
	 * @return BitMatrix
	 */
	public function sampleGrid(
		$image,
		$dimensionX,
		$dimensionY,
		$p1ToX,
		$p1ToY,
		$p2ToX,
		$p2ToY,
		$p3ToX,
		$p3ToY,
		$p4ToX,
		$p4ToY,
		$p1FromX,
		$p1FromY,
		$p2FromX,
		$p2FromY,
		$p3FromX,
		$p3FromY,
		$p4FromX,
		$p4FromY
	) {
		$transform = PerspectiveTransform::quadrilateralToQuadrilateral(
			$p1ToX,
			$p1ToY,
			$p2ToX,
			$p2ToY,
			$p3ToX,
			$p3ToY,
			$p4ToX,
			$p4ToY,
			$p1FromX,
			$p1FromY,
			$p2FromX,
			$p2FromY,
			$p3FromX,
			$p3FromY,
			$p4FromX,
			$p4FromY
		);

		return $this->sampleGrid_($image, $dimensionX, $dimensionY, $transform);
	}


	/**
	 * @return BitMatrix
	 */
	public function sampleGrid_(
		BitMatrix $image,
		int $dimensionX,
		int $dimensionY,
		PerspectiveTransform $transform
	): BitMatrix {
		if ($dimensionX <= 0 || $dimensionY <= 0) {
			throw new NotFoundException("X or Y dimensions smaller than zero");
		}
		$bits = new BitMatrix($dimensionX, $dimensionY);
		$points = fill_array(0, 2 * $dimensionX, 0.0);
		for ($y = 0; $y < $dimensionY; $y++) {
			$max = is_countable($points) ? count($points) : 0;
			$iValue = (float)$y + 0.5;
			for ($x = 0; $x < $max; $x += 2) {
				$points[$x] = (float)($x / 2) + 0.5;
				$points[$x + 1] = $iValue;
			}
			$transform->transformPoints($points);
			// Quick check to see if points transformed to something inside the image;
			// sufficient to check the endpoints
			self::checkAndNudgePoints($image, $points);
			try {
				for ($x = 0; $x < $max; $x += 2) {
					if ($image->get((int)$points[$x], (int)$points[$x + 1])) {
						// Black(-ish) pixel
						$bits->set($x / 2, $y);
					}
				}
			} catch (\Exception) { //ArrayIndexOutOfBoundsException
				// This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting
				// transform gets "twisted" such that it maps a straight line of points to a set of points
				// whose endpoints are in bounds, but others are not. There is probably some mathematical
				// way to detect this about the transformation that I don't know yet.
				// This results in an ugly runtime exception despite our clever checks above -- can't have
				// that. We could check each point's coordinates but that feels duplicative. We settle for
				// catching and wrapping ArrayIndexOutOfBoundsException.
				throw new NotFoundException("ArrayIndexOutOfBoundsException");
			}
		}

		return $bits;
	}
}

DetectorResult.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Common;

/**
 * <p>Encapsulates the result of detecting a barcode in an image. This includes the raw
 * matrix of black/white pixels corresponding to the barcode, and possibly points of interest
 * in the image, like the location of finder patterns or corners of the barcode in the image.</p>
 *
 * @author Sean Owen
 */
class DetectorResult
{
	public function __construct(private $bits, private $points)
	{
	}

	final public function getBits()
	{
		return $this->bits;
	}

	final public function getPoints()
	{
		return $this->points;
	}
}

GlobalHistogramBinarizer.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Common;

use Zxing\Binarizer;
use Zxing\NotFoundException;

/**
 * This Binarizer implementation uses the old ZXing global histogram approach. It is suitable
 * for low-end mobile devices which don't have enough CPU or memory to use a local thresholding
 * algorithm. However, because it picks a global black point, it cannot handle difficult shadows
 * and gradients.
 *
 * Faster mobile devices and all desktop applications should probably use HybridBinarizer instead.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 * @author Sean Owen
 */
class GlobalHistogramBinarizer extends Binarizer
{
	private static int $LUMINANCE_BITS = 5;
	private static int $LUMINANCE_SHIFT = 3;
	private static int $LUMINANCE_BUCKETS = 32;

	private static array $EMPTY = [];

	private array $luminances = [];
	private array $buckets = [];
	/**
  * @var mixed|\Zxing\LuminanceSource
  */
	private $source = [];

	public function __construct($source)
	{
		self::$LUMINANCE_SHIFT = 8 - self::$LUMINANCE_BITS;
		self::$LUMINANCE_BUCKETS = 1 << self::$LUMINANCE_BITS;

		parent::__construct($source);

		$this->luminances = self::$EMPTY;
		$this->buckets = fill_array(0, self::$LUMINANCE_BUCKETS, 0);
		$this->source = $source;
	}

	// Applies simple sharpening to the row data to improve performance of the 1D Readers.
	public function getBlackRow(int $y, ?BitArray $row = null): BitArray
	{
		$this->source = $this->getLuminanceSource();
		$width = $this->source->getWidth();
		if ($row == null || $row->getSize() < $width) {
			$row = new BitArray($width);
		} else {
			$row->clear();
		}

		$this->initArrays($width);
		$localLuminances = $this->source->getRow($y, $this->luminances);
		$localBuckets = $this->buckets;
		for ($x = 0; $x < $width; $x++) {
			$pixel = $localLuminances[$x] & 0xff;
			$localBuckets[$pixel >> self::$LUMINANCE_SHIFT]++;
		}
		$blackPoint = self::estimateBlackPoint($localBuckets);

		$left = $localLuminances[0] & 0xff;
		$center = $localLuminances[1] & 0xff;
		for ($x = 1; $x < $width - 1; $x++) {
			$right = $localLuminances[$x + 1] & 0xff;
			// A simple -1 4 -1 box filter with a weight of 2.
			$luminance = (($center * 4) - $left - $right) / 2;
			if ($luminance < $blackPoint) {
				$row->set($x);
			}
			$left = $center;
			$center = $right;
		}

		return $row;
	}

	// Does not sharpen the data, as this call is intended to only be used by 2D Readers.
	private function initArrays(float $luminanceSize): void
	{
		if (count($this->luminances) < $luminanceSize) {
			$this->luminances = [];
		}
		for ($x = 0; $x < self::$LUMINANCE_BUCKETS; $x++) {
			$this->buckets[$x] = 0;
		}
	}

	private static function estimateBlackPoint(array $buckets): int
	{
		// Find the tallest peak in the histogram.
		$numBuckets = is_countable($buckets) ? count($buckets) : 0;
		$maxBucketCount = 0;
		$firstPeak = 0;
		$firstPeakSize = 0;
		for ($x = 0; $x < $numBuckets; $x++) {
			if ($buckets[$x] > $firstPeakSize) {
				$firstPeak = $x;
				$firstPeakSize = $buckets[$x];
			}
			if ($buckets[$x] > $maxBucketCount) {
				$maxBucketCount = $buckets[$x];
			}
		}

		// Find the second-tallest peak which is somewhat far from the tallest peak.
		$secondPeak = 0;
		$secondPeakScore = 0;
		for ($x = 0; $x < $numBuckets; $x++) {
			$distanceToBiggest = $x - $firstPeak;
			// Encourage more distant second peaks by multiplying by square of distance.
			$score = $buckets[$x] * $distanceToBiggest * $distanceToBiggest;
			if ($score > $secondPeakScore) {
				$secondPeak = $x;
				$secondPeakScore = $score;
			}
		}

		// Make sure firstPeak corresponds to the black peak.
		if ($firstPeak > $secondPeak) {
			$temp = $firstPeak;
			$firstPeak = $secondPeak;
			$secondPeak = $temp;
		}

		// If there is too little contrast in the image to pick a meaningful black point, throw rather
		// than waste time trying to decode the image, and risk false positives.
		if ($secondPeak - $firstPeak <= $numBuckets / 16) {
			throw new NotFoundException("too little contrast in the image to pick a meaningful black point");
		}

		// Find a valley between them that is low and closer to the white peak.
		$bestValley = $secondPeak - 1;
		$bestValleyScore = -1;
		for ($x = $secondPeak - 1; $x > $firstPeak; $x--) {
			$fromFirst = $x - $firstPeak;
			$score = $fromFirst * $fromFirst * ($secondPeak - $x) * ($maxBucketCount - $buckets[$x]);
			if ($score > $bestValleyScore) {
				$bestValley = $x;
				$bestValleyScore = $score;
			}
		}

		return $bestValley << self::$LUMINANCE_SHIFT;
	}

	public function getBlackMatrix()
	{
		$source = $this->getLuminanceSource();
		$width = $source->getWidth();
		$height = $source->getHeight();
		$matrix = new BitMatrix($width, $height);

		// Quickly calculates the histogram by sampling four rows from the image. This proved to be
		// more robust on the blackbox tests than sampling a diagonal as we used to do.
		$this->initArrays($width);
		$localBuckets = $this->buckets;
		for ($y = 1; $y < 5; $y++) {
			$row = (int)($height * $y / 5);
			$localLuminances = $source->getRow($row, $this->luminances);
			$right = (int)(($width * 4) / 5);
			for ($x = (int)($width / 5); $x < $right; $x++) {
				$pixel = ($localLuminances[(int)($x)] & 0xff);
				$localBuckets[($pixel >> self::$LUMINANCE_SHIFT)]++;
			}
		}
		$blackPoint = self::estimateBlackPoint($localBuckets);

		// We delay reading the entire image luminance until the black point estimation succeeds.
		// Although we end up reading four rows twice, it is consistent with our motto of
		// "fail quickly" which is necessary for continuous scanning.
		$localLuminances = $source->getMatrix();
		for ($y = 0; $y < $height; $y++) {
			$offset = $y * $width;
			for ($x = 0; $x < $width; $x++) {
				$pixel = (int)($localLuminances[$offset + $x] & 0xff);
				if ($pixel < $blackPoint) {
					$matrix->set($x, $y);
				}
			}
		}

		return $matrix;
	}

	public function createBinarizer($source): \Zxing\Common\GlobalHistogramBinarizer
	{
		return new GlobalHistogramBinarizer($source);
	}
}

GridSampler.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Common;

use Zxing\NotFoundException;

/**
 * Implementations of this class can, given locations of finder patterns for a QR code in an
 * image, sample the right points in the image to reconstruct the QR code, accounting for
 * perspective distortion. It is abstracted since it is relatively expensive and should be allowed
 * to take advantage of platform-specific optimized implementations, like Sun's Java Advanced
 * Imaging library, but which may not be available in other environments such as J2ME, and vice
 * versa.
 *
 * The implementation used can be controlled by calling {@link #setGridSampler(GridSampler)}
 * with an instance of a class which implements this interface.
 *
 * @author Sean Owen
 */
abstract class GridSampler
{
	/**
	 * @var GridSampler|null
	 */
	private static $gridSampler;

	/**
	 * Sets the implementation of GridSampler used by the library. One global
	 * instance is stored, which may sound problematic. But, the implementation provided
	 * ought to be appropriate for the entire platform, and all uses of this library
	 * in the whole lifetime of the JVM. For instance, an Android activity can swap in
	 * an implementation that takes advantage of native platform libraries.
	 *
	 * @param GridSampler $newGridSampler The platform-specific object to install.
	 */
	public static function setGridSampler($newGridSampler): void
	{
		self::$gridSampler = $newGridSampler;
	}

	/**
	 * @return GridSampler the current implementation of GridSampler
	 */
	public static function getInstance()
	{
		if (!self::$gridSampler) {
			self::$gridSampler = new DefaultGridSampler();
		}

		return self::$gridSampler;
	}

	/**
	 * <p>Checks a set of points that have been transformed to sample points on an image against
	 * the image's dimensions to see if the point are even within the image.</p>
	 *
	 * <p>This method will actually "nudge" the endpoints back onto the image if they are found to be
	 * barely (less than 1 pixel) off the image. This accounts for imperfect detection of finder
	 * patterns in an image where the QR Code runs all the way to the image border.</p>
	 *
	 * <p>For efficiency, the method will check points from either end of the line until one is found
	 * to be within the image. Because the set of points are assumed to be linear, this is valid.</p>
	 *
	 * @param BitMatrix $image  image into which the points should map
	 * @param array $points actual points in x1,y1,...,xn,yn form
	 * @param float[] $points
	 *
	 * @throws NotFoundException if an endpoint is lies outside the image boundaries
	 *
	 * @psalm-param array<int, float> $points
	 */
	protected static function checkAndNudgePoints(
		BitMatrix $image,
		array $points
	): void {
		$width = $image->getWidth();
		$height = $image->getHeight();
		// Check and nudge points from start until we see some that are OK:
		$nudged = true;
		for ($offset = 0; $offset < (is_countable($points) ? count($points) : 0) && $nudged; $offset += 2) {
			$x = (int)$points[$offset];
			$y = (int)$points[$offset + 1];
			if ($x < -1 || $x > $width || $y < -1 || $y > $height) {
				throw new NotFoundException("Endpoint ($x, $y) lies outside the image boundaries ($width, $height)");
			}
			$nudged = false;
			if ($x == -1) {
				$points[$offset] = 0.0;
				$nudged = true;
			} elseif ($x == $width) {
				$points[$offset] = $width - 1;
				$nudged = true;
			}
			if ($y == -1) {
				$points[$offset + 1] = 0.0;
				$nudged = true;
			} elseif ($y == $height) {
				$points[$offset + 1] = $height - 1;
				$nudged = true;
			}
		}
		// Check and nudge points from end:
		$nudged = true;
		for ($offset = (is_countable($points) ? count($points) : 0) - 2; $offset >= 0 && $nudged; $offset -= 2) {
			$x = (int)$points[$offset];
			$y = (int)$points[$offset + 1];
			if ($x < -1 || $x > $width || $y < -1 || $y > $height) {
				throw new NotFoundException("Endpoint ($x, $y) lies outside the image boundaries ($width, $height)");
			}
			$nudged = false;
			if ($x == -1) {
				$points[$offset] = 0.0;
				$nudged = true;
			} elseif ($x == $width) {
				$points[$offset] = $width - 1;
				$nudged = true;
			}
			if ($y == -1) {
				$points[$offset + 1] = 0.0;
				$nudged = true;
			} elseif ($y == $height) {
				$points[$offset + 1] = $height - 1;
				$nudged = true;
			}
		}
	}

	/**
	 * Samples an image for a rectangular matrix of bits of the given dimension. The sampling
	 * transformation is determined by the coordinates of 4 points, in the original and transformed
	 * image space.
	 *
	 * @param BitMatrix $image      image to sample
	 * @param int $dimensionX width of {@link BitMatrix} to sample from image
	 * @param int $dimensionY height of {@link BitMatrix} to sample from image
	 * @param float      $p1ToX point 1 preimage X
	 * @param float      $p1ToY point 1 preimage Y
	 * @param float      $p2ToX point 2 preimage X
	 * @param float      $p2ToY point 2 preimage Y
	 * @param float      $p3ToX point 3 preimage X
	 * @param float      $p3ToY point 3 preimage Y
	 * @param float      $p4ToX point 4 preimage X
	 * @param float      $p4ToY point 4 preimage Y
	 * @param float    $p1FromX point 1 image X
	 * @param float    $p1FromY point 1 image Y
	 * @param float    $p2FromX point 2 image X
	 * @param float    $p2FromY point 2 image Y
	 * @param float    $p3FromX point 3 image X
	 * @param float    $p3FromY point 3 image Y
	 * @param float    $p4FromX point 4 image X
	 * @param float    $p4FromY point 4 image Y
	 *
	 * @return {@link BitMatrix} representing a grid of points sampled from the image within a region
	 *   defined by the "from" parameters
	 * @throws NotFoundException if image can't be sampled, for example, if the transformation defined
	 *   by the given points is invalid or results in sampling outside the image boundaries
	 */
	abstract public function sampleGrid(
		$image,
		$dimensionX,
		$dimensionY,
		$p1ToX,
		$p1ToY,
		$p2ToX,
		$p2ToY,
		$p3ToX,
		$p3ToY,
		$p4ToX,
		$p4ToY,
		$p1FromX,
		$p1FromY,
		$p2FromX,
		$p2FromY,
		$p3FromX,
		$p3FromY,
		$p4FromX,
		$p4FromY
	);

	abstract public function sampleGrid_(
		BitMatrix $image,
		int $dimensionX,
		int $dimensionY,
		PerspectiveTransform $transform
	): BitMatrix;
}

HybridBinarizer.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Common;

use Zxing\Binarizer;

/**
 * This class implements a local thresholding algorithm, which while slower than the
 * GlobalHistogramBinarizer, is fairly efficient for what it does. It is designed for
 * high frequency images of barcodes with black data on white backgrounds. For this application,
 * it does a much better job than a global blackpoint with severe shadows and gradients.
 * However it tends to produce artifacts on lower frequency images and is therefore not
 * a good general purpose binarizer for uses outside ZXing.
 *
 * This class extends GlobalHistogramBinarizer, using the older histogram approach for 1D readers,
 * and the newer local approach for 2D readers. 1D decoding using a per-row histogram is already
 * inherently local, and only fails for horizontal gradients. We can revisit that problem later,
 * but for now it was not a win to use local blocks for 1D.
 *
 * This Binarizer is the default for the unit tests and the recommended class for library users.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 */
final class HybridBinarizer extends GlobalHistogramBinarizer
{
	// This class uses 5x5 blocks to compute local luminance, where each block is 8x8 pixels.
	// So this is the smallest dimension in each axis we can accept.
	private static int $BLOCK_SIZE_POWER = 3;
	private static int $BLOCK_SIZE = 8; // ...0100...00
	private static int $BLOCK_SIZE_MASK = 7;   // ...0011...11
	private static int $MINIMUM_DIMENSION = 40;
	private static int $MIN_DYNAMIC_RANGE = 24;

	private ?\Zxing\Common\BitMatrix $matrix = null;

	public function __construct($source)
	{
		parent::__construct($source);
		self::$BLOCK_SIZE_POWER = 3;
		self::$BLOCK_SIZE = 1 << self::$BLOCK_SIZE_POWER; // ...0100...00
		self::$BLOCK_SIZE_MASK = self::$BLOCK_SIZE - 1;   // ...0011...11
		self::$MINIMUM_DIMENSION = self::$BLOCK_SIZE * 5;
		self::$MIN_DYNAMIC_RANGE = 24;
	}

	/**
	 * Calculates the final BitMatrix once for all requests. This could be called once from the
	 * constructor instead, but there are some advantages to doing it lazily, such as making
	 * profiling easier, and not doing heavy lifting when callers don't expect it.
	 */
	public function getBlackMatrix()
	{
		if ($this->matrix !== null) {
			return $this->matrix;
		}
		$source = $this->getLuminanceSource();
		$width = $source->getWidth();
		$height = $source->getHeight();
		if ($width >= self::$MINIMUM_DIMENSION && $height >= self::$MINIMUM_DIMENSION) {
			$luminances = $source->getMatrix();
			$subWidth = $width >> self::$BLOCK_SIZE_POWER;
			if (($width & self::$BLOCK_SIZE_MASK) != 0) {
				$subWidth++;
			}
			$subHeight = $height >> self::$BLOCK_SIZE_POWER;
			if (($height & self::$BLOCK_SIZE_MASK) != 0) {
				$subHeight++;
			}
			$blackPoints = self::calculateBlackPoints($luminances, $subWidth, $subHeight, $width, $height);

			$newMatrix = new BitMatrix($width, $height);
			self::calculateThresholdForBlock($luminances, $subWidth, $subHeight, $width, $height, $blackPoints, $newMatrix);
			$this->matrix = $newMatrix;
		} else {
			// If the image is too small, fall back to the global histogram approach.
			$this->matrix = parent::getBlackMatrix();
		}

		return $this->matrix;
	}

	/**
	 * Calculates a single black point for each block of pixels and saves it away.
	 * See the following thread for a discussion of this algorithm:
	 *  http://groups.google.com/group/zxing/browse_thread/thread/d06efa2c35a7ddc0
	 *
	 * @return ((int|mixed)[]|mixed)[]
	 *
	 * @psalm-return array<int, array<int, int|mixed>|mixed>
	 */
	private static function calculateBlackPoints(
		array|BitMatrix $luminances,
		float $subWidth,
		float $subHeight,
		float $width,
		float $height
	): array {
		$blackPoints = fill_array(0, $subHeight, 0);
		foreach ($blackPoints as $key => $point) {
			$blackPoints[$key] = fill_array(0, $subWidth, 0);
		}
		for ($y = 0; $y < $subHeight; $y++) {
			$yoffset = ($y << self::$BLOCK_SIZE_POWER);
			$maxYOffset = $height - self::$BLOCK_SIZE;
			if ($yoffset > $maxYOffset) {
				$yoffset = $maxYOffset;
			}
			for ($x = 0; $x < $subWidth; $x++) {
				$xoffset = ($x << self::$BLOCK_SIZE_POWER);
				$maxXOffset = $width - self::$BLOCK_SIZE;
				if ($xoffset > $maxXOffset) {
					$xoffset = $maxXOffset;
				}
				$sum = 0;
				$min = 0xFF;
				$max = 0;
				for ($yy = 0, $offset = $yoffset * $width + $xoffset; $yy < self::$BLOCK_SIZE; $yy++, $offset += $width) {
					for ($xx = 0; $xx < self::$BLOCK_SIZE; $xx++) {
						$pixel = ((int)($luminances[(int)($offset + $xx)]) & 0xFF);
						$sum += $pixel;
						// still looking for good contrast
						if ($pixel < $min) {
							$min = $pixel;
						}
						if ($pixel > $max) {
							$max = $pixel;
						}
					}
					// short-circuit min/max tests once dynamic range is met
					if ($max - $min > self::$MIN_DYNAMIC_RANGE) {
						// finish the rest of the rows quickly
						for ($yy++, $offset += $width; $yy < self::$BLOCK_SIZE; $yy++, $offset += $width) {
							for ($xx = 0; $xx < self::$BLOCK_SIZE; $xx++) {
								$sum += (((int)$luminances[(int)round($offset + $xx)]) & 0xFF);
							}
						}
					}
				}

				// The default estimate is the average of the values in the block.
				$average = ($sum >> (self::$BLOCK_SIZE_POWER * 2));
				if ($max - $min <= self::$MIN_DYNAMIC_RANGE) {
					// If variation within the block is low, assume this is a block with only light or only
					// dark pixels. In that case we do not want to use the average, as it would divide this
					// low contrast area into black and white pixels, essentially creating data out of noise.
					//
					// The default assumption is that the block is light/background. Since no estimate for
					// the level of dark pixels exists locally, use half the min for the block.
					$average = (int)($min / 2);

					if ($y > 0 && $x > 0) {
						// Correct the "white background" assumption for blocks that have neighbors by comparing
						// the pixels in this block to the previously calculated black points. This is based on
						// the fact that dark barcode symbology is always surrounded by some amount of light
						// background for which reasonable black point estimates were made. The bp estimated at
						// the boundaries is used for the interior.

						// The (min < bp) is arbitrary but works better than other heuristics that were tried.
						$averageNeighborBlackPoint =
							(int)(($blackPoints[$y - 1][$x] + (2 * $blackPoints[$y][$x - 1]) + $blackPoints[$y - 1][$x - 1]) / 4);
						if ($min < $averageNeighborBlackPoint) {
							$average = $averageNeighborBlackPoint;
						}
					}
				}
				$blackPoints[$y][$x] = (int)($average);
			}
		}

		return $blackPoints;
	}

	/**
	 * For each block in the image, calculate the average black point using a 5x5 grid
	 * of the blocks around it. Also handles the corner cases (fractional blocks are computed based
	 * on the last pixels in the row/column which are also used in the previous block).
	 *
	 * @param ((int|mixed)[]|mixed)[] $blackPoints
	 *
	 * @psalm-param array<int, array<int, int|mixed>|mixed> $blackPoints
	 */
	private static function calculateThresholdForBlock(
		array|BitMatrix $luminances,
		float $subWidth,
		float $subHeight,
		float $width,
		float $height,
		array $blackPoints,
		BitMatrix $matrix
	): void {
		for ($y = 0; $y < $subHeight; $y++) {
			$yoffset = ($y << self::$BLOCK_SIZE_POWER);
			$maxYOffset = $height - self::$BLOCK_SIZE;
			if ($yoffset > $maxYOffset) {
				$yoffset = $maxYOffset;
			}
			for ($x = 0; $x < $subWidth; $x++) {
				$xoffset = ($x << self::$BLOCK_SIZE_POWER);
				$maxXOffset = $width - self::$BLOCK_SIZE;
				if ($xoffset > $maxXOffset) {
					$xoffset = $maxXOffset;
				}
				$left = self::cap($x, 2, $subWidth - 3);
				$top = self::cap($y, 2, $subHeight - 3);
				$sum = 0;
				for ($z = -2; $z <= 2; $z++) {
					$blackRow = $blackPoints[$top + $z];
					$sum += $blackRow[$left - 2] + $blackRow[$left - 1] + $blackRow[$left] + $blackRow[$left + 1] + $blackRow[$left + 2];
				}
				$average = (int)($sum / 25);

				self::thresholdBlock($luminances, $xoffset, $yoffset, $average, $width, $matrix);
			}
		}
	}

	/**
	 * @psalm-param 0|positive-int $value
	 * @psalm-param 2 $min
	 *
	 * @return float|int
	 *
	 * @psalm-return float|int<2, max>
	 */
	private static function cap(int $value, int $min, float $max): int|float
	{
		if ($value < $min) {
			return $min;
		} elseif ($value > $max) {
			return $max;
		} else {
			return $value;
		}
	}

	/**
	 * Applies a single threshold to a block of pixels.
	 *
	 * @param BitMatrix|array $luminances
	 * @param float|int $xoffset
	 * @param float|int $yoffset
	 */
	private static function thresholdBlock(
		array|BitMatrix $luminances,
		int|float $xoffset,
		int|float $yoffset,
		int $threshold,
		float $stride,
		BitMatrix $matrix
	): void {
		for ($y = 0, $offset = $yoffset * $stride + $xoffset; $y < self::$BLOCK_SIZE; $y++, $offset += $stride) {
			for ($x = 0; $x < self::$BLOCK_SIZE; $x++) {
				// Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0.
				if ((((int)$luminances[(int)round($offset + $x)]) & 0xFF) <= $threshold) {
					$matrix->set($xoffset + $x, $yoffset + $y);
				}
			}
		}
	}

	public function createBinarizer($source): \Zxing\Common\HybridBinarizer
	{
		return new HybridBinarizer($source);
	}
}

PerspectiveTransform.php
Formulario de entrada de datos.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Common;

/**
 * <p>This class implements a perspective transform in two dimensions. Given four source and four
 * destination points, it will compute the transformation implied between them. The code is based
 * directly upon section 3.4.2 of George Wolberg's "Digital Image Warping"; see pages 54-56.</p>
 *
 * @author Sean Owen
 */
final class PerspectiveTransform
{
	private function __construct(private $a11, private $a21, private $a31, private $a12, private $a22, private $a32, private $a13, private $a23, private $a33)
	{
	}

	public static function quadrilateralToQuadrilateral(
		float $x0,
		float $y0,
		float $x1,
		float $y1,
		float $x2,
		float $y2,
		float $x3,
		float $y3,
		float $x0p,
		float $y0p,
		float $x1p,
		float $y1p,
		float $x2p,
		float $y2p,
		float $x3p,
		float $y3p
	): self {
		$qToS = self::quadrilateralToSquare($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3);
		$sToQ = self::squareToQuadrilateral($x0p, $y0p, $x1p, $y1p, $x2p, $y2p, $x3p, $y3p);

		return $sToQ->times($qToS);
	}

	public static function quadrilateralToSquare(
		float $x0,
		float $y0,
		float $x1,
		float $y1,
		float $x2,
		float $y2,
		float $x3,
		float $y3
	): self {
		// Here, the adjoint serves as the inverse:
		return self::squareToQuadrilateral($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3)->buildAdjoint();
	}

	public function buildAdjoint(): \Zxing\Common\PerspectiveTransform
	{
		// Adjoint is the transpose of the cofactor matrix:
		return new PerspectiveTransform(
			$this->a22 * $this->a33 - $this->a23 * $this->a32,
			$this->a23 * $this->a31 - $this->a21 * $this->a33,
			$this->a21 * $this->a32 - $this->a22 * $this->a31,
			$this->a13 * $this->a32 - $this->a12 * $this->a33,
			$this->a11 * $this->a33 - $this->a13 * $this->a31,
			$this->a12 * $this->a31 - $this->a11 * $this->a32,
			$this->a12 * $this->a23 - $this->a13 * $this->a22,
			$this->a13 * $this->a21 - $this->a11 * $this->a23,
			$this->a11 * $this->a22 - $this->a12 * $this->a21
		);
	}

	public static function squareToQuadrilateral(
		float $x0,
		float $y0,
		float $x1,
		float $y1,
		float $x2,
		float $y2,
		float $x3,
		float $y3
	): \Zxing\Common\PerspectiveTransform {
		$dx3 = $x0 - $x1 + $x2 - $x3;
		$dy3 = $y0 - $y1 + $y2 - $y3;
		if ($dx3 == 0.0 && $dy3 == 0.0) {
			// Affine
			return new PerspectiveTransform(
				$x1 - $x0,
				$x2 - $x1,
				$x0,
				$y1 - $y0,
				$y2 - $y1,
				$y0,
				0.0,
				0.0,
				1.0
			);
		} else {
			$dx1 = $x1 - $x2;
			$dx2 = $x3 - $x2;
			$dy1 = $y1 - $y2;
			$dy2 = $y3 - $y2;
			$denominator = $dx1 * $dy2 - $dx2 * $dy1;
			$a13 = ($dx3 * $dy2 - $dx2 * $dy3) / $denominator;
			$a23 = ($dx1 * $dy3 - $dx3 * $dy1) / $denominator;

			return new PerspectiveTransform(
				$x1 - $x0 + $a13 * $x1,
				$x3 - $x0 + $a23 * $x3,
				$x0,
				$y1 - $y0 + $a13 * $y1,
				$y3 - $y0 + $a23 * $y3,
				$y0,
				$a13,
				$a23,
				1.0
			);
		}
	}

	public function times(self $other): \Zxing\Common\PerspectiveTransform
	{
		return new PerspectiveTransform(
			$this->a11 * $other->a11 + $this->a21 * $other->a12 + $this->a31 * $other->a13,
			$this->a11 * $other->a21 + $this->a21 * $other->a22 + $this->a31 * $other->a23,
			$this->a11 * $other->a31 + $this->a21 * $other->a32 + $this->a31 * $other->a33,
			$this->a12 * $other->a11 + $this->a22 * $other->a12 + $this->a32 * $other->a13,
			$this->a12 * $other->a21 + $this->a22 * $other->a22 + $this->a32 * $other->a23,
			$this->a12 * $other->a31 + $this->a22 * $other->a32 + $this->a32 * $other->a33,
			$this->a13 * $other->a11 + $this->a23 * $other->a12 + $this->a33 * $other->a13,
			$this->a13 * $other->a21 + $this->a23 * $other->a22 + $this->a33 * $other->a23,
			$this->a13 * $other->a31 + $this->a23 * $other->a32 + $this->a33 * $other->a33
		);
	}

	/**
	 * @param (float|mixed)[] $points
	 *
	 * @psalm-param array<int, float|mixed> $points
	 */
	public function transformPoints(array &$points, &$yValues = 0): void
	{
		if ($yValues) {
			$this->transformPoints_($points, $yValues);

			return;
		}
		$max = is_countable($points) ? count($points) : 0;
		$a11 = $this->a11;
		$a12 = $this->a12;
		$a13 = $this->a13;
		$a21 = $this->a21;
		$a22 = $this->a22;
		$a23 = $this->a23;
		$a31 = $this->a31;
		$a32 = $this->a32;
		$a33 = $this->a33;
		for ($i = 0; $i < $max; $i += 2) {
			$x = $points[$i];
			$y = $points[$i + 1];
			$denominator = $a13 * $x + $a23 * $y + $a33;
			// TODO: think what we do if $denominator == 0 (division by zero)
			if ($denominator != 0.0) {
				$points[$i] = ($a11 * $x + $a21 * $y + $a31) / $denominator;
				$points[$i + 1] = ($a12 * $x + $a22 * $y + $a32) / $denominator;
			}
		}
	}

	/**
	 * @param (float|mixed)[] $xValues
	 *
	 * @psalm-param array<int, float|mixed> $xValues
	 */
	public function transformPoints_(array &$xValues, &$yValues): void
	{
		$n = is_countable($xValues) ? count($xValues) : 0;
		for ($i = 0; $i < $n; $i++) {
			$x = $xValues[$i];
			$y = $yValues[$i];
			$denominator = $this->a13 * $x + $this->a23 * $y + $this->a33;
			$xValues[$i] = ($this->a11 * $x + $this->a21 * $y + $this->a31) / $denominator;
			$yValues[$i] = ($this->a12 * $x + $this->a22 * $y + $this->a32) / $denominator;
		}
	}
}

customFunctions.php
Script de practica.
Abrir
Ver codigo

<?php

if (!function_exists('arraycopy')) {
	function arraycopy($srcArray, $srcPos, $destArray, $destPos, $length): array
	{
		$srcArrayToCopy = array_slice($srcArray, $srcPos, $length);
		array_splice($destArray, $destPos, $length, $srcArrayToCopy);

		return $destArray;
	}
}

if (!function_exists('hashCode')) {
	function hashCode($s): int
	{
		$h = 0;
		$len = strlen((string) $s);
		for ($i = 0; $i < $len; $i++) {
			$h = (31 * $h + ord($s[$i]));
		}

		return $h;
	}
}

if (!function_exists('numberOfTrailingZeros')) {
	/**
	 * @psalm-return 0|32|positive-int
	 */
	function numberOfTrailingZeros($i): int
	{
		if ($i == 0) {
			return 32;
		}
		$num = 0;
		while (($i & 1) == 0) {
			$i >>= 1;
			$num++;
		}

		return $num;
	}
}

if (!function_exists('uRShift')) {
	function uRShift($a, $b)
	{
		static $mask = (8 * PHP_INT_SIZE - 1);
		if ($b === 0) {
			return $a;
		}

		return ($a >> $b) & ~(1 << $mask >> ($b - 1));
	}
}

/*
function sdvig3($num,$count=1){//>>> 32 bit
	$s = decbin($num);

	$sarray  = str_split($s,1);
	$sarray = array_slice($sarray,-32);//32bit

	for($i=0;$i<=1;$i++) {
		array_pop($sarray);
		array_unshift($sarray, '0');
	}
	return bindec(implode($sarray));
}
*/

if (!function_exists('sdvig3')) {
	function sdvig3($a, $b): float|int
	{
		if ($a >= 0) {
			return bindec(decbin($a >> $b)); //simply right shift for positive number
		}

		$bin = decbin($a >> $b);

		$bin = substr($bin, $b); // zero fill on the left side

		return bindec($bin);
	}
}

if (!function_exists('floatToIntBits')) {
	function floatToIntBits($float_val)
	{
		$int = unpack('i', pack('f', $float_val));

		return $int[1];
	}
}


if (!function_exists('fill_array')) {
	/**
	 * @psalm-return array<int, mixed>
	 */
	function fill_array($index, $count, $value): array
	{
		if ($count <= 0) {
			return [0];
		}

		return array_fill($index, $count, $value);
	}
}

GenericGF.php
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Common\Reedsolomon;

/**
 * <p>This class contains utility methods for performing mathematical operations over
 * the Galois Fields. Operations use a given primitive polynomial in calculations.</p>
 *
 * <p>Throughout this package, elements of the GF are represented as an {@code int}
 * for convenience and speed (but at the cost of memory).
 * </p>
 *
 * @author Sean Owen
 * @author David Olivier
 */
final class GenericGF
{
	public static $AZTEC_DATA_12;
	public static $AZTEC_DATA_10;
	public static $AZTEC_DATA_6;
	public static $AZTEC_PARAM;
	public static $QR_CODE_FIELD_256;
	public static $DATA_MATRIX_FIELD_256;
	public static $AZTEC_DATA_8;
	public static $MAXICODE_FIELD_64;

	private array $expTable = [];
	private array $logTable = [];
	private readonly \Zxing\Common\Reedsolomon\GenericGFPoly $zero;
	private readonly \Zxing\Common\Reedsolomon\GenericGFPoly $one;

	/**
 * Create a representation of GF(size) using the given primitive polynomial.
 *
 * @param int $primitive irreducible polynomial whose coefficients are represented by
 *                  the bits of an int, where the least-significant bit represents the constant
 *                  coefficient
 * @param int $size      the size of the field
  * @param int $generatorBase the factor b in the generator polynomial can be 0- or 1-based
				  (g(x) = (x+a^b)(x+a^(b+1))...(x+a^(b+2t-1))).
				  In most cases it should be 1, but for QR code it is 0.
 */
	public function __construct(private $primitive, private $size, private $generatorBase)
	{
		$x = 1;
		for ($i = 0; $i < $size; $i++) {
			$this->expTable[$i] = $x;
			$x *= 2; // we're assuming the generator alpha is 2
			if ($x >= $size) {
				$x ^= $primitive;
				$x &= $size - 1;
			}
		}
		for ($i = 0; $i < $size - 1; $i++) {
			$this->logTable[$this->expTable[$i]] = $i;
		}
		// logTable[0] == 0 but this should never be used
		$this->zero = new GenericGFPoly($this, [0]);
		$this->one = new GenericGFPoly($this, [1]);
	}

	public static function Init(): void
	{
		self::$AZTEC_DATA_12 = new GenericGF(0x1069, 4096, 1); // x^12 + x^6 + x^5 + x^3 + 1
		self::$AZTEC_DATA_10 = new GenericGF(0x409, 1024, 1); // x^10 + x^3 + 1
		self::$AZTEC_DATA_6 = new GenericGF(0x43, 64, 1); // x^6 + x + 1
		self::$AZTEC_PARAM = new GenericGF(0x13, 16, 1); // x^4 + x + 1
		self::$QR_CODE_FIELD_256 = new GenericGF(0x011D, 256, 0); // x^8 + x^4 + x^3 + x^2 + 1
		self::$DATA_MATRIX_FIELD_256 = new GenericGF(0x012D, 256, 1); // x^8 + x^5 + x^3 + x^2 + 1
		self::$AZTEC_DATA_8 = self::$DATA_MATRIX_FIELD_256;
		self::$MAXICODE_FIELD_64 = self::$AZTEC_DATA_6;
	}

	/**
	 * Implements both addition and subtraction -- they are the same in GF(size).
	 *
	 * @return float|int sum/difference of a and b
	 *
	 * @param float|int|null $b
	 */
	public static function addOrSubtract(int $a, int|float|null $b)
	{
		return $a ^ $b;
	}

	public function getZero(): GenericGFPoly
	{
		return $this->zero;
	}

	public function getOne(): GenericGFPoly
	{
		return $this->one;
	}

	/**
	 * @return GenericGFPoly  the monomial representing coefficient * x^degree
	 */
	public function buildMonomial($degree, int $coefficient)
	{
		if ($degree < 0) {
			throw new \InvalidArgumentException();
		}
		if ($coefficient == 0) {
			return $this->zero;
		}
		$coefficients = fill_array(0, $degree + 1, 0);//new int[degree + 1];
		$coefficients[0] = $coefficient;

		return new GenericGFPoly($this, $coefficients);
	}

	/**
	 * @return 2 to the power of a in GF(size)
	 */
	public function exp($a)
	{
		return $this->expTable[$a];
	}

	/**
	 * @return float base 2 log of a in GF(size)
	 */
	public function log(float|int|null $a)
	{
		if ($a == 0) {
			throw new \InvalidArgumentException();
		}

		return $this->logTable[$a];
	}

	/**
	 * @return float multiplicative inverse of a
	 */
	public function inverse($a)
	{
		if ($a == 0) {
			throw new \Exception();
		}

		return $this->expTable[$this->size - $this->logTable[$a] - 1];
	}

	/**
	 * @return int product of a and b in GF(size)
	 *
	 * @param float|int|null $b
	 * @param float|int|null $a
	 */
	public function multiply(int|float|null $a, int|float|null $b)
	{
		if ($a == 0 || $b == 0) {
			return 0;
		}

		return $this->expTable[($this->logTable[$a] + $this->logTable[$b]) % ($this->size - 1)];
	}

	public function getSize()
	{
		return $this->size;
	}

	public function getGeneratorBase()
	{
		return $this->generatorBase;
	}

	// @Override
	public function toString(): string
	{
		return "GF(0x" . dechex((int)($this->primitive)) . ',' . $this->size . ')';
	}
}

GenericGF::Init();

GenericGFPoly.php
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Common\Reedsolomon;

/**
 * <p>Represents a polynomial whose coefficients are elements of a GF.
 * Instances of this class are immutable.</p>
 *
 * <p>Much credit is due to William Rucklidge since portions of this code are an indirect
 * port of his C++ Reed-Solomon implementation.</p>
 *
 * @author Sean Owen
 */
final class GenericGFPoly
{
	/**
  * @var int[]|float[]|null
  */
	private $coefficients;

	/**
	 * @param GenericGF $field {@link GenericGF} the        instance representing the field to use
	 * to perform computations
	 * @param array $coefficients coefficients as ints representing elements of GF(size), arranged
	 *                     from most significant (highest-power term) coefficient to least significant
	 *
	 * @throws \InvalidArgumentException if argument is null or empty,
	 * or if leading coefficient is 0 and this is not a
	 * constant polynomial (that is, it is not the monomial "0")
	 */
	public function __construct(private $field, $coefficients)
	{
		if (count($coefficients) == 0) {
			throw new \InvalidArgumentException();
		}
		$coefficientsLength = count($coefficients);
		if ($coefficientsLength > 1 && $coefficients[0] == 0) {
			// Leading term must be non-zero for anything except the constant polynomial "0"
			$firstNonZero = 1;
			while ($firstNonZero < $coefficientsLength && $coefficients[$firstNonZero] == 0) {
				$firstNonZero++;
			}
			if ($firstNonZero == $coefficientsLength) {
				$this->coefficients = [0];
			} else {
				$this->coefficients = fill_array(0, $coefficientsLength - $firstNonZero, 0);
				$this->coefficients = arraycopy(
					$coefficients,
					$firstNonZero,
					$this->coefficients,
					0,
					is_countable($this->coefficients) ? count($this->coefficients) : 0
				);
			}
		} else {
			$this->coefficients = $coefficients;
		}
	}

	/**
	 * @return (float|int)[]|null
	 *
	 * @psalm-return array<float|int>|null
	 */
	public function getCoefficients(): array|null
	{
		return $this->coefficients;
	}

	/**
	 * @return float|int|null evaluation of this polynomial at a given point
	 */
	public function evaluateAt($a): int|float|null
	{
		if ($a == 0) {
			// Just return the x^0 coefficient
			return $this->getCoefficient(0);
		}
		$size = is_countable($this->coefficients) ? count($this->coefficients) : 0;
		if ($a == 1) {
			// Just the sum of the coefficients
			$result = 0;
			foreach ($this->coefficients as $coefficient) {
				$result = GenericGF::addOrSubtract($result, $coefficient);
			}

			return $result;
		}
		$result = $this->coefficients[0];
		for ($i = 1; $i < $size; $i++) {
			$result = GenericGF::addOrSubtract($this->field->multiply($a, $result), $this->coefficients[$i]);
		}

		return $result;
	}

	/**
	 * @return float|int|null coefficient of x^degree term in this polynomial
	 *
	 * @param float|int $degree
	 */
	public function getCoefficient(int|float $degree): int|float|null
	{
		return $this->coefficients[(is_countable($this->coefficients) ? count($this->coefficients) : 0) - 1 - $degree];
	}

	public function multiply($other): self
	{
		$aCoefficients = [];
		$bCoefficients = [];
		$aLength = null;
		$bLength = null;
		$product = [];
		if (is_int($other)) {
			return $this->multiply_($other);
		}
		if ($this->field !== $other->field) {
			throw new \InvalidArgumentException("GenericGFPolys do not have same GenericGF field");
		}
		if ($this->isZero() || $other->isZero()) {
			return $this->field->getZero();
		}
		$aCoefficients = $this->coefficients;
		$aLength = count($aCoefficients);
		$bCoefficients = $other->coefficients;
		$bLength = count($bCoefficients);
		$product = fill_array(0, $aLength + $bLength - 1, 0);
		for ($i = 0; $i < $aLength; $i++) {
			$aCoeff = $aCoefficients[$i];
			for ($j = 0; $j < $bLength; $j++) {
				$product[$i + $j] = GenericGF::addOrSubtract(
					$product[$i + $j],
					$this->field->multiply($aCoeff, $bCoefficients[$j])
				);
			}
		}

		return new GenericGFPoly($this->field, $product);
	}

	public function multiply_(int $scalar): self
	{
		if ($scalar == 0) {
			return $this->field->getZero();
		}
		if ($scalar == 1) {
			return $this;
		}
		$size = is_countable($this->coefficients) ? count($this->coefficients) : 0;
		$product = fill_array(0, $size, 0);
		for ($i = 0; $i < $size; $i++) {
			$product[$i] = $this->field->multiply($this->coefficients[$i], $scalar);
		}

		return new GenericGFPoly($this->field, $product);
	}

	/**
	 * @return bool iff this polynomial is the monomial "0"
	 */
	public function isZero(): bool
	{
		return $this->coefficients[0] == 0;
	}

	public function multiplyByMonomial($degree, $coefficient): self
	{
		if ($degree < 0) {
			throw new \InvalidArgumentException();
		}
		if ($coefficient == 0) {
			return $this->field->getZero();
		}
		$size = is_countable($this->coefficients) ? count($this->coefficients) : 0;
		$product = fill_array(0, $size + $degree, 0);
		for ($i = 0; $i < $size; $i++) {
			$product[$i] = $this->field->multiply($this->coefficients[$i], $coefficient);
		}

		return new GenericGFPoly($this->field, $product);
	}

	/**
	 * @psalm-return array{0: mixed, 1: mixed}
	 */
	public function divide($other): array
	{
		if ($this->field !== $other->field) {
			throw new \InvalidArgumentException("GenericGFPolys do not have same GenericGF field");
		}
		if ($other->isZero()) {
			throw new \InvalidArgumentException("Divide by 0");
		}

		$quotient = $this->field->getZero();
		$remainder = $this;

		$denominatorLeadingTerm = $other->getCoefficient($other->getDegree());
		$inverseDenominatorLeadingTerm = $this->field->inverse($denominatorLeadingTerm);

		while ($remainder->getDegree() >= $other->getDegree() && !$remainder->isZero()) {
			$degreeDifference = $remainder->getDegree() - $other->getDegree();
			$scale = $this->field->multiply($remainder->getCoefficient($remainder->getDegree()), $inverseDenominatorLeadingTerm);
			$term = $other->multiplyByMonomial($degreeDifference, $scale);
			$iterationQuotient = $this->field->buildMonomial($degreeDifference, $scale);
			$quotient = $quotient->addOrSubtract($iterationQuotient);
			$remainder = $remainder->addOrSubtract($term);
		}

		return [$quotient, $remainder];
	}

	/**
	 * @return int of this polynomial
	 */
	public function getDegree(): int
	{
		return (is_countable($this->coefficients) ? count($this->coefficients) : 0) - 1;
	}

	public function addOrSubtract(self $other): self
	{
		$smallerCoefficients = [];
		$largerCoefficients = [];
		$sumDiff = [];
		$lengthDiff = null;
		$countLargerCoefficients = null;
		if ($this->field !== $other->field) {
			throw new \InvalidArgumentException("GenericGFPolys do not have same GenericGF field");
		}
		if ($this->isZero()) {
			return $other;
		}
		if ($other->isZero()) {
			return $this;
		}

		$smallerCoefficients = $this->coefficients;
		$largerCoefficients = $other->coefficients;
		if (count($smallerCoefficients) > count($largerCoefficients)) {
			$temp = $smallerCoefficients;
			$smallerCoefficients = $largerCoefficients;
			$largerCoefficients = $temp;
		}
		$sumDiff = fill_array(0, count($largerCoefficients), 0);
		$lengthDiff = count($largerCoefficients) - count($smallerCoefficients);
		// Copy high-order terms only found in higher-degree polynomial's coefficients
		$sumDiff = arraycopy($largerCoefficients, 0, $sumDiff, 0, $lengthDiff);

		$countLargerCoefficients = count($largerCoefficients);
		for ($i = $lengthDiff; $i < $countLargerCoefficients; $i++) {
			$sumDiff[$i] = GenericGF::addOrSubtract($smallerCoefficients[$i - $lengthDiff], $largerCoefficients[$i]);
		}

		return new GenericGFPoly($this->field, $sumDiff);
	}

	

	public function toString(): string
	{
		$result = '';
		for ($degree = $this->getDegree(); $degree >= 0; $degree--) {
			$coefficient = $this->getCoefficient($degree);
			if ($coefficient != 0) {
				if ($coefficient < 0) {
					$result .= " - ";
					$coefficient = -$coefficient;
				} else {
					if (strlen((string) $result) > 0) {
						$result .= " + ";
					}
				}
				if ($degree == 0 || $coefficient != 1) {
					$alphaPower = $this->field->log($coefficient);
					if ($alphaPower == 0) {
						$result .= '1';
					} elseif ($alphaPower == 1) {
						$result .= 'a';
					} else {
						$result .= "a^";
						$result .= ($alphaPower);
					}
				}
				if ($degree != 0) {
					if ($degree == 1) {
						$result .= 'x';
					} else {
						$result .= "x^";
						$result .= $degree;
					}
				}
			}
		}

		return $result;
	}
}

ReedSolomonDecoder.php
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Common\Reedsolomon;

/**
 * <p>Implements Reed-Solomon decoding, as the name implies.</p>
 *
 * <p>The algorithm will not be explained here, but the following references were helpful
 * in creating this implementation:</p>
 *
 * <ul>
 * <li>Bruce Maggs.
 * <a href="http://www.cs.cmu.edu/afs/cs.cmu.edu/project/pscico-guyb/realworld/www/rs_decode.ps">
 * "Decoding Reed-Solomon Codes"</a> (see discussion of Forney's Formula)</li>
 * <li>J.I. Hall. <a href="www.mth.msu.edu/~jhall/classes/codenotes/GRS.pdf">
 * "Chapter 5. Generalized Reed-Solomon Codes"</a>
 * (see discussion of Euclidean algorithm)</li>
 * </ul>
 *
 * <p>Much credit is due to William Rucklidge since portions of this code are an indirect
 * port of his C++ Reed-Solomon implementation.</p>
 *
 * @author Sean Owen
 * @author William Rucklidge
 * @author sanfordsquires
 */
final class ReedSolomonDecoder
{
	public function __construct(private $field)
	{
	}

	/**
	 * <p>Decodes given set of received codewords, which include both data and error-correction
	 * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
	 * in the input.</p>
	 *
	 * @param array $received data and error-correction codewords
	 * @param int|float $twoS number     of error-correction codewords available
	 *
	 * @throws ReedSolomonException if decoding fails for any reason
	 *
	 * @return void
	 */
	public function decode(&$received, $twoS)
	{
		$poly = new GenericGFPoly($this->field, $received);
		$syndromeCoefficients = fill_array(0, $twoS, 0);
		$noError = true;
		for ($i = 0; $i < $twoS; $i++) {
			$eval = $poly->evaluateAt($this->field->exp($i + $this->field->getGeneratorBase()));
			$syndromeCoefficients[(is_countable($syndromeCoefficients) ? count($syndromeCoefficients) : 0) - 1 - $i] = $eval;
			if ($eval != 0) {
				$noError = false;
			}
		}
		if ($noError) {
			return;
		}
		$syndrome = new GenericGFPoly($this->field, $syndromeCoefficients);
		$sigmaOmega =
			$this->runEuclideanAlgorithm($this->field->buildMonomial($twoS, 1), $syndrome, $twoS);
		$sigma = $sigmaOmega[0];
		$omega = $sigmaOmega[1];
		$errorLocations = $this->findErrorLocations($sigma);
		$errorMagnitudes = $this->findErrorMagnitudes($omega, $errorLocations);
		$errorLocationsCount = is_countable($errorLocations) ? count($errorLocations) : 0;
		for ($i = 0; $i < $errorLocationsCount; $i++) {
			$position = (is_countable($received) ? count($received) : 0) - 1 - $this->field->log($errorLocations[$i]);
			if ($position < 0) {
				throw new ReedSolomonException("Bad error location");
			}
			$received[$position] = GenericGF::addOrSubtract($received[$position], $errorMagnitudes[$i]);
		}
	}

	/**
	 * @psalm-return array{0: mixed, 1: mixed}
	 */
	private function runEuclideanAlgorithm($a, \Zxing\Common\Reedsolomon\GenericGFPoly $b, int|float $R): array
	{
		// Assume a's degree is >= b's
		if ($a->getDegree() < $b->getDegree()) {
			$temp = $a;
			$a = $b;
			$b = $temp;
		}

		$rLast = $a;
		$r = $b;
		$tLast = $this->field->getZero();
		$t = $this->field->getOne();

		// Run Euclidean algorithm until r's degree is less than R/2
		while ($r->getDegree() >= $R / 2) {
			$rLastLast = $rLast;
			$tLastLast = $tLast;
			$rLast = $r;
			$tLast = $t;

			// Divide rLastLast by rLast, with quotient in q and remainder in r
			if ($rLast->isZero()) {
				// Oops, Euclidean algorithm already terminated?
				throw new ReedSolomonException("r_{i-1} was zero");
			}
			$r = $rLastLast;
			$q = $this->field->getZero();
			$denominatorLeadingTerm = $rLast->getCoefficient($rLast->getDegree());
			$dltInverse = $this->field->inverse($denominatorLeadingTerm);
			while ($r->getDegree() >= $rLast->getDegree() && !$r->isZero()) {
				$degreeDiff = $r->getDegree() - $rLast->getDegree();
				$scale = $this->field->multiply($r->getCoefficient($r->getDegree()), $dltInverse);
				$q = $q->addOrSubtract($this->field->buildMonomial($degreeDiff, $scale));
				$r = $r->addOrSubtract($rLast->multiplyByMonomial($degreeDiff, $scale));
			}

			$t = $q->multiply($tLast)->addOrSubtract($tLastLast);

			if ($r->getDegree() >= $rLast->getDegree()) {
				throw new ReedSolomonException("Division algorithm failed to reduce polynomial?");
			}
		}

		$sigmaTildeAtZero = $t->getCoefficient(0);
		if ($sigmaTildeAtZero == 0) {
			throw new ReedSolomonException("sigmaTilde(0) was zero");
		}

		$inverse = $this->field->inverse($sigmaTildeAtZero);
		$sigma = $t->multiply($inverse);
		$omega = $r->multiply($inverse);

		return [$sigma, $omega];
	}

	/**
	 * @psalm-return array<int, mixed>
	 */
	private function findErrorLocations($errorLocator): array
	{
		// This is a direct application of Chien's search
		$numErrors = $errorLocator->getDegree();
		if ($numErrors == 1) { // shortcut
			return [$errorLocator->getCoefficient(1)];
		}
		$result = fill_array(0, $numErrors, 0);
		$e = 0;
		for ($i = 1; $i < $this->field->getSize() && $e < $numErrors; $i++) {
			if ($errorLocator->evaluateAt($i) == 0) {
				$result[$e] = $this->field->inverse($i);
				$e++;
			}
		}
		if ($e != $numErrors) {
			throw new ReedSolomonException("Error locator degree does not match number of roots");
		}

		return $result;
	}

	/**
	 * @psalm-return array<int, mixed>
	 * @psalm-param array<int, mixed> $errorLocations
	 */
	private function findErrorMagnitudes($errorEvaluator, array $errorLocations): array
	{
		// This is directly applying Forney's Formula
		$s = is_countable($errorLocations) ? count($errorLocations) : 0;
		$result = fill_array(0, $s, 0);
		for ($i = 0; $i < $s; $i++) {
			$xiInverse = $this->field->inverse($errorLocations[$i]);
			$denominator = 1;
			for ($j = 0; $j < $s; $j++) {
				if ($i != $j) {
					//denominator = field.multiply(denominator,
					//    GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)));
					// Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
					// Below is a funny-looking workaround from Steven Parkes
					$term = $this->field->multiply($errorLocations[$j], $xiInverse);
					$termPlus1 = ($term & 0x1) == 0 ? $term | 1 : $term & ~1;
					$denominator = $this->field->multiply($denominator, $termPlus1);
				}
			}
			$result[$i] = $this->field->multiply(
				$errorEvaluator->evaluateAt($xiInverse),
				$this->field->inverse($denominator)
			);
			if ($this->field->getGeneratorBase() != 0) {
				$result[$i] = $this->field->multiply($result[$i], $xiInverse);
			}
		}

		return $result;
	}
}

ReedSolomonException.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Common\Reedsolomon;

/**
 * <p>Thrown when an exception occurs during Reed-Solomon decoding, such as when
 * there are too many errors to correct.</p>
 *
 * @author Sean Owen
 */
final class ReedSolomonException extends \Exception
{
}

MathUtils.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2012 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Common\Detector;

final class MathUtils
{
	private function __construct()
	{
	}

	/**
	 * Ends up being a bit faster than {@link Math#round(float)}. This merely rounds its
	 * argument to the nearest int, where x.5 rounds up to x+1. Semantics of this shortcut
	 * differ slightly from {@link Math#round(float)} in that half rounds down for negative
	 * values. -2.5 rounds to -3, not -2. For purposes here it makes no difference.
	 *
	 * @param float $d real value to round
	 *
	 * @return int {@code int}
	 */
	public static function round(float $d)
	{
		return (int)($d + ($d < 0.0 ? -0.5 : 0.5));
	}

	public static function distance(float|int $aX, float|int $aY, float $bX, float $bY): float
	{
		$xDiff = $aX - $bX;
		$yDiff = $aY - $bY;

		return (float)sqrt($xDiff * $xDiff + $yDiff * $yDiff);
	}
}

MonochromeRectangleDetector.php
Script de practica.
Abrir
Ver codigo

<?php
/**
 * Created by PhpStorm.
 * User: Ashot
 * Date: 3/24/15
 * Time: 21:23
 */

namespace Zxing\Common\Detector;

use Zxing\BinaryBitmap;
use Zxing\NotFoundException;
use Zxing\ResultPoint;

/*
 *
 *
import com.google.zxing.NotFoundException;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.BitMatrix;

 */
//require_once('./lib/NotFoundException.php');
//require_once('./lib/ResultPoint.php');
//require_once('./lib/common/BitMatrix.php');


/**
 * <p>A somewhat generic detector that looks for a barcode-like rectangular region within an image.
 * It looks within a mostly white region of an image for a region of black and white, but mostly
 * black. It returns the four corners of the region, as best it can determine.</p>
 *
 * @author Sean Owen
 * @port   Ashot Khanamiryan
 */
class MonochromeRectangleDetector
{
	private static int $MAX_MODULES = 32;

	public function __construct(private readonly BinaryBitmap $image)
	{
	}

	/**
	 * <p>Detects a rectangular region of black and white -- mostly black -- with a region of mostly
	 * white, in an image.</p>
	 *
	 * @return {@link ResultPoint}[] describing the corners of the rectangular region. The first and
	 *  last points are opposed on the diagonal, as are the second and third. The first point will be
	 *  the topmost point and the last, the bottommost. The second point will be leftmost and the
	 *  third, the rightmost
	 * @throws NotFoundException if no Data Matrix Code can be found
	 */
	public function detect(): \Zxing\ResultPoint
	{
		$height = $this->image->getHeight();
		$width = $this->image->getWidth();
		$halfHeight = $height / 2;
		$halfWidth = $width / 2;

		$deltaY = max(1, $height / (self::$MAX_MODULES * 8));
		$deltaX = max(1, $width / (self::$MAX_MODULES * 8));


		$top = 0;
		$bottom = $height;
		$left = 0;
		$right = $width;
		$pointA = $this->findCornerFromCenter(
			$halfWidth,
			0,
			$left,
			$right,
			$halfHeight,
			-$deltaY,
			$top,
			$bottom,
			$halfWidth / 2
		);
		$top = (int)$pointA->getY() - 1;
		$pointB = $this->findCornerFromCenter(
			$halfWidth,
			-$deltaX,
			$left,
			$right,
			$halfHeight,
			0,
			$top,
			$bottom,
			$halfHeight / 2
		);
		$left = (int)$pointB->getX() - 1;
		$pointC = $this->findCornerFromCenter(
			$halfWidth,
			$deltaX,
			$left,
			$right,
			$halfHeight,
			0,
			$top,
			$bottom,
			$halfHeight / 2
		);
		$right = (int)$pointC->getX() + 1;
		$pointD = $this->findCornerFromCenter(
			$halfWidth,
			0,
			$left,
			$right,
			$halfHeight,
			$deltaY,
			$top,
			$bottom,
			$halfWidth / 2
		);
		$bottom = (int)$pointD->getY() + 1;

		// Go try to find po$A again with better information -- might have been off at first.
		$pointA = $this->findCornerFromCenter(
			$halfWidth,
			0,
			$left,
			$right,
			$halfHeight,
			-$deltaY,
			$top,
			$bottom,
			$halfWidth / 4
		);

		return new ResultPoint($pointA, $pointB, $pointC, $pointD);
	}


	/**
	 * Attempts to locate a corner of the barcode by scanning up, down, left or right from a center
	 * point which should be within the barcode.
	 *
	 * @param float $centerX     center's x component (horizontal)
	 * @param float $deltaX      same as deltaY but change in x per step instead
	 * @param int $left
	 * @param int $right
	 * @param float $centerY     center's y component (vertical)
	 * @param float $deltaY      change in y per step. If scanning up this is negative; down, positive;
	 *                    left or right, 0
	 * @param int $top
	 * @param int $bottom
	 * @param float $maxWhiteRun maximum run of white pixels that can still be considered to be within
	 *                    the barcode
	 *
	 * @return ResultPoint {@link com.google.zxing.ResultPoint} encapsulating the corner that was found
	 *
	 * @throws NotFoundException if such a point cannot be found
	 */
	private function findCornerFromCenter(
		int|float $centerX,
		int|float $deltaX,
		int $left,
		int $right,
		int|float $centerY,
		float|int $deltaY,
		int $top,
		int $bottom,
		int|float $maxWhiteRun
	): \Zxing\ResultPoint {
		$lastRange = null;
		for ($y = $centerY, $x = $centerX;
			 $y < $bottom && $y >= $top && $x < $right && $x >= $left;
			 $y += $deltaY, $x += $deltaX) {
			$range = 0;
			if ($deltaX == 0) {
				// horizontal slices, up and down
				$range = $this->blackWhiteRange($y, $maxWhiteRun, $left, $right, true);
			} else {
				// vertical slices, left and right
				$range = $this->blackWhiteRange($x, $maxWhiteRun, $top, $bottom, false);
			}
			if ($range == null) {
				if ($lastRange == null) {
					throw new NotFoundException("No corner from center found");
				}
				// lastRange was found
				if ($deltaX == 0) {
					$lastY = $y - $deltaY;
					if ($lastRange[0] < $centerX) {
						if ($lastRange[1] > $centerX) {
							// straddle, choose one or the other based on direction
							return new ResultPoint($deltaY > 0 ? $lastRange[0] : $lastRange[1], $lastY);
						}

						return new ResultPoint($lastRange[0], $lastY);
					} else {
						return new ResultPoint($lastRange[1], $lastY);
					}
				} else {
					$lastX = $x - $deltaX;
					if ($lastRange[0] < $centerY) {
						if ($lastRange[1] > $centerY) {
							return new ResultPoint($lastX, $deltaX < 0 ? $lastRange[0] : $lastRange[1]);
						}

						return new ResultPoint($lastX, $lastRange[0]);
					} else {
						return new ResultPoint($lastX, $lastRange[1]);
					}
				}
			}
			$lastRange = $range;
		}
		throw new NotFoundException("No corner from center found");
	}


	/**
	 * Computes the start and end of a region of pixels, either horizontally or vertically, that could
	 * be part of a Data Matrix barcode.
	 *
	 * @param float|int $fixedDimension
	 * @param float|int $maxWhiteRun
	 * @param int $minDim
	 * @param int $maxDim
	 * @param bool $horizontal
	 *
	 * @return (float|int)[]|null with start and end of found range, or null if no such range is found (e.g. only white was found)
	 *
	 * @psalm-return array{0: float|int, 1: float|int}|null
	 */
	private function blackWhiteRange(float|int $fixedDimension, int|float $maxWhiteRun, int $minDim, int $maxDim, bool $horizontal): array|null
	{
		$center = ($minDim + $maxDim) / 2;

		// Scan left/up first
		$start = $center;
		while ($start >= $minDim) {
			if ($horizontal ? $this->image->get($start, $fixedDimension) : $this->image->get($fixedDimension, $start)) {
				$start--;
			} else {
				$whiteRunStart = $start;
				do {
					$start--;
				} while ($start >= $minDim && !($horizontal ? $this->image->get($start, $fixedDimension) :
					$this->image->get($fixedDimension, $start)));
				$whiteRunSize = $whiteRunStart - $start;
				if ($start < $minDim || $whiteRunSize > $maxWhiteRun) {
					$start = $whiteRunStart;
					break;
				}
			}
		}
		$start++;

		// Then try right/down
		$end = $center;
		while ($end < $maxDim) {
			if ($horizontal ? $this->image->get($end, $fixedDimension) : $this->image->get($fixedDimension, $end)) {
				$end++;
			} else {
				$whiteRunStart = $end;
				do {
					$end++;
				} while ($end < $maxDim && !($horizontal ? $this->image->get($end, $fixedDimension) :
					$this->image->get($fixedDimension, $end)));
				$whiteRunSize = $end - $whiteRunStart;
				if ($end >= $maxDim || $whiteRunSize > $maxWhiteRun) {
					$end = $whiteRunStart;
					break;
				}
			}
		}
		$end--;

		return $end > $start ? [$start, $end] : null;
	}
}

QRCodeReader.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode;

use Zxing\BinaryBitmap;
use Zxing\ChecksumException;
use Zxing\Common\BitMatrix;
use Zxing\FormatException;
use Zxing\NotFoundException;
use Zxing\Qrcode\Decoder\Decoder;
use Zxing\Qrcode\Detector\Detector;
use Zxing\Reader;
use Zxing\Result;

/**
 * This implementation can detect and decode QR Codes in an image.
 *
 * @author Sean Owen
 */
class QRCodeReader implements Reader
{
	private static array $NO_POINTS = [];
	private readonly Decoder $decoder;

	public function __construct()
	{
		$this->decoder = new Decoder();
	}

	/**
  * @param null         $hints
  *
  * @return Result
  * @throws \Zxing\FormatException
  * @throws \Zxing\NotFoundException
  */
	public function decode(BinaryBitmap $image, $hints = null)
	{
		$decoderResult = null;
		if ($hints !== null && array_key_exists('PURE_BARCODE', $hints) && $hints['PURE_BARCODE']) {
			$bits = self::extractPureBits($image->getBlackMatrix());
			$decoderResult = $this->decoder->decode($bits, $hints);
			$points = self::$NO_POINTS;
		} else {
			$detector = new Detector($image->getBlackMatrix());
			$detectorResult = $detector->detect($hints);

			$decoderResult = $this->decoder->decode($detectorResult->getBits(), $hints);
			$points = $detectorResult->getPoints();
		}
		$result = new Result($decoderResult->getText(), $decoderResult->getRawBytes(), $points, 'QR_CODE');//BarcodeFormat.QR_CODE

		$byteSegments = $decoderResult->getByteSegments();
		if ($byteSegments !== null) {
			$result->putMetadata('BYTE_SEGMENTS', $byteSegments);//ResultMetadataType.BYTE_SEGMENTS
		}
		$ecLevel = $decoderResult->getECLevel();
		if ($ecLevel !== null) {
			$result->putMetadata('ERROR_CORRECTION_LEVEL', $ecLevel);//ResultMetadataType.ERROR_CORRECTION_LEVEL
		}
		if ($decoderResult->hasStructuredAppend()) {
			$result->putMetadata(
				'STRUCTURED_APPEND_SEQUENCE',//ResultMetadataType.STRUCTURED_APPEND_SEQUENCE
				$decoderResult->getStructuredAppendSequenceNumber()
			);
			$result->putMetadata(
				'STRUCTURED_APPEND_PARITY',//ResultMetadataType.STRUCTURED_APPEND_PARITY
				$decoderResult->getStructuredAppendParity()
			);
		}

		return $result;
	}

	/**
	 * Locates and decodes a QR code in an image.
	 * This method detects a code in a "pure" image -- that is, pure monochrome image
	 * which contains only an unrotated, unskewed, image of a code, with some white border
	 * around it. This is a specialized method that works exceptionally fast in this special
	 * case.
	 *
	 * @return BitMatrix a String representing the content encoded by the QR code
	 * @throws NotFoundException if a QR code cannot be found
	 * @throws FormatException if a QR code cannot be decoded
	 * @throws ChecksumException if error correction fails
	 *
	 * @see com.google.zxing.datamatrix.DataMatrixReader#extractPureBits(BitMatrix)
	 */
	private static function extractPureBits(BitMatrix $image): BitMatrix
	{
		$leftTopBlack = $image->getTopLeftOnBit();
		$rightBottomBlack = $image->getBottomRightOnBit();
		if ($leftTopBlack === null || $rightBottomBlack == null) {
			throw new NotFoundException("Top left or bottom right on bit not found");
		}

		$moduleSize = self::moduleSize($leftTopBlack, $image);

		$top = $leftTopBlack[1];
		$bottom = $rightBottomBlack[1];
		$left = $leftTopBlack[0];
		$right = $rightBottomBlack[0];

		// Sanity check!
		if ($left >= $right || $top >= $bottom) {
			throw new NotFoundException("Left vs. right ($left >= $right) or top vs. bottom ($top >= $bottom) sanity violated.");
		}

		if ($bottom - $top != $right - $left) {
			// Special case, where bottom-right module wasn't black so we found something else in the last row
			// Assume it's a square, so use height as the width
			$right = $left + ($bottom - $top);
		}

		$matrixWidth = round(($right - $left + 1) / $moduleSize);
		$matrixHeight = round(($bottom - $top + 1) / $moduleSize);
		if ($matrixWidth <= 0 || $matrixHeight <= 0) {
			throw new NotFoundException("Matrix dimensions <= 0 ($matrixWidth, $matrixHeight)");
		}
		if ($matrixHeight != $matrixWidth) {
			// Only possibly decode square regions
			throw new NotFoundException("Matrix height  $matrixHeight != matrix width $matrixWidth");
		}

		// Push in the "border" by half the module width so that we start
		// sampling in the middle of the module. Just in case the image is a
		// little off, this will help recover.
		$nudge = (int)($moduleSize / 2.0);// $nudge = (int) ($moduleSize / 2.0f);
		$top += $nudge;
		$left += $nudge;

		// But careful that this does not sample off the edge
		// "right" is the farthest-right valid pixel location -- right+1 is not necessarily
		// This is positive by how much the inner x loop below would be too large
		$nudgedTooFarRight = $left + (int)(($matrixWidth - 1) * $moduleSize) - $right;
		if ($nudgedTooFarRight > 0) {
			if ($nudgedTooFarRight > $nudge) {
				// Neither way fits; abort
				throw new NotFoundException("Nudge too far right ($nudgedTooFarRight > $nudge), no fit found");
			}
			$left -= $nudgedTooFarRight;
		}
		// See logic above
		$nudgedTooFarDown = $top + (int)(($matrixHeight - 1) * $moduleSize) - $bottom;
		if ($nudgedTooFarDown > 0) {
			if ($nudgedTooFarDown > $nudge) {
				// Neither way fits; abort
				throw new NotFoundException("Nudge too far down ($nudgedTooFarDown > $nudge), no fit found");
			}
			$top -= $nudgedTooFarDown;
		}

		// Now just read off the bits
		$bits = new BitMatrix($matrixWidth, $matrixHeight);
		for ($y = 0; $y < $matrixHeight; $y++) {
			$iOffset = (int)($top + (int)($y * $moduleSize));
			for ($x = 0; $x < $matrixWidth; $x++) {
				if ($image->get((int)($left + (int)($x * $moduleSize)), $iOffset)) {
					$bits->set($x, $y);
				}
			}
		}

		return $bits;
	}

	/**
	 * @psalm-param array{0: mixed, 1: mixed} $leftTopBlack
	 */
	private static function moduleSize(array $leftTopBlack, BitMatrix $image)
	{
		$height = $image->getHeight();
		$width = $image->getWidth();
		$x = $leftTopBlack[0];
		$y = $leftTopBlack[1];
		/*$x           = $leftTopBlack[0];
		$y           = $leftTopBlack[1];*/
		$inBlack = true;
		$transitions = 0;
		while ($x < $width && $y < $height) {
			if ($inBlack != $image->get((int)round($x), (int)round($y))) {
				if (++$transitions == 5) {
					break;
				}
				$inBlack = !$inBlack;
			}
			$x++;
			$y++;
		}
		if ($x == $width || $y == $height) {
			throw new NotFoundException("$x == $width || $y == $height");
		}

		return ($x - $leftTopBlack[0]) / 7.0; //return ($x - $leftTopBlack[0]) / 7.0f;
	}

	public function reset(): void
	{
		// do nothing
	}

	final protected function getDecoder(): Decoder
	{
		return $this->decoder;
	}
}

BitMatrixParser.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Decoder;

use Zxing\Common\BitMatrix;
use Zxing\FormatException;

/**
 * @author Sean Owen
 */
final class BitMatrixParser
{
	private $bitMatrix;
	/**
  * @var mixed|null
  */
	private $parsedVersion;
	private $parsedFormatInfo;
	private $mirror;

	/**
	 * @param $bitMatrix {@link BitMatrix} to parse
	 *
	 * @throws FormatException if dimension is not >= 21 and 1 mod 4
	 */
	public function __construct($bitMatrix)
	{
		$dimension = $bitMatrix->getHeight();
		if ($dimension < 21 || ($dimension & 0x03) != 1) {
			throw new FormatException();
		}
		$this->bitMatrix = $bitMatrix;
	}

	/**
	 * <p>Reads the bits in the {@link BitMatrix} representing the finder pattern in the
	 * correct order in order to reconstruct the codewords bytes contained within the
	 * QR Code.</p>
	 *
	 * @return array bytes encoded within the QR Code
	 * @throws FormatException if the exact number of bytes expected is not read
	 */
	public function readCodewords()
	{
		$formatInfo = $this->readFormatInformation();
		$version = $this->readVersion();

		// Get the data mask for the format used in this QR Code. This will exclude
		// some bits from reading as we wind through the bit matrix.
		$dataMask = DataMask::forReference($formatInfo->getDataMask());
		$dimension = $this->bitMatrix->getHeight();
		$dataMask->unmaskBitMatrix($this->bitMatrix, $dimension);

		$functionPattern = $version->buildFunctionPattern();

		$readingUp = true;
		if ($version->getTotalCodewords()) {
			$result = fill_array(0, $version->getTotalCodewords(), 0);
		} else {
			$result = [];
		}
		$resultOffset = 0;
		$currentByte = 0;
		$bitsRead = 0;
		// Read columns in pairs, from right to left
		for ($j = $dimension - 1; $j > 0; $j -= 2) {
			if ($j == 6) {
				// Skip whole column with vertical alignment pattern;
				// saves time and makes the other code proceed more cleanly
				$j--;
			}
			// Read alternatingly from bottom to top then top to bottom
			for ($count = 0; $count < $dimension; $count++) {
				$i = $readingUp ? $dimension - 1 - $count : $count;
				for ($col = 0; $col < 2; $col++) {
					// Ignore bits covered by the function pattern
					if (!$functionPattern->get($j - $col, $i)) {
						// Read a bit
						$bitsRead++;
						$currentByte <<= 1;
						if ($this->bitMatrix->get($j - $col, $i)) {
							$currentByte |= 1;
						}
						// If we've made a whole byte, save it off
						if ($bitsRead == 8) {
							$result[$resultOffset++] = $currentByte; //(byte)
							$bitsRead = 0;
							$currentByte = 0;
						}
					}
				}
			}
			$readingUp ^= true; // readingUp = !readingUp; // switch directions
		}
		if ($resultOffset != $version->getTotalCodewords()) {
			throw new FormatException();
		}

		return $result;
	}

	/**
	 * <p>Reads format information from one of its two locations within the QR Code.</p>
	 *
	 * @return {@link FormatInformation} encapsulating the QR Code's format info
	 * @throws FormatException if both format information locations cannot be parsed as
	 * the valid encoding of format information
	 */
	public function readFormatInformation()
	{
		if ($this->parsedFormatInfo != null) {
			return $this->parsedFormatInfo;
		}

		// Read top-left format info bits
		$formatInfoBits1 = 0;
		for ($i = 0; $i < 6; $i++) {
			$formatInfoBits1 = $this->copyBit($i, 8, $formatInfoBits1);
		}
		// .. and skip a bit in the timing pattern ...
		$formatInfoBits1 = $this->copyBit(7, 8, $formatInfoBits1);
		$formatInfoBits1 = $this->copyBit(8, 8, $formatInfoBits1);
		$formatInfoBits1 = $this->copyBit(8, 7, $formatInfoBits1);
		// .. and skip a bit in the timing pattern ...
		for ($j = 5; $j >= 0; $j--) {
			$formatInfoBits1 = $this->copyBit(8, $j, $formatInfoBits1);
		}

		// Read the top-right/bottom-left pattern too
		$dimension = $this->bitMatrix->getHeight();
		$formatInfoBits2 = 0;
		$jMin = $dimension - 7;
		for ($j = $dimension - 1; $j >= $jMin; $j--) {
			$formatInfoBits2 = $this->copyBit(8, $j, $formatInfoBits2);
		}
		for ($i = $dimension - 8; $i < $dimension; $i++) {
			$formatInfoBits2 = $this->copyBit($i, 8, $formatInfoBits2);
		}

		$parsedFormatInfo = FormatInformation::decodeFormatInformation($formatInfoBits1, $formatInfoBits2);
		if ($parsedFormatInfo != null) {
			return $parsedFormatInfo;
		}
		throw new FormatException();
	}

	/**
	 * @psalm-param 0 $versionBits
	 *
	 * @psalm-return 0|1
	 */
	private function copyBit(int|float $i, int|float $j, int $versionBits): int
	{
		$bit = $this->mirror ? $this->bitMatrix->get($j, $i) : $this->bitMatrix->get($i, $j);

		return $bit ? ($versionBits << 1) | 0x1 : $versionBits << 1;
	}

	/**
	 * <p>Reads version information from one of its two locations within the QR Code.</p>
	 *
	 * @return {@link Version} encapsulating the QR Code's version
	 * @throws FormatException if both version information locations cannot be parsed as
	 * the valid encoding of version information
	 */
	public function readVersion()
	{
		if ($this->parsedVersion != null) {
			return $this->parsedVersion;
		}

		$dimension = $this->bitMatrix->getHeight();

		$provisionalVersion = ($dimension - 17) / 4;
		if ($provisionalVersion <= 6) {
			return Version::getVersionForNumber($provisionalVersion);
		}

		// Read top-right version info: 3 wide by 6 tall
		$versionBits = 0;
		$ijMin = $dimension - 11;
		for ($j = 5; $j >= 0; $j--) {
			for ($i = $dimension - 9; $i >= $ijMin; $i--) {
				$versionBits = $this->copyBit($i, $j, $versionBits);
			}
		}

		$theParsedVersion = Version::decodeVersionInformation($versionBits);
		if ($theParsedVersion != null && $theParsedVersion->getDimensionForVersion() == $dimension) {
			$this->parsedVersion = $theParsedVersion;

			return $theParsedVersion;
		}

		// Hmm, failed. Try bottom left: 6 wide by 3 tall
		$versionBits = 0;
		for ($i = 5; $i >= 0; $i--) {
			for ($j = $dimension - 9; $j >= $ijMin; $j--) {
				$versionBits = $this->copyBit($i, $j, $versionBits);
			}
		}

		$theParsedVersion = Version::decodeVersionInformation($versionBits);
		if ($theParsedVersion != null && $theParsedVersion->getDimensionForVersion() == $dimension) {
			$this->parsedVersion = $theParsedVersion;

			return $theParsedVersion;
		}
		throw new FormatException("both version information locations cannot be parsed as the valid encoding of version information");
	}

	/**
	 * Revert the mask removal done while reading the code words. The bit matrix should revert to its original state.
	 */
	public function remask(): void
	{
		if ($this->parsedFormatInfo == null) {
			return; // We have no format information, and have no data mask
		}
		$dataMask = DataMask::forReference($this->parsedFormatInfo->getDataMask());
		$dimension = $this->bitMatrix->getHeight();
		$dataMask->unmaskBitMatrix($this->bitMatrix, $dimension);
	}

	/**
	 * Prepare the parser for a mirrored operation.
	 * This flag has effect only on the {@link #readFormatInformation()} and the
	 * {@link #readVersion()}. Before proceeding with {@link #readCodewords()} the
	 * {@link #mirror()} method should be called.
	 *
	 * @param bool $mirror Whether to read version and format information mirrored.
	 */
	public function setMirror($mirror): void
	{
		$parsedVersion = null;
		$parsedFormatInfo = null;
		$this->mirror = $mirror;
	}

	/** Mirror the bit matrix in order to attempt a second reading. */
	public function mirror(): void
	{
		for ($x = 0; $x < $this->bitMatrix->getWidth(); $x++) {
			for ($y = $x + 1; $y < $this->bitMatrix->getHeight(); $y++) {
				if ($this->bitMatrix->get($x, $y) != $this->bitMatrix->get($y, $x)) {
					$this->bitMatrix->flip($y, $x);
					$this->bitMatrix->flip($x, $y);
				}
			}
		}
	}
}

DataBlock.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Decoder;

/**
 * <p>Encapsulates a block of data within a QR Code. QR Codes may split their data into
 * multiple blocks, each of which is a unit of data and error-correction codewords. Each
 * is represented by an instance of this class.</p>
 *
 * @author Sean Owen
 */
final class DataBlock
{
	//byte[]

	private function __construct(private $numDataCodewords, private $codewords)
	{
	}

	/**
	 * <p>When QR Codes use multiple data blocks, they are actually interleaved.
	 * That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This
	 * method will separate the data into original blocks.</p>
	 *
	 * @param array $rawCodewords as read directly from the QR Code
	 * @param Version $version of the QR Code
	 * @param ErrorCorrectionLevel $ecLevel error-correction level of the QR Code
	 *
	 * @return \Zxing\Qrcode\Decoder\DataBlock[] DataBlocks containing original bytes, "de-interleaved" from representation in the
		 QR Code
	 */
	public static function getDataBlocks(
		$rawCodewords,
		Version $version,
		ErrorCorrectionLevel $ecLevel
	): array {
		if ((is_countable($rawCodewords) ? count($rawCodewords) : 0) != $version->getTotalCodewords()) {
			throw new \InvalidArgumentException();
		}

		// Figure out the number and size of data blocks used by this version and
		// error correction level
		$ecBlocks = $version->getECBlocksForLevel($ecLevel);

		// First count the total number of data blocks
		$totalBlocks = 0;
		$ecBlockArray = $ecBlocks->getECBlocks();
		foreach ($ecBlockArray as $ecBlock) {
			$totalBlocks += $ecBlock->getCount();
		}

		// Now establish DataBlocks of the appropriate size and number of data codewords
		$result = []; //new DataBlock[$totalBlocks];
		$numResultBlocks = 0;
		foreach ($ecBlockArray as $ecBlock) {
			$ecBlockCount = $ecBlock->getCount();
			for ($i = 0; $i < $ecBlockCount; $i++) {
				$numDataCodewords = $ecBlock->getDataCodewords();
				$numBlockCodewords = $ecBlocks->getECCodewordsPerBlock() + $numDataCodewords;
				$result[$numResultBlocks++] = new DataBlock($numDataCodewords, fill_array(0, $numBlockCodewords, 0));
			}
		}

		// All blocks have the same amount of data, except that the last n
		// (where n may be 0) have 1 more byte. Figure out where these start.
		$shorterBlocksTotalCodewords = is_countable($result[0]->codewords) ? count($result[0]->codewords) : 0;
		$longerBlocksStartAt = count($result) - 1;
		while ($longerBlocksStartAt >= 0) {
			$numCodewords = is_countable($result[$longerBlocksStartAt]->codewords) ? count($result[$longerBlocksStartAt]->codewords) : 0;
			if ($numCodewords == $shorterBlocksTotalCodewords) {
				break;
			}
			$longerBlocksStartAt--;
		}
		$longerBlocksStartAt++;

		$shorterBlocksNumDataCodewords = $shorterBlocksTotalCodewords - $ecBlocks->getECCodewordsPerBlock();
		// The last elements of result may be 1 element longer;
		// first fill out as many elements as all of them have
		$rawCodewordsOffset = 0;
		for ($i = 0; $i < $shorterBlocksNumDataCodewords; $i++) {
			for ($j = 0; $j < $numResultBlocks; $j++) {
				$result[$j]->codewords[$i] = $rawCodewords[$rawCodewordsOffset++];
			}
		}
		// Fill out the last data block in the longer ones
		for ($j = $longerBlocksStartAt; $j < $numResultBlocks; $j++) {
			$result[$j]->codewords[$shorterBlocksNumDataCodewords] = $rawCodewords[$rawCodewordsOffset++];
		}
		// Now add in error correction blocks
		$max = is_countable($result[0]->codewords) ? count($result[0]->codewords) : 0;
		for ($i = $shorterBlocksNumDataCodewords; $i < $max; $i++) {
			for ($j = 0; $j < $numResultBlocks; $j++) {
				$iOffset = $j < $longerBlocksStartAt ? $i : $i + 1;
				$result[$j]->codewords[$iOffset] = $rawCodewords[$rawCodewordsOffset++];
			}
		}

		return $result;
	}

	public function getNumDataCodewords()
	{
		return $this->numDataCodewords;
	}

	public function getCodewords()
	{
		return $this->codewords;
	}
}

DataMask.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Decoder;

use Zxing\Common\BitMatrix;

/**
 * <p>Encapsulates data masks for the data bits in a QR code, per ISO 18004:2006 6.8. Implementations
 * of this class can un-mask a raw BitMatrix. For simplicity, they will unmask the entire BitMatrix,
 * including areas used for finder patterns, timing patterns, etc. These areas should be unused
 * after the point they are unmasked anyway.</p>
 *
 * <p>Note that the diagram in section 6.8.1 is misleading since it indicates that i is column position
 * and j is row position. In fact, as the text says, i is row position and j is column position.</p>
 *
 * @author Sean Owen
 */
abstract class DataMask
{
	/**
	 * See ISO 18004:2006 6.8.1
	 */
	private static array $DATA_MASKS = [];

	public function __construct()
	{
	}

	public static function Init(): void
	{
		self::$DATA_MASKS = [
			new DataMask000(),
			new DataMask001(),
			new DataMask010(),
			new DataMask011(),
			new DataMask100(),
			new DataMask101(),
			new DataMask110(),
			new DataMask111(),
		];
	}

	/**
	 * @param int $reference a value between 0 and 7 indicating one of the eight possible
	 *                  data mask patterns a QR Code may use
	 *
	 * @return DataMask encapsulating the data mask pattern
	 */
	public static function forReference($reference)
	{
		if ($reference < 0 || $reference > 7) {
			throw new \InvalidArgumentException();
		}

		return self::$DATA_MASKS[$reference];
	}

	/**
	 * <p>Implementations of this method reverse the data masking process applied to a QR Code and
	 * make its bits ready to read.</p>
	 *
	 * @param BitMatrix $bits representation      of QR Code bits
	 * @param int $dimension dimension of QR Code, represented by bits, being unmasked
	 */
	final public function unmaskBitMatrix($bits, $dimension): void
	{
		for ($i = 0; $i < $dimension; $i++) {
			for ($j = 0; $j < $dimension; $j++) {
				if ($this->isMasked($i, $j)) {
					$bits->flip($j, $i);
				}
			}
		}
	}

	/**
	 * @psalm-param 0|positive-int $i
	 * @psalm-param 0|positive-int $j
	 */
	abstract public function isMasked(int $i, int $j);
}

DataMask::Init();

/**
 * 000: mask bits for which (x + y) mod 2 == 0
 */
final class DataMask000 extends DataMask
{
	// @Override
	public function isMasked($i, $j): bool
	{
		return (($i + $j) & 0x01) == 0;
	}
}

/**
 * 001: mask bits for which x mod 2 == 0
 */
final class DataMask001 extends DataMask
{
	public function isMasked($i, $j): bool
	{
		return ($i & 0x01) == 0;
	}
}

/**
 * 010: mask bits for which y mod 3 == 0
 */
final class DataMask010 extends DataMask
{
	public function isMasked($i, $j): bool
	{
		return $j % 3 == 0;
	}
}

/**
 * 011: mask bits for which (x + y) mod 3 == 0
 */
final class DataMask011 extends DataMask
{
	public function isMasked($i, $j): bool
	{
		return ($i + $j) % 3 == 0;
	}
}

/**
 * 100: mask bits for which (x/2 + y/3) mod 2 == 0
 */
final class DataMask100 extends DataMask
{
	public function isMasked($i, $j): bool
	{
		return (int)(((int)($i / 2) + (int)($j / 3)) & 0x01) == 0;
	}
}

/**
 * 101: mask bits for which xy mod 2 + xy mod 3 == 0
 */
final class DataMask101 extends DataMask
{
	public function isMasked($i, $j): bool
	{
		$temp = $i * $j;

		return ($temp & 0x01) + ($temp % 3) == 0;
	}
}

/**
 * 110: mask bits for which (xy mod 2 + xy mod 3) mod 2 == 0
 */
final class DataMask110 extends DataMask
{
	public function isMasked($i, $j): bool
	{
		$temp = $i * $j;

		return ((($temp & 0x01) + ($temp % 3)) & 0x01) == 0;
	}
}

/**
 * 111: mask bits for which ((x+y)mod 2 + xy mod 3) mod 2 == 0
 */
final class DataMask111 extends DataMask
{
	public function isMasked($i, $j): bool
	{
		return (((($i + $j) & 0x01) + (($i * $j) % 3)) & 0x01) == 0;
	}
}

DecodedBitStreamParser.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Decoder;

use ValueError;
use Zxing\Common\BitSource;
use Zxing\Common\CharacterSetECI;
use Zxing\Common\DecoderResult;
use Zxing\FormatException;

/**
 * <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes
 * in one QR Code. This class decodes the bits back into text.</p>
 *
 * <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p>
 *
 * @author Sean Owen
 */
final class DecodedBitStreamParser
{
	/**
	 * See ISO 18004:2006, 6.4.4 Table 5
	 */
	private static array $ALPHANUMERIC_CHARS = [
		'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
		'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
		'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
		' ', '$', '%', '*', '+', '-', '.', '/', ':',
	];
	private static int $GB2312_SUBSET = 1;

	/**
	 * @psalm-param array<int, mixed> $bytes
	 */
	public static function decode(
		array $bytes,
		Version $version,
		ErrorCorrectionLevel $ecLevel,
		array|null $hints
	): \Zxing\Common\DecoderResult {
		$bits = new BitSource($bytes);
		$result = ''; //new StringBuilder(50);
		$byteSegments = [];
		$symbolSequence = -1;
		$parityData = -1;

		try {
			$currentCharacterSetECI = null;
			$fc1InEffect = false;
			$mode = '';
			do {
				// While still another segment to read...
				if ($bits->available() < 4) {
					// OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
					$mode = Mode::$TERMINATOR;
				} else {
					$mode = Mode::forBits($bits->readBits(4)); // mode is encoded by 4 bits
				}
				if ($mode != Mode::$TERMINATOR) {
					if ($mode == Mode::$FNC1_FIRST_POSITION || $mode == Mode::$FNC1_SECOND_POSITION) {
						// We do little with FNC1 except alter the parsed result a bit according to the spec
						$fc1InEffect = true;
					} elseif ($mode == Mode::$STRUCTURED_APPEND) {
						if ($bits->available() < 16) {
							throw new FormatException("Bits available < 16");
						}
						// sequence number and parity is added later to the result metadata
						// Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue
						$symbolSequence = $bits->readBits(8);
						$parityData = $bits->readBits(8);
					} elseif ($mode == Mode::$ECI) {
						// Count doesn't apply to ECI
						$value = self::parseECIValue($bits);
						$currentCharacterSetECI = CharacterSetECI::getCharacterSetECIByValue($value);
						if ($currentCharacterSetECI == null) {
							throw new FormatException("Current character set ECI is null");
						}
					} else {
						// First handle Hanzi mode which does not start with character count
						if ($mode == Mode::$HANZI) {
							//chinese mode contains a sub set indicator right after mode indicator
							$subset = $bits->readBits(4);
							$countHanzi = $bits->readBits($mode->getCharacterCountBits($version));
							if ($subset == self::$GB2312_SUBSET) {
								self::decodeHanziSegment($bits, $result, $countHanzi);
							}
						} else {
							// "Normal" QR code modes:
							// How many characters will follow, encoded in this mode?
							$count = $bits->readBits($mode->getCharacterCountBits($version));
							if ($mode == Mode::$NUMERIC) {
								self::decodeNumericSegment($bits, $result, $count);
							} elseif ($mode == Mode::$ALPHANUMERIC) {
								self::decodeAlphanumericSegment($bits, $result, $count, $fc1InEffect);
							} elseif ($mode == Mode::$BYTE) {
								self::decodeByteSegment($bits, $result, $count, $currentCharacterSetECI, $byteSegments, $hints);
							} elseif ($mode == Mode::$KANJI) {
								self::decodeKanjiSegment($bits, $result, $count);
							} else {
								throw new FormatException("Unknown mode $mode to decode");
							}
						}
					}
				}
			} while ($mode != Mode::$TERMINATOR);
		} catch (\InvalidArgumentException $e) {
			// from readBits() calls
			throw new FormatException("Invalid argument exception when formatting: " . $e->getMessage());
		}

		return new DecoderResult(
			$bytes,
			$result,
			empty($byteSegments) ? null : $byteSegments,
			$ecLevel == null ? null : 'L', //ErrorCorrectionLevel::toString($ecLevel),
			$symbolSequence,
			$parityData
		);
	}

	private static function parseECIValue(BitSource $bits): int
	{
		$firstByte = $bits->readBits(8);
		if (($firstByte & 0x80) == 0) {
			// just one byte
			return $firstByte & 0x7F;
		}
		if (($firstByte & 0xC0) == 0x80) {
			// two bytes
			$secondByte = $bits->readBits(8);

			return (($firstByte & 0x3F) << 8) | $secondByte;
		}
		if (($firstByte & 0xE0) == 0xC0) {
			// three bytes
			$secondThirdBytes = $bits->readBits(16);

			return (($firstByte & 0x1F) << 16) | $secondThirdBytes;
		}
		throw new FormatException("ECI Value parsing failed.");
	}

	/**
	 * See specification GBT 18284-2000
	 *
	 * @psalm-param '' $result
	 */
	private static function decodeHanziSegment(
		BitSource $bits,
		string &$result,
		int $count
	): void {
		// Don't crash trying to read more bits than we have available.
		if ($count * 13 > $bits->available()) {
			throw new FormatException("Trying to read more bits than we have available");
		}

		// Each character will require 2 bytes. Read the characters as 2-byte pairs
		// and decode as GB2312 afterwards
		$buffer = fill_array(0, 2 * $count, 0);
		$offset = 0;
		while ($count > 0) {
			// Each 13 bits encodes a 2-byte character
			$twoBytes = $bits->readBits(13);
			$assembledTwoBytes = (($twoBytes / 0x060) << 8) | ($twoBytes % 0x060);
			if ($assembledTwoBytes < 0x003BF) {
				// In the 0xA1A1 to 0xAAFE range
				$assembledTwoBytes += 0x0A1A1;
			} else {
				// In the 0xB0A1 to 0xFAFE range
				$assembledTwoBytes += 0x0A6A1;
			}
			$buffer[$offset] = (($assembledTwoBytes >> 8) & 0xFF); //(byte)
			$buffer[$offset + 1] = ($assembledTwoBytes & 0xFF); //(byte)
			$offset += 2;
			$count--;
		}
		$result .= iconv('GB2312', 'UTF-8', implode($buffer));
	}

	private static function decodeNumericSegment(
		BitSource $bits,
		string &$result,
		int $count
	): void {
		// Read three digits at a time
		while ($count >= 3) {
			// Each 10 bits encodes three digits
			if ($bits->available() < 10) {
				throw new FormatException("Not enough bits available");
			}
			$threeDigitsBits = $bits->readBits(10);
			if ($threeDigitsBits >= 1000) {
				throw new FormatException("Too many three digit bits");
			}
			$result .= (self::toAlphaNumericChar(intdiv($threeDigitsBits, 100)));
			$result .= (self::toAlphaNumericChar(intdiv($threeDigitsBits, 10) % 10));
			$result .= (self::toAlphaNumericChar($threeDigitsBits % 10));
			$count -= 3;
		}
		if ($count == 2) {
			// Two digits left over to read, encoded in 7 bits
			if ($bits->available() < 7) {
				throw new FormatException("Two digits left over to read, encoded in 7 bits, but only " . $bits->available() . ' bits available');
			}
			$twoDigitsBits = $bits->readBits(7);
			if ($twoDigitsBits >= 100) {
				throw new FormatException("Too many bits: $twoDigitsBits expected < 100");
			}
			$result .= (self::toAlphaNumericChar(intdiv($twoDigitsBits, 10)));
			$result .= (self::toAlphaNumericChar($twoDigitsBits % 10));
		} elseif ($count == 1) {
			// One digit left over to read
			if ($bits->available() < 4) {
				throw new FormatException("One digit left to read, but < 4 bits available");
			}
			$digitBits = $bits->readBits(4);
			if ($digitBits >= 10) {
				throw new FormatException("Too many bits: $digitBits expected < 10");
			}
			$result .= (self::toAlphaNumericChar($digitBits));
		}
	}

	/**
	 * @param float|int $value
	 */
	private static function toAlphaNumericChar(int|float $value)
	{
		$intVal = (int) $value;
		if ($intVal >= count(self::$ALPHANUMERIC_CHARS)) {
			throw new FormatException("$intVal is too many alphanumeric chars");
		}

		return self::$ALPHANUMERIC_CHARS[(int)($intVal)];
	}

	private static function decodeAlphanumericSegment(
		BitSource $bits,
		string &$result,
		int $count,
		bool $fc1InEffect
	): void {
		// Read two characters at a time
		$start = strlen((string) $result);
		while ($count > 1) {
			if ($bits->available() < 11) {
				throw new FormatException("Not enough bits available to read two expected characters");
			}
			$nextTwoCharsBits = $bits->readBits(11);
			$result .= (self::toAlphaNumericChar(intdiv($nextTwoCharsBits, 45)));
			$result .= (self::toAlphaNumericChar($nextTwoCharsBits % 45));
			$count -= 2;
		}
		if ($count == 1) {
			// special case: one character left
			if ($bits->available() < 6) {
				throw new FormatException("Not enough bits available to read one expected character");
			}
			$result .= self::toAlphaNumericChar($bits->readBits(6));
		}
		// See section 6.4.8.1, 6.4.8.2
		if ($fc1InEffect) {
			// We need to massage the result a bit if in an FNC1 mode:
			for ($i = $start; $i < strlen((string) $result); $i++) {
				if ($result[$i] == '%') {
					if ($i < strlen((string) $result) - 1 && $result[$i + 1] == '%') {
						// %% is rendered as %
						$result = substr_replace($result, '', $i + 1, 1); //deleteCharAt(i + 1);
					} else {
						// In alpha mode, % should be converted to FNC1 separator 0x1D
						$result[$i] = chr(0x1D);
					}
				}
			}
		}
	}

	private static function decodeByteSegment(
		BitSource $bits,
		string &$result,
		int $count,
		CharacterSetECI|null $currentCharacterSetECI,
		array &$byteSegments,
		array|null $hints
	): void {
		// Don't crash trying to read more bits than we have available.
		if (8 * $count > $bits->available()) {
			throw new FormatException("Trying to read more bits than we have available");
		}

		$readBytes = fill_array(0, $count, 0);
		for ($i = 0; $i < $count; $i++) {
			$readBytes[$i] = $bits->readBits(8); //(byte)
		}
		$text = implode(array_map('chr', $readBytes));
        if ($hints !== null && array_key_exists('BINARY_MODE', $hints) && $hints['BINARY_MODE']) {
            $result .= $text;
        } else {
            $encoding = '';
            if ($currentCharacterSetECI == null) {
                // The spec isn't clear on this mode; see
                // section 6.4.5: t does not say which encoding to assuming
                // upon decoding. I have seen ISO-8859-1 used as well as
                // Shift_JIS -- without anything like an ECI designator to
                // give a hint.

                try {
                    $encoding = mb_detect_encoding($text, $hints);
                } catch (ValueError $e) {
                    $encoding = mb_detect_encoding($text, mb_detect_order(), false);
                }
            } else {
                $encoding = $currentCharacterSetECI->name();
            }
            $result .= mb_convert_encoding($text, $encoding); //(new String(readBytes, encoding));
        }

		$byteSegments = array_merge($byteSegments, $readBytes);
	}

	private static function decodeKanjiSegment(
		BitSource $bits,
		string &$result,
		int $count
	): void {
		// Don't crash trying to read more bits than we have available.
		if ($count * 13 > $bits->available()) {
			throw new FormatException("Trying to read more bits than we have available");
		}

		// Each character will require 2 bytes. Read the characters as 2-byte pairs
		// and decode as Shift_JIS afterwards
		$buffer = [0, 2 * $count, 0];
		$offset = 0;
		while ($count > 0) {
			// Each 13 bits encodes a 2-byte character
			$twoBytes = $bits->readBits(13);
			$assembledTwoBytes = (($twoBytes / 0x0C0) << 8) | ($twoBytes % 0x0C0);
			if ($assembledTwoBytes < 0x01F00) {
				// In the 0x8140 to 0x9FFC range
				$assembledTwoBytes += 0x08140;
			} else {
				// In the 0xE040 to 0xEBBF range
				$assembledTwoBytes += 0x0C140;
			}
			$buffer[$offset] = ($assembledTwoBytes >> 8); //(byte)
			$buffer[$offset + 1] = $assembledTwoBytes; //(byte)
			$offset += 2;
			$count--;
		}
		// Shift_JIS may not be supported in some environments:

		$result .= iconv('shift-jis', 'utf-8', implode($buffer));
	}

	private function DecodedBitStreamParser(): void
	{
	}
}

Decoder.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Decoder;

use Zxing\ChecksumException;
use Zxing\Common\BitMatrix;
use Zxing\Common\DecoderResult;
use Zxing\Common\Reedsolomon\GenericGF;
use Zxing\Common\Reedsolomon\ReedSolomonDecoder;
use Zxing\Common\Reedsolomon\ReedSolomonException;
use Zxing\FormatException;

/**
 * <p>The main class which implements QR Code decoding -- as opposed to locating and extracting
 * the QR Code from an image.</p>
 *
 * @author Sean Owen
 */
final class Decoder
{
	private readonly \Zxing\Common\Reedsolomon\ReedSolomonDecoder $rsDecoder;

	public function __construct()
	{
		$this->rsDecoder = new ReedSolomonDecoder(GenericGF::$QR_CODE_FIELD_256);
	}

	public function decode(BitMatrix|BitMatrixParser $variable, array|null $hints = null): string|DecoderResult
	{
		if (is_array($variable)) {
			return $this->decodeImage($variable, $hints);
		} elseif ($variable instanceof BitMatrix) {
			return $this->decodeBits($variable, $hints);
		} elseif ($variable instanceof BitMatrixParser) {
			return $this->decodeParser($variable, $hints);
		}
		die('decode error Decoder.php');
	}

	/**
	 * <p>Convenience method that can decode a QR Code represented as a 2D array of booleans.
	 * "true" is taken to mean a black module.</p>
	 *
	 * @param array $image booleans representing white/black QR Code modules
	 * @param array|null $hints       decoding  hints that should be used to influence decoding
	 *
	 * @return DecoderResult|string text and bytes encoded within the QR Code
	 *
	 * @throws FormatException if the QR Code cannot be decoded
	 * @throws ChecksumException if error correction fails
	 */
	public function decodeImage(array $image, $hints = null): string|DecoderResult
	{
		$dimension = is_countable($image) ? count($image) : 0;
		$bits = new BitMatrix($dimension);
		for ($i = 0; $i < $dimension; $i++) {
			for ($j = 0; $j < $dimension; $j++) {
				if ($image[$i][$j]) {
					$bits->set($j, $i);
				}
			}
		}

		return $this->decode($bits, $hints);
	}


	/**
	 * <p>Decodes a QR Code represented as a {@link BitMatrix}. A 1 or "true" is taken to mean a black module.</p>
	 *
	 * @param BitMatrix $bits booleans representing white/black QR Code modules
	 * @param array|null          $hints decoding hints that should be used to influence decoding
	 *
	 * @return DecoderResult|string string text and bytes encoded within the QR Code
	 *
	 * @throws FormatException if the QR Code cannot be decoded
	 * @throws ChecksumException if error correction fails
	 */
	public function decodeBits(\Zxing\Common\BitMatrix $bits, $hints = null): string|DecoderResult
	{

		// Construct a parser and read version, error-correction level
		$parser = new BitMatrixParser($bits);
		$fe = null;
		$ce = null;
		try {
			return $this->decode($parser, $hints);
		} catch (FormatException $e) {
			$fe = $e;
		} catch (ChecksumException $e) {
			$ce = $e;
		}

		try {

			// Revert the bit matrix
			$parser->remask();

			// Will be attempting a mirrored reading of the version and format info.
			$parser->setMirror(true);

			// Preemptively read the version.
			$parser->readVersion();

			// Preemptively read the format information.
			$parser->readFormatInformation();

			/*
			* Since we're here, this means we have successfully detected some kind
			* of version and format information when mirrored. This is a good sign,
			* that the QR code may be mirrored, and we should try once more with a
			* mirrored content.
			*/
			// Prepare for a mirrored reading.
			$parser->mirror();

			$result = $this->decode($parser, $hints);

			// Success! Notify the caller that the code was mirrored.
			$result->setOther(new QRCodeDecoderMetaData(true));

			return $result;
		} catch (FormatException $e) { // catch (FormatException | ChecksumException e) {
			// Throw the exception from the original reading
			if ($fe != null) {
				throw $fe;
			}
			if ($ce != null) {
				throw $ce;
			}
			throw $e;
		}
	}

	private function decodeParser(\Zxing\Qrcode\Decoder\BitMatrixParser $parser, ?array $hints = null): DecoderResult
	{
		$version = $parser->readVersion();
		$ecLevel = $parser->readFormatInformation()->getErrorCorrectionLevel();

		// Read codewords
		$codewords = $parser->readCodewords();
		// Separate into data blocks
		$dataBlocks = DataBlock::getDataBlocks($codewords, $version, $ecLevel);

		// Count total number of data bytes
		$totalBytes = 0;
		foreach ($dataBlocks as $dataBlock) {
			$totalBytes += $dataBlock->getNumDataCodewords();
		}
		$resultBytes = fill_array(0, $totalBytes, 0);
		$resultOffset = 0;

		// Error-correct and copy data blocks together into a stream of bytes
		foreach ($dataBlocks as $dataBlock) {
			$codewordBytes = $dataBlock->getCodewords();
			$numDataCodewords = $dataBlock->getNumDataCodewords();
			$this->correctErrors($codewordBytes, $numDataCodewords);
			for ($i = 0; $i < $numDataCodewords; $i++) {
				$resultBytes[$resultOffset++] = $codewordBytes[$i];
			}
		}

		// Decode the contents of that stream of bytes
		return DecodedBitStreamParser::decode($resultBytes, $version, $ecLevel, $hints);
	}

	/**
	 * <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to
	 * correct the errors in-place using Reed-Solomon error correction.</p>
	 *
	 * @param array $codewordBytes and error correction codewords
	 * @param int $numDataCodewords of codewords that are data bytes
	 *
	 * @throws ChecksumException if error correction fails
	 */
	private function correctErrors(&$codewordBytes, int $numDataCodewords): void
	{
		$numCodewords = is_countable($codewordBytes) ? count($codewordBytes) : 0;
		// First read into an array of ints
		$codewordsInts = fill_array(0, $numCodewords, 0);
		for ($i = 0; $i < $numCodewords; $i++) {
			$codewordsInts[$i] = $codewordBytes[$i] & 0xFF;
		}
		$numECCodewords = (is_countable($codewordBytes) ? count($codewordBytes) : 0) - $numDataCodewords;
		try {
			$this->rsDecoder->decode($codewordsInts, $numECCodewords);
		} catch (ReedSolomonException) {
			throw ChecksumException::getChecksumInstance();
		}
		// Copy back into array of bytes -- only need to worry about the bytes that were data
		// We don't care about errors in the error-correction codewords
		for ($i = 0; $i < $numDataCodewords; $i++) {
			$codewordBytes[$i] = $codewordsInts[$i];
		}
	}
}

ErrorCorrectionLevel.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Decoder;

/**
 * <p>See ISO 18004:2006, 6.5.1. This enum encapsulates the four error correction levels
 * defined by the QR code standard.</p>
 *
 * @author Sean Owen
 */
class ErrorCorrectionLevel
{
	/**
  * @var \Zxing\Qrcode\Decoder\ErrorCorrectionLevel[]|null
  */
	private static ?array $FOR_BITS = null;

	public function __construct(private $bits, private $ordinal = 0)
	{
	}

	public static function Init(): void
	{
		self::$FOR_BITS = [


			new ErrorCorrectionLevel(0x00, 1), //M
			new ErrorCorrectionLevel(0x01, 0), //L
			new ErrorCorrectionLevel(0x02, 3), //H
			new ErrorCorrectionLevel(0x03, 2), //Q

		];
	}
	/** L = ~7% correction */
	//  self::$L = new ErrorCorrectionLevel(0x01);
	/** M = ~15% correction */
	//self::$M = new ErrorCorrectionLevel(0x00);
	/** Q = ~25% correction */
	//self::$Q = new ErrorCorrectionLevel(0x03);
	/** H = ~30% correction */
	//self::$H = new ErrorCorrectionLevel(0x02);
	/**
	 * @param int $bits containing the two bits encoding a QR Code's error correction level
	 *
	 * @return null|self representing the encoded error correction level
	 */
	public static function forBits(int $bits): self|null
	{
		if ($bits < 0 || $bits >= (is_countable(self::$FOR_BITS) ? count(self::$FOR_BITS) : 0)) {
			throw new \InvalidArgumentException();
		}
		$level = self::$FOR_BITS[$bits];

		// $lev = self::$$bit;
		return $level;
	}


	public function getBits()
	{
		return $this->bits;
	}

	public function toString()
	{
		return $this->bits;
	}

	public function getOrdinal()
	{
		return $this->ordinal;
	}
}

ErrorCorrectionLevel::Init();

FormatInformation.phpQR
Formulario de entrada de datos.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Decoder;

/**
 * <p>Encapsulates a QR Code's format information, including the data mask used and
 * error correction level.</p>
 *
 * @author Sean Owen
 * @see    DataMask
 * @see    ErrorCorrectionLevel
 */
final class FormatInformation
{
	public static $FORMAT_INFO_MASK_QR;

	/**
	 * See ISO 18004:2006, Annex C, Table C.1
	 */
	public static $FORMAT_INFO_DECODE_LOOKUP;
	/**
  * Offset i holds the number of 1 bits in the binary representation of i
  * @var int[]|null
  */
	private static ?array $BITS_SET_IN_HALF_BYTE = null;

	private readonly \Zxing\Qrcode\Decoder\ErrorCorrectionLevel $errorCorrectionLevel;
	private readonly int $dataMask;

	private function __construct($formatInfo)
	{
		// Bits 3,4
		$this->errorCorrectionLevel = ErrorCorrectionLevel::forBits(($formatInfo >> 3) & 0x03);
		// Bottom 3 bits
		$this->dataMask = ($formatInfo & 0x07);//(byte)
	}

	public static function Init(): void
	{
		self::$FORMAT_INFO_MASK_QR = 0x5412;
		self::$BITS_SET_IN_HALF_BYTE = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4];
		self::$FORMAT_INFO_DECODE_LOOKUP = [
			[0x5412, 0x00],
			[0x5125, 0x01],
			[0x5E7C, 0x02],
			[0x5B4B, 0x03],
			[0x45F9, 0x04],
			[0x40CE, 0x05],
			[0x4F97, 0x06],
			[0x4AA0, 0x07],
			[0x77C4, 0x08],
			[0x72F3, 0x09],
			[0x7DAA, 0x0A],
			[0x789D, 0x0B],
			[0x662F, 0x0C],
			[0x6318, 0x0D],
			[0x6C41, 0x0E],
			[0x6976, 0x0F],
			[0x1689, 0x10],
			[0x13BE, 0x11],
			[0x1CE7, 0x12],
			[0x19D0, 0x13],
			[0x0762, 0x14],
			[0x0255, 0x15],
			[0x0D0C, 0x16],
			[0x083B, 0x17],
			[0x355F, 0x18],
			[0x3068, 0x19],
			[0x3F31, 0x1A],
			[0x3A06, 0x1B],
			[0x24B4, 0x1C],
			[0x2183, 0x1D],
			[0x2EDA, 0x1E],
			[0x2BED, 0x1F],
		];
	}

	/**
	 * @param $maskedFormatInfo1 ; format info indicator, with mask still applied
	 * @param $maskedFormatInfo2 ; second copy of same info; both are checked at the same time
	 *                          to establish best match
	 *
	 * @return FormatInformation|null information about the format it specifies, or {@code null}
	 *  if doesn't seem to match any known pattern
	 *
	 * @psalm-param 0|1 $maskedFormatInfo1
	 * @psalm-param 0|1 $maskedFormatInfo2
	 */
	public static function decodeFormatInformation(int $maskedFormatInfo1, int $maskedFormatInfo2)
	{
		$formatInfo = self::doDecodeFormatInformation($maskedFormatInfo1, $maskedFormatInfo2);
		if ($formatInfo != null) {
			return $formatInfo;
		}
		// Should return null, but, some QR codes apparently
		// do not mask this info. Try again by actually masking the pattern
		// first
		return self::doDecodeFormatInformation(
			$maskedFormatInfo1 ^ self::$FORMAT_INFO_MASK_QR,
			$maskedFormatInfo2 ^ self::$FORMAT_INFO_MASK_QR
		);
	}

	/**
	 * @psalm-param 0|1 $maskedFormatInfo1
	 * @psalm-param 0|1 $maskedFormatInfo2
	 */
	private static function doDecodeFormatInformation(int $maskedFormatInfo1, int $maskedFormatInfo2): self|null
	{
		// Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing
		$bestDifference = PHP_INT_MAX;
		$bestFormatInfo = 0;
		foreach (self::$FORMAT_INFO_DECODE_LOOKUP as $decodeInfo) {
			$targetInfo = $decodeInfo[0];
			if ($targetInfo == $maskedFormatInfo1 || $targetInfo == $maskedFormatInfo2) {
				// Found an exact match
				return new FormatInformation($decodeInfo[1]);
			}
			$bitsDifference = self::numBitsDiffering($maskedFormatInfo1, $targetInfo);
			if ($bitsDifference < $bestDifference) {
				$bestFormatInfo = $decodeInfo[1];
				$bestDifference = $bitsDifference;
			}
			if ($maskedFormatInfo1 != $maskedFormatInfo2) {
				// also try the other option
				$bitsDifference = self::numBitsDiffering($maskedFormatInfo2, $targetInfo);
				if ($bitsDifference < $bestDifference) {
					$bestFormatInfo = $decodeInfo[1];
					$bestDifference = $bitsDifference;
				}
			}
		}
		// Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits
		// differing means we found a match
		if ($bestDifference <= 3) {
			return new FormatInformation($bestFormatInfo);
		}

		return null;
	}

	/**
	 * @psalm-param 0|1 $a
	 */
	public static function numBitsDiffering(int $a, $b): int
	{
		$a ^= $b; // a now has a 1 bit exactly where its bit differs with b's
		// Count bits set quickly with a series of lookups:
		return self::$BITS_SET_IN_HALF_BYTE[$a & 0x0F] +
			self::$BITS_SET_IN_HALF_BYTE[(int)(uRShift($a, 4) & 0x0F)] +
			self::$BITS_SET_IN_HALF_BYTE[(uRShift($a, 8) & 0x0F)] +
			self::$BITS_SET_IN_HALF_BYTE[(uRShift($a, 12) & 0x0F)] +
			self::$BITS_SET_IN_HALF_BYTE[(uRShift($a, 16) & 0x0F)] +
			self::$BITS_SET_IN_HALF_BYTE[(uRShift($a, 20) & 0x0F)] +
			self::$BITS_SET_IN_HALF_BYTE[(uRShift($a, 24) & 0x0F)] +
			self::$BITS_SET_IN_HALF_BYTE[(uRShift($a, 28) & 0x0F)];
	}

	public function getErrorCorrectionLevel(): ErrorCorrectionLevel
	{
		return $this->errorCorrectionLevel;
	}

	public function getDataMask(): int
	{
		return $this->dataMask;
	}

	
	public function hashCode()
	{
		return ($this->errorCorrectionLevel->ordinal() << 3) | (int)($this->dataMask);
	}

	
	public function equals($o): bool
	{
		if (!($o instanceof FormatInformation)) {
			return false;
		}
		$other = $o;

		return $this->errorCorrectionLevel == $other->errorCorrectionLevel &&
			$this->dataMask == $other->dataMask;
	}
}

FormatInformation::Init();

Mode.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Decoder;

/**
 * <p>See ISO 18004:2006, 6.4.1, Tables 2 and 3. This enum encapsulates the various modes in which
 * data can be encoded to bits in the QR code standard.</p>
 *
 * @author Sean Owen
 */
class Mode
{
	public static $TERMINATOR;
	public static $NUMERIC;
	public static $ALPHANUMERIC;
	public static $STRUCTURED_APPEND;
	public static $BYTE;
	public static $ECI;
	public static $KANJI;
	public static $FNC1_FIRST_POSITION;
	public static $FNC1_SECOND_POSITION;
	public static $HANZI;

	public function __construct(private $characterCountBitsForVersions, private $bits)
	{
	}

	public static function Init(): void
	{
		self::$TERMINATOR = new Mode([0, 0, 0], 0x00); // Not really a mode...
		self::$NUMERIC = new Mode([10, 12, 14], 0x01);
		self::$ALPHANUMERIC = new Mode([9, 11, 13], 0x02);
		self::$STRUCTURED_APPEND = new Mode([0, 0, 0], 0x03); // Not supported
		self::$BYTE = new Mode([8, 16, 16], 0x04);
		self::$ECI = new Mode([0, 0, 0], 0x07); // character counts don't apply
		self::$KANJI = new Mode([8, 10, 12], 0x08);
		self::$FNC1_FIRST_POSITION = new Mode([0, 0, 0], 0x05);
		self::$FNC1_SECOND_POSITION = new Mode([0, 0, 0], 0x09);
		/** See GBT 18284-2000; "Hanzi" is a transliteration of this mode name. */
		self::$HANZI = new Mode([8, 10, 12], 0x0D);
	}

	/**
	 * @param int $bits four bits encoding a QR Code data mode
	 *
	 * @return Mode encoded by these bits
	 * @throws \InvalidArgumentException if bits do not correspond to a known mode
	 */
	public static function forBits($bits)
	{
		return match ($bits) {
			0x0 => self::$TERMINATOR,
			0x1 => self::$NUMERIC,
			0x2 => self::$ALPHANUMERIC,
			0x3 => self::$STRUCTURED_APPEND,
			0x4 => self::$BYTE,
			0x5 => self::$FNC1_FIRST_POSITION,
			0x7 => self::$ECI,
			0x8 => self::$KANJI,
			0x9 => self::$FNC1_SECOND_POSITION,
			0xD => self::$HANZI,
			default => throw new \InvalidArgumentException(),
		};
	}

	/**
	 * @param version $version in question
	 *
	 * @return int number of bits used, in this QR Code symbol {@link Version}, to encode the
	 *         count of characters that will follow encoded in this Mode
	 */
	public function getCharacterCountBits(\Zxing\Qrcode\Decoder\version $version)
	{
		$number = $version->getVersionNumber();
		$offset = 0;
		if ($number <= 9) {
			$offset = 0;
		} elseif ($number <= 26) {
			$offset = 1;
		} else {
			$offset = 2;
		}

		return $this->characterCountBitsForVersions[$offset];
	}

	public function getBits()
	{
		return $this->bits;
	}
}

Mode::Init();

QRCodeDecoderMetaData.phpQR
Script de practica.
Abrir
Ver codigo

<?php

namespace Zxing\Qrcode\Decoder;

class QRCodeDecoderMetaData
{
	/**
	 * QRCodeDecoderMetaData constructor.
	 * @param bool $mirrored
	 */
	public function __construct(private $mirrored)
	{
	}

	public function isMirrored(): bool
	{
		return $this->mirrored;
	}
}

Version.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Qrcode\Decoder;

use Zxing\Common\BitMatrix;
use Zxing\FormatException;

/**
 * See ISO 18004:2006 Annex D
 *
 * @author Sean Owen
 */
class Version
{
	/**
	 * See ISO 18004:2006 Annex D.
	 * Element i represents the raw version bits that specify version i + 7
	 */
	private static array $VERSION_DECODE_INFO = [
		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
	];

	/**
  * @var mixed|null
  */
	private static $VERSIONS;
	private readonly float|int $totalCodewords;

	public function __construct(
		private $versionNumber,
		private $alignmentPatternCenters,
		private $ecBlocks
	) {
		$total = 0;
		if (is_array($ecBlocks)) {
			$ecCodewords = $ecBlocks[0]->getECCodewordsPerBlock();
			$ecbArray = $ecBlocks[0]->getECBlocks();
		} else {
			$ecCodewords = $ecBlocks->getECCodewordsPerBlock();
			$ecbArray = $ecBlocks->getECBlocks();
		}
		foreach ($ecbArray as $ecBlock) {
			$total += $ecBlock->getCount() * ($ecBlock->getDataCodewords() + $ecCodewords);
		}
		$this->totalCodewords = $total;
	}
	public function getVersionNumber()
	{
		return $this->versionNumber;
	}

	public function getAlignmentPatternCenters()
	{
		return $this->alignmentPatternCenters;
	}

	public function getTotalCodewords(): int|float
	{
		return $this->totalCodewords;
	}

	public function getDimensionForVersion()
	{
		return 17 + 4 * $this->versionNumber;
	}

	public function getECBlocksForLevel(ErrorCorrectionLevel $ecLevel)
	{
		return $this->ecBlocks[$ecLevel->getOrdinal()];
	}

	/**
	 * <p>Deduces version information purely from QR Code dimensions.</p>
	 *
	 * @param int $dimension dimension in modules
	 * @return Version for a QR Code of that dimension
	 * @throws FormatException if dimension is not 1 mod 4
	 */
	public static function getProvisionalVersionForDimension($dimension)
	{
		if ($dimension % 4 != 1) {
			throw new FormatException();
		}
		try {
			return self::getVersionForNumber(($dimension - 17) / 4);
		} catch (\InvalidArgumentException) {
			throw new FormatException();
		}
	}

	/**
	 * @param float|int $versionNumber
	 */
	public static function getVersionForNumber(int|float $versionNumber)
	{
		if ($versionNumber < 1 || $versionNumber > 40) {
			throw new \InvalidArgumentException();
		}
		if (!self::$VERSIONS) {
			self::$VERSIONS = self::buildVersions();
		}
		return self::$VERSIONS[$versionNumber - 1];
	}

	/**
	 * @psalm-param 0|1 $versionBits
	 */
	public static function decodeVersionInformation(int $versionBits)
	{
		$bestDifference = PHP_INT_MAX;
		$bestVersion = 0;
		for ($i = 0; $i < count(self::$VERSION_DECODE_INFO); $i++) {
			$targetVersion = self::$VERSION_DECODE_INFO[$i];
			// Do the version info bits match exactly? done.
			if ($targetVersion == $versionBits) {
				return self::getVersionForNumber($i + 7);
			}
			// Otherwise see if this is the closest to a real version info bit string
			// we have seen so far
			$bitsDifference = FormatInformation::numBitsDiffering($versionBits, $targetVersion);
			if ($bitsDifference < $bestDifference) {
				$bestVersion = $i + 7;
				$bestDifference = $bitsDifference;
			}
		}
		// We can tolerate up to 3 bits of error since no two version info codewords will
		// differ in less than 8 bits.
		if ($bestDifference <= 3) {
			return self::getVersionForNumber($bestVersion);
		}
		// If we didn't find a close enough match, fail
		return null;
	}

	/**
	 * See ISO 18004:2006 Annex E
	 */
	public function buildFunctionPattern(): BitMatrix
	{
		$dimension = self::getDimensionForVersion();
		$bitMatrix = new BitMatrix($dimension);

		// Top left finder pattern + separator + format
		$bitMatrix->setRegion(0, 0, 9, 9);
		// Top right finder pattern + separator + format
		$bitMatrix->setRegion($dimension - 8, 0, 8, 9);
		// Bottom left finder pattern + separator + format
		$bitMatrix->setRegion(0, $dimension - 8, 9, 8);

		// Alignment patterns
		$max = is_countable($this->alignmentPatternCenters) ? count($this->alignmentPatternCenters) : 0;
		for ($x = 0; $x < $max; $x++) {
			$i = $this->alignmentPatternCenters[$x] - 2;
			for ($y = 0; $y < $max; $y++) {
				if (($x == 0 && ($y == 0 || $y == $max - 1)) || ($x == $max - 1 && $y == 0)) {
					// No alignment patterns near the three finder paterns
					continue;
				}
				$bitMatrix->setRegion($this->alignmentPatternCenters[$y] - 2, $i, 5, 5);
			}
		}

		// Vertical timing pattern
		$bitMatrix->setRegion(6, 9, 1, $dimension - 17);
		// Horizontal timing pattern
		$bitMatrix->setRegion(9, 6, $dimension - 17, 1);

		if ($this->versionNumber > 6) {
			// Version info, top right
			$bitMatrix->setRegion($dimension - 11, 0, 3, 6);
			// Version info, bottom left
			$bitMatrix->setRegion(0, $dimension - 11, 6, 3);
		}

		return $bitMatrix;
	}
	/**
	 * See ISO 18004:2006 6.5.1 Table 9
	 *
	 * @return self[]
	 *
	 * @psalm-return array{0: self, 1: self, 2: self, 3: self, 4: self, 5: self, 6: self, 7: self, 8: self, 9: self, 10: self, 11: self, 12: self, 13: self, 14: self, 15: self, 16: self, 17: self, 18: self, 19: self, 20: self, 21: self, 22: self, 23: self, 24: self, 25: self, 26: self, 27: self, 28: self, 29: self, 30: self, 31: self, 32: self, 33: self, 34: self, 35: self, 36: self, 37: self, 38: self, 39: self}
	 */
	private static function buildVersions(): array
	{
		return [
			new Version(
				1,
				[],
				[new ECBlocks(7, [new ECB(1, 19)]),
					new ECBlocks(10, [new ECB(1, 16)]),
					new ECBlocks(13, [new ECB(1, 13)]),
					new ECBlocks(17, [new ECB(1, 9)])]
			),
			new Version(
				2,
				[6, 18],
				[new ECBlocks(10, [new ECB(1, 34)]),
					new ECBlocks(16, [new ECB(1, 28)]),
					new ECBlocks(22, [new ECB(1, 22)]),
					new ECBlocks(28, [new ECB(1, 16)])]
			),
			new Version(
				3,
				[6, 22],
				[ new ECBlocks(15, [new ECB(1, 55)]),
					new ECBlocks(26, [new ECB(1, 44)]),
					new ECBlocks(18, [new ECB(2, 17)]),
					new ECBlocks(22, [new ECB(2, 13)])]
			),
			new Version(
				4,
				[6, 26],
				[new ECBlocks(20, [new ECB(1, 80)]),
					new ECBlocks(18, [new ECB(2, 32)]),
					new ECBlocks(26, [new ECB(2, 24)]),
					new ECBlocks(16, [new ECB(4, 9)])]
			),
			new Version(
				5,
				[6, 30],
				[new ECBlocks(26, [new ECB(1, 108)]),
					new ECBlocks(24, [new ECB(2, 43)]),
					new ECBlocks(18, [new ECB(2, 15),
						new ECB(2, 16)]),
					new ECBlocks(22, [new ECB(2, 11),
						new ECB(2, 12)])]
			),
			new Version(
				6,
				[6, 34],
				[new ECBlocks(18, [new ECB(2, 68)]),
					new ECBlocks(16, [new ECB(4, 27)]),
					new ECBlocks(24, [new ECB(4, 19)]),
					new ECBlocks(28, [new ECB(4, 15)])]
			),
			new Version(
				7,
				[6, 22, 38],
				[new ECBlocks(20, [new ECB(2, 78)]),
					new ECBlocks(18, [new ECB(4, 31)]),
					new ECBlocks(18, [new ECB(2, 14),
						new ECB(4, 15)]),
					new ECBlocks(26, [new ECB(4, 13),
						new ECB(1, 14)])]
			),
			new Version(
				8,
				[6, 24, 42],
				[new ECBlocks(24, [new ECB(2, 97)]),
					new ECBlocks(22, [new ECB(2, 38),
						new ECB(2, 39)]),
					new ECBlocks(22, [new ECB(4, 18),
						new ECB(2, 19)]),
					new ECBlocks(26, [new ECB(4, 14),
						new ECB(2, 15)])]
			),
			new Version(
				9,
				[6, 26, 46],
				[new ECBlocks(30, [new ECB(2, 116)]),
					new ECBlocks(22, [new ECB(3, 36),
						new ECB(2, 37)]),
					new ECBlocks(20, [new ECB(4, 16),
						new ECB(4, 17)]),
					new ECBlocks(24, [new ECB(4, 12),
						new ECB(4, 13)])]
			),
			new Version(
				10,
				[6, 28, 50],
				[new ECBlocks(18, [new ECB(2, 68),
					new ECB(2, 69)]),
					new ECBlocks(26, [new ECB(4, 43),
						new ECB(1, 44)]),
					new ECBlocks(24, [new ECB(6, 19),
						new ECB(2, 20)]),
					new ECBlocks(28, [new ECB(6, 15),
						new ECB(2, 16)])]
			),
			new Version(
				11,
				[6, 30, 54],
				[new ECBlocks(20, [new ECB(4, 81)]),
					new ECBlocks(30, [new ECB(1, 50),
						new ECB(4, 51)]),
					new ECBlocks(28, [new ECB(4, 22),
						new ECB(4, 23)]),
					new ECBlocks(24, [new ECB(3, 12),
						new ECB(8, 13)])]
			),
			new Version(
				12,
				[6, 32, 58],
				[new ECBlocks(24, [new ECB(2, 92),
					new ECB(2, 93)]),
					new ECBlocks(22, [new ECB(6, 36),
						new ECB(2, 37)]),
					new ECBlocks(26, [new ECB(4, 20),
						new ECB(6, 21)]),
					new ECBlocks(28, [new ECB(7, 14),
						new ECB(4, 15)])]
			),
			new Version(
				13,
				[6, 34, 62],
				[new ECBlocks(26, [new ECB(4, 107)]),
					new ECBlocks(22, [new ECB(8, 37),
						new ECB(1, 38)]),
					new ECBlocks(24, [new ECB(8, 20),
						new ECB(4, 21)]),
					new ECBlocks(22, [new ECB(12, 11),
						new ECB(4, 12)])]
			),
			new Version(
				14,
				[6, 26, 46, 66],
				[new ECBlocks(30, [new ECB(3, 115),
					new ECB(1, 116)]),
					new ECBlocks(24, [new ECB(4, 40),
						new ECB(5, 41)]),
					new ECBlocks(20, [new ECB(11, 16),
						new ECB(5, 17)]),
					new ECBlocks(24, [new ECB(11, 12),
						new ECB(5, 13)])]
			),
			new Version(
				15,
				[6, 26, 48, 70],
				[new ECBlocks(22, [new ECB(5, 87),
					new ECB(1, 88)]),
					new ECBlocks(24, [new ECB(5, 41),
						new ECB(5, 42)]),
					new ECBlocks(30, [new ECB(5, 24),
						new ECB(7, 25)]),
					new ECBlocks(24, [new ECB(11, 12),
						new ECB(7, 13)])]
			),
			new Version(
				16,
				[6, 26, 50, 74],
				[new ECBlocks(24, [new ECB(5, 98),
					new ECB(1, 99)]),
					new ECBlocks(28, [new ECB(7, 45),
						new ECB(3, 46)]),
					new ECBlocks(24, [new ECB(15, 19),
						new ECB(2, 20)]),
					new ECBlocks(30, [new ECB(3, 15),
						new ECB(13, 16)])]
			),
			new Version(
				17,
				[6, 30, 54, 78],
				[new ECBlocks(28, [new ECB(1, 107),
					new ECB(5, 108)]),
					new ECBlocks(28, [new ECB(10, 46),
						new ECB(1, 47)]),
					new ECBlocks(28, [new ECB(1, 22),
						new ECB(15, 23)]),
					new ECBlocks(28, [new ECB(2, 14),
						new ECB(17, 15)])]
			),
			new Version(
				18,
				[6, 30, 56, 82],
				[new ECBlocks(30, [new ECB(5, 120),
					new ECB(1, 121)]),
					new ECBlocks(26, [new ECB(9, 43),
						new ECB(4, 44)]),
					new ECBlocks(28, [new ECB(17, 22),
						new ECB(1, 23)]),
					new ECBlocks(28, [new ECB(2, 14),
						new ECB(19, 15)])]
			),
			new Version(
				19,
				[6, 30, 58, 86],
				[new ECBlocks(28, [new ECB(3, 113),
					new ECB(4, 114)]),
					new ECBlocks(26, [new ECB(3, 44),
						new ECB(11, 45)]),
					new ECBlocks(26, [new ECB(17, 21),
						new ECB(4, 22)]),
					new ECBlocks(26, [new ECB(9, 13),
						new ECB(16, 14)])]
			),
			new Version(
				20,
				[6, 34, 62, 90],
				[new ECBlocks(28, [new ECB(3, 107),
					new ECB(5, 108)]),
					new ECBlocks(26, [new ECB(3, 41),
						new ECB(13, 42)]),
					new ECBlocks(30, [new ECB(15, 24),
						new ECB(5, 25)]),
					new ECBlocks(28, [new ECB(15, 15),
						new ECB(10, 16)])]
			),
			new Version(
				21,
				[6, 28, 50, 72, 94],
				[ new ECBlocks(28, [new ECB(4, 116),
					new ECB(4, 117)]),
					new ECBlocks(26, [new ECB(17, 42)]),
					new ECBlocks(28, [new ECB(17, 22),
						new ECB(6, 23)]),
					new ECBlocks(30, [new ECB(19, 16),
						new ECB(6, 17)])]
			),
			new Version(
				22,
				[6, 26, 50, 74, 98],
				[new ECBlocks(28, [new ECB(2, 111),
					new ECB(7, 112)]),
					new ECBlocks(28, [new ECB(17, 46)]),
					new ECBlocks(30, [new ECB(7, 24),
						new ECB(16, 25)]),
					new ECBlocks(24, [new ECB(34, 13)])]
			),
			new Version(
				23,
				[6, 30, 54, 78, 102],
				new ECBlocks(30, [new ECB(4, 121),
					new ECB(5, 122)]),
				new ECBlocks(28, [new ECB(4, 47),
					new ECB(14, 48)]),
				new ECBlocks(30, [new ECB(11, 24),
					new ECB(14, 25)]),
				new ECBlocks(30, [new ECB(16, 15),
					new ECB(14, 16)])
			),
			new Version(
				24,
				[6, 28, 54, 80, 106],
				[new ECBlocks(30, [new ECB(6, 117),
					new ECB(4, 118)]),
					new ECBlocks(28, [new ECB(6, 45),
						new ECB(14, 46)]),
					new ECBlocks(30, [new ECB(11, 24),
						new ECB(16, 25)]),
					new ECBlocks(30, [new ECB(30, 16),
						new ECB(2, 17)])]
			),
			new Version(
				25,
				[6, 32, 58, 84, 110],
				[new ECBlocks(26, [new ECB(8, 106),
					new ECB(4, 107)]),
					new ECBlocks(28, [new ECB(8, 47),
						new ECB(13, 48)]),
					new ECBlocks(30, [new ECB(7, 24),
						new ECB(22, 25)]),
					new ECBlocks(30, [new ECB(22, 15),
						new ECB(13, 16)])]
			),
			new Version(
				26,
				[6, 30, 58, 86, 114],
				[new ECBlocks(28, [new ECB(10, 114),
					new ECB(2, 115)]),
					new ECBlocks(28, [new ECB(19, 46),
						new ECB(4, 47)]),
					new ECBlocks(28, [new ECB(28, 22),
						new ECB(6, 23)]),
					new ECBlocks(30, [new ECB(33, 16),
						new ECB(4, 17)])]
			),
			new Version(
				27,
				[6, 34, 62, 90, 118],
				[new ECBlocks(30, [new ECB(8, 122),
					new ECB(4, 123)]),
					new ECBlocks(28, [new ECB(22, 45),
						new ECB(3, 46)]),
					new ECBlocks(30, [new ECB(8, 23),
						new ECB(26, 24)]),
					new ECBlocks(30, [new ECB(12, 15),
						new ECB(28, 16)])]
			),
			new Version(
				28,
				[6, 26, 50, 74, 98, 122],
				[new ECBlocks(30, [new ECB(3, 117),
					new ECB(10, 118)]),
					new ECBlocks(28, [new ECB(3, 45),
						new ECB(23, 46)]),
					new ECBlocks(30, [new ECB(4, 24),
						new ECB(31, 25)]),
					new ECBlocks(30, [new ECB(11, 15),
						new ECB(31, 16)])]
			),
			new Version(
				29,
				[6, 30, 54, 78, 102, 126],
				[new ECBlocks(30, [new ECB(7, 116),
					new ECB(7, 117)]),
					new ECBlocks(28, [new ECB(21, 45),
						new ECB(7, 46)]),
					new ECBlocks(30, [new ECB(1, 23),
						new ECB(37, 24)]),
					new ECBlocks(30, [new ECB(19, 15),
						new ECB(26, 16)])]
			),
			new Version(
				30,
				[6, 26, 52, 78, 104, 130],
				[new ECBlocks(30, [new ECB(5, 115),
					new ECB(10, 116)]),
					new ECBlocks(28, [new ECB(19, 47),
						new ECB(10, 48)]),
					new ECBlocks(30, [new ECB(15, 24),
						new ECB(25, 25)]),
					new ECBlocks(30, [new ECB(23, 15),
						new ECB(25, 16)])]
			),
			new Version(
				31,
				[6, 30, 56, 82, 108, 134],
				[new ECBlocks(30, [new ECB(13, 115),
					new ECB(3, 116)]),
					new ECBlocks(28, [new ECB(2, 46),
						new ECB(29, 47)]),
					new ECBlocks(30, [new ECB(42, 24),
						new ECB(1, 25)]),
					new ECBlocks(30, [new ECB(23, 15),
						new ECB(28, 16)])]
			),
			new Version(
				32,
				[6, 34, 60, 86, 112, 138],
				[new ECBlocks(30, [new ECB(17, 115)]),
					new ECBlocks(28, [new ECB(10, 46),
						new ECB(23, 47)]),
					new ECBlocks(30, [new ECB(10, 24),
						new ECB(35, 25)]),
					new ECBlocks(30, [new ECB(19, 15),
						new ECB(35, 16)])]
			),
			new Version(
				33,
				[6, 30, 58, 86, 114, 142],
				[new ECBlocks(30, [new ECB(17, 115),
					new ECB(1, 116)]),
					new ECBlocks(28, [new ECB(14, 46),
						new ECB(21, 47)]),
					new ECBlocks(30, [new ECB(29, 24),
						new ECB(19, 25)]),
					new ECBlocks(30, [new ECB(11, 15),
						new ECB(46, 16)])]
			),
			new Version(
				34,
				[6, 34, 62, 90, 118, 146],
				[new ECBlocks(30, [new ECB(13, 115),
					new ECB(6, 116)]),
					new ECBlocks(28, [new ECB(14, 46),
						new ECB(23, 47)]),
					new ECBlocks(30, [new ECB(44, 24),
						new ECB(7, 25)]),
					new ECBlocks(30, [new ECB(59, 16),
						new ECB(1, 17)])]
			),
			new Version(
				35,
				[6, 30, 54, 78, 102, 126, 150],
				[new ECBlocks(30, [new ECB(12, 121),
					new ECB(7, 122)]),
					new ECBlocks(28, [new ECB(12, 47),
						new ECB(26, 48)]),
					new ECBlocks(30, [new ECB(39, 24),
						new ECB(14, 25)]),
					new ECBlocks(30, [new ECB(22, 15),
						new ECB(41, 16)])]
			),
			new Version(
				36,
				[6, 24, 50, 76, 102, 128, 154],
				[new ECBlocks(30, [new ECB(6, 121),
					new ECB(14, 122)]),
					new ECBlocks(28, [new ECB(6, 47),
						new ECB(34, 48)]),
					new ECBlocks(30, [new ECB(46, 24),
						new ECB(10, 25)]),
					new ECBlocks(30, [new ECB(2, 15),
						new ECB(64, 16)])]
			),
			new Version(
				37,
				[6, 28, 54, 80, 106, 132, 158],
				[new ECBlocks(30, [new ECB(17, 122),
					new ECB(4, 123)]),
					new ECBlocks(28, [new ECB(29, 46),
						new ECB(14, 47)]),
					new ECBlocks(30, [new ECB(49, 24),
						new ECB(10, 25)]),
					new ECBlocks(30, [new ECB(24, 15),
						new ECB(46, 16)])]
			),
			new Version(
				38,
				[6, 32, 58, 84, 110, 136, 162],
				[new ECBlocks(30, [new ECB(4, 122),
					new ECB(18, 123)]),
					new ECBlocks(28, [new ECB(13, 46),
						new ECB(32, 47)]),
					new ECBlocks(30, [new ECB(48, 24),
						new ECB(14, 25)]),
					new ECBlocks(30, [new ECB(42, 15),
						new ECB(32, 16)])]
			),
			new Version(
				39,
				[6, 26, 54, 82, 110, 138, 166],
				[new ECBlocks(30, [new ECB(20, 117),
					new ECB(4, 118)]),
					new ECBlocks(28, [new ECB(40, 47),
						new ECB(7, 48)]),
					new ECBlocks(30, [new ECB(43, 24),
						new ECB(22, 25)]),
					new ECBlocks(30, [new ECB(10, 15),
						new ECB(67, 16)])]
			),
			new Version(
				40,
				[6, 30, 58, 86, 114, 142, 170],
				[new ECBlocks(30, [new ECB(19, 118),
					new ECB(6, 119)]),
					new ECBlocks(28, [new ECB(18, 47),
						new ECB(31, 48)]),
					new ECBlocks(30, [new ECB(34, 24),
						new ECB(34, 25)]),
					new ECBlocks(30, [new ECB(20, 15),
						new ECB(61, 16)])]
			)
		];
	}
}

/**
 * <p>Encapsulates a set of error-correction blocks in one symbol version. Most versions will
 * use blocks of differing sizes within one version, so, this encapsulates the parameters for
 * each set of blocks. It also holds the number of error-correction codewords per block since it
 * will be the same across all blocks within one version.</p>
 */
final class ECBlocks
{
	public function __construct(private $ecCodewordsPerBlock, private $ecBlocks)
	{
	}

	public function getECCodewordsPerBlock()
	{
		return $this->ecCodewordsPerBlock;
	}

	public function getNumBlocks()
	{
		$total = 0;
		foreach ($this->ecBlocks as $ecBlock) {
			$total += $ecBlock->getCount();
		}
		return $total;
	}

	public function getTotalECCodewords()
	{
		return $this->ecCodewordsPerBlock * $this->getNumBlocks();
	}

	public function getECBlocks()
	{
		return $this->ecBlocks;
	}
}

/**
 * <p>Encapsualtes the parameters for one error-correction block in one symbol version.
 * This includes the number of data codewords, and the number of times a block with these
 * parameters is used consecutively in the QR code version's format.</p>
 */
final class ECB
{
	public function __construct(private $count, private $dataCodewords)
	{
	}

	public function getCount()
	{
		return $this->count;
	}

	public function getDataCodewords()
	{
		return $this->dataCodewords;
	}

	public function toString(): string
	{
		die('Version ECB toString()');
		//  return parent::$versionNumber;
	}
}

AlignmentPattern.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Detector;

use Zxing\ResultPoint;

/**
 * <p>Encapsulates an alignment pattern, which are the smaller square patterns found in
 * all but the simplest QR Codes.</p>
 *
 * @author Sean Owen
 */
final class AlignmentPattern extends ResultPoint
{
	public function __construct($posX, $posY, private $estimatedModuleSize)
	{
		parent::__construct($posX, $posY);
	}

	/**
	 * <p>Determines if this alignment pattern "about equals" an alignment pattern at the stated
	 * position and size -- meaning, it is at nearly the same center with nearly the same size.</p>
	 */
	public function aboutEquals($moduleSize, $i, $j): bool
	{
		if (abs($i - $this->getY()) <= $moduleSize && abs($j - $this->getX()) <= $moduleSize) {
			$moduleSizeDiff = abs($moduleSize - $this->estimatedModuleSize);

			return $moduleSizeDiff <= 1.0 || $moduleSizeDiff <= $this->estimatedModuleSize;
		}

		return false;
	}

	/**
	 * Combines this object's current estimate of a finder pattern position and module size
	 * with a new estimate. It returns a new {@code FinderPattern} containing an average of the two.
	 */
	public function combineEstimate($i, $j, $newModuleSize): \Zxing\Qrcode\Detector\AlignmentPattern
	{
		$combinedX = ($this->getX() + $j) / 2.0;
		$combinedY = ($this->getY() + $i) / 2.0;
		$combinedModuleSize = ($this->estimatedModuleSize + $newModuleSize) / 2.0;

		return new AlignmentPattern($combinedX, $combinedY, $combinedModuleSize);
	}
}

AlignmentPatternFinder.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Detector;

use Zxing\NotFoundException;

/**
 * <p>This class attempts to find alignment patterns in a QR Code. Alignment patterns look like finder
 * patterns but are smaller and appear at regular intervals throughout the image.</p>
 *
 * <p>At the moment this only looks for the bottom-right alignment pattern.</p>
 *
 * <p>This is mostly a simplified copy of {@link FinderPatternFinder}. It is copied,
 * pasted and stripped down here for maximum performance but does unfortunately duplicate
 * some code.</p>
 *
 * <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.</p>
 *
 * @author Sean Owen
 */
final class AlignmentPatternFinder
{
	private array $possibleCenters = [];
	private array $crossCheckStateCount = [];

	/**
	 * <p>Creates a finder that will look in a portion of the whole image.</p>
	 *
	 * @param \Imagick image      $image to search
	 * @param int left     $startX column from which to start searching
	 * @param int top     $startY row from which to start searching
	 * @param float width      $width of region to search
	 * @param float height     $height of region to search
	 * @param float estimated $moduleSize module size so far
	 */
	public function __construct(private $image, private $startX, private $startY, private $width, private $height, private $moduleSize, private $resultPointCallback)
	{
	}

	/**
	 * <p>This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since
	 * it's pretty performance-critical and so is written to be fast foremost.</p>
	 *
	 * @return {@link AlignmentPattern} if found
	 * @throws NotFoundException if not found
	 */
	public function find()
	{
		$startX = $this->startX;
		$height = $this->height;
		$maxJ = $startX + $this->width;
		$middleI = $this->startY + ($height / 2);
		// We are looking for black/white/black modules in 1:1:1 ratio;
		// this tracks the number of black/white/black modules seen so far
		$stateCount = [];
		for ($iGen = 0; $iGen < $height; $iGen++) {
			// Search from middle outwards
			$i = $middleI + (($iGen & 0x01) == 0 ? ($iGen + 1) / 2 : -(($iGen + 1) / 2));
			$i = (int)($i);
			$stateCount[0] = 0;
			$stateCount[1] = 0;
			$stateCount[2] = 0;
			$j = $startX;
			// Burn off leading white pixels before anything else; if we start in the middle of
			// a white run, it doesn't make sense to count its length, since we don't know if the
			// white run continued to the left of the start point
			while ($j < $maxJ && !$this->image->get($j, $i)) {
				$j++;
			}
			$currentState = 0;
			while ($j < $maxJ) {
				if ($this->image->get($j, $i)) {
					// Black pixel
					if ($currentState == 1) { // Counting black pixels
						$stateCount[$currentState]++;
					} else { // Counting white pixels
						if ($currentState == 2) { // A winner?
							if ($this->foundPatternCross($stateCount)) { // Yes
								$confirmed = $this->handlePossibleCenter($stateCount, $i, $j);
								if ($confirmed != null) {
									return $confirmed;
								}
							}
							$stateCount[0] = $stateCount[2];
							$stateCount[1] = 1;
							$stateCount[2] = 0;
							$currentState = 1;
						} else {
							$stateCount[++$currentState]++;
						}
					}
				} else { // White pixel
					if ($currentState == 1) { // Counting black pixels
						$currentState++;
					}
					$stateCount[$currentState]++;
				}
				$j++;
			}
			if ($this->foundPatternCross($stateCount)) {
				$confirmed = $this->handlePossibleCenter($stateCount, $i, $maxJ);
				if ($confirmed != null) {
					return $confirmed;
				}
			}
		}

		// Hmm, nothing we saw was observed and confirmed twice. If we had
		// any guess at all, return it.
		if (count($this->possibleCenters)) {
			return $this->possibleCenters[0];
		}

		throw  new NotFoundException("Bottom right alignment pattern not found");
	}

	/**
	 * @param int $stateCount count of black/white/black pixels just read
	 *
	 * @return bool iff the proportions of the counts is close enough to the 1/1/1 ratios used by alignment patterns to be considered a match
	 */
	private function foundPatternCross($stateCount): bool
	{
		$moduleSize = $this->moduleSize;
		$maxVariance = $moduleSize / 2.0;
		for ($i = 0; $i < 3; $i++) {
			if (abs($moduleSize - $stateCount[$i]) >= $maxVariance) {
				return false;
			}
		}

		return true;
	}

	/**
	 * <p>This is called when a horizontal scan finds a possible alignment pattern. It will
	 * cross check with a vertical scan, and if successful, will see if this pattern had been
	 * found on a previous horizontal scan. If so, we consider it confirmed and conclude we have
	 * found the alignment pattern.</p>
	 *
	 * @param array $stateCount state module counts from horizontal scan
	 * @param int $i where alignment pattern may be found
	 * @param int $j number of possible alignment pattern in row
	 *
	 * @return {@link AlignmentPattern} if we have found the same pattern twice, or null if not
	 */
	private function handlePossibleCenter($stateCount, $i, $j)
	{
		$stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2];
		$centerJ = self::centerFromEnd($stateCount, $j);
		$centerI = $this->crossCheckVertical($i, (int)$centerJ, 2 * $stateCount[1], $stateCountTotal);
		if (!is_nan($centerI)) {
			$estimatedModuleSize = (float)($stateCount[0] + $stateCount[1] + $stateCount[2]) / 3.0;
			foreach ($this->possibleCenters as $center) {
				// Look for about the same center and module size:
				if ($center->aboutEquals($estimatedModuleSize, $centerI, $centerJ)) {
					return $center->combineEstimate($centerI, $centerJ, $estimatedModuleSize);
				}
			}
			// Hadn't found this before; save it
			$point = new AlignmentPattern($centerJ, $centerI, $estimatedModuleSize);
			$this->possibleCenters[] = $point;
			if ($this->resultPointCallback != null) {
				$this->resultPointCallback->foundPossibleResultPoint($point);
			}
		}

		return null;
	}

	/**
	 * Given a count of black/white/black pixels just seen and an end position,
	 * figures the location of the center of this black/white/black run.
	 */
	private static function centerFromEnd(array $stateCount, int $end)
	{
		return (float)($end - $stateCount[2]) - $stateCount[1] / 2.0;
	}

	/**
	 * <p>After a horizontal scan finds a potential alignment pattern, this method
	 * "cross-checks" by scanning down vertically through the center of the possible
	 * alignment pattern to see if the same proportion is detected.</p>
	 *
	 * @param int $startI row   where an alignment pattern was detected
	 * @param float $centerJ center  of the section that appears to cross an alignment pattern
	 * @param int $maxCount maximum reasonable number of modules that should be
	 *                 observed in any reading state, based on the results of the horizontal scan
	 *
	 * @return float vertical center of alignment pattern, or {@link Float#NaN} if not found
	 */
	private function crossCheckVertical(
		int $startI,
		int $centerJ,
		$maxCount,
		$originalStateCountTotal
	) {
		$image = $this->image;

		$maxI = $image->getHeight();
		$stateCount = $this->crossCheckStateCount;
		$stateCount[0] = 0;
		$stateCount[1] = 0;
		$stateCount[2] = 0;

		// Start counting up from center
		$i = $startI;
		while ($i >= 0 && $image->get($centerJ, $i) && $stateCount[1] <= $maxCount) {
			$stateCount[1]++;
			$i--;
		}
		// If already too many modules in this state or ran off the edge:
		if ($i < 0 || $stateCount[1] > $maxCount) {
			return NAN;
		}
		while ($i >= 0 && !$image->get($centerJ, $i) && $stateCount[0] <= $maxCount) {
			$stateCount[0]++;
			$i--;
		}
		if ($stateCount[0] > $maxCount) {
			return NAN;
		}

		// Now also count down from center
		$i = $startI + 1;
		while ($i < $maxI && $image->get($centerJ, $i) && $stateCount[1] <= $maxCount) {
			$stateCount[1]++;
			$i++;
		}
		if ($i == $maxI || $stateCount[1] > $maxCount) {
			return NAN;
		}
		while ($i < $maxI && !$image->get($centerJ, $i) && $stateCount[2] <= $maxCount) {
			$stateCount[2]++;
			$i++;
		}
		if ($stateCount[2] > $maxCount) {
			return NAN;
		}

		$stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2];
		if (5 * abs($stateCountTotal - $originalStateCountTotal) >= 2 * $originalStateCountTotal) {
			return NAN;
		}

		return $this->foundPatternCross($stateCount) ? self::centerFromEnd($stateCount, $i) : NAN;
	}
}

Detector.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Qrcode\Detector;

use Zxing\Common\BitMatrix;
use Zxing\Common\Detector\MathUtils;
use Zxing\Common\DetectorResult;
use Zxing\Common\GridSampler;
use Zxing\Common\PerspectiveTransform;
use Zxing\DecodeHintType;
use Zxing\FormatException;
use Zxing\NotFoundException;
use Zxing\Qrcode\Decoder\Version;
use Zxing\ResultPoint;
use Zxing\ResultPointCallback;

/**
 * <p>Encapsulates logic that can detect a QR Code in an image, even if the QR Code
 * is rotated or skewed, or partially obscured.</p>
 *
 * @author Sean Owen
 */
class Detector
{
	private $resultPointCallback;

	public function __construct(private BitMatrix $image)
	{
	}

	/**
	 * <p>Detects a QR Code in an image.</p>
	 *
	 * @param array|null optional $hints hints to detector
	 *
	 * @return {@link DetectorResult} encapsulating results of detecting a QR Code
	 * @throws NotFoundException if QR Code cannot be found
	 * @throws FormatException if a QR Code cannot be decoded
	 */
	final public function detect(?array $hints = null): DetectorResult
	{/*Map<DecodeHintType,?>*/

		$resultPointCallback = ($hints !== null && array_key_exists('NEED_RESULT_POINT_CALLBACK', $hints)) ?
			$hints['NEED_RESULT_POINT_CALLBACK'] : null;
		/* resultPointCallback = hints == null ? null :
				(ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);*/
		$finder = new FinderPatternFinder($this->image, $resultPointCallback);
		$info = $finder->find($hints);

		return $this->processFinderPatternInfo($info);
	}

	final protected function processFinderPatternInfo(FinderPatternInfo $info): \Zxing\Common\DetectorResult
	{
		$topLeft = $info->getTopLeft();
		$topRight = $info->getTopRight();
		$bottomLeft = $info->getBottomLeft();

		$moduleSize = (float)$this->calculateModuleSize($topLeft, $topRight, $bottomLeft);
		if ($moduleSize < 1.0) {
			throw new NotFoundException("Module size $moduleSize < 1.0");
		}
		$dimension = (int)self::computeDimension($topLeft, $topRight, $bottomLeft, $moduleSize);
		$provisionalVersion = \Zxing\Qrcode\Decoder\Version::getProvisionalVersionForDimension($dimension);
		$modulesBetweenFPCenters = $provisionalVersion->getDimensionForVersion() - 7;

		$alignmentPattern = null;
		// Anything above version 1 has an alignment pattern
		if ((is_countable($provisionalVersion->getAlignmentPatternCenters()) ? count($provisionalVersion->getAlignmentPatternCenters()) : 0) > 0) {

			// Guess where a "bottom right" finder pattern would have been
			$bottomRightX = $topRight->getX() - $topLeft->getX() + $bottomLeft->getX();
			$bottomRightY = $topRight->getY() - $topLeft->getY() + $bottomLeft->getY();

			// Estimate that alignment pattern is closer by 3 modules
			// from "bottom right" to known top left location
			$correctionToTopLeft = 1.0 - 3.0 / (float)$modulesBetweenFPCenters;
			$estAlignmentX = (int)round($topLeft->getX() + $correctionToTopLeft * ($bottomRightX - $topLeft->getX()));
			$estAlignmentY = (int)round($topLeft->getY() + $correctionToTopLeft * ($bottomRightY - $topLeft->getY()));

			// Kind of arbitrary -- expand search radius before giving up
			for ($i = 4; $i <= 16; $i = $i << 1) { //??????????
				try {
					$alignmentPattern = $this->findAlignmentInRegion(
						$moduleSize,
						$estAlignmentX,
						$estAlignmentY,
						(float)$i
					);
					break;
				} catch (NotFoundException $e) {
					// try next round
					$alignmentPattern = null;
				}
			}
			// If we didn't find alignment pattern... well try anyway without it
		}

		$transform = self::createTransform($topLeft, $topRight, $bottomLeft, $alignmentPattern, $dimension);

		$bits = self::sampleGrid($this->image, $transform, $dimension);

		$points = [];
		if ($alignmentPattern == null) {
			$points = [$bottomLeft, $topLeft, $topRight];
		} else {
			// die('$points = new ResultPoint[]{bottomLeft, topLeft, topRight, alignmentPattern};');
			$points = [$bottomLeft, $topLeft, $topRight, $alignmentPattern];
		}

		return new DetectorResult($bits, $points);
	}

	/**
	 * <p>Detects a QR Code in an image.</p>
	 *
	 * @return {@link DetectorResult} encapsulating results of detecting a QR Code
	 * @throws NotFoundException if QR Code cannot be found
	 * @throws FormatException if a QR Code cannot be decoded
	 */

	/**
	 * <p>Computes an average estimated module size based on estimated derived from the positions
	 * of the three finder patterns.</p>
	 *
	 * @param FinderPattern $topLeft detected    top-left finder pattern center
	 * @param FinderPattern $topRight detected   top-right finder pattern center
	 * @param FinderPattern $bottomLeft detected bottom-left finder pattern center
	 *
	 * @return float estimated module size
	 */
	final protected function calculateModuleSize($topLeft, $topRight, $bottomLeft): float
	{
		// Take the average
		return ($this->calculateModuleSizeOneWay($topLeft, $topRight) +
			$this->calculateModuleSizeOneWay($topLeft, $bottomLeft)) / 2.0;
	}

	/**
	 * <p>Estimates module size based on two finder patterns -- it uses
	 * {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the
	 * width of each, measuring along the axis between their centers.</p>
	 */
	private function calculateModuleSizeOneWay(FinderPattern $pattern, FinderPattern $otherPattern): float
	{
		$moduleSizeEst1 = $this->sizeOfBlackWhiteBlackRunBothWays(
			(int)$pattern->getX(),
			(int)$pattern->getY(),
			(int)$otherPattern->getX(),
			(int)$otherPattern->getY()
		);
		$moduleSizeEst2 = $this->sizeOfBlackWhiteBlackRunBothWays(
			(int)$otherPattern->getX(),
			(int)$otherPattern->getY(),
			(int)$pattern->getX(),
			(int)$pattern->getY()
		);
		if (is_nan($moduleSizeEst1)) {
			return $moduleSizeEst2 / 7.0;
		}
		if (is_nan($moduleSizeEst2)) {
			return $moduleSizeEst1 / 7.0;
		}
		// Average them, and divide by 7 since we've counted the width of 3 black modules,
		// and 1 white and 1 black module on either side. Ergo, divide sum by 14.
		return ($moduleSizeEst1 + $moduleSizeEst2) / 14.0;
	}

	/**
	 * See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of
	 * a finder pattern by looking for a black-white-black run from the center in the direction
	 * of another po$(another finder pattern center), and in the opposite direction too.</p>
	 */
	private function sizeOfBlackWhiteBlackRunBothWays(int $fromX, int $fromY, int $toX, int $toY): float
	{
		$result = $this->sizeOfBlackWhiteBlackRun($fromX, $fromY, $toX, $toY);

		// Now count other way -- don't run off image though of course
		$scale = 1.0;
		$otherToX = $fromX - ($toX - $fromX);
		if ($otherToX < 0) {
			$scale = (float)$fromX / (float)($fromX - $otherToX);
			$otherToX = 0;
		} elseif ($otherToX >= $this->image->getWidth()) {
			$scale = (float)($this->image->getWidth() - 1 - $fromX) / (float)($otherToX - $fromX);
			$otherToX = $this->image->getWidth() - 1;
		}
		$otherToY = (int)($fromY - ($toY - $fromY) * $scale);

		$scale = 1.0;
		if ($otherToY < 0) {
			$scale = (float)$fromY / (float)($fromY - $otherToY);
			$otherToY = 0;
		} elseif ($otherToY >= $this->image->getHeight()) {
			$scale = (float)($this->image->getHeight() - 1 - $fromY) / (float)($otherToY - $fromY);
			$otherToY = $this->image->getHeight() - 1;
		}
		$otherToX = (int)($fromX + ($otherToX - $fromX) * $scale);

		$result += $this->sizeOfBlackWhiteBlackRun($fromX, $fromY, $otherToX, $otherToY);

		// Middle pixel is double-counted this way; subtract 1
		return $result - 1.0;
	}

	/**
	 * <p>This method traces a line from a po$in the image, in the direction towards another point.
	 * It begins in a black region, and keeps going until it finds white, then black, then white again.
	 * It reports the distance from the start to this point.</p>
	 *
	 * <p>This is used when figuring out how wide a finder pattern is, when the finder pattern
	 * may be skewed or rotated.</p>
	 */
	private function sizeOfBlackWhiteBlackRun(int $fromX, int $fromY, int $toX, int|float $toY): float
	{
		// Mild variant of Bresenham's algorithm;
		// see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
		$steep = abs($toY - $fromY) > abs($toX - $fromX);
		if ($steep) {
			$temp = $fromX;
			$fromX = $fromY;
			$fromY = $temp;
			$temp = $toX;
			$toX = $toY;
			$toY = $temp;
		}

		$dx = abs($toX - $fromX);
		$dy = abs($toY - $fromY);
		$error = -$dx / 2;
		$xstep = $fromX < $toX ? 1 : -1;
		$ystep = $fromY < $toY ? 1 : -1;

		// In black pixels, looking for white, first or second time.
		$state = 0;
		// Loop up until x == toX, but not beyond
		$xLimit = $toX + $xstep;
		for ($x = $fromX, $y = $fromY; $x != $xLimit; $x += $xstep) {
			$realX = $steep ? $y : $x;
			$realY = $steep ? $x : $y;

			// Does current pixel mean we have moved white to black or vice versa?
			// Scanning black in state 0,2 and white in state 1, so if we find the wrong
			// color, advance to next state or end if we are in state 2 already
			if (($state == 1) == $this->image->get($realX, $realY)) {
				if ($state == 2) {
					return MathUtils::distance($x, $y, $fromX, $fromY);
				}
				$state++;
			}

			$error += $dy;
			if ($error > 0) {
				if ($y == $toY) {
					break;
				}
				$y += $ystep;
				$error -= $dx;
			}
		}
		// Found black-white-black; give the benefit of the doubt that the next pixel outside the image
		// is "white" so this last po$at (toX+xStep,toY) is the right ending. This is really a
		// small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this.
		if ($state == 2) {
			return MathUtils::distance($toX + $xstep, $toY, $fromX, $fromY);
		}

		// else we didn't find even black-white-black; no estimate is really possible
		return NAN;
	}

	/**
	 * <p>Computes the dimension (number of modules on a size) of the QR Code based on the position
	 * of the finder patterns and estimated module size.</p>
	 */
	private static function computeDimension(
		$topLeft,
		$topRight,
		$bottomLeft,
		float $moduleSize
	): int {
		$tltrCentersDimension = MathUtils::round(ResultPoint::distance($topLeft, $topRight) / $moduleSize);
		$tlblCentersDimension = MathUtils::round(ResultPoint::distance($topLeft, $bottomLeft) / $moduleSize);
		$dimension = (int)round((($tltrCentersDimension + $tlblCentersDimension) / 2) + 7);
		switch ($dimension & 0x03) { // mod 4
			case 0:
				$dimension++;
				break;
				// 1? do nothing
			case 2:
				$dimension--;
				break;
			case 3:
				throw new NotFoundException("Dimension ($dimension) mod 4 == 3 unusable");
		}

		return (int)round($dimension);
	}

	/**
	 * <p>Attempts to locate an alignment pattern in a limited region of the image, which is
	 * guessed to contain it. This method uses {@link AlignmentPattern}.</p>
	 *
	 * @param float $overallEstModuleSize module size so far
	 * @param int $estAlignmentX coordinate of center of area probably containing alignment pattern
	 * @param int $estAlignmentY coordinate of above
	 * @param float      $allowanceFactor of pixels in all directions to search from the center
	 *
	 * @return {@link AlignmentPattern} if found, or null otherwise
	 * @throws NotFoundException if an unexpected error occurs during detection
	 */
	final protected function findAlignmentInRegion(
		float $overallEstModuleSize,
		int $estAlignmentX,
		int $estAlignmentY,
		float $allowanceFactor
	) {
		// Look for an alignment pattern (3 modules in size) around where it
		// should be
		$allowance = (int)($allowanceFactor * $overallEstModuleSize);
		$alignmentAreaLeftX = max(0, $estAlignmentX - $allowance);
		$alignmentAreaRightX = min($this->image->getWidth() - 1, $estAlignmentX + $allowance);
		if ($alignmentAreaRightX - $alignmentAreaLeftX < $overallEstModuleSize * 3) {
			throw new NotFoundException("Alignment area right smaller than overall module size: $alignmentAreaRightX - $alignmentAreaLeftX < $overallEstModuleSize * 3. Allowance: $allowance, estimage of x: $estAlignmentX");
		}

		$alignmentAreaTopY = max(0, $estAlignmentY - $allowance);
		$alignmentAreaBottomY = min($this->image->getHeight() - 1, $estAlignmentY + $allowance);
		if ($alignmentAreaBottomY - $alignmentAreaTopY < $overallEstModuleSize * 3) {
			throw new NotFoundException("Alignment area bottom smaller than overall module size: $alignmentAreaBottomY - $alignmentAreaTopY < $overallEstModuleSize * 3. Allowance: $allowance, estimage of y: $estAlignmentY");
		}

		$alignmentFinder =
			new AlignmentPatternFinder(
				$this->image,
				$alignmentAreaLeftX,
				$alignmentAreaTopY,
				$alignmentAreaRightX - $alignmentAreaLeftX,
				$alignmentAreaBottomY - $alignmentAreaTopY,
				$overallEstModuleSize,
				$this->resultPointCallback
			);

		return $alignmentFinder->find();
	}

	private static function createTransform(
		$topLeft,
		$topRight,
		$bottomLeft,
		$alignmentPattern,
		int $dimension
	): PerspectiveTransform {
		$dimMinusThree = (float)$dimension - 3.5;
		$bottomRightX = 0.0;
		$bottomRightY = 0.0;
		$sourceBottomRightX = 0.0;
		$sourceBottomRightY = 0.0;
		if ($alignmentPattern != null) {
			$bottomRightX = $alignmentPattern->getX();
			$bottomRightY = $alignmentPattern->getY();
			$sourceBottomRightX = $dimMinusThree - 3.0;
			$sourceBottomRightY = $sourceBottomRightX;
		} else {
			// Don't have an alignment pattern, just make up the bottom-right point
			$bottomRightX = ($topRight->getX() - $topLeft->getX()) + $bottomLeft->getX();
			$bottomRightY = ($topRight->getY() - $topLeft->getY()) + $bottomLeft->getY();
			$sourceBottomRightX = $dimMinusThree;
			$sourceBottomRightY = $dimMinusThree;
		}

		return PerspectiveTransform::quadrilateralToQuadrilateral(
			3.5,
			3.5,
			$dimMinusThree,
			3.5,
			$sourceBottomRightX,
			$sourceBottomRightY,
			3.5,
			$dimMinusThree,
			$topLeft->getX(),
			$topLeft->getY(),
			$topRight->getX(),
			$topRight->getY(),
			$bottomRightX,
			$bottomRightY,
			$bottomLeft->getX(),
			$bottomLeft->getY()
		);
	}

	private static function sampleGrid(
		$image,
		PerspectiveTransform $transform,
		int $dimension
	): \Zxing\Common\BitMatrix {
		$sampler = GridSampler::getInstance();

		return $sampler->sampleGrid_($image, $dimension, $dimension, $transform);
	}

	final protected function getImage()
	{
		return $this->image;
	}

	final protected function getResultPointCallback()
	{
		return $this->resultPointCallback;
	}
}

FinderPattern.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Detector;

use  Zxing\ResultPoint;

/**
 * <p>Encapsulates a finder pattern, which are the three square patterns found in
 * the corners of QR Codes. It also encapsulates a count of similar finder patterns,
 * as a convenience to the finder's bookkeeping.</p>
 *
 * @author Sean Owen
 */
final class FinderPattern extends ResultPoint
{
	public function __construct($posX, $posY, private $estimatedModuleSize, private $count = 1)
	{
		parent::__construct($posX, $posY);
	}

	public function getEstimatedModuleSize()
	{
		return $this->estimatedModuleSize;
	}

	public function getCount()
	{
		return $this->count;
	}

	/*
	void incrementCount() {
	  this.count++;
	}
	 */

	/**
	 * <p>Determines if this finder pattern "about equals" a finder pattern at the stated
	 * position and size -- meaning, it is at nearly the same center with nearly the same size.</p>
	 */
	public function aboutEquals($moduleSize, $i, $j): bool
	{
		if (abs($i - $this->getY()) <= $moduleSize && abs($j - $this->getX()) <= $moduleSize) {
			$moduleSizeDiff = abs($moduleSize - $this->estimatedModuleSize);

			return $moduleSizeDiff <= 1.0 || $moduleSizeDiff <= $this->estimatedModuleSize;
		}

		return false;
	}

	/**
	 * Combines this object's current estimate of a finder pattern position and module size
	 * with a new estimate. It returns a new {@code FinderPattern} containing a weighted average
	 * based on count.
	 */
	public function combineEstimate($i, $j, $newModuleSize): \Zxing\Qrcode\Detector\FinderPattern
	{
		$combinedCount = $this->count + 1;
		$combinedX = ($this->count * $this->getX() + $j) / $combinedCount;
		$combinedY = ($this->count * $this->getY() + $i) / $combinedCount;
		$combinedModuleSize = ($this->count * $this->estimatedModuleSize + $newModuleSize) / $combinedCount;

		return new FinderPattern($combinedX, $combinedY, $combinedModuleSize, $combinedCount);
	}
}

FinderPatternFinder.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Qrcode\Detector;

use Zxing\Common\BitMatrix;
use Zxing\NotFoundException;
use Zxing\ResultPoint;

/**
 * <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square
 * markers at three corners of a QR Code.</p>
 *
 * <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.
 *
 * @author Sean Owen
 */
class FinderPatternFinder
{
	protected static int $MIN_SKIP = 3;
	protected static int $MAX_MODULES = 57; // 1 pixel/module times 3 modules/center
	private static int $CENTER_QUORUM = 2;
	private ?float $average = null;
	private array $possibleCenters = []; //private final List<FinderPattern> possibleCenters;
	private bool $hasSkipped = false;
	/**
	 * @var mixed|int[]
	 */
	private $crossCheckStateCount;

	/**
	 * <p>Creates a finder that will search the image for three finder patterns.</p>
	 *
	 * @param BitMatrix $image image to search
	 */
	public function __construct(private $image, private $resultPointCallback = null)
	{
		//new ArrayList<>();
		$this->crossCheckStateCount = fill_array(0, 5, 0);
	}

	final public function find(array|null $hints): \Zxing\Qrcode\Detector\FinderPatternInfo
	{/*final FinderPatternInfo find(Map<DecodeHintType,?> hints) throws NotFoundException {*/
		$tryHarder = $hints != null && array_key_exists('TRY_HARDER', $hints) && $hints['TRY_HARDER'];
		$pureBarcode = $hints != null && array_key_exists('PURE_BARCODE', $hints) && $hints['PURE_BARCODE'];
		$nrOfRowsSkippable = $hints != null && array_key_exists('NR_ALLOW_SKIP_ROWS', $hints) ? $hints['NR_ALLOW_SKIP_ROWS'] : ($tryHarder ? 0 : null);
		$allowedDeviation = $hints != null && array_key_exists('ALLOWED_DEVIATION', $hints) ? $hints['ALLOWED_DEVIATION'] : 0.05;
		$maxVariance = $hints != null && array_key_exists('MAX_VARIANCE', $hints) ? $hints['MAX_VARIANCE'] : 0.5;
		$maxI = $this->image->getHeight();
		$maxJ = $this->image->getWidth();
		// We are looking for black/white/black/white/black modules in
		// 1:1:3:1:1 ratio; this tracks the number of such modules seen so far

		// Let's assume that the maximum version QR Code we support takes up 1/4 the height of the
		// image, and then account for the center being 3 modules in size. This gives the smallest
		// number of pixels the center could be, so skip this often. When trying harder, look for all
		// QR versions regardless of how dense they are.
		$iSkip = (int)((3 * $maxI) / (4 * self::$MAX_MODULES));
		if ($iSkip < self::$MIN_SKIP || $tryHarder) {
			$iSkip = self::$MIN_SKIP;
		}

		$done = false;
		$stateCount = [];
		for ($i = $iSkip - 1; $i < $maxI && !$done; $i += $iSkip) {
			// Get a row of black/white values
			$stateCount[0] = 0;
			$stateCount[1] = 0;
			$stateCount[2] = 0;
			$stateCount[3] = 0;
			$stateCount[4] = 0;
			$currentState = 0;
			for ($j = 0; $j < $maxJ; $j++) {
				if ($this->image->get($j, $i)) {
					// Black pixel
					if (($currentState & 1) == 1) { // Counting white pixels
						$currentState++;
					}
					$stateCount[$currentState]++;
				} else { // White pixel
					if (($currentState & 1) == 0) { // Counting black pixels
						if ($currentState == 4) { // A winner?
							if (self::foundPatternCross($stateCount, $maxVariance)) { // Yes
								$confirmed = $this->handlePossibleCenter($stateCount, $i, $j, $pureBarcode);
								if ($confirmed) {
									// Start examining every other line. Checking each line turned out to be too
									// expensive and didn't improve performance.
									$iSkip = 3;
									if ($this->hasSkipped) {
										$done = $this->haveMultiplyConfirmedCenters($allowedDeviation);
									} else {
										$rowSkip = $nrOfRowsSkippable === null ? $this->findRowSkip() : $nrOfRowsSkippable;
										if ($rowSkip > $stateCount[2]) {
											// Skip rows between row of lower confirmed center
											// and top of presumed third confirmed center
											// but back up a bit to get a full chance of detecting
											// it, entire width of center of finder pattern

											// Skip by rowSkip, but back off by $stateCount[2] (size of last center
											// of pattern we saw) to be conservative, and also back off by iSkip which
											// is about to be re-added
											$i += $rowSkip - $stateCount[2] - $iSkip;
											$j = $maxJ - 1;
										}
									}
								} else {
									$stateCount[0] = $stateCount[2];
									$stateCount[1] = $stateCount[3];
									$stateCount[2] = $stateCount[4];
									$stateCount[3] = 1;
									$stateCount[4] = 0;
									$currentState = 3;
									continue;
								}
								// Clear state to start looking again
								$currentState = 0;
								$stateCount[0] = 0;
								$stateCount[1] = 0;
								$stateCount[2] = 0;
								$stateCount[3] = 0;
								$stateCount[4] = 0;
							} else { // No, shift counts back by two
								$stateCount[0] = $stateCount[2];
								$stateCount[1] = $stateCount[3];
								$stateCount[2] = $stateCount[4];
								$stateCount[3] = 1;
								$stateCount[4] = 0;
								$currentState = 3;
							}
						} else {
							$stateCount[++$currentState]++;
						}
					} else { // Counting white pixels
						$stateCount[$currentState]++;
					}
				}
			}
			if (self::foundPatternCross($stateCount, $maxVariance)) {
				$confirmed = $this->handlePossibleCenter($stateCount, $i, $maxJ, $pureBarcode);
				if ($confirmed) {
					$iSkip = $stateCount[0];
					if ($this->hasSkipped) {
						// Found a third one
						$done = $this->haveMultiplyConfirmedCenters($allowedDeviation);
					}
				}
			}
		}

		$patternInfo = $this->selectBestPatterns();
		$patternInfo = ResultPoint::orderBestPatterns($patternInfo);

		return new FinderPatternInfo($patternInfo);
	}

	/**
	 * @param $stateCount ; count of black/white/black/white/black pixels just read
	 * @param int[] $stateCount
	 *
	 * @return bool iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios used by finder patterns to be considered a match
	 *
	 * @psalm-param array<0|positive-int, int> $stateCount
	 */
	protected static function foundPatternCross(array $stateCount, float $maxVariance = 0.5): bool
	{
		$totalModuleSize = 0;
		for ($i = 0; $i < 5; $i++) {
			$count = $stateCount[$i];
			if ($count == 0) {
				return false;
			}
			$totalModuleSize += $count;
		}
		if ($totalModuleSize < 7) {
			return false;
		}
		$moduleSize = $totalModuleSize / 7.0;
		$maxVariance = $moduleSize * $maxVariance;

		// Allow less than 50% variance from 1-1-3-1-1 proportions
		return
			abs($moduleSize - $stateCount[0]) < $maxVariance &&
			abs($moduleSize - $stateCount[1]) < $maxVariance &&
			abs(3.0 * $moduleSize - $stateCount[2]) < 3 * $maxVariance &&
			abs($moduleSize - $stateCount[3]) < $maxVariance &&
			abs($moduleSize - $stateCount[4]) < $maxVariance;
	}

	/**
	 * <p>This is called when a horizontal scan finds a possible alignment pattern. It will
	 * cross check with a vertical scan, and if successful, will, ah, cross-cross-check
	 * with another horizontal scan. This is needed primarily to locate the real horizontal
	 * center of the pattern in cases of extreme skew.
	 * And then we cross-cross-cross check with another diagonal scan.</p>
	 *
	 * <p>If that succeeds the finder pattern location is added to a list that tracks
	 * the number of times each location has been nearly-matched as a finder pattern.
	 * Each additional find is more evidence that the location is in fact a finder
	 * pattern center
	 *
	 * @param array $stateCount reading state module counts from horizontal scan
	 * @param int $i row           where finder pattern may be found
	 * @param int $j end           of possible finder pattern in row
	 * @param bool $pureBarcode true if in "pure barcode" mode
	 *
	 * @return bool if a finder pattern candidate was found this time
	 */
	final protected function handlePossibleCenter($stateCount, int $i, int $j, bool $pureBarcode): bool
	{
		$stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2] + $stateCount[3] +
			$stateCount[4];
		$centerJ = self::centerFromEnd($stateCount, $j);
		$centerI = $this->crossCheckVertical($i, (int)($centerJ), $stateCount[2], $stateCountTotal);
		if (!is_nan($centerI)) {
			// Re-cross check
			$centerJ = $this->crossCheckHorizontal((int)($centerJ), (int)($centerI), $stateCount[2], $stateCountTotal);
			if (
				!is_nan($centerJ) &&
				(!$pureBarcode || $this->crossCheckDiagonal((int)($centerI), (int)($centerJ), $stateCount[2], $stateCountTotal))
			) {
				$estimatedModuleSize = (float)$stateCountTotal / 7.0;
				$found = false;
				for ($index = 0; $index < count($this->possibleCenters); $index++) {
					$center = $this->possibleCenters[$index];
					// Look for about the same center and module size:
					if ($center->aboutEquals($estimatedModuleSize, $centerI, $centerJ)) {
						$this->possibleCenters[$index] = $center->combineEstimate($centerI, $centerJ, $estimatedModuleSize);
						$found = true;
						break;
					}
				}
				if (!$found) {
					$point = new FinderPattern($centerJ, $centerI, $estimatedModuleSize);
					$this->possibleCenters[] = $point;
					if ($this->resultPointCallback != null) {
						$this->resultPointCallback->foundPossibleResultPoint($point);
					}
				}

				return true;
			}
		}

		return false;
	}

	/**
	 * Given a count of black/white/black/white/black pixels just seen and an end position,
	 * figures the location of the center of this run.
	 */
	private static function centerFromEnd(array $stateCount, int $end)
	{
		return (float)($end - $stateCount[4] - $stateCount[3]) - $stateCount[2] / 2.0;
	}

	/**
	 * <p>After a horizontal scan finds a potential finder pattern, this method
	 * "cross-checks" by scanning down vertically through the center of the possible
	 * finder pattern to see if the same proportion is detected.</p>
	 *
	 * @param int $startI   ;  row where a finder pattern was detected
	 * @param int $centerJ   ; center of the section that appears to cross a finder pattern
	 * @param int $maxCount ; maximum reasonable number of modules that should be
	 *                  observed in any reading state, based on the results of the horizontal scan
	 *
	 * @return float vertical center of finder pattern, or {@link Float#NaN} if not found
	 */
	private function crossCheckVertical(
		int $startI,
		int $centerJ,
		int $maxCount,
		int|float $originalStateCountTotal
	) {
		$image = $this->image;

		$maxI = $image->getHeight();
		$stateCount = $this->getCrossCheckStateCount();

		// Start counting up from center
		$i = $startI;
		while ($i >= 0 && $image->get($centerJ, $i)) {
			$stateCount[2]++;
			$i--;
		}
		if ($i < 0) {
			return NAN;
		}
		while ($i >= 0 && !$image->get($centerJ, $i) && $stateCount[1] <= $maxCount) {
			$stateCount[1]++;
			$i--;
		}
		// If already too many modules in this state or ran off the edge:
		if ($i < 0 || $stateCount[1] > $maxCount) {
			return NAN;
		}
		while ($i >= 0 && $image->get($centerJ, $i) && $stateCount[0] <= $maxCount) {
			$stateCount[0]++;
			$i--;
		}
		if ($stateCount[0] > $maxCount) {
			return NAN;
		}

		// Now also count down from center
		$i = $startI + 1;
		while ($i < $maxI && $image->get($centerJ, $i)) {
			$stateCount[2]++;
			$i++;
		}
		if ($i == $maxI) {
			return NAN;
		}
		while ($i < $maxI && !$image->get($centerJ, $i) && $stateCount[3] < $maxCount) {
			$stateCount[3]++;
			$i++;
		}
		if ($i == $maxI || $stateCount[3] >= $maxCount) {
			return NAN;
		}
		while ($i < $maxI && $image->get($centerJ, $i) && $stateCount[4] < $maxCount) {
			$stateCount[4]++;
			$i++;
		}
		if ($stateCount[4] >= $maxCount) {
			return NAN;
		}

		// If we found a finder-pattern-like section, but its size is more than 40% different than
		// the original, assume it's a false positive
		$stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2] + $stateCount[3] +
			$stateCount[4];
		if (5 * abs($stateCountTotal - $originalStateCountTotal) >= 2 * $originalStateCountTotal) {
			return NAN;
		}

		return self::foundPatternCross($stateCount) ? self::centerFromEnd($stateCount, $i) : NAN;
	}

	private function getCrossCheckStateCount()
	{
		$this->crossCheckStateCount[0] = 0;
		$this->crossCheckStateCount[1] = 0;
		$this->crossCheckStateCount[2] = 0;
		$this->crossCheckStateCount[3] = 0;
		$this->crossCheckStateCount[4] = 0;

		return $this->crossCheckStateCount;
	}

	/**
	 * <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical,
	 * except it reads horizontally instead of vertically. This is used to cross-cross
	 * check a vertical cross check and locate the real center of the alignment pattern.</p>
	 */
	private function crossCheckHorizontal(
		int $startJ,
		int $centerI,
		int $maxCount,
		int|float $originalStateCountTotal
	) {
		$image = $this->image;

		$maxJ = $this->image->getWidth();
		$stateCount = $this->getCrossCheckStateCount();

		$j = $startJ;
		while ($j >= 0 && $image->get($j, $centerI)) {
			$stateCount[2]++;
			$j--;
		}
		if ($j < 0) {
			return NAN;
		}
		while ($j >= 0 && !$image->get($j, $centerI) && $stateCount[1] <= $maxCount) {
			$stateCount[1]++;
			$j--;
		}
		if ($j < 0 || $stateCount[1] > $maxCount) {
			return NAN;
		}
		while ($j >= 0 && $image->get($j, $centerI) && $stateCount[0] <= $maxCount) {
			$stateCount[0]++;
			$j--;
		}
		if ($stateCount[0] > $maxCount) {
			return NAN;
		}

		$j = $startJ + 1;
		while ($j < $maxJ && $image->get($j, $centerI)) {
			$stateCount[2]++;
			$j++;
		}
		if ($j == $maxJ) {
			return NAN;
		}
		while ($j < $maxJ && !$image->get($j, $centerI) && $stateCount[3] < $maxCount) {
			$stateCount[3]++;
			$j++;
		}
		if ($j == $maxJ || $stateCount[3] >= $maxCount) {
			return NAN;
		}
		while ($j < $maxJ && $this->image->get($j, $centerI) && $stateCount[4] < $maxCount) {
			$stateCount[4]++;
			$j++;
		}
		if ($stateCount[4] >= $maxCount) {
			return NAN;
		}

		// If we found a finder-pattern-like section, but its size is significantly different than
		// the original, assume it's a false positive
		$stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2] + $stateCount[3] +
			$stateCount[4];
		if (5 * abs($stateCountTotal - $originalStateCountTotal) >= $originalStateCountTotal) {
			return NAN;
		}

		return static::foundPatternCross($stateCount) ? self::centerFromEnd($stateCount, $j) : NAN;
	}

	/**
	 * After a vertical and horizontal scan finds a potential finder pattern, this method
	 * "cross-cross-cross-checks" by scanning down diagonally through the center of the possible
	 * finder pattern to see if the same proportion is detected.
	 *
	 * @param $startI                 ;  row where a finder pattern was detected
	 * @param $centerJ                 ; center of the section that appears to cross a finder pattern
	 * @param $maxCount               ; maximum reasonable number of modules that should be
	 *                                observed in any reading state, based on the results of the horizontal scan
	 * @param $originalStateCountTotal ; The original state count total.
	 *
	 * @return bool if proportions are withing expected limits
	 */
	private function crossCheckDiagonal(int $startI, int $centerJ, $maxCount, int|float $originalStateCountTotal): bool
	{
		$stateCount = $this->getCrossCheckStateCount();

		// Start counting up, left from center finding black center mass
		$i = 0;
		while ($startI >= $i && $centerJ >= $i && $this->image->get($centerJ - $i, $startI - $i)) {
			$stateCount[2]++;
			$i++;
		}

		if ($startI < $i || $centerJ < $i) {
			return false;
		}

		// Continue up, left finding white space
		while (
			$startI >= $i && $centerJ >= $i && !$this->image->get($centerJ - $i, $startI - $i) &&
			$stateCount[1] <= $maxCount
		) {
			$stateCount[1]++;
			$i++;
		}

		// If already too many modules in this state or ran off the edge:
		if ($startI < $i || $centerJ < $i || $stateCount[1] > $maxCount) {
			return false;
		}

		// Continue up, left finding black border
		while (
			$startI >= $i && $centerJ >= $i && $this->image->get($centerJ - $i, $startI - $i) &&
			$stateCount[0] <= $maxCount
		) {
			$stateCount[0]++;
			$i++;
		}
		if ($stateCount[0] > $maxCount) {
			return false;
		}

		$maxI = $this->image->getHeight();
		$maxJ = $this->image->getWidth();

		// Now also count down, right from center
		$i = 1;
		while ($startI + $i < $maxI && $centerJ + $i < $maxJ && $this->image->get($centerJ + $i, $startI + $i)) {
			$stateCount[2]++;
			$i++;
		}

		// Ran off the edge?
		if ($startI + $i >= $maxI || $centerJ + $i >= $maxJ) {
			return false;
		}

		while (
			$startI + $i < $maxI && $centerJ + $i < $maxJ && !$this->image->get($centerJ + $i, $startI + $i) &&
			$stateCount[3] < $maxCount
		) {
			$stateCount[3]++;
			$i++;
		}

		if ($startI + $i >= $maxI || $centerJ + $i >= $maxJ || $stateCount[3] >= $maxCount) {
			return false;
		}

		while (
			$startI + $i < $maxI && $centerJ + $i < $maxJ && $this->image->get($centerJ + $i, $startI + $i) &&
			$stateCount[4] < $maxCount
		) {
			$stateCount[4]++;
			$i++;
		}

		if ($stateCount[4] >= $maxCount) {
			return false;
		}

		// If we found a finder-pattern-like section, but its size is more than 100% different than
		// the original, assume it's a false positive
		$stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2] + $stateCount[3] + $stateCount[4];

		return
			abs($stateCountTotal - $originalStateCountTotal) < 2 * $originalStateCountTotal &&
			self::foundPatternCross($stateCount);
	}

	/**
	 * @return bool iff we have found at least 3 finder patterns that have been detected at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the candidates is "pretty similar"
	 */
	private function haveMultiplyConfirmedCenters(?float $allowedDeviation = 0.05): bool
	{
		$confirmedCount = 0;
		$totalModuleSize = 0.0;
		$max = count($this->possibleCenters);
		foreach ($this->possibleCenters as $pattern) {
			if ($pattern->getCount() >= self::$CENTER_QUORUM) {
				$confirmedCount++;
				$totalModuleSize += $pattern->getEstimatedModuleSize();
			}
		}
		if ($confirmedCount < 3) {
			return false;
		}
		// OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"
		// and that we need to keep looking. We detect this by asking if the estimated module sizes
		// vary too much. We arbitrarily say that when the total deviation from average exceeds
		// 5% of the total module size estimates, it's too much.
		$average = $totalModuleSize / (float)$max;
		$totalDeviation = 0.0;
		foreach ($this->possibleCenters as $pattern) {
			$totalDeviation += abs($pattern->getEstimatedModuleSize() - $average);
		}

		return $totalDeviation <= $allowedDeviation * $totalModuleSize;
	}

	/**
	 * @return int number of rows we could safely skip during scanning, based on the first
	 *         two finder patterns that have been located. In some cases their position will
	 *         allow us to infer that the third pattern must lie below a certain point farther
	 *         down in the image.
	 */
	private function findRowSkip()
	{
		$max = count($this->possibleCenters);
		if ($max <= 1) {
			return 0;
		}
		$firstConfirmedCenter = null;
		foreach ($this->possibleCenters as $center) {
			if ($center->getCount() >= self::$CENTER_QUORUM) {
				if ($firstConfirmedCenter == null) {
					$firstConfirmedCenter = $center;
				} else {
					// We have two confirmed centers
					// How far down can we skip before resuming looking for the next
					// pattern? In the worst case, only the difference between the
					// difference in the x / y coordinates of the two centers.
					// This is the case where you find top left last.
					$this->hasSkipped = true;

					return (int)((abs($firstConfirmedCenter->getX() - $center->getX()) -
						abs($firstConfirmedCenter->getY() - $center->getY())) / 2);
				}
			}
		}

		return 0;
	}

	/**
	 * @return array the 3 best {@link FinderPattern}s from our list of candidates. The "best" are
	 *         those that have been detected at least {@link #CENTER_QUORUM} times, and whose module
	 *         size differs from the average among those patterns the least
	 * @throws NotFoundException if 3 such finder patterns do not exist
	 */
	private function selectBestPatterns()
	{
		$startSize = count($this->possibleCenters);
		if ($startSize < 3) {
			// Couldn't find enough finder patterns
			throw new NotFoundException("Could not find 3 finder patterns ($startSize found)");
		}

		// Filter outlier possibilities whose module size is too different
		if ($startSize > 3) {
			// But we can only afford to do so if we have at least 4 possibilities to choose from
			$totalModuleSize = 0.0;
			$square = 0.0;
			foreach ($this->possibleCenters as $center) {
				$size = $center->getEstimatedModuleSize();
				$totalModuleSize += $size;
				$square += $size * $size;
			}
			$this->average = $totalModuleSize / (float)$startSize;
			$stdDev = (float)sqrt($square / $startSize - $this->average * $this->average);

			usort($this->possibleCenters, $this->FurthestFromAverageComparator(...));

			$limit = max(0.2 * $this->average, $stdDev);

			for ($i = 0; $i < count($this->possibleCenters) && count($this->possibleCenters) > 3; $i++) {
				$pattern = $this->possibleCenters[$i];
				if (abs($pattern->getEstimatedModuleSize() - $this->average) > $limit) {
					unset($this->possibleCenters[$i]); //возможно что ключи меняются в java при вызове .remove(i) ???
					$this->possibleCenters = array_values($this->possibleCenters);
					$i--;
				}
			}
		}

		if (count($this->possibleCenters) > 3) {
			// Throw away all but those first size candidate points we found.

			$totalModuleSize = 0.0;
			foreach ($this->possibleCenters as $possibleCenter) {
				$totalModuleSize += $possibleCenter->getEstimatedModuleSize();
			}

			$this->average = $totalModuleSize / (float)count($this->possibleCenters);

			usort($this->possibleCenters, $this->CenterComparator(...));

			array_slice($this->possibleCenters, 3, count($this->possibleCenters) - 3);
		}

		return [$this->possibleCenters[0], $this->possibleCenters[1], $this->possibleCenters[2]];
	}

	/**
	 * <p>Orders by furthest from average</p>
	 *
	 * @psalm-return -1|0|1
	 */
	public function FurthestFromAverageComparator($center1, $center2): int
	{
		$dA = abs($center2->getEstimatedModuleSize() - $this->average);
		$dB = abs($center1->getEstimatedModuleSize() - $this->average);
		if ($dA < $dB) {
			return -1;
		} elseif ($dA == $dB) {
			return 0;
		} else {
			return 1;
		}
	}

	public function CenterComparator($center1, $center2)
	{
		if ($center2->getCount() == $center1->getCount()) {
			$dA = abs($center2->getEstimatedModuleSize() - $this->average);
			$dB = abs($center1->getEstimatedModuleSize() - $this->average);
			if ($dA < $dB) {
				return 1;
			} elseif ($dA == $dB) {
				return 0;
			} else {
				return -1;
			}
		} else {
			return $center2->getCount() - $center1->getCount();
		}
	}

	final protected function getImage(): BitMatrix
	{
		return $this->image;
	}
	/**
	 * <p>Orders by {@link FinderPattern#getCount()}, descending.</p>
	 */
	final protected function getPossibleCenters(): array
	{ //List<FinderPattern> getPossibleCenters()
		return $this->possibleCenters;
	}
}

FinderPatternInfo.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Detector;

/**
 * <p>Encapsulates information about finder patterns in an image, including the location of
 * the three finder patterns, and their estimated module size.</p>
 *
 * @author Sean Owen
 */
final class FinderPatternInfo
{
	private $bottomLeft;
	private $topLeft;
	private $topRight;

	public function __construct($patternCenters)
	{
		$this->bottomLeft = $patternCenters[0];
		$this->topLeft = $patternCenters[1];
		$this->topRight = $patternCenters[2];
	}

	public function getBottomLeft()
	{
		return $this->bottomLeft;
	}

	public function getTopLeft()
	{
		return $this->topLeft;
	}

	public function getTopRight()
	{
		return $this->topRight;
	}
}

PROYECTOS_FLORES_JURADO_DONOVAN

Proyectos finales: banco, calificaciones y control de estudiantes.
buscarCliente.phpArchivos de texto
Busqueda de registros.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Buscar Cliente</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a5276; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #2980b9; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #2471a3; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
        table { border-collapse: collapse; margin-top: 15px; width: 100%; }
        td, th { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background: #1a5276; color: white; }
    </style>
</head>
<body>
    <h3>BUSCAR CLIENTE</h3>
    <form action="buscarCliente.php" method="get">
        <label>Buscar por (num cuenta, CI o nombre):</label>
        <input type="text" name="criterio" required><br>
        <input type="submit" value="Buscar">
    </form>
    <?php
      $criterio = $_GET["criterio"] ?? "";
      if($criterio != "" && file_exists("clientes.txt")){
        $recurso = fopen("clientes.txt","r");
        echo "<table>";
        echo "<tr><th>Cuenta</th><th>CI</th><th>Nombre</th><th>Celular</th><th>Direccion</th><th>Estado</th><th>Fecha</th></tr>";
        $encontrados = 0;
        while(!feof($recurso)){
          $linea = fgets($recurso);
          if(trim($linea) != ""){
            $reg = explode("|",$linea);
            if(count($reg) >= 7){
              // Buscar en cuenta, CI y nombre
              if(stripos($reg[0],$criterio) !== false || stripos($reg[1],$criterio) !== false || stripos($reg[2],$criterio) !== false){
                echo "<tr>";
                echo "<td>".htmlspecialchars($reg[0])."</td>";
                echo "<td>".htmlspecialchars($reg[1])."</td>";
                echo "<td>".htmlspecialchars($reg[2])."</td>";
                echo "<td>".htmlspecialchars($reg[3])."</td>";
                echo "<td>".htmlspecialchars($reg[4])."</td>";
                echo "<td>".htmlspecialchars($reg[5])."</td>";
                echo "<td>".htmlspecialchars($reg[6])."</td>";
                echo "</tr>";
                $encontrados++;
              }
            }
          }
        }
        echo "</table>";
        fclose($recurso);
        if($encontrados == 0) echo "<p>No se encontraron resultados para: $criterio</p>";
      }
    ?>
</body>
</html>

eliminarCliente.phpArchivos de texto
Elimina o anula un registro.
Abrir
Ver codigo

<?php
  $ci = $_POST["ci"];

  if(!file_exists("clientes.txt")){
    echo "<p>No hay registros</p>";
    exit;
  }

  $lineas = file("clientes.txt");
  $encontrado = false;

  for($i=0; $i<count($lineas); $i++){
    if(trim($lineas[$i]) != ""){
      $reg = explode("|",$lineas[$i]);
      if(count($reg) >= 6 && trim($reg[1]) == $ci){
        if(trim($reg[5]) == "BAJA"){
          echo "<p style='color:orange'>El cliente ya esta dado de baja</p>";
          echo "<a href='formEliminarCliente.php'>Volver</a>";
          exit;
        }
        // Cambiar estado a BAJA
        $reg[5] = "BAJA";
        $lineas[$i] = implode("|",$reg)."\n";
        $encontrado = true;
        break;
      }
    }
  }

  if(!$encontrado){
    echo "<p style='color:red'>Cliente con CI $ci no encontrado</p>";
    echo "<a href='formEliminarCliente.php'>Volver</a>";
    exit;
  }

  file_put_contents("clientes.txt", implode("",$lineas));

  echo "<h3 style='color:green'>Cliente dado de baja exitosamente!</h3>";
  echo "<p>CI: $ci - Estado: BAJA</p>";
  echo "<p><a href='listarClientes.php' target='_parent'>Ver listado</a></p>";
?>

estadoCuenta.phpArchivos de texto
Script de practica.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Estado de Cuenta</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a5276; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #2980b9; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #2471a3; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
        table { border-collapse: collapse; margin-top: 15px; width: 100%; }
        td, th { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background: #1a5276; color: white; }
        .deposito { color: green; font-weight: bold; }
        .retiro { color: red; font-weight: bold; }
    </style>
</head>
<body>
    <h3>ESTADO DE CUENTA</h3>
    <form action="estadoCuenta.php" method="get">
        <label>Numero de cuenta:</label>
        <input type="text" name="cuenta" required><br>
        <input type="submit" value="Consultar">
    </form>
    <?php
      $cuenta = $_GET["cuenta"] ?? "";
      if($cuenta != "" && file_exists("clientes.txt")){
        // Buscar cliente
        $recurso = fopen("clientes.txt","r");
        $cliente = null;
        while(!feof($recurso)){
          $linea = fgets($recurso);
          if(trim($linea) != ""){
            $reg = explode("|",$linea);
            if(count($reg) >= 7 && trim($reg[0]) == $cuenta){
              $cliente = $reg;
              break;
            }
          }
        }
        fclose($recurso);

        if($cliente == null){
          echo "<p style='color:red'>Cuenta no encontrada</p>";
          exit;
        }

        echo "<h4>Cuenta: ".htmlspecialchars($cliente[0])." - Titular: ".htmlspecialchars($cliente[2])."</h4>";

        if(!file_exists("movimientos.txt")){
          echo "<p>No hay movimientos registrados</p>";
          exit;
        }

        $recurso = fopen("movimientos.txt","r");
        echo "<table>";
        echo "<tr><th>Fecha</th><th>Tipo</th><th>Monto</th><th>Saldo</th><th>Depositante</th></tr>";
        $totalDepositos = 0;
        $totalRetiros = 0;
        while(!feof($recurso)){
          $linea = fgets($recurso);
          if(trim($linea) != ""){
            $m = explode("|",$linea);
            if(count($m) >= 6 && trim($m[0]) == $cuenta){
              $tipo = trim($m[2]);
              $monto = floatval($m[3]);
              $clase = ($tipo == "DEPOSITO") ? "deposito" : "retiro";
              echo "<tr>";
              echo "<td>".htmlspecialchars($m[1])."</td>";
              echo "<td class='$clase'>".htmlspecialchars($m[2])."</td>";
              echo "<td>".htmlspecialchars($m[3])."</td>";
              echo "<td>".htmlspecialchars($m[4])."</td>";
              echo "<td>".htmlspecialchars($m[5])."</td>";
              echo "</tr>";
              if($tipo == "DEPOSITO") $totalDepositos += $monto;
              else $totalRetiros += $monto;
            }
          }
        }
        echo "</table>";
        fclose($recurso);
        echo "<p><strong>Total depositos:</strong> $totalDepositos Bs | <strong>Total retiros:</strong> $totalRetiros Bs</p>";
      }
    ?>
</body>
</html>

formDeposito.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Deposito</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a5276; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #27ae60; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #219a52; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
    </style>
</head>
<body>
    <h3>REALIZAR DEPOSITO</h3>
    <form action="procesarDeposito.php" method="post">
        <label>Numero de cuenta:</label>
        <input type="text" name="cuenta" required><br>
        <label>Monto a depositar:</label>
        <input type="number" name="monto" min="0.01" step="0.01" required><br>
        <input type="submit" value="Depositar">
    </form>
</body>
</html>

formDepositoTercero.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Deposito de Tercero</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a5276; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #8e44ad; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #7d3c98; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
    </style>
</head>
<body>
    <h3>DEPOSITO DE TERCERO</h3>
    <form action="procesarDepositoTercero.php" method="post">
        <label>Numero de cuenta a depositar:</label>
        <input type="text" name="cuenta" required><br>
        <label>Nombre del depositante:</label>
        <input type="text" name="depositante" required><br>
        <label>Monto a depositar:</label>
        <input type="number" name="monto" min="0.01" step="0.01" required><br>
        <input type="submit" value="Depositar">
    </form>
</body>
</html>

formEliminarCliente.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Eliminar Cliente</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a5276; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #c0392b; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #a93226; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
    </style>
</head>
<body>
    <h3>ELIMINAR CLIENTE (BAJA LOGICA)</h3>
    <form action="eliminarCliente.php" method="post">
        <label>CI del cliente:</label>
        <input type="text" name="ci" required><br>
        <input type="submit" value="Dar de Baja">
    </form>
</body>
</html>

formModificarCliente.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Modificar Cliente</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a5276; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #f39c12; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #d68910; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
        table { border-collapse: collapse; margin-top: 15px; }
        td, th { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background: #1a5276; color: white; }
    </style>
</head>
<body>
    <h3>BUSCAR CLIENTE PARA MODIFICAR</h3>
    <form action="modificarCliente.php" method="post">
        <label>CI del cliente:</label>
        <input type="text" name="ci" required><br>
        <input type="submit" value="Buscar">
    </form>
</body>
</html>

formRegistrarCliente.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Registrar Cliente</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a5276; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #27ae60; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #219a52; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
    </style>
</head>
<body>
    <h3>REGISTRAR NUEVO CLIENTE</h3>
    <form action="registrarCliente.php" method="post">
        <label>Nombre completo:</label>
        <input type="text" name="nombre" required><br>
        <label>CI (Carnet de Identidad):</label>
        <input type="text" name="ci" required><br>
        <label>Celular:</label>
        <input type="text" name="celular" required><br>
        <label>Direccion:</label>
        <input type="text" name="direccion" required><br>
        <input type="submit" value="Registrar Cliente">
    </form>
</body>
</html>

formRetiro.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Retiro</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a5276; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #e67e22; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #d35400; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
    </style>
</head>
<body>
    <h3>REALIZAR RETIRO</h3>
    <form action="procesarRetiro.php" method="post">
        <label>Numero de cuenta:</label>
        <input type="text" name="cuenta" required><br>
        <label>Monto a retirar:</label>
        <input type="number" name="monto" min="0.01" step="0.01" required><br>
        <input type="submit" value="Retirar">
    </form>
</body>
</html>

guardarModificarCliente.phpArchivos de texto
Modifica un registro existente.
Abrir
Ver codigo

<?php
  $ci = $_POST["ci"];
  $idx = intval($_POST["idx"]);
  $nombre = $_POST["nombre"];
  $celular = $_POST["celular"];
  $direccion = $_POST["direccion"];

  $lineas = file("clientes.txt");
  $lineas[$idx] = trim($lineas[$idx]);
  $reg = explode("|",$lineas[$idx]);

  // Reconstruir la linea manteniendo cuenta y estado
  $nuevaLinea = $reg[0]."|".$reg[1]."|".$nombre."|".$celular."|".$direccion."|".$reg[5]."|".$reg[6];
  $lineas[$idx] = $nuevaLinea."\n";

  file_put_contents("clientes.txt", implode("",$lineas));

  echo "<h3 style='color:green'>Cliente modificado exitosamente!</h3>";
  echo "<p><a href='listarClientes.php' target='_parent'>Ver listado</a> | <a href='formModificarCliente.php'>Modificar otro</a></p>";
?>

inicio.php
Listado / indice del ejercicio.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SISTEMA BANCARIO</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: Arial, sans-serif; background: #f0f0f0; }
        #principal { display: flex; height: 100vh; }
        #menu {
            width: 25%;
            background: linear-gradient(135deg, #1a5276, #2e86c1);
            color: white;
            padding: 15px;
        }
        #menu h2 { text-align: center; margin-bottom: 20px; border-bottom: 2px solid white; padding-bottom: 10px; }
        #menu ul { list-style: none; }
        #menu ul li { margin: 8px 0; }
        #menu ul li a {
            display: block;
            color: white;
            text-decoration: none;
            padding: 10px 15px;
            border-radius: 5px;
            background: rgba(255,255,255,0.1);
            transition: background 0.3s;
        }
        #menu ul li a:hover { background: rgba(255,255,255,0.3); }
        #menu h3 { margin-top: 20px; margin-bottom: 10px; font-size: 14px; opacity: 0.8; }
        #conte { width: 75%; }
        #conte iframe { width: 100%; height: 100%; border: none; }
    </style>
</head>
<body>
    <div id="principal">
        <div id="menu">
            <h2>BANCO VIRTUAL</h2>
            <h3>CLIENTES</h3>
            <nav>
                <ul>
                    <li><a href="formRegistrarCliente.php" target="container">REGISTRAR CLIENTE</a></li>
                    <li><a href="formModificarCliente.php" target="container">MODIFICAR CLIENTE</a></li>
                    <li><a href="formEliminarCliente.php" target="container">ELIMINAR CLIENTE (BAJA)</a></li>
                    <li><a href="buscarCliente.php" target="container">BUSCAR CLIENTE</a></li>
                    <li><a href="listarClientes.php" target="container">LISTAR CLIENTES</a></li>
                </ul>
            </nav>
            <h3>OPERACIONES</h3>
            <nav>
                <ul>
                    <li><a href="formDeposito.php" target="container">DEPOSITO</a></li>
                    <li><a href="formRetiro.php" target="container">RETIRO</a></li>
                    <li><a href="formDepositoTercero.php" target="container">DEPOSITO DE TERCERO</a></li>
                    <li><a href="estadoCuenta.php" target="container">ESTADO DE CUENTA</a></li>
                </ul>
            </nav>
        </div>
        <div id="conte">
            <iframe name="container" src="" frameborder="0"></iframe>
        </div>
    </div>
</body>
</html>

listarClientes.phpArchivos de texto
Listado / indice del ejercicio.
Abrir
Ver codigo

<?php
  if(!file_exists("clientes.txt")){
    echo "<p>No hay registros de clientes</p>";
    exit;
  }

  $filtro = $_GET["filtro"] ?? "todos";
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Listar Clientes</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a5276; }
        table { border-collapse: collapse; margin-top: 15px; width: 100%; }
        td, th { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background: #1a5276; color: white; }
        .activo { color: green; font-weight: bold; }
        .baja { color: red; font-weight: bold; }
        a.filtro {
            display: inline-block; margin: 5px 3px; padding: 8px 15px;
            background: #2e86c1; color: white; text-decoration: none; border-radius: 4px;
        }
        a.filtro:hover { background: #1a5276; }
        a.filtro.activo-f { background: #1a5276; }
    </style>
</head>
<body>
    <h3>LISTADO DE CLIENTES</h3>
    <a href="listarClientes.php?filtro=activos" class="filtro <?php echo $filtro=='activos'?'activo-f':''; ?>">ACTIVOS</a>
    <a href="listarClientes.php?filtro=baja" class="filtro <?php echo $filtro=='baja'?'activo-f':''; ?>">DADOS DE BAJA</a>
    <a href="listarClientes.php?filtro=todos" class="filtro <?php echo $filtro=='todos'?'activo-f':''; ?>">TODOS</a>
    <br><br>
    <?php
      $recurso = fopen("clientes.txt","r");
      echo "<table>";
      echo "<tr><th>Cuenta</th><th>CI</th><th>Nombre</th><th>Celular</th><th>Direccion</th><th>Estado</th><th>Fecha</th></tr>";
      $total = 0;
      while(!feof($recurso)){
        $linea = fgets($recurso);
        if(trim($linea) != ""){
          $reg = explode("|",$linea);
          if(count($reg) >= 7){
            $estado = trim($reg[5]);
            $mostrar = false;
            if($filtro == "todos") $mostrar = true;
            elseif($filtro == "activos" && $estado == "ACTIVO") $mostrar = true;
            elseif($filtro == "baja" && $estado == "BAJA") $mostrar = true;

            if($mostrar){
              $clase = ($estado == "BAJA") ? "baja" : "activo";
              echo "<tr>";
              echo "<td>".htmlspecialchars($reg[0])."</td>";
              echo "<td>".htmlspecialchars($reg[1])."</td>";
              echo "<td>".htmlspecialchars($reg[2])."</td>";
              echo "<td>".htmlspecialchars($reg[3])."</td>";
              echo "<td>".htmlspecialchars($reg[4])."</td>";
              echo "<td class='$clase'>".htmlspecialchars($reg[5])."</td>";
              echo "<td>".htmlspecialchars($reg[6])."</td>";
              echo "</tr>";
              $total++;
            }
          }
        }
      }
      echo "</table>";
      fclose($recurso);
      echo "<p><strong>Total: $total clientes</strong></p>";
    ?>
</body>
</html>

modificarCliente.php
Modifica un registro existente.
Abrir
Ver codigo

<?php
  $ci = $_POST["ci"] ?? "";

  if($ci == ""){
    echo "<p style='color:red'>Error: Ingrese la CI</p>";
    echo "<a href='formModificarCliente.php'>Volver</a>";
    exit;
  }

  if(!file_exists("clientes.txt")){
    echo "<p>No hay registros</p>";
    exit;
  }

  $encontrado = false;
  $lineas = file("clientes.txt");
  foreach($lineas as $i => $linea){
    if(trim($linea) != ""){
      $reg = explode("|",$linea);
      if(count($reg) >= 6 && trim($reg[1]) == $ci){
        $encontrado = true;
        $idx = $i;
        break;
      }
    }
  }

  if(!$encontrado){
    echo "<p style='color:red'>Cliente con CI $ci no encontrado</p>";
    echo "<a href='formModificarCliente.php'>Volver</a>";
    exit;
  }
?>
<h3>MODIFICAR CLIENTE - CI: <?php echo $ci; ?></h3>
<form action="guardarModificarCliente.php" method="post">
    <input type="hidden" name="ci" value="<?php echo $ci; ?>">
    <input type="hidden" name="idx" value="<?php echo $idx; ?>">
    <label>Nombre completo:</label>
    <input type="text" name="nombre" value="<?php echo trim($reg[2]); ?>" required><br>
    <label>Celular:</label>
    <input type="text" name="celular" value="<?php echo trim($reg[3]); ?>" required><br>
    <label>Direccion:</label>
    <input type="text" name="direccion" value="<?php echo trim($reg[4]); ?>" required><br>
    <input type="submit" value="Guardar Cambios">
</form>

procesarDeposito.phpArchivos de texto
Script de practica.
Abrir
Ver codigo

<?php
  $cuenta = $_POST["cuenta"] ?? "";
  $monto = floatval($_POST["monto"] ?? 0);

  if($cuenta == "" || $monto <= 0){
    echo "<p style='color:red'>Error: Cuenta y monto son obligatorios (monto > 0)</p>";
    echo "<a href='formDeposito.php'>Volver</a>";
    exit;
  }

  if(!file_exists("clientes.txt")){
    echo "<p style='color:red'>No hay clientes registrados</p>";
    exit;
  }

  // Verificar que la cuenta existe y esta activa
  $encontrado = false;
  $lineas = file("clientes.txt");
  for($i=0; $i<count($lineas); $i++){
    if(trim($lineas[$i]) != ""){
      $reg = explode("|",$lineas[$i]);
      if(count($reg) >= 6 && trim($reg[0]) == $cuenta){
        if(trim($reg[5]) != "ACTIVO"){
          echo "<p style='color:red'>La cuenta $cuenta esta dada de baja</p>";
          echo "<a href='formDeposito.php'>Volver</a>";
          exit;
        }
        $encontrado = true;
        $nombre = trim($reg[2]);
        break;
      }
    }
  }

  if(!$encontrado){
    echo "<p style='color:red'>Cuenta $cuenta no encontrada</p>";
    echo "<a href='formDeposito.php'>Volver</a>";
    exit;
  }

  // Calcular saldo actual
  $saldo = 0;
  if(file_exists("movimientos.txt")){
    $fmov = fopen("movimientos.txt","r");
    while(!feof($fmov)){
      $linea = fgets($fmov);
      if(trim($linea) != ""){
        $m = explode("|",$linea);
        if(count($m) >= 5 && trim($m[0]) == $cuenta){
          $saldo = floatval($m[4]);
        }
      }
    }
    fclose($fmov);
  }

  $saldo = $saldo + $monto;
  $fecha = date("Y-m-d H:i:s");
  $registro = $cuenta."|".$fecha."|DEPOSITO|".$monto."|".$saldo."|TITULAR";

  $recurso = fopen("movimientos.txt","a");
  fwrite($recurso, $registro."\n");
  fclose($recurso);

  echo "<h3 style='color:green'>Deposito realizado exitosamente!</h3>";
  echo "<p><strong>Cuenta:</strong> $cuenta</p>";
  echo "<p><strong>Titular:</strong> $nombre</p>";
  echo "<p><strong>Monto:</strong> $monto Bs</p>";
  echo "<p><strong>Saldo actual:</strong> $saldo Bs</p>";
  echo "<p><a href='formDeposito.php'>Otro deposito</a> | <a href='estadoCuenta.php' target='_parent'>Estado de cuenta</a></p>";
?>

procesarDepositoTercero.phpArchivos de texto
Script de practica.
Abrir
Ver codigo

<?php
  $cuenta = $_POST["cuenta"] ?? "";
  $depositante = $_POST["depositante"] ?? "";
  $monto = floatval($_POST["monto"] ?? 0);

  if($cuenta == "" || $depositante == "" || $monto <= 0){
    echo "<p style='color:red'>Error: Todos los campos son obligatorios</p>";
    echo "<a href='formDepositoTercero.php'>Volver</a>";
    exit;
  }

  if(!file_exists("clientes.txt")){
    echo "<p style='color:red'>No hay clientes registrados</p>";
    exit;
  }

  // Verificar que la cuenta existe y esta activa
  $encontrado = false;
  $lineas = file("clientes.txt");
  for($i=0; $i<count($lineas); $i++){
    if(trim($lineas[$i]) != ""){
      $reg = explode("|",$lineas[$i]);
      if(count($reg) >= 6 && trim($reg[0]) == $cuenta){
        if(trim($reg[5]) != "ACTIVO"){
          echo "<p style='color:red'>La cuenta $cuenta esta dada de baja</p>";
          echo "<a href='formDepositoTercero.php'>Volver</a>";
          exit;
        }
        $encontrado = true;
        $nombre = trim($reg[2]);
        break;
      }
    }
  }

  if(!$encontrado){
    echo "<p style='color:red'>Cuenta $cuenta no encontrada</p>";
    echo "<a href='formDepositoTercero.php'>Volver</a>";
    exit;
  }

  // Calcular saldo actual
  $saldo = 0;
  if(file_exists("movimientos.txt")){
    $fmov = fopen("movimientos.txt","r");
    while(!feof($fmov)){
      $linea = fgets($fmov);
      if(trim($linea) != ""){
        $m = explode("|",$linea);
        if(count($m) >= 5 && trim($m[0]) == $cuenta){
          $saldo = floatval($m[4]);
        }
      }
    }
    fclose($fmov);
  }

  $saldo = $saldo + $monto;
  $fecha = date("Y-m-d H:i:s");
  $registro = $cuenta."|".$fecha."|DEPOSITO|".$monto."|".$saldo."|".$depositante;

  $recurso = fopen("movimientos.txt","a");
  fwrite($recurso, $registro."\n");
  fclose($recurso);

  echo "<h3 style='color:green'>Deposito de tercero realizado exitosamente!</h3>";
  echo "<p><strong>Cuenta:</strong> $cuenta ($nombre)</p>";
  echo "<p><strong>Depositante:</strong> $depositante</p>";
  echo "<p><strong>Monto:</strong> $monto Bs</p>";
  echo "<p><strong>Saldo actual:</strong> $saldo Bs</p>";
  echo "<p><a href='formDepositoTercero.php'>Otro deposito</a> | <a href='estadoCuenta.php' target='_parent'>Estado de cuenta</a></p>";
?>

procesarRetiro.phpArchivos de texto
Script de practica.
Abrir
Ver codigo

<?php
  $cuenta = $_POST["cuenta"] ?? "";
  $monto = floatval($_POST["monto"] ?? 0);

  if($cuenta == "" || $monto <= 0){
    echo "<p style='color:red'>Error: Cuenta y monto son obligatorios (monto > 0)</p>";
    echo "<a href='formRetiro.php'>Volver</a>";
    exit;
  }

  if(!file_exists("clientes.txt")){
    echo "<p style='color:red'>No hay clientes registrados</p>";
    exit;
  }

  // Verificar que la cuenta existe y esta activa
  $encontrado = false;
  $lineas = file("clientes.txt");
  for($i=0; $i<count($lineas); $i++){
    if(trim($lineas[$i]) != ""){
      $reg = explode("|",$lineas[$i]);
      if(count($reg) >= 6 && trim($reg[0]) == $cuenta){
        if(trim($reg[5]) != "ACTIVO"){
          echo "<p style='color:red'>La cuenta $cuenta esta dada de baja</p>";
          echo "<a href='formRetiro.php'>Volver</a>";
          exit;
        }
        $encontrado = true;
        $nombre = trim($reg[2]);
        break;
      }
    }
  }

  if(!$encontrado){
    echo "<p style='color:red'>Cuenta $cuenta no encontrada</p>";
    echo "<a href='formRetiro.php'>Volver</a>";
    exit;
  }

  // Calcular saldo actual
  $saldo = 0;
  if(file_exists("movimientos.txt")){
    $fmov = fopen("movimientos.txt","r");
    while(!feof($fmov)){
      $linea = fgets($fmov);
      if(trim($linea) != ""){
        $m = explode("|",$linea);
        if(count($m) >= 5 && trim($m[0]) == $cuenta){
          $saldo = floatval($m[4]);
        }
      }
    }
    fclose($fmov);
  }

  if($monto > $saldo){
    echo "<p style='color:red'>Saldo insuficiente! Saldo actual: $saldo Bs</p>";
    echo "<a href='formRetiro.php'>Volver</a>";
    exit;
  }

  $saldo = $saldo - $monto;
  $fecha = date("Y-m-d H:i:s");
  $registro = $cuenta."|".$fecha."|RETIRO|".$monto."|".$saldo."|TITULAR";

  $recurso = fopen("movimientos.txt","a");
  fwrite($recurso, $registro."\n");
  fclose($recurso);

  echo "<h3 style='color:green'>Retiro realizado exitosamente!</h3>";
  echo "<p><strong>Cuenta:</strong> $cuenta</p>";
  echo "<p><strong>Titular:</strong> $nombre</p>";
  echo "<p><strong>Monto:</strong> $monto Bs</p>";
  echo "<p><strong>Saldo actual:</strong> $saldo Bs</p>";
  echo "<p><a href='formRetiro.php'>Otro retiro</a> | <a href='estadoCuenta.php' target='_parent'>Estado de cuenta</a></p>";
?>

registrarCliente.phpArchivos de texto
Procesa el alta y guarda los datos.
Abrir
Ver codigo

<?php
  $nombre = $_POST["nombre"] ?? "";
  $ci = $_POST["ci"] ?? "";
  $celular = $_POST["celular"] ?? "";
  $direccion = $_POST["direccion"] ?? "";

  if($nombre == "" || $ci == "" || $celular == "" || $direccion == ""){
    echo "<p style='color:red'>Error: Todos los campos son obligatorios</p>";
    echo "<a href='formRegistrarCliente.php'>Volver</a>";
    exit;
  }

  // Verificar si ya existe la CI
  if(file_exists("clientes.txt")){
    $recurso = fopen("clientes.txt","r");
    while(!feof($recurso)){
      $linea = fgets($recurso);
      if(trim($linea) != ""){
        $reg = explode("|",$linea);
        if(count($reg) >= 2 && trim($reg[1]) == $ci){
          echo "<p style='color:red'>Error: Ya existe un cliente con CI $ci</p>";
          echo "<a href='formRegistrarCliente.php'>Volver</a>";
          fclose($recurso);
          exit;
        }
      }
    }
    fclose($recurso);
  }

  // Generar numero de cuenta autoincremental
  $numCuenta = "CTA00001";
  if(file_exists("clientes.txt")){
    $recurso = fopen("clientes.txt","r");
    while(!feof($recurso)){
      $linea = fgets($recurso);
      if(trim($linea) != ""){
        $reg = explode("|",$linea);
        if(count($reg) >= 1){
          $ultimo = trim($reg[0]);
          if(preg_match('/CTA(\d+)/',$ultimo,$m)){
            $num = intval($m[1]) + 1;
            $numCuenta = "CTA" . str_pad($num, 5, "0", STR_PAD_LEFT);
          }
        }
      }
    }
    fclose($recurso);
  }

  $fecha = date("Y-m-d H:i:s");
  $registro = $numCuenta."|".$ci."|".$nombre."|".$celular."|".$direccion."|ACTIVO|".$fecha;

  $recurso = fopen("clientes.txt","a");
  fwrite($recurso, $registro."\n");
  fclose($recurso);

  echo "<h3 style='color:green'>Cliente registrado exitosamente!</h3>";
  echo "<p><strong>Cuenta:</strong> $numCuenta</p>";
  echo "<p><strong>Nombre:</strong> $nombre</p>";
  echo "<p><strong>CI:</strong> $ci</p>";
  echo "<p><a href='formRegistrarCliente.php'>Registrar otro</a> | <a href='listarClientes.php' target='_parent'>Ver listado</a></p>";
?>

asignarMaterias.phpArchivos de texto
Script de practica.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Asignar Materias</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a237e; }
        input, select { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #27ae60; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #219a52; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
        table { border-collapse: collapse; margin-top: 15px; width: 100%; }
        td, th { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background: #1a237e; color: white; }
    </style>
</head>
<body>
    <h3>ASIGNAR MATERIAS A CURSOS</h3>
    <p>Cada curso tiene 7 materias. Un docente no puede repetirse en el mismo curso.</p>
    <form action="guardarAsignacion.php" method="post">
        <label>Curso:</label>
        <select name="curso" required>
            <option value="">-- Seleccionar --</option>
            <?php
              $cursos = array("1A","1B","1C","1D","2A","2B","3A","3B");
              foreach($cursos as $c) echo "<option value='$c'>$c</option>";
            ?>
        </select><br>
        <label>Materia:</label>
        <input type="text" name="materia" required><br>
        <label>Docente (carnet):</label>
        <select name="docente" required>
            <option value="">-- Seleccionar --</option>
            <?php
              if(file_exists("docentes.txt")){
                $recurso = fopen("docentes.txt","r");
                while(!feof($recurso)){
                  $linea = fgets($recurso);
                  if(trim($linea) != ""){
                    $reg = explode("|",$linea);
                    if(count($reg) >= 2){
                      echo "<option value='".trim($reg[0])."'>".trim($reg[0])." - ".trim($reg[1])."</option>";
                    }
                  }
                }
                fclose($recurso);
              }
            ?>
        </select><br>
        <input type="submit" value="Asignar Materia">
    </form>
    <br>
    <h4>Materias asignadas actualmente:</h4>
    <?php
      if(file_exists("materias.txt")){
        $recurso = fopen("materias.txt","r");
        echo "<table>";
        echo "<tr><th>Curso</th><th>Materia</th><th>Docente</th></tr>";
        while(!feof($recurso)){
          $linea = fgets($recurso);
          if(trim($linea) != ""){
            $reg = explode("|",$linea);
            if(count($reg) >= 3){
              echo "<tr>";
              echo "<td>".htmlspecialchars($reg[0])."</td>";
              echo "<td>".htmlspecialchars($reg[1])."</td>";
              echo "<td>".htmlspecialchars($reg[2])."</td>";
              echo "</tr>";
            }
          }
        }
        echo "</table>";
        fclose($recurso);
      }
    ?>
</body>
</html>

buscarDocente.phpArchivos de texto
Busqueda de registros.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Buscar Docente</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a237e; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #2980b9; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #2471a3; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
        table { border-collapse: collapse; margin-top: 15px; width: 100%; }
        td, th { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background: #1a237e; color: white; }
    </style>
</head>
<body>
    <h3>BUSCAR DOCENTE</h3>
    <form action="buscarDocente.php" method="get">
        <label>Buscar por (carnet o nombre):</label>
        <input type="text" name="criterio" required><br>
        <input type="submit" value="Buscar">
    </form>
    <?php
      $criterio = $_GET["criterio"] ?? "";
      if($criterio != "" && file_exists("docentes.txt")){
        $recurso = fopen("docentes.txt","r");
        echo "<table>";
        echo "<tr><th>Carnet</th><th>Nombre</th></tr>";
        $encontrados = 0;
        while(!feof($recurso)){
          $linea = fgets($recurso);
          if(trim($linea) != ""){
            $reg = explode("|",$linea);
            if(count($reg) >= 2){
              if(stripos($reg[0],$criterio) !== false || stripos($reg[1],$criterio) !== false){
                echo "<tr>";
                echo "<td>".htmlspecialchars($reg[0])."</td>";
                echo "<td>".htmlspecialchars($reg[1])."</td>";
                echo "</tr>";
                $encontrados++;
              }
            }
          }
        }
        echo "</table>";
        fclose($recurso);
        if($encontrados == 0) echo "<p>No se encontraron resultados para: $criterio</p>";
      }
    ?>
</body>
</html>

buscarEstudiante.phpArchivos de texto
Busqueda de registros.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Buscar Estudiante</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a237e; }
        input, select { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #2980b9; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #2471a3; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
        table { border-collapse: collapse; margin-top: 15px; width: 100%; }
        td, th { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background: #1a237e; color: white; }
    </style>
</head>
<body>
    <h3>BUSCAR ESTUDIANTE</h3>
    <form action="buscarEstudiante.php" method="get">
        <label>Buscar por (carnet, nombre o curso):</label>
        <input type="text" name="criterio" required><br>
        <input type="submit" value="Buscar">
    </form>
    <?php
      $criterio = $_GET["criterio"] ?? "";
      if($criterio != "" && file_exists("estudiantes.txt")){
        $recurso = fopen("estudiantes.txt","r");
        echo "<table>";
        echo "<tr><th>Carnet</th><th>Nombre</th><th>Curso</th><th>Foto</th></tr>";
        $encontrados = 0;
        while(!feof($recurso)){
          $linea = fgets($recurso);
          if(trim($linea) != ""){
            $reg = explode("|",$linea);
            if(count($reg) >= 3){
              if(stripos($reg[0],$criterio) !== false || stripos($reg[1],$criterio) !== false || stripos($reg[2],$criterio) !== false){
                echo "<tr>";
                echo "<td>".htmlspecialchars($reg[0])."</td>";
                echo "<td>".htmlspecialchars($reg[1])."</td>";
                echo "<td>".htmlspecialchars($reg[2])."</td>";
                $foto = (count($reg) >= 4 && trim($reg[3]) != "") ? "<img src='".trim($reg[3])."' width='50'>" : "Sin foto";
                echo "<td>$foto</td>";
                echo "</tr>";
                $encontrados++;
              }
            }
          }
        }
        echo "</table>";
        fclose($recurso);
        if($encontrados == 0) echo "<p>No se encontraron resultados para: $criterio</p>";
      }
    ?>
</body>
</html>

eliminarDocente.phpArchivos de texto
Elimina o anula un registro.
Abrir
Ver codigo

<?php
  $carnet = $_POST["carnet"];

  if(!file_exists("docentes.txt")){
    echo "<p>No hay docentes registrados</p>";
    exit;
  }

  $temporal = "docentes_temporal.txt";
  $recurso = fopen("docentes.txt","r");
  $recurso_tmp = fopen($temporal,"w");
  $encontrado = false;
  while(!feof($recurso)){
    $linea = fgets($recurso);
    $reg = explode("|",$linea);
    if(count($reg) >= 2 && trim($reg[0]) == $carnet){
      echo "Docente $carnet (".$reg[1].") eliminado<br>";
      $encontrado = true;
    } else {
      fwrite($recurso_tmp,$linea);
    }
  }
  fclose($recurso_tmp);
  fclose($recurso);

  if(!$encontrado){
    echo "<p style='color:red'>Docente con carnet $carnet no encontrado</p>";
    unlink($temporal);
  } else {
    unlink("docentes.txt");
    rename($temporal,"docentes.txt");
    // También eliminar sus asignaciones en materias.txt
    if(file_exists("materias.txt")){
      $temp2 = "materias_temporal.txt";
      $f1 = fopen("materias.txt","r");
      $f2 = fopen($temp2,"w");
      while(!feof($f1)){
        $linea = fgets($f1);
        $reg = explode("|",$linea);
        if(count($reg) >= 3 && trim($reg[2]) != $carnet){
          fwrite($f2,$linea);
        }
      }
      fclose($f1);
      fclose($f2);
      unlink("materias.txt");
      rename($temp2,"materias.txt");
    }
  }

  echo "<a href='formEliminarDocente.php'>Eliminar otro</a>";
?>

eliminarEstudiante.phpArchivos de texto
Elimina o anula un registro.
Abrir
Ver codigo

<?php
  $carnet = $_POST["carnet"];

  if(!file_exists("estudiantes.txt")){
    echo "<p>No hay estudiantes registrados</p>";
    exit;
  }

  $temporal = "estudiantes_temporal.txt";
  $recurso = fopen("estudiantes.txt","r");
  $recurso_tmp = fopen($temporal,"w");
  $encontrado = false;
  while(!feof($recurso)){
    $linea = fgets($recurso);
    $reg = explode("|",$linea);
    if(count($reg) >= 3 && trim($reg[0]) == $carnet){
      echo "Estudiante $carnet (".$reg[1].") eliminado<br>";
      $encontrado = true;
    } else {
      fwrite($recurso_tmp,$linea);
    }
  }
  fclose($recurso_tmp);
  fclose($recurso);

  if(!$encontrado){
    echo "<p style='color:red'>Estudiante con carnet $carnet no encontrado</p>";
    unlink($temporal);
  } else {
    unlink("estudiantes.txt");
    rename($temporal,"estudiantes.txt");
  }

  echo "<a href='formEliminarEstudiante.php'>Eliminar otro</a>";
?>

formEliminarDocente.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Eliminar Docente</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a237e; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #c0392b; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #a93226; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
    </style>
</head>
<body>
    <h3>ELIMINAR DOCENTE</h3>
    <form action="eliminarDocente.php" method="post">
        <label>Carnet del docente:</label>
        <input type="text" name="carnet" required><br>
        <input type="submit" value="Eliminar">
    </form>
</body>
</html>

formEliminarEstudiante.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Eliminar Estudiante</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a237e; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #c0392b; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #a93226; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
    </style>
</head>
<body>
    <h3>ELIMINAR ESTUDIANTE</h3>
    <form action="eliminarEstudiante.php" method="post">
        <label>Carnet del estudiante:</label>
        <input type="text" name="carnet" required><br>
        <input type="submit" value="Eliminar">
    </form>
</body>
</html>

formModificarDocente.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Modificar Docente</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a237e; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #f39c12; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #d68910; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
    </style>
</head>
<body>
    <h3>BUSCAR DOCENTE PARA MODIFICAR</h3>
    <form action="modificarDocente.php" method="post">
        <label>Carnet del docente:</label>
        <input type="text" name="carnet" required><br>
        <input type="submit" value="Buscar">
    </form>
</body>
</html>

formModificarEstudiante.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Modificar Estudiante</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a237e; }
        input, select { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #f39c12; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #d68910; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
    </style>
</head>
<body>
    <h3>BUSCAR ESTUDIANTE PARA MODIFICAR</h3>
    <form action="modificarEstudiante.php" method="post">
        <label>Carnet del estudiante:</label>
        <input type="text" name="carnet" required><br>
        <input type="submit" value="Buscar">
    </form>
</body>
</html>

formRegistrarDocente.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Registrar Docente</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a237e; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #27ae60; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #219a52; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
    </style>
</head>
<body>
    <h3>REGISTRAR DOCENTE</h3>
    <form action="guardarDocente.php" method="post">
        <label>Carnet:</label>
        <input type="text" name="carnet" required><br>
        <label>Nombre completo:</label>
        <input type="text" name="nombre" required><br>
        <input type="submit" value="Registrar Docente">
    </form>
</body>
</html>

formRegistrarEstudiante.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Registrar Estudiante</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a237e; }
        input, select { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #27ae60; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #219a52; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
    </style>
</head>
<body>
    <h3>REGISTRAR ESTUDIANTE</h3>
    <form action="registrarEstudiante.php" method="post" enctype="multipart/form-data">
        <label>Carnet:</label>
        <input type="text" name="carnet" required><br>
        <label>Nombre completo:</label>
        <input type="text" name="nombre" required><br>
        <label>Curso:</label>
        <select name="curso" required>
            <option value="">-- Seleccionar --</option>
            <option value="1A">1A</option>
            <option value="1B">1B</option>
            <option value="1C">1C</option>
            <option value="1D">1D</option>
            <option value="2A">2A</option>
            <option value="2B">2B</option>
            <option value="3A">3A</option>
            <option value="3B">3B</option>
        </select><br>
        <label>Fotografia (opcional):</label>
        <input type="file" name="foto" accept="image/*"><br>
        <input type="submit" value="Registrar Estudiante">
    </form>
</body>
</html>

guardarAsignacion.phpArchivos de texto
Procesa el alta y guarda los datos.
Abrir
Ver codigo

<?php
  $curso = $_POST["curso"] ?? "";
  $materia = $_POST["materia"] ?? "";
  $docente = $_POST["docente"] ?? "";

  if($curso == "" || $materia == "" || $docente == ""){
    echo "<p style='color:red'>Error: Todos los campos son obligatorios</p>";
    echo "<a href='asignarMaterias.php'>Volver</a>";
    exit;
  }

  // Verificar que el docente no este repetido en el mismo curso
  if(file_exists("materias.txt")){
    $recurso = fopen("materias.txt","r");
    while(!feof($recurso)){
      $linea = fgets($recurso);
      if(trim($linea) != ""){
        $reg = explode("|",$linea);
        if(count($reg) >= 3 && trim($reg[0]) == $curso && trim($reg[2]) == $docente){
          echo "<p style='color:red'>Error: El docente $docente ya esta asignado en el curso $curso</p>";
          echo "<a href='asignarMaterias.php'>Volver</a>";
          fclose($recurso);
          exit;
        }
      }
    }
    fclose($recurso);
  }

  // Verificar maximo 7 materias por curso
  if(file_exists("materias.txt")){
    $cuenta = 0;
    $recurso = fopen("materias.txt","r");
    while(!feof($recurso)){
      $linea = fgets($recurso);
      if(trim($linea) != ""){
        $reg = explode("|",$linea);
        if(count($reg) >= 3 && trim($reg[0]) == $curso){
          $cuenta++;
        }
      }
    }
    fclose($recurso);
    if($cuenta >= 7){
      echo "<p style='color:red'>El curso $curso ya tiene 7 materias asignadas (maximo)</p>";
      echo "<a href='asignarMaterias.php'>Volver</a>";
      exit;
    }
  }

  $registro = $curso."|".$materia."|".$docente;

  $recurso = fopen("materias.txt","a");
  fwrite($recurso, $registro."\n");
  fclose($recurso);

  echo "<h3 style='color:green'>Materia asignada exitosamente!</h3>";
  echo "<p><strong>Curso:</strong> $curso</p>";
  echo "<p><strong>Materia:</strong> $materia</p>";
  echo "<p><strong>Docente:</strong> $docente</p>";
  echo "<p><a href='asignarMaterias.php'>Asignar otra</a></p>";
?>

guardarDocente.phpArchivos de texto
Procesa el alta y guarda los datos.
Abrir
Ver codigo

<?php
  $carnet = $_POST["carnet"] ?? "";
  $nombre = $_POST["nombre"] ?? "";

  if($carnet == "" || $nombre == ""){
    echo "<p style='color:red'>Error: Todos los campos son obligatorios</p>";
    echo "<a href='formRegistrarDocente.php'>Volver</a>";
    exit;
  }

  // Verificar si ya existe
  if(file_exists("docentes.txt")){
    $recurso = fopen("docentes.txt","r");
    while(!feof($recurso)){
      $linea = fgets($recurso);
      if(trim($linea) != ""){
        $reg = explode("|",$linea);
        if(count($reg) >= 2 && trim($reg[0]) == $carnet){
          echo "<p style='color:red'>Error: Ya existe un docente con carnet $carnet</p>";
          echo "<a href='formRegistrarDocente.php'>Volver</a>";
          fclose($recurso);
          exit;
        }
      }
    }
    fclose($recurso);
  }

  $registro = $carnet."|".$nombre;

  $recurso = fopen("docentes.txt","a");
  fwrite($recurso, $registro."\n");
  fclose($recurso);

  echo "<h3 style='color:green'>Docente registrado exitosamente!</h3>";
  echo "<p><strong>Carnet:</strong> $carnet</p>";
  echo "<p><strong>Nombre:</strong> $nombre</p>";
  echo "<p><a href='formRegistrarDocente.php'>Registrar otro</a></p>";
?>

guardarModificarDocente.phpArchivos de texto
Modifica un registro existente.
Abrir
Ver codigo

<?php
  $carnet = $_POST["carnet"];
  $idx = intval($_POST["idx"]);
  $nombre = $_POST["nombre"];

  $lineas = file("docentes.txt");
  $nuevaLinea = $carnet."|".$nombre;
  $lineas[$idx] = $nuevaLinea."\n";

  file_put_contents("docentes.txt", implode("",$lineas));

  echo "<h3 style='color:green'>Docente modificado exitosamente!</h3>";
  echo "<p><a href='buscarDocente.php' target='_parent'>Buscar</a> | <a href='formModificarDocente.php'>Modificar otro</a></p>";
?>

guardarModificarEstudiante.phpSubida de archivosArchivos de texto
Modifica un registro existente.
Abrir
Ver codigo

<?php
  $carnet = $_POST["carnet"];
  $idx = intval($_POST["idx"]);
  $nombre = $_POST["nombre"];
  $curso = $_POST["curso"];

  $lineas = file("estudiantes.txt");
  $reg = explode("|",$lineas[$idx]);

  // Guardar foto nueva si se subio
  $rutaFoto = trim($reg[3]);
  if(isset($_FILES["foto"]) && $_FILES["foto"]["error"] == 0){
    $permitidos = array("image/jpeg","image/png","image/gif","image/webp");
    if(in_array($_FILES["foto"]["type"], $permitidos) && $_FILES["foto"]["size"] <= 5*1024*1024){
      $nombreFoto = $carnet . "_" . time() . "." . pathinfo($_FILES["foto"]["name"], PATHINFO_EXTENSION);
      move_uploaded_file($_FILES["foto"]["tmp_name"], "fotos/" . $nombreFoto);
      $rutaFoto = "fotos/" . $nombreFoto;
    }
  }

  $nuevaLinea = $carnet."|".$nombre."|".$curso."|".$rutaFoto;
  $lineas[$idx] = $nuevaLinea."\n";

  file_put_contents("estudiantes.txt", implode("",$lineas));

  echo "<h3 style='color:green'>Estudiante modificado exitosamente!</h3>";
  echo "<p><a href='buscarEstudiante.php' target='_parent'>Buscar</a> | <a href='formModificarEstudiante.php'>Modificar otro</a></p>";
?>

guardarNotas.phpArchivos de texto
Procesa el alta y guarda los datos.
Abrir
Ver codigo

<?php
  $curso = $_POST["curso"];
  $guardados = 0;

  // Cargar materias del curso
  $materiasCurso = array();
  if(file_exists("materias.txt")){
    $recurso = fopen("materias.txt","r");
    while(!feof($recurso)){
      $linea = fgets($recurso);
      if(trim($linea) != ""){
        $reg = explode("|",$linea);
        if(count($reg) >= 3 && trim($reg[0]) == $curso){
          $materiasCurso[] = trim($reg[1]);
        }
      }
    }
    fclose($recurso);
  }

  // Cargar estudiantes del curso
  $estudiantesCurso = array();
  if(file_exists("estudiantes.txt")){
    $recurso = fopen("estudiantes.txt","r");
    while(!feof($recurso)){
      $linea = fgets($recurso);
      if(trim($linea) != ""){
        $reg = explode("|",$linea);
        if(count($reg) >= 3 && trim($reg[2]) == $curso){
          $estudiantesCurso[] = trim($reg[0]);
        }
      }
    }
    fclose($recurso);
  }

  // Eliminar notas anteriores del curso
  if(file_exists("notas.txt")){
    $temporal = "notas_temporal.txt";
    $f1 = fopen("notas.txt","r");
    $f2 = fopen($temporal,"w");
    while(!feof($f1)){
      $linea = fgets($f1);
      if(trim($linea) != ""){
        $reg = explode("|",$linea);
        if(count($reg) >= 4 && trim($reg[2]) != $curso){
          fwrite($f2,$linea);
        }
      }
    }
    fclose($f1);
    fclose($f2);
    unlink("notas.txt");
    rename($temporal,"notas.txt");
  }

  // Guardar nuevas notas
  foreach($estudiantesCurso as $carnet){
    foreach($materiasCurso as $materia){
      $key = "nota_".$carnet."_".$materia;
      $nota = floatval($_POST[$key] ?? 0);

      // Determinar estado
      if($nota >= 61) $estado = "APROBADO";
      elseif($nota >= 40) $estado = "REPROBADO";
      else $estado = "ABANDONO";

      $registro = $carnet."|".$materia."|".$curso."|".$nota."|".$estado;
      $f = fopen("notas.txt","a");
      fwrite($f,$registro."\n");
      fclose($f);
      $guardados++;
    }
  }

  echo "<h3 style='color:green'>Notas guardadas exitosamente!</h3>";
  echo "<p>Se registraron $guardados registros de notas para el curso $curso</p>";
  echo "<p><a href='verPlanilla.php?curso=$curso' target='_parent'>Ver planilla</a> | <a href='registrarNotas.php'>Registrar notas de otro curso</a></p>";
?>

inicio.php
Listado / indice del ejercicio.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CALIFICACIONES SISTEMAS</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: Arial, sans-serif; background: #f0f0f0; }
        #principal { display: flex; height: 100vh; }
        #menu {
            width: 25%;
            background: linear-gradient(135deg, #1a237e, #3949ab);
            color: white;
            padding: 15px;
        }
        #menu h2 { text-align: center; margin-bottom: 20px; border-bottom: 2px solid white; padding-bottom: 10px; }
        #menu ul { list-style: none; }
        #menu ul li { margin: 8px 0; }
        #menu ul li a {
            display: block;
            color: white;
            text-decoration: none;
            padding: 10px 15px;
            border-radius: 5px;
            background: rgba(255,255,255,0.1);
            transition: background 0.3s;
        }
        #menu ul li a:hover { background: rgba(255,255,255,0.3); }
        #menu h3 { margin-top: 20px; margin-bottom: 10px; font-size: 14px; opacity: 0.8; }
        #conte { width: 75%; }
        #conte iframe { width: 100%; height: 100%; border: none; }
    </style>
</head>
<body>
    <div id="principal">
        <div id="menu">
            <h2>SISTEMA DE CALIFICACIONES</h2>
            <h3>ESTUDIANTES</h3>
            <nav>
                <ul>
                    <li><a href="formRegistrarEstudiante.php" target="container">REGISTRAR ESTUDIANTE</a></li>
                    <li><a href="formModificarEstudiante.php" target="container">MODIFICAR ESTUDIANTE</a></li>
                    <li><a href="formEliminarEstudiante.php" target="container">ELIMINAR ESTUDIANTE</a></li>
                    <li><a href="buscarEstudiante.php" target="container">BUSCAR ESTUDIANTE</a></li>
                </ul>
            </nav>
            <h3>DOCENTES</h3>
            <nav>
                <ul>
                    <li><a href="formRegistrarDocente.php" target="container">REGISTRAR DOCENTE</a></li>
                    <li><a href="formModificarDocente.php" target="container">MODIFICAR DOCENTE</a></li>
                    <li><a href="formEliminarDocente.php" target="container">ELIMINAR DOCENTE</a></li>
                    <li><a href="buscarDocente.php" target="container">BUSCAR DOCENTE</a></li>
                </ul>
            </nav>
            <h3>ACADEMICO</h3>
            <nav>
                <ul>
                    <li><a href="asignarMaterias.php" target="container">ASIGNAR MATERIAS</a></li>
                    <li><a href="registrarNotas.php" target="container">REGISTRAR NOTAS</a></li>
                    <li><a href="verPlanilla.php" target="container">VER PLANILLAS</a></li>
                </ul>
            </nav>
        </div>
        <div id="conte">
            <iframe name="container" src="" frameborder="0"></iframe>
        </div>
    </div>
</body>
</html>

modificarDocente.php
Modifica un registro existente.
Abrir
Ver codigo

<?php
  $carnet = $_POST["carnet"] ?? "";

  if($carnet == ""){
    echo "<p style='color:red'>Ingrese el carnet</p>";
    echo "<a href='formModificarDocente.php'>Volver</a>";
    exit;
  }

  if(!file_exists("docentes.txt")){
    echo "<p>No hay docentes registrados</p>";
    exit;
  }

  $encontrado = false;
  $lineas = file("docentes.txt");
  for($i=0; $i<count($lineas); $i++){
    if(trim($lineas[$i]) != ""){
      $reg = explode("|",$lineas[$i]);
      if(count($reg) >= 2 && trim($reg[0]) == $carnet){
        $encontrado = true;
        $idx = $i;
        break;
      }
    }
  }

  if(!$encontrado){
    echo "<p style='color:red'>Docente con carnet $carnet no encontrado</p>";
    echo "<a href='formModificarDocente.php'>Volver</a>";
    exit;
  }
?>
<h3>MODIFICAR DOCENTE - Carnet: <?php echo $carnet; ?></h3>
<form action="guardarModificarDocente.php" method="post">
    <input type="hidden" name="carnet" value="<?php echo $carnet; ?>">
    <input type="hidden" name="idx" value="<?php echo $idx; ?>">
    <label>Nombre completo:</label>
    <input type="text" name="nombre" value="<?php echo trim($reg[1]); ?>" required><br>
    <input type="submit" value="Guardar Cambios">
</form>

modificarEstudiante.php
Modifica un registro existente.
Abrir
Ver codigo

<?php
  $carnet = $_POST["carnet"] ?? "";

  if($carnet == ""){
    echo "<p style='color:red'>Ingrese el carnet</p>";
    echo "<a href='formModificarEstudiante.php'>Volver</a>";
    exit;
  }

  if(!file_exists("estudiantes.txt")){
    echo "<p>No hay estudiantes registrados</p>";
    exit;
  }

  $encontrado = false;
  $lineas = file("estudiantes.txt");
  for($i=0; $i<count($lineas); $i++){
    if(trim($lineas[$i]) != ""){
      $reg = explode("|",$lineas[$i]);
      if(count($reg) >= 3 && trim($reg[0]) == $carnet){
        $encontrado = true;
        $idx = $i;
        break;
      }
    }
  }

  if(!$encontrado){
    echo "<p style='color:red'>Estudiante con carnet $carnet no encontrado</p>";
    echo "<a href='formModificarEstudiante.php'>Volver</a>";
    exit;
  }
?>
<h3>MODIFICAR ESTUDIANTE - Carnet: <?php echo $carnet; ?></h3>
<form action="guardarModificarEstudiante.php" method="post" enctype="multipart/form-data">
    <input type="hidden" name="carnet" value="<?php echo $carnet; ?>">
    <input type="hidden" name="idx" value="<?php echo $idx; ?>">
    <label>Nombre completo:</label>
    <input type="text" name="nombre" value="<?php echo trim($reg[1]); ?>" required><br>
    <label>Curso:</label>
    <select name="curso" required>
        <?php
          $cursos = array("1A","1B","1C","1D","2A","2B","3A","3B");
          foreach($cursos as $c){
            $sel = ($c == trim($reg[2])) ? "selected" : "";
            echo "<option value='$c' $sel>$c</option>";
          }
        ?>
    </select><br>
    <label>Nueva fotografia (opcional):</label>
    <input type="file" name="foto" accept="image/*"><br>
    <?php if(count($reg) >= 4 && trim($reg[3]) != ""): ?>
        <p>Foto actual: <img src="<?php echo trim($reg[3]); ?>" width="100"></p>
    <?php endif; ?>
    <input type="submit" value="Guardar Cambios">
</form>

registrarEstudiante.phpSubida de archivosArchivos de texto
Procesa el alta y guarda los datos.
Abrir
Ver codigo

<?php
  $carnet = $_POST["carnet"] ?? "";
  $nombre = $_POST["nombre"] ?? "";
  $curso = $_POST["curso"] ?? "";

  if($carnet == "" || $nombre == "" || $curso == ""){
    echo "<p style='color:red'>Error: Todos los campos son obligatorios</p>";
    echo "<a href='formRegistrarEstudiante.php'>Volver</a>";
    exit;
  }

  // Verificar si ya existe el carnet
  if(file_exists("estudiantes.txt")){
    $recurso = fopen("estudiantes.txt","r");
    while(!feof($recurso)){
      $linea = fgets($recurso);
      if(trim($linea) != ""){
        $reg = explode("|",$linea);
        if(count($reg) >= 2 && trim($reg[0]) == $carnet){
          echo "<p style='color:red'>Error: Ya existe un estudiante con carnet $carnet</p>";
          echo "<a href='formRegistrarEstudiante.php'>Volver</a>";
          fclose($recurso);
          exit;
        }
      }
    }
    fclose($recurso);
  }

  // Verificar cupo (maximo 38 por curso)
  if(file_exists("estudiantes.txt")){
    $cuenta = 0;
    $recurso = fopen("estudiantes.txt","r");
    while(!feof($recurso)){
      $linea = fgets($recurso);
      if(trim($linea) != ""){
        $reg = explode("|",$linea);
        if(count($reg) >= 3 && trim($reg[2]) == $curso){
          $cuenta++;
        }
      }
    }
    fclose($recurso);
    if($cuenta >= 38){
      echo "<p style='color:red'>El curso $curso esta lleno (maximo 38 estudiantes). No se puede registrar.</p>";
      echo "<a href='formRegistrarEstudiante.php'>Volver</a>";
      exit;
    }
  }

  // Guardar foto
  $rutaFoto = "";
  if(isset($_FILES["foto"]) && $_FILES["foto"]["error"] == 0){
    $permitidos = array("image/jpeg","image/png","image/gif","image/webp");
    if(in_array($_FILES["foto"]["type"], $permitidos) && $_FILES["foto"]["size"] <= 5*1024*1024){
      $nombreFoto = $carnet . "_" . time() . "." . pathinfo($_FILES["foto"]["name"], PATHINFO_EXTENSION);
      move_uploaded_file($_FILES["foto"]["tmp_name"], "fotos/" . $nombreFoto);
      $rutaFoto = "fotos/" . $nombreFoto;
    }
  }

  $registro = $carnet."|".$nombre."|".$curso."|".$rutaFoto;

  $recurso = fopen("estudiantes.txt","a");
  fwrite($recurso, $registro."\n");
  fclose($recurso);

  echo "<h3 style='color:green'>Estudiante registrado exitosamente!</h3>";
  echo "<p><strong>Carnet:</strong> $carnet</p>";
  echo "<p><strong>Nombre:</strong> $nombre</p>";
  echo "<p><strong>Curso:</strong> $curso</p>";
  if($rutaFoto != "") echo "<p><strong>Foto:</strong> <img src='$rutaFoto' width='100'></p>";
  echo "<p><a href='formRegistrarEstudiante.php'>Registrar otro</a></p>";
?>

registrarNotas.phpArchivos de texto
Procesa el alta y guarda los datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Registrar Notas</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a237e; }
        input, select { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #27ae60; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #219a52; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
        .aprobado { color: green; font-weight: bold; }
        .reprobado { color: orange; font-weight: bold; }
        .abandono { color: red; font-weight: bold; }
    </style>
</head>
<body>
    <h3>REGISTRAR NOTAS FINALES</h3>
    <form action="registrarNotas.php" method="get">
        <label>Curso:</label>
        <select name="curso" required>
            <option value="">-- Seleccionar --</option>
            <?php
              $cursos = array("1A","1B","1C","1D","2A","2B","3A","3B");
              foreach($cursos as $c) echo "<option value='$c'>$c</option>";
            ?>
        </select><br>
        <input type="submit" value="Cargar Estudiantes y Materias">
    </form>
    <?php
      $curso = $_GET["curso"] ?? "";
      if($curso != ""){
        // Cargar materias del curso
        $materiasCurso = array();
        if(file_exists("materias.txt")){
          $recurso = fopen("materias.txt","r");
          while(!feof($recurso)){
            $linea = fgets($recurso);
            if(trim($linea) != ""){
              $reg = explode("|",$linea);
              if(count($reg) >= 3 && trim($reg[0]) == $curso){
                $materiasCurso[] = trim($reg[1]);
              }
            }
          }
          fclose($recurso);
        }

        if(count($materiasCurso) == 0){
          echo "<p style='color:red'>No hay materias asignadas al curso $curso. Asigne materias primero.</p>";
          exit;
        }

        // Cargar estudiantes del curso
        $estudiantesCurso = array();
        if(file_exists("estudiantes.txt")){
          $recurso = fopen("estudiantes.txt","r");
          while(!feof($recurso)){
            $linea = fgets($recurso);
            if(trim($linea) != ""){
              $reg = explode("|",$linea);
              if(count($reg) >= 3 && trim($reg[2]) == $curso){
                $estudiantesCurso[] = array(trim($reg[0]), trim($reg[1]));
              }
            }
          }
          fclose($recurso);
        }

        if(count($estudiantesCurso) == 0){
          echo "<p style='color:red'>No hay estudiantes en el curso $curso</p>";
          exit;
        }

        echo "<h4>Curso: $curso</h4>";
        echo "<form action='guardarNotas.php' method='post'>";
        echo "<input type='hidden' name='curso' value='$curso'>";
        echo "<table>";
        echo "<tr><th>Carnet</th><th>Nombre</th>";
        foreach($materiasCurso as $m) echo "<th>$m</th>";
        echo "</tr>";

        foreach($estudiantesCurso as $est){
          echo "<tr>";
          echo "<td>".htmlspecialchars($est[0])."</td>";
          echo "<td>".htmlspecialchars($est[1])."</td>";
          foreach($materiasCurso as $m){
            echo "<td><input type='number' name='nota_".$est[0]."_".$m."' min='0' max='100' value='0' style='width:60px'></td>";
          }
          echo "</tr>";
        }
        echo "</table>";
        echo "<br><input type='submit' value='Guardar Notas'>";
        echo "</form>";
      }
    ?>
</body>
</html>

verPlanilla.phpArchivos de texto
Script de practica.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Ver Planillas</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a237e; }
        input, select { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #2980b9; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #2471a3; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
        table { border-collapse: collapse; margin-top: 15px; width: 100%; }
        td, th { border: 1px solid #ccc; padding: 8px; text-align: center; }
        th { background: #1a237e; color: white; }
        .aprobado { background: #d4efdf; color: #27ae60; font-weight: bold; }
        .reprobado { background: #fdebd0; color: #e67e22; font-weight: bold; }
        .abandono { background: #fadbd8; color: #c0392b; font-weight: bold; }
        @media print { .no-print { display: none; } }
    </style>
</head>
<body>
    <h3>PLANILLAS DE NOTAS</h3>
    <div class="no-print">
        <form action="verPlanilla.php" method="get">
            <label>Curso:</label>
            <select name="curso" required>
                <option value="">-- Seleccionar --</option>
                <?php
                  $cursos = array("1A","1B","1C","1D","2A","2B","3A","3B");
                  foreach($cursos as $c) echo "<option value='$c' ".(($curso==$c)?'selected':'').">$c</option>";
                ?>
            </select><br>
            <input type="submit" value="Ver Planilla">
        </form>
    </div>
    <?php
      $curso = $_GET["curso"] ?? "";
      if($curso != "" && file_exists("notas.txt")){
        // Cargar materias del curso
        $materiasCurso = array();
        if(file_exists("materias.txt")){
          $recurso = fopen("materias.txt","r");
          while(!feof($recurso)){
            $linea = fgets($recurso);
            if(trim($linea) != ""){
              $reg = explode("|",$linea);
              if(count($reg) >= 3 && trim($reg[0]) == $curso){
                $materiasCurso[] = trim($reg[1]);
              }
            }
          }
          fclose($recurso);
        }

        // Cargar estudiantes del curso
        $estudiantesCurso = array();
        if(file_exists("estudiantes.txt")){
          $recurso = fopen("estudiantes.txt","r");
          while(!feof($recurso)){
            $linea = fgets($recurso);
            if(trim($linea) != ""){
              $reg = explode("|",$linea);
              if(count($reg) >= 3 && trim($reg[2]) == $curso){
                $estudiantesCurso[trim($reg[0])] = trim($reg[1]);
              }
            }
          }
          fclose($recurso);
        }

        // Cargar notas
        $notas = array();
        if(file_exists("notas.txt")){
          $recurso = fopen("notas.txt","r");
          while(!feof($recurso)){
            $linea = fgets($recurso);
            if(trim($linea) != ""){
              $reg = explode("|",$linea);
              if(count($reg) >= 5 && trim($reg[2]) == $curso){
                $key = trim($reg[0])."|".trim($reg[1]);
                $notas[$key] = array("nota" => $reg[3], "estado" => $reg[4]);
              }
            }
          }
          fclose($recurso);
        }

        echo "<h4>Curso: $curso</h4>";
        echo "<table>";
        echo "<tr><th>Carnet</th><th>Nombre</th>";
        foreach($materiasCurso as $m) echo "<th>$m</th>";
        echo "<th>Promedio</th></tr>";

        $aprobados = 0;
        $reprobados = 0;
        $abandonos = 0;

        foreach($estudiantesCurso as $carnet => $nombre){
          echo "<tr>";
          echo "<td>".htmlspecialchars($carnet)."</td>";
          echo "<td>".htmlspecialchars($nombre)."</td>";
          $suma = 0;
          $cont = 0;
          foreach($materiasCurso as $m){
            $key = $carnet."|".$m;
            if(isset($notas[$key])){
              $nota = $notas[$key]["nota"];
              $estado = $notas[$key]["estado"];
              $clase = strtolower($estado);
              echo "<td class='$clase'>".htmlspecialchars($nota)."</td>";
              $suma += floatval($nota);
              $cont++;
            } else {
              echo "<td>-</td>";
            }
          }
          $promedio = ($cont > 0) ? round($suma/$cont, 1) : 0;
          if($promedio >= 61) $aprobados++;
          elseif($promedio >= 40) $reprobados++;
          else $abandonos++;
          echo "<td><strong>$promedio</strong></td>";
          echo "</tr>";
        }
        echo "</table>";
        echo "<p><strong>Aprobados:</strong> $aprobados | <strong>Reprobados:</strong> $reprobados | <strong>Abandonos:</strong> $abandonos</p>";
        echo "<p class='no-print'><button onclick='window.print()' style='padding:10px 20px;background:#1a237e;color:white;border:none;cursor:pointer;border-radius:4px;font-weight:bold;'>IMPRIMIR</button></p>";
      }
    ?>
</body>
</html>

buscarCliente.phpArchivos de texto
Busqueda de registros.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Buscar por Cliente</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #6d4c41; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #2980b9; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #2471a3; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
        table { border-collapse: collapse; margin-top: 15px; width: 100%; }
        td, th { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background: #6d4c41; color: white; }
    </style>
</head>
<body>
    <h3>BUSCAR VENTAS POR CLIENTE</h3>
    <form action="buscarCliente.php" method="get">
        <label>Buscar por (NIT/CI o nombre):</label>
        <input type="text" name="criterio" required><br>
        <input type="submit" value="Buscar">
    </form>
    <?php
      $criterio = $_GET["criterio"] ?? "";
      if($criterio != "" && file_exists("pedidos.txt")){
        $recurso = fopen("pedidos.txt","r");
        echo "<table>";
        echo "<tr><th>Pedido</th><th>NIT/CI</th><th>Cliente</th><th>Fecha</th><th>Estado</th><th>Detalle</th></tr>";
        $encontrados = 0;
        while(!feof($recurso)){
          $linea = fgets($recurso);
          if(trim($linea) != ""){
            $reg = explode("|",$linea);
            if(count($reg) >= 5){
              if(stripos($reg[1],$criterio) !== false || stripos($reg[2],$criterio) !== false){
                echo "<tr>";
                echo "<td>".htmlspecialchars($reg[0])."</td>";
                echo "<td>".htmlspecialchars($reg[1])."</td>";
                echo "<td>".htmlspecialchars($reg[2])."</td>";
                echo "<td>".htmlspecialchars($reg[3])."</td>";
                echo "<td>".htmlspecialchars($reg[4])."</td>";
                // Mostrar detalle
                $detalle = "";
                if(file_exists("detalle_pedidos.txt")){
                  $fd = fopen("detalle_pedidos.txt","r");
                  while(!feof($fd)){
                    $dl = fgets($fd);
                    if(trim($dl) != ""){
                      $dd = explode("|",$dl);
                      if(count($dd) >= 5 && trim($dd[0]) == trim($reg[0])){
                        $detalle .= trim($dd[1])." x".$dd[3]." (".$dd[4]." Bs), ";
                      }
                    }
                  }
                  fclose($fd);
                }
                echo "<td>".htmlspecialchars(rtrim($detalle,", "))."</td>";
                echo "</tr>";
                $encontrados++;
              }
            }
          }
        }
        echo "</table>";
        fclose($recurso);
        if($encontrados == 0) echo "<p>No se encontraron resultados para: $criterio</p>";
      }
    ?>
</body>
</html>

eliminarPedido.phpArchivos de texto
Elimina o anula un registro.
Abrir
Ver codigo

<?php
  $numPedido = $_POST["numPedido"];

  if(!file_exists("pedidos.txt")){
    echo "<p>No hay pedidos registrados</p>";
    exit;
  }

  // Verificar si esta vendido
  $lineas = file("pedidos.txt");
  $encontrado = false;
  for($i=0; $i<count($lineas); $i++){
    if(trim($lineas[$i]) != ""){
      $reg = explode("|",$lineas[$i]);
      if(count($reg) >= 5 && trim($reg[0]) == $numPedido){
        if(trim($reg[4]) == "VENDIDO"){
          echo "<p style='color:red'>El pedido $numPedido ya fue vendido. No se puede eliminar.</p>";
          echo "<a href='formEliminarPedido.php'>Volver</a>";
          exit;
        }
        $encontrado = true;
        break;
      }
    }
  }

  if(!$encontrado){
    echo "<p style='color:red'>Pedido $numPedido no encontrado</p>";
    echo "<a href='formEliminarPedido.php'>Volver</a>";
    exit;
  }

  // Eliminar pedido del archivo
  $temporal = "pedidos_temporal.txt";
  $recurso = fopen("pedidos.txt","r");
  $recurso_tmp = fopen($temporal,"w");
  while(!feof($recurso)){
    $linea = fgets($recurso);
    $reg = explode("|",$linea);
    if(count($reg) >= 5 && trim($reg[0]) == $numPedido){
      echo "Pedido $numPedido eliminado<br>";
    } else {
      fwrite($recurso_tmp,$linea);
    }
  }
  fclose($recurso_tmp);
  fclose($recurso);
  unlink("pedidos.txt");
  rename($temporal,"pedidos.txt");

  // Eliminar detalle del pedido
  if(file_exists("detalle_pedidos.txt")){
    $temporal2 = "detalle_temporal.txt";
    $recurso = fopen("detalle_pedidos.txt","r");
    $recurso_tmp = fopen($temporal2,"w");
    while(!feof($recurso)){
      $linea = fgets($recurso);
      $reg = explode("|",$linea);
      if(count($reg) >= 5 && trim($reg[0]) != $numPedido){
        fwrite($recurso_tmp,$linea);
      }
    }
    fclose($recurso_tmp);
    fclose($recurso);
    unlink("detalle_pedidos.txt");
    rename($temporal2,"detalle_pedidos.txt");
  }

  echo "<h3 style='color:green'>Pedido eliminado exitosamente!</h3>";
  echo "<p><a href='formEliminarPedido.php'>Eliminar otro</a></p>";
?>

formEliminarPedido.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Eliminar Pedido</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #6d4c41; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #c0392b; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #a93226; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
    </style>
</head>
<body>
    <h3>ELIMINAR PEDIDO</h3>
    <p>Solo puede eliminar pedidos en estado PENDIENTE</p>
    <form action="eliminarPedido.php" method="post">
        <label>Numero de pedido:</label>
        <input type="text" name="numPedido" required><br>
        <input type="submit" value="Eliminar Pedido">
    </form>
</body>
</html>

formModificarPedido.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Modificar Pedido</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #6d4c41; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #f39c12; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #d68910; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
    </style>
</head>
<body>
    <h3>MODIFICAR PEDIDO</h3>
    <p>Solo puede modificar pedidos en estado PENDIENTE</p>
    <form action="modificarPedido.php" method="post">
        <label>Numero de pedido:</label>
        <input type="text" name="numPedido" required><br>
        <input type="submit" value="Buscar Pedido">
    </form>
</body>
</html>

formProducto.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Registrar Producto</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #6d4c41; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #27ae60; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #219a52; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
    </style>
</head>
<body>
    <h3>REGISTRAR PRODUCTO</h3>
    <form action="guardarProducto.php" method="post">
        <label>Nombre del producto:</label>
        <input type="text" name="nombre" required><br>
        <label>Cantidad existente:</label>
        <input type="number" name="cantidad" min="0" required><br>
        <label>Precio (Bs):</label>
        <input type="number" name="precio" min="0" step="0.01" required><br>
        <input type="submit" value="Registrar Producto">
    </form>
</body>
</html>

formRegistrarPedido.phpArchivos de texto
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Registrar Pedido</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #6d4c41; }
        input, select { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #27ae60; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #219a52; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
        .linea { background: white; padding: 10px; margin: 5px 0; border-radius: 4px; border: 1px solid #ddd; }
    </style>
</head>
<body>
    <h3>REGISTRAR NUEVO PEDIDO</h3>
    <form action="registrarPedido.php" method="post">
        <label>NIT/CI del cliente:</label>
        <input type="text" name="nit" required><br>
        <label>Nombre del cliente:</label>
        <input type="text" name="cliente" required><br>
        <hr>
        <h4>Detalle del pedido:</h4>
        <?php
          // Cargar productos disponibles
          if(file_exists("productos.txt")){
            $productos = [];
            $recurso = fopen("productos.txt","r");
            while(!feof($recurso)){
              $linea = fgets($recurso);
              if(trim($linea) != ""){
                $reg = explode("|",$linea);
                if(count($reg) >= 5 && trim($reg[4]) == "ACTIVO"){
                  $productos[] = $reg;
                }
              }
            }
            fclose($recurso);

            for($i=0; $i<5; $i++){
              echo "<div class='linea'>";
              echo "Linea ".($i+1).": <select name='producto_$i'>";
              echo "<option value=''>-- Seleccionar --</option>";
              foreach($productos as $p){
                echo "<option value='".trim($p[0])."'>".trim($p[1])." - ".trim($p[3])." Bs</option>";
              }
              echo "</select><br>";
              echo "Cantidad: <input type='number' name='cantidad_$i' min='1' value='1'><br>";
              echo "</div>";
            }
          } else {
            echo "<p style='color:red'>No hay productos registrados. Registre productos primero.</p>";
          }
        ?>
        <br>
        <input type="submit" value="Registrar Pedido">
    </form>
</body>
</html>

guardarModificarPedido.phpArchivos de texto
Modifica un registro existente.
Abrir
Ver codigo

<?php
  $numPedido = $_POST["numPedido"];
  $idx = intval($_POST["idx"]);
  $nit = $_POST["nit"];
  $cliente = $_POST["cliente"];

  $lineas = file("pedidos.txt");
  $reg = explode("|",$lineas[$idx]);
  $nuevaLinea = $reg[0]."|".$nit."|".$cliente."|".$reg[3]."|".$reg[4];
  $lineas[$idx] = $nuevaLinea."\n";

  file_put_contents("pedidos.txt", implode("",$lineas));

  echo "<h3 style='color:green'>Pedido modificado exitosamente!</h3>";
  echo "<p><a href='listarVentas.php' target='_parent'>Ver pedidos</a> | <a href='formModificarPedido.php'>Modificar otro</a></p>";
?>

guardarProducto.phpArchivos de texto
Procesa el alta y guarda los datos.
Abrir
Ver codigo

<?php
  $nombre = $_POST["nombre"] ?? "";
  $cantidad = intval($_POST["cantidad"] ?? 0);
  $precio = floatval($_POST["precio"] ?? 0);

  if($nombre == "" || $precio <= 0){
    echo "<p style='color:red'>Error: Nombre y precio son obligatorios</p>";
    echo "<a href='formProducto.php'>Volver</a>";
    exit;
  }

  // Generar codigo autoincremental
  $cod = "PROD001";
  if(file_exists("productos.txt")){
    $recurso = fopen("productos.txt","r");
    while(!feof($recurso)){
      $linea = fgets($recurso);
      if(trim($linea) != ""){
        $reg = explode("|",$linea);
        if(count($reg) >= 1){
          $ultimo = trim($reg[0]);
          if(preg_match('/PROD(\d+)/',$ultimo,$m)){
            $num = intval($m[1]) + 1;
            $cod = "PROD" . str_pad($num, 3, "0", STR_PAD_LEFT);
          }
        }
      }
    }
    fclose($recurso);
  }

  $registro = $cod."|".$nombre."|".$cantidad."|".$precio."|ACTIVO";

  $recurso = fopen("productos.txt","a");
  fwrite($recurso, $registro."\n");
  fclose($recurso);

  echo "<h3 style='color:green'>Producto registrado exitosamente!</h3>";
  echo "<p><strong>Codigo:</strong> $cod</p>";
  echo "<p><strong>Nombre:</strong> $nombre</p>";
  echo "<p><a href='formProducto.php'>Registrar otro</a> | <a href='listarProductos.php' target='_parent'>Ver productos</a></p>";
?>

inactivarProducto.phpArchivos de texto
Script de practica.
Abrir
Ver codigo

<?php
  $cod = $_GET["cod"] ?? "";

  if($cod == "" || !file_exists("productos.txt")){
    echo "<p style='color:red'>Producto no encontrado</p>";
    exit;
  }

  $temporal = "productos_temporal.txt";
  $recurso = fopen("productos.txt","r");
  $recurso_tmp = fopen($temporal,"w");
  while(!feof($recurso)){
    $linea = fgets($recurso);
    $reg = explode("|",$linea);
    if(count($reg) >= 5 && trim($reg[0]) == $cod){
      // Cambiar estado
      if(trim($reg[4]) == "ACTIVO"){
        $reg[4] = "INACTIVO";
        echo "Producto $cod inactivado<br>";
      } else {
        $reg[4] = "ACTIVO";
        echo "Producto $cod activado<br>";
      }
      fwrite($recurso_tmp, implode("|",$reg)."\n");
    } else {
      fwrite($recurso_tmp,$linea);
    }
  }
  fclose($recurso_tmp);
  fclose($recurso);
  unlink("productos.txt");
  rename($temporal,"productos.txt");

  echo "<a href='listarProductos.php' target='_parent'>Ver productos</a>";
?>

inicio.php
Listado / indice del ejercicio.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CAFETERIA ILLIMANI</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: Arial, sans-serif; background: #f0f0f0; }
        #principal { display: flex; height: 100vh; }
        #menu {
            width: 25%;
            background: linear-gradient(135deg, #6d4c41, #8d6e63);
            color: white;
            padding: 15px;
        }
        #menu h2 { text-align: center; margin-bottom: 20px; border-bottom: 2px solid white; padding-bottom: 10px; }
        #menu ul { list-style: none; }
        #menu ul li { margin: 8px 0; }
        #menu ul li a {
            display: block;
            color: white;
            text-decoration: none;
            padding: 10px 15px;
            border-radius: 5px;
            background: rgba(255,255,255,0.1);
            transition: background 0.3s;
        }
        #menu ul li a:hover { background: rgba(255,255,255,0.3); }
        #menu h3 { margin-top: 20px; margin-bottom: 10px; font-size: 14px; opacity: 0.8; }
        #conte { width: 75%; }
        #conte iframe { width: 100%; height: 100%; border: none; }
    </style>
</head>
<body>
    <div id="principal">
        <div id="menu">
            <h2>CAFETERIA ILLIMANI</h2>
            <h3>PEDIDOS</h3>
            <nav>
                <ul>
                    <li><a href="formRegistrarPedido.php" target="container">REGISTRAR PEDIDO</a></li>
                    <li><a href="formModificarPedido.php" target="container">MODIFICAR PEDIDO</a></li>
                    <li><a href="formEliminarPedido.php" target="container">ELIMINAR PEDIDO</a></li>
                    <li><a href="formRegistrarVenta.php" target="container">CONSOLIDAR VENTA</a></li>
                </ul>
            </nav>
            <h3>CONSULTAS</h3>
            <nav>
                <ul>
                    <li><a href="buscarCliente.php" target="container">BUSCAR POR CLIENTE</a></li>
                    <li><a href="reporteFechas.php" target="container">REPORTE POR FECHAS</a></li>
                    <li><a href="listarVentas.php" target="container">LISTAR VENTAS</a></li>
                </ul>
            </nav>
            <h3>PRODUCTOS</h3>
            <nav>
                <ul>
                    <li><a href="formProducto.php" target="container">REGISTRAR PRODUCTO</a></li>
                    <li><a href="listarProductos.php" target="container">LISTAR PRODUCTOS</a></li>
                </ul>
            </nav>
        </div>
        <div id="conte">
            <iframe name="container" src="" frameborder="0"></iframe>
        </div>
    </div>
</body>
</html>

listarProductos.phpError de sintaxisArchivos de texto
Listado / indice del ejercicio.
No ejecutable
Ver codigo

<?php
  if(!file_exists("productos.txt")){
    echo "<p>No hay productos registrados</p>";
    exit;
  }
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Listar Productos</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #6d4c41; }
        table { border-collapse: collapse; margin-top: 15px; width: 100%; }
        td, th { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background: #6d4c41; color: white; }
        .activo { color: green; font-weight: bold; }
        .inactivo { color: red; font-weight: bold; }
    </style>
</head>
<body>
    <h3>LISTADO DE PRODUCTOS</h3>
    <?php
      $recurso = fopen("productos.txt","r");
      echo "<table>";
      echo "<tr><th>Codigo</th><th>Producto</th><th>Cantidad</th><th>Precio</th><th>Estado</th><th>Acciones</th></tr>";
      while(!feof($recurso)){
        $linea = fgets($recurso);
        if(trim($linea) != ""){
          $reg = explode("|",$linea);
          if(count($reg) >= 5){
            $clase = (trim($reg[4]) == "ACTIVO") ? "activo" : "inactivo";
            echo "<tr>";
            echo "<td>".htmlspecialchars($reg[0])."</td>";
            echo "<td>".htmlspecialchars($reg[1])."</td>";
            echo "<td>".htmlspecialchars($reg[2])."</td>";
            echo "<td>".htmlspecialchars($reg[3])." Bs</td>";
            echo "<td class='$clase'>".htmlspecialchars($reg[4])."</td>";
            echo "<td>";
            echo "<a href='formProducto.php?cod=".urlencode(trim($reg[0]))."'>Modificar</a> | ";
            echo "<a href='inactivarProducto.php?cod=".urlencode(trim($reg[0])."' style='color:red'>Inactivar</a>";
            echo "</td>";
            echo "</tr>";
          }
        }
      }
      echo "</table>";
      fclose($recurso);
    ?>
</body>
</html>

listarVentas.phpArchivos de texto
Listado / indice del ejercicio.
Abrir
Ver codigo

<?php
  if(!file_exists("pedidos.txt")){
    echo "<p>No hay pedidos registrados</p>";
    exit;
  }
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Listar Ventas</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #6d4c41; }
        table { border-collapse: collapse; margin-top: 15px; width: 100%; }
        td, th { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background: #6d4c41; color: white; }
        .pendiente { color: orange; font-weight: bold; }
        .vendido { color: green; font-weight: bold; }
    </style>
</head>
<body>
    <h3>TODOS LOS PEDIDOS / VENTAS</h3>
    <?php
      $recurso = fopen("pedidos.txt","r");
      echo "<table>";
      echo "<tr><th>Pedido</th><th>NIT/CI</th><th>Cliente</th><th>Fecha</th><th>Estado</th><th>Detalle</th><th>Total</th></tr>";
      while(!feof($recurso)){
        $linea = fgets($recurso);
        if(trim($linea) != ""){
          $reg = explode("|",$linea);
          if(count($reg) >= 5){
            $clase = (trim($reg[4]) == "VENDIDO") ? "vendido" : "pendiente";
            $detalle = "";
            $total = 0;
            if(file_exists("detalle_pedidos.txt")){
              $fd = fopen("detalle_pedidos.txt","r");
              while(!feof($fd)){
                $dl = fgets($fd);
                if(trim($dl) != ""){
                  $dd = explode("|",$dl);
                  if(count($dd) >= 5 && trim($dd[0]) == trim($reg[0])){
                    $detalle .= trim($dd[1])." x".$dd[3]." (".$dd[4]." Bs), ";
                    $total += floatval($dd[4]);
                  }
                }
              }
              fclose($fd);
            }
            echo "<tr>";
            echo "<td>".htmlspecialchars($reg[0])."</td>";
            echo "<td>".htmlspecialchars($reg[1])."</td>";
            echo "<td>".htmlspecialchars($reg[2])."</td>";
            echo "<td>".htmlspecialchars($reg[3])."</td>";
            echo "<td class='$clase'>".htmlspecialchars($reg[4])."</td>";
            echo "<td>".htmlspecialchars(rtrim($detalle,", "))."</td>";
            echo "<td>$total Bs</td>";
            echo "</tr>";
          }
        }
      }
      echo "</table>";
      fclose($recurso);
    ?>
</body>
</html>

modificarPedido.php
Modifica un registro existente.
Abrir
Ver codigo

<?php
  $numPedido = $_POST["numPedido"] ?? "";

  if($numPedido == ""){
    echo "<p style='color:red'>Ingrese el numero de pedido</p>";
    echo "<a href='formModificarPedido.php'>Volver</a>";
    exit;
  }

  if(!file_exists("pedidos.txt")){
    echo "<p>No hay pedidos registrados</p>";
    exit;
  }

  $encontrado = false;
  $lineas = file("pedidos.txt");
  for($i=0; $i<count($lineas); $i++){
    if(trim($lineas[$i]) != ""){
      $reg = explode("|",$lineas[$i]);
      if(count($reg) >= 5 && trim($reg[0]) == $numPedido){
        if(trim($reg[4]) != "PENDIENTE"){
          echo "<p style='color:red'>El pedido $numPedido ya fue vendido. No se puede modificar.</p>";
          echo "<a href='formModificarPedido.php'>Volver</a>";
          exit;
        }
        $encontrado = true;
        $idx = $i;
        break;
      }
    }
  }

  if(!$encontrado){
    echo "<p style='color:red'>Pedido $numPedido no encontrado</p>";
    echo "<a href='formModificarPedido.php'>Volver</a>";
    exit;
  }
?>
<h3>MODIFICAR PEDIDO: <?php echo $numPedido; ?></h3>
<form action="guardarModificarPedido.php" method="post">
    <input type="hidden" name="numPedido" value="<?php echo $numPedido; ?>">
    <input type="hidden" name="idx" value="<?php echo $idx; ?>">
    <label>NIT/CI del cliente:</label>
    <input type="text" name="nit" value="<?php echo trim($reg[1]); ?>" required><br>
    <label>Nombre del cliente:</label>
    <input type="text" name="cliente" value="<?php echo trim($reg[2]); ?>" required><br>
    <input type="submit" value="Guardar Cambios">
</form>
<p><a href='formEliminarPedido.php'>Eliminar lineas del pedido</a></p>

registrarPedido.phpArchivos de texto
Procesa el alta y guarda los datos.
Abrir
Ver codigo

<?php
  $nit = $_POST["nit"] ?? "";
  $cliente = $_POST["cliente"] ?? "";

  if($nit == "" || $cliente == ""){
    echo "<p style='color:red'>Error: NIT/CI y nombre son obligatorios</p>";
    echo "<a href='formRegistrarPedido.php'>Volver</a>";
    exit;
  }

  // Generar numero de pedido autoincremental
  $numPedido = "PED00001";
  if(file_exists("pedidos.txt")){
    $recurso = fopen("pedidos.txt","r");
    while(!feof($recurso)){
      $linea = fgets($recurso);
      if(trim($linea) != ""){
        $reg = explode("|",$linea);
        if(count($reg) >= 1){
          $ultimo = trim($reg[0]);
          if(preg_match('/PED(\d+)/',$ultimo,$m)){
            $num = intval($m[1]) + 1;
            $numPedido = "PED" . str_pad($num, 5, "0", STR_PAD_LEFT);
          }
        }
      }
    }
    fclose($recurso);
  }

  $fecha = date("Y-m-d H:i:s");
  $registroPedido = $numPedido."|".$nit."|".$cliente."|".$fecha."|PENDIENTE";

  $recurso = fopen("pedidos.txt","a");
  fwrite($recurso, $registroPedido."\n");
  fclose($recurso);

  // Registrar detalle del pedido
  $total = 0;
  for($i=0; $i<5; $i++){
    $codProducto = $_POST["producto_$i"] ?? "";
    $cantidad = intval($_POST["cantidad_$i"] ?? 0);

    if($codProducto != "" && $cantidad > 0){
      // Buscar precio del producto
      if(file_exists("productos.txt")){
        $fp = fopen("productos.txt","r");
        while(!feof($fp)){
          $linea = fgets($fp);
          if(trim($linea) != ""){
            $p = explode("|",$linea);
            if(count($p) >= 5 && trim($p[0]) == $codProducto){
              $precio = floatval($p[3]);
              $subtotal = $precio * $cantidad;
              $total += $subtotal;

              $registroDetalle = $numPedido."|".trim($p[1])."|".$precio."|".$cantidad."|".$subtotal;
              $fd = fopen("detalle_pedidos.txt","a");
              fwrite($fd, $registroDetalle."\n");
              fclose($fd);
              break;
            }
          }
        }
        fclose($fp);
      }
    }
  }

  echo "<h3 style='color:green'>Pedido registrado exitosamente!</h3>";
  echo "<p><strong>Pedido:</strong> $numPedido</p>";
  echo "<p><strong>Cliente:</strong> $cliente ($nit)</p>";
  echo "<p><strong>Fecha:</strong> $fecha</p>";
  echo "<p><strong>Total:</strong> $total Bs</p>";
  echo "<p><a href='formRegistrarPedido.php'>Otro pedido</a> | <a href='formRegistrarVenta.php' target='_parent'>Consolidar venta</a></p>";
?>

registrarVenta.phpArchivos de texto
Procesa el alta y guarda los datos.
Abrir
Ver codigo

<?php
  $numPedido = $_POST["numPedido"] ?? "";

  if($numPedido == ""){
    echo "<p style='color:red'>Ingrese el numero de pedido</p>";
    echo "<a href='formRegistrarVenta.php'>Volver</a>";
    exit;
  }

  if(!file_exists("pedidos.txt")){
    echo "<p>No hay pedidos registrados</p>";
    exit;
  }

  // Buscar el pedido
  $encontrado = false;
  $lineas = file("pedidos.txt");
  for($i=0; $i<count($lineas); $i++){
    if(trim($lineas[$i]) != ""){
      $reg = explode("|",$lineas[$i]);
      if(count($reg) >= 5 && trim($reg[0]) == $numPedido){
        if(trim($reg[4]) != "PENDIENTE"){
          echo "<p style='color:red'>El pedido $numPedido ya fue vendido</p>";
          echo "<a href='formRegistrarVenta.php'>Volver</a>";
          exit;
        }
        $encontrado = true;
        $idx = $i;
        break;
      }
    }
  }

  if(!$encontrado){
    echo "<p style='color:red'>Pedido $numPedido no encontrado</p>";
    echo "<a href='formRegistrarVenta.php'>Volver</a>";
    exit;
  }

  // Cambiar estado a VENDIDO
  $reg = explode("|",$lineas[$idx]);
  $reg[4] = "VENDIDO";
  $lineas[$idx] = implode("|",$reg)."\n";
  file_put_contents("pedidos.txt", implode("",$lineas));

  // Calcular total desde detalle
  $total = 0;
  if(file_exists("detalle_pedidos.txt")){
    $fd = fopen("detalle_pedidos.txt","r");
    while(!feof($fd)){
      $linea = fgets($fd);
      if(trim($linea) != ""){
        $d = explode("|",$linea);
        if(count($d) >= 5 && trim($d[0]) == $numPedido){
          $total += floatval($d[4]);
        }
      }
    }
    fclose($fd);
  }

  echo "<h3 style='color:green'>Venta consolidada exitosamente!</h3>";
  echo "<p><strong>Pedido:</strong> $numPedido</p>";
  echo "<p><strong>Cliente:</strong> ".trim($reg[2])." (".trim($reg[1]).")</p>";
  echo "<p><strong>Total:</strong> $total Bs</p>";
  echo "<p><a href='formRegistrarVenta.php'>Otra venta</a> | <a href='listarVentas.php' target='_parent'>Ver ventas</a></p>";
?>

reporteFechas.phpArchivos de texto
Generacion de reportes.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Reporte por Fechas</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #6d4c41; }
        input { margin: 5px 0; padding: 8px; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
        input[type=submit] { width: auto; background: #2980b9; color: white; border: none; padding: 10px 25px; cursor: pointer; border-radius: 4px; font-weight: bold; }
        input[type=submit]:hover { background: #2471a3; }
        label { display: block; margin-top: 8px; font-weight: bold; color: #333; }
        table { border-collapse: collapse; margin-top: 15px; width: 100%; }
        td, th { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background: #6d4c41; color: white; }
    </style>
</head>
<body>
    <h3>REPORTE DE VENTAS POR RANGO DE FECHAS</h3>
    <form action="reporteFechas.php" method="get">
        <label>Fecha inicio:</label>
        <input type="date" name="fechaInicio" required><br>
        <label>Fecha fin:</label>
        <input type="date" name="fechaFin" required><br>
        <input type="submit" value="Generar Reporte">
    </form>
    <?php
      $fechaInicio = $_GET["fechaInicio"] ?? "";
      $fechaFin = $_GET["fechaFin"] ?? "";

      if($fechaInicio != "" && $fechaFin != "" && file_exists("pedidos.txt")){
        $recurso = fopen("pedidos.txt","r");
        echo "<h4>Ventas del $fechaInicio al $fechaFin</h4>";
        echo "<table>";
        echo "<tr><th>Pedido</th><th>NIT/CI</th><th>Cliente</th><th>Fecha</th><th>Detalle</th><th>Total</th></tr>";
        $totalGeneral = 0;
        $totalVentas = 0;
        while(!feof($recurso)){
          $linea = fgets($recurso);
          if(trim($linea) != ""){
            $reg = explode("|",$linea);
            if(count($reg) >= 5 && trim($reg[4]) == "VENDIDO"){
              $fechaPedido = substr(trim($reg[3]),0,10);
              if($fechaPedido >= $fechaInicio && $fechaPedido <= $fechaFin){
                $detalle = "";
                $total = 0;
                if(file_exists("detalle_pedidos.txt")){
                  $fd = fopen("detalle_pedidos.txt","r");
                  while(!feof($fd)){
                    $dl = fgets($fd);
                    if(trim($dl) != ""){
                      $dd = explode("|",$dl);
                      if(count($dd) >= 5 && trim($dd[0]) == trim($reg[0])){
                        $detalle .= trim($dd[1])." x".$dd[3]." (".$dd[4]." Bs), ";
                        $total += floatval($dd[4]);
                      }
                    }
                  }
                  fclose($fd);
                }
                echo "<tr>";
                echo "<td>".htmlspecialchars($reg[0])."</td>";
                echo "<td>".htmlspecialchars($reg[1])."</td>";
                echo "<td>".htmlspecialchars($reg[2])."</td>";
                echo "<td>".htmlspecialchars($reg[3])."</td>";
                echo "<td>".htmlspecialchars(rtrim($detalle,", "))."</td>";
                echo "<td>$total Bs</td>";
                echo "</tr>";
                $totalGeneral += $total;
                $totalVentas++;
              }
            }
          }
        }
        echo "</table>";
        fclose($recurso);
        echo "<p><strong>Total ventas:</strong> $totalVentas | <strong>Monto total:</strong> $totalGeneral Bs</p>";
      }
    ?>
</body>
</html>

SISCOOP

Sistema cooperativo: clientes, depositos, retiros y reportes sobre archivos de texto.
adicionar.phpArchivos de texto
Procesa el alta y guarda los datos.
Abrir
Ver codigo

<?php
  $carnet = $_POST["carnet"];
  $paterno = $_POST["paterno"];
  $materno = $_POST["materno"];
  $nombres = $_POST["nombres"];
  $celular = $_POST["celular"];
  $email = $_POST["email"];

  $nomArch = "clientes.txt";
  $recurso = fopen($nomArch,"a+") or die("NO se puede crear el recurso");
  $registro = $carnet."|".$paterno."|".$materno."|".$nombres."|".$celular."|".$email;
  fwrite($recurso,$registro."\n");

  fclose($recurso);

  echo "Se ha registrado exitosamente !";
?>
busqueda.phpArchivos de texto
Busqueda de registros.
Abrir
Ver codigo

<?php

$nomArch = "programacion.csv";

$recurso = false;
if (file_exists($nomArch)) {
    $recurso = fopen($nomArch,"r");
}
if ($recurso == false) {
    echo "<p>No existe la planilla. Ejecute primero el codigo2.php</p>";
} else {
    echo "<table border = '1'>";
    echo "<tr>";
    echo "<th>Carnet</th>";
    echo "<th>Paterno</th>";
    echo "<th>Materno</th>";
    echo "<th>Nombres</th>";
    echo "<th>Curso</th>";
    echo "<th>Ciudad</th>";
    echo "<th>Nota Final</th>";
    echo "<th>Estado</th>";
    echo "</tr>";
    while (!feof($recurso)) {
        $linea = fgets($recurso);
        if (trim($linea)!="") {
            $registro = explode(",",$linea);

            $nota1 = trim($registro[5]);
            $nota2 = trim($registro[6]);
            $nota3 = trim($registro[7]);
            $nota4 = trim($registro[8]);

            $notaFinal = ($nota1 + $nota2 + $nota3 + $nota4) / 4;
            $notaFinal = round($notaFinal);

            if ($notaFinal >= 51) {
                $estado = "Aprobado";
            } else {
                $estado = "Reprobado";
            }

            echo "<tr>";
            echo "<td>".trim($registro[0])."</td>";
            echo "<td>".trim($registro[1])."</td>";
            echo "<td>".trim($registro[2])."</td>";
            echo "<td>".trim($registro[3])."</td>";
            echo "<td>Programación</td>";
            echo "<td>".trim($registro[10])."</td>";
            echo "<td>".$notaFinal."</td>";
            echo "<td>".$estado."</td>";
            echo "</tr>";
        }
    }
    echo "</table>";
    fclose($recurso);
}
echo "<p><a href='index.php'>Volver al menu</a></p>";
?>
depositos.phpArchivos de texto
Script de practica.
Abrir
Ver codigo

<?php
  $carnet_cliente = $_POST["carnet_cliente"];
  $hora_deposito = $_POST["hora_deposito"];
  $fecha_deposito = $_POST["fecha_deposito"];
  $nom_depositante = $_POST["nom_depositante"];
  $nombres = $_POST["nombres"];
  $monto_deposito = $_POST["monto_deposito"];

  $nomArch = "depositos.txt";
  $recurso = fopen($nomArch,"a+") or die("NO se puede crear el recurso");
  $registro = $carnet_cliente."|".$hora_deposito."|".$fecha_deposito."|".$nom_depositante."|".$nombres."|".$monto_deposito;
  fwrite($recurso,$registro."\n");

  fclose($recurso);

  echo "Cliente ".$nom_depositante." ha depositado con exito el monto de: ".$monto_deposito." Bs.";
?>
eliminar.phpArchivos de texto
Elimina o anula un registro.
Abrir
Ver codigo

<?php
 $carnet = $_POST["carnet"];
 $nomArch = "clientes.txt";
 $temporal ="clientes_temporal.txt";
 $recurso = fopen($nomArch,"r") or die("NO se puede crear el recurso");
 $recurso_tmp = fopen($temporal,"w") or die("NO se puede crear el recurso");
 while(!feof($recurso)){
    $linea = fgets($recurso);
    $registro = explode("|", $linea) ;
    if($registro[0]==trim($carnet)){
        echo "REGISTRO ENCONTRADO...!carnet: ".$carnet."<br>";
    }
    else{
        fwrite($recurso_tmp,$linea);
    }
 }
fclose($recurso_tmp);
fclose($recurso);
unlink($nomArch);
rename($temporal,$nomArch);

?>
formAdicionar.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <h3>AGREGAR CLIENTES</h3>
        <form action="adicionar.php" method="post">
            carnet:<input type="number" name="carnet" required><br>
            paterno:<input type="text" name="paterno"><br>
            materno:<input type="text" name="materno"><br>
            nombres:<input type="text" name="nombres" required><br>
            celular:<input type="number" name="celular" required><br>
            email:<input type="email" name="email" required><br>
            <input type="submit" value="Registrar Cliente">
        </form>
    </div>
</body>
</html>
formDepositos.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <h3>REALIZAR DEPOSITOS</h3>
        <form action="depositos.php" method="post">
            carnet:<input type="number" name="carnet_cliente" required><br>
            hora del deposito:<input type="time" name="hora_deposito"><br>
            fecha del deposito:<input type="date" name="fecha_deposito"><br>
            nombre:<input type="text" name="nom_depositante"><br>
            nombre del depositante:<input type="text" name="nombres" required><br>
            monto del deposito:<input type="number" name="monto_deposito" required><br>
            <input type="submit" value="REALIZAR DEPOSITO">
        </form>
    </div>
</body>
</html>
formEliminar.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ELIMINAR CLIENTES</title>
</head>
<body>
    <div>
        <h3>ELIMINAR CLIENTES</h3>
        <form action="eliminar.php" method="post">
            Carnet:<input type="number" name="carnet" required><br>
            <input type="submit" value="Registrar Cliente">
        </form>
    </div>
</body>
</html>
formModificar.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ELIMINAR CLIENTES</title>
</head>
<body>
    <div>
        <h3>MODIFICAR CLIENTES</h3>
        <form action="formModificar2.php" method="post">
            Carnet:<input type="number" name="carnet" required><br>
            <input type="submit" value="Buscar Cliente">
        </form>
    </div>
</body>
</html>
formModificar2.phpArchivos de texto
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PLANILLA MODIFICAR</title>
</head>
<body>
    <div>
        <h3>MODIFICAR CLIENTES</h3>

            <?php
                $carnet = $_POST["carnet"];
                $recurso = fopen("clientes.txt","r");
                while(!feof($recurso)){
                    $linea = fgets($recurso);
                    $datos = explode("|",$linea);
                    if($datos[0]==$carnet){
?>
        <form action="modificar.php" method="post">
            carnet:<input type="number" name="carnet"  value="<?=$datos[0];?>" disabled><br>
            paterno:<input type="text" name="paterno" value="<?=$datos[1];?>"><br>
            materno:<input type="text" name="materno" value="<?=$datos[2];?>"><br>
            nombres:<input type="text" name="nombres" value="<?=$datos[3];?>" required><br>
            celular:<input type="number" name="celular" value="<?=$datos[4];?>" required><br>
            email:<input type="email" name="email"  value="<?=$datos[5];?>" required><br>
            <input type="submit" value="Modificar Cliente">
        </form>
<?php
                    }
                }
            ?>        

    </div>
</body>
</html>
formRetiros.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <h3>REALIZAR RETIROS</h3>
        <form action="retiros.php" method="post">
            carnet:<input type="number" name="carnet_cliente" required><br>
            hora del deposito:<input type="time" name="hora_deposito"><br>
            fecha del deposito:<input type="date" name="fecha_deposito"><br>
            monto de retiro:<input type="text" name="monto_retiro"><br>
            <input type="submit" value="REALIZAR RETIRO">
        </form>
    </div>
</body>
</html>
inicio.php
Listado / indice del ejercicio.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>COOPERATIVA</title>
    <style>
        #principal{
            background-color:lightgray;
            width:100%;
            height:600px;
        }
        #principal div#menu{
            background-color:lightgreen;
            width:25%;
            float: left;
        }
        #principal div#conte{
            width:75%;
            float: right;
        }        
    </style>
</head>
<body>
    <h3>SISTEMA COOPERATIVA SISINFO</h3>
    <div id="principal">
        <div id="menu">
            <h3>MENU</h3>
            <nav>
                <ul>
                    <li><a href="formAdicionar.php" target="container">AGREGAR CLIENTE</a></li>
                    <li><a href="formEliminar.php" target="container">ELIMINAR CLIENTE</a></li>
                    <li><a href="formModificar.php" target="container">MODIFICAR CLIENTE</a></li>
                    <li><a>MOSTRAR CLIENTES</a></li>
                </ul>
            </nav>
            <nav>
                <ul>
                    <li><a href="formDepositos.php" target="container">REALIZAR DEPOSITOS</a></li>
                    <li><a href="formRetiros.php" target="container">REALIZAR RETIROS</a></li>
                    <li><a href="reportes.php" target="container">REPORTES</a></li>
                    
                </ul>
            </nav>
        </div>
        <div id="conte">
            <iframe name="container" src="" frameborder="0" width="100%" height="600"></iframe>
        </div>
    </div>
</body>
</html>
reportes.phpArchivos de texto
Generacion de reportes.
Abrir
Ver codigo

<?php
$retiros = "retiros.txt";
$depositos = "depositos.txt";

$recurso = false;
if (file_exists($depositos)|| file_exists($retiros)) {
    $recurso = fopen($retiros,"r");
    $recurso = fopen($depositos,"r");
}
if ($recurso == false) {
    echo "<p>No existen datos</p>";
} else {

    echo "<h3>DEPOSITOS</h3>";
    echo "<table border = '1'>";
    echo "<tr>";
    echo "<th>Carnet</th>";
    echo "<th>Hora del deposito</th>";
    echo "<th>Fecha del deposito</th>";
    echo "<th>Nombre</th>";
    echo "<th>Nombre del depositante</th>";
    echo "<th>Monto del deposito</th>";
    echo "</tr>";
    echo "</table>";
    $nota1 = trim($registro[5]);
    $nota2 = trim($registro[6]);
    $nota3 = trim($registro[7]);
    $nota4 = trim($registro[8]);
    echo "<h3>RETIROS</h3>";
    echo "<table border = '1'>";
    echo "<tr>";
    echo "<th>Carnet</th>";
    echo "<th>Hora del deposito</th>";
    echo "<th>Fecha del deposito</th>";
    echo "<th>Monto del retiro</th>";
    echo "</tr>";
    echo "</table>";
    fclose($recurso);
}
?>
retiros.phpArchivos de texto
Script de practica.
Abrir
Ver codigo

<?php
  $carnet_cliente = $_POST["carnet_cliente"];
  $hora_deposito = $_POST["hora_deposito"];
  $fecha_deposito = $_POST["fecha_deposito"];
  $monto_retiro = $_POST["monto_retiro"];


  $nomArch = "retiros.txt";
  $recurso = fopen($nomArch,"a+") or die("NO se puede crear el recurso");
  $registro = $carnet_cliente."|".$hora_deposito."|".$fecha_deposito."|".$monto_retiro;
  fwrite($recurso,$registro."\n");

  fclose($recurso);

  echo "Se ha rerirado el monto de ".$monto_retiro."!";
?>

SISTEMA_VENTAS

Sistema de ventas con MySQL: clientes, productos, usuarios, ventas y reportes.
cliente_detalle.phpMySQL
Script de practica.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirLogin();

$id = isset($_GET["id"]) ? (int) $_GET["id"] : 0;
$consulta = mysqli_query($conexion,
    "SELECT * FROM clientes WHERE id_cliente = $id LIMIT 1");
$cliente = mysqli_fetch_assoc($consulta);

if (!$cliente) {
    flash("error", "El cliente solicitado no existe.");
    redirigir("clientes.php");
}

$ventas = mysqli_query($conexion,
    "SELECT v.*, u.nombre AS vendedor
     FROM ventas v
     INNER JOIN usuarios u ON u.id_usuario = v.id_usuario
     WHERE v.id_cliente = $id
     ORDER BY v.fecha DESC");

$resumen = mysqli_fetch_assoc(mysqli_query($conexion,
    "SELECT COUNT(*) AS compras,
            COALESCE(SUM(total), 0) AS total,
            MAX(fecha) AS ultima
     FROM ventas
     WHERE id_cliente = $id AND estado = 'EMITIDA'"));

$titulo = "Cliente: " . $cliente["nombre"];
$activo = "clientes";
include "header.php";
?>

<div class="caja">
    <div class="caja-cabecera">
        <div>
            <h2><?= e($cliente["nombre"]) ?></h2>
            <p>Código <?= e($cliente["codigo"]) ?> &middot; <?= $cliente["activo"] ? "Activo" : "Inactivo" ?></p>
        </div>
        <div class="acciones">
            <a href="venta_nueva.php?cliente=<?= (int) $cliente["id_cliente"] ?>" class="btn btn-verde">Nueva venta</a>
            <?php if (esAdmin()) { ?>
                <a href="cliente_form.php?id=<?= (int) $cliente["id_cliente"] ?>" class="btn btn-gris">Editar</a>
            <?php } ?>
            <a href="clientes.php" class="btn btn-gris">Volver</a>
        </div>
    </div>

    <div class="campos">
        <div class="campo">
            <label>CI / NIT</label>
            <p><?= e($cliente["ci_nit"]) ?: "-" ?></p>
        </div>
        <div class="campo">
            <label>Teléfono</label>
            <p><?= e($cliente["telefono"]) ?: "-" ?></p>
        </div>
        <div class="campo">
            <label>Dirección</label>
            <p><?= e($cliente["direccion"]) ?: "-" ?></p>
        </div>
        <div class="campo">
            <label>Correo electrónico</label>
            <p><?= e($cliente["email"]) ?: "-" ?></p>
        </div>
    </div>
</div>

<div class="tarjetas">
    <div class="tarjeta">
        <div class="etiqueta">Compras realizadas</div>
        <div class="valor"><?= (int) $resumen["compras"] ?></div>
    </div>
    <div class="tarjeta verde">
        <div class="etiqueta">Total comprado</div>
        <div class="valor">Bs <?= dinero($resumen["total"]) ?></div>
    </div>
    <div class="tarjeta">
        <div class="etiqueta">Última compra</div>
        <div class="valor" style="font-size:18px;"><?= $resumen["ultima"] ? fechaBonita($resumen["ultima"]) : "Sin compras" ?></div>
    </div>
</div>

<div class="caja">
    <div class="caja-cabecera">
        <div>
            <h2>Historial de compras</h2>
            <p>Todas las ventas registradas a este cliente</p>
        </div>
    </div>

    <div class="tabla-caja">
        <table class="tabla">
            <thead>
            <tr>
                <th>N°</th>
                <th>Fecha</th>
                <th>Vendedor</th>
                <th class="derecha">Subtotal</th>
                <th class="derecha">Descuento</th>
                <th class="derecha">Total</th>
                <th>Estado</th>
                <th></th>
            </tr>
            </thead>
            <tbody>
            <?php if (mysqli_num_rows($ventas) === 0) { ?>
                <tr><td colspan="8" class="sin-datos">Este cliente todavía no tiene compras.</td></tr>
            <?php } ?>
            <?php while ($venta = mysqli_fetch_assoc($ventas)) { ?>
                <tr>
                    <td>#<?= (int) $venta["id_venta"] ?></td>
                    <td><?= fechaBonita($venta["fecha"]) ?></td>
                    <td><?= e($venta["vendedor"]) ?></td>
                    <td class="derecha">Bs <?= dinero($venta["subtotal"]) ?></td>
                    <td class="derecha">Bs <?= dinero($venta["descuento"]) ?></td>
                    <td class="derecha"><strong>Bs <?= dinero($venta["total"]) ?></strong></td>
                    <td>
                        <span class="badge <?= $venta["estado"] === "ANULADA" ? "rojo" : "" ?>">
                            <?= e($venta["estado"]) ?>
                        </span>
                    </td>
                    <td>
                        <a href="venta_detalle.php?id=<?= (int) $venta["id_venta"] ?>"
                           class="btn btn-gris btn-pequeno">Ver</a>
                    </td>
                </tr>
            <?php } ?>
            </tbody>
        </table>
    </div>
</div>

<?php include "footer.php"; ?>

cliente_estado.phpMySQL
Script de practica.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirAdmin();

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    redirigir("clientes.php");
}

$id = (int) ($_POST["id"] ?? 0);
$accion = $_POST["accion"] ?? "";

if ($id <= 0 || !in_array($accion, ["activar", "inactivar"])) {
    flash("error", "Solicitud no válida.");
    redirigir("clientes.php");
}

$nuevoEstado = $accion === "activar" ? 1 : 0;

$sentencia = mysqli_prepare($conexion,
    "UPDATE clientes SET activo = ? WHERE id_cliente = ?");
mysqli_stmt_bind_param($sentencia, "ii", $nuevoEstado, $id);
mysqli_stmt_execute($sentencia);

flash("exito", $nuevoEstado ? "Cliente activado." : "Cliente inactivado.");
redirigir("clientes.php");

cliente_form.phpMySQL
Formulario de entrada de datos.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirAdmin();

$id = isset($_GET["id"]) ? (int) $_GET["id"] : 0;
$cliente = [
    "codigo" => siguienteCodigo($conexion, "clientes", "codigo", "CLI-", 4),
    "nombre" => "",
    "ci_nit" => "",
    "telefono" => "",
    "direccion" => "",
    "email" => "",
    "activo" => 1
];

if ($id > 0) {
    $consulta = mysqli_query($conexion, "SELECT * FROM clientes WHERE id_cliente = $id LIMIT 1");
    $encontrado = mysqli_fetch_assoc($consulta);
    if (!$encontrado) {
        flash("error", "El cliente solicitado no existe.");
        redirigir("clientes.php");
    }
    $cliente = $encontrado;
}

$titulo = $id > 0 ? "Editar cliente" : "Nuevo cliente";
$activo = "clientes";
include "header.php";
?>

<div class="caja formulario">
    <div class="caja-cabecera">
        <div>
            <h2><?= $id > 0 ? "Editar cliente" : "Registrar cliente" ?></h2>
            <p>Los campos con (*) son obligatorios</p>
        </div>
    </div>

    <form method="post" action="cliente_guardar.php">
        <input type="hidden" name="id" value="<?= (int) $id ?>">

        <div class="campos">
            <div class="campo">
                <label for="codigo">Código *</label>
                <input type="text" name="codigo" id="codigo" required maxlength="20"
                       value="<?= e($cliente["codigo"]) ?>">
            </div>

            <div class="campo">
                <label for="nombre">Nombre o razón social *</label>
                <input type="text" name="nombre" id="nombre" required maxlength="150"
                       value="<?= e($cliente["nombre"]) ?>">
            </div>

            <div class="campo">
                <label for="ci_nit">CI / NIT</label>
                <input type="text" name="ci_nit" id="ci_nit" maxlength="30"
                       value="<?= e($cliente["ci_nit"]) ?>">
            </div>

            <div class="campo">
                <label for="telefono">Teléfono</label>
                <input type="text" name="telefono" id="telefono" maxlength="30"
                       value="<?= e($cliente["telefono"]) ?>">
            </div>

            <div class="campo campo-completo">
                <label for="direccion">Dirección</label>
                <input type="text" name="direccion" id="direccion" maxlength="200"
                       value="<?= e($cliente["direccion"]) ?>">
            </div>

            <div class="campo campo-completo">
                <label for="email">Correo electrónico</label>
                <input type="email" name="email" id="email" maxlength="120"
                       value="<?= e($cliente["email"]) ?>">
            </div>
        </div>

        <div class="form-acciones">
            <button type="submit" class="btn btn-verde">Guardar cliente</button>
            <a href="clientes.php" class="btn btn-gris">Cancelar</a>
        </div>
    </form>
</div>

<?php include "footer.php"; ?>

cliente_guardar.phpMySQL
Procesa el alta y guarda los datos.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirAdmin();

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    redirigir("clientes.php");
}

$id = (int) ($_POST["id"] ?? 0);
$codigo = trim($_POST["codigo"] ?? "");
$nombre = trim($_POST["nombre"] ?? "");
$ciNit = trim($_POST["ci_nit"] ?? "");
$telefono = trim($_POST["telefono"] ?? "");
$direccion = trim($_POST["direccion"] ?? "");
$email = trim($_POST["email"] ?? "");

if ($codigo === "" || $nombre === "") {
    flash("error", "El código y el nombre del cliente son obligatorios.");
    redirigir($id > 0 ? "cliente_form.php?id=$id" : "cliente_form.php");
}

if ($email !== "" && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    flash("error", "El correo electrónico no es válido.");
    redirigir($id > 0 ? "cliente_form.php?id=$id" : "cliente_form.php");
}

// Verificar que el código no esté repetido
$sentencia = mysqli_prepare($conexion,
    "SELECT id_cliente FROM clientes WHERE codigo = ? AND id_cliente <> ? LIMIT 1");
mysqli_stmt_bind_param($sentencia, "si", $codigo, $id);
mysqli_stmt_execute($sentencia);
mysqli_stmt_store_result($sentencia);

if (mysqli_stmt_num_rows($sentencia) > 0) {
    flash("error", "Ya existe otro cliente con el código $codigo.");
    redirigir($id > 0 ? "cliente_form.php?id=$id" : "cliente_form.php");
}
mysqli_stmt_close($sentencia);

if ($id > 0) {
    $sentencia = mysqli_prepare($conexion,
        "UPDATE clientes
         SET codigo = ?, nombre = ?, ci_nit = ?, telefono = ?, direccion = ?, email = ?
         WHERE id_cliente = ?");
    mysqli_stmt_bind_param($sentencia, "ssssssi",
        $codigo, $nombre, $ciNit, $telefono, $direccion, $email, $id);
    mysqli_stmt_execute($sentencia);
    flash("exito", "Cliente actualizado correctamente.");
} else {
    $sentencia = mysqli_prepare($conexion,
        "INSERT INTO clientes (codigo, nombre, ci_nit, telefono, direccion, email)
         VALUES (?, ?, ?, ?, ?, ?)");
    mysqli_stmt_bind_param($sentencia, "ssssss",
        $codigo, $nombre, $ciNit, $telefono, $direccion, $email);
    mysqli_stmt_execute($sentencia);
    flash("exito", "Cliente registrado correctamente.");
}

redirigir("clientes.php");

clientes.phpMySQL
Script de practica.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirLogin();

$buscar = trim($_GET["buscar"] ?? "");
$estado = $_GET["estado"] ?? "activos";

$condiciones = [];
if ($buscar !== "") {
    $buscarSeguro = mysqli_real_escape_string($conexion, $buscar);
    $condiciones[] = "(c.nombre LIKE '%$buscarSeguro%' OR c.codigo LIKE '%$buscarSeguro%' OR c.ci_nit LIKE '%$buscarSeguro%')";
}

if ($estado === "activos") {
    $condiciones[] = "c.activo = 1";
} elseif ($estado === "inactivos") {
    $condiciones[] = "c.activo = 0";
}

$where = count($condiciones) > 0 ? "WHERE " . implode(" AND ", $condiciones) : "";

$clientes = mysqli_query($conexion,
    "SELECT c.*,
            (SELECT COUNT(*) FROM ventas v
              WHERE v.id_cliente = c.id_cliente AND v.estado = 'EMITIDA') AS compras,
            (SELECT COALESCE(SUM(v.total), 0) FROM ventas v
              WHERE v.id_cliente = c.id_cliente AND v.estado = 'EMITIDA') AS total_comprado
     FROM clientes c
     $where
     ORDER BY c.nombre ASC");

$titulo = "Clientes";
$activo = "clientes";
include "header.php";
?>

<div class="caja">
    <div class="caja-cabecera">
        <div>
            <h2>Clientes registrados</h2>
            <p>Datos de contacto e historial de compras</p>
        </div>
        <?php if (esAdmin()) { ?>
            <a href="cliente_form.php" class="btn btn-verde">Nuevo cliente</a>
        <?php } ?>
    </div>

    <form method="get" action="clientes.php" class="filtros">
        <div class="campo">
            <label for="buscar">Buscar</label>
            <input type="text" name="buscar" id="buscar" value="<?= e($buscar) ?>"
                   placeholder="Nombre, código o documento">
        </div>
        <div class="campo">
            <label for="estado">Estado</label>
            <select name="estado" id="estado">
                <option value="activos" <?= $estado === "activos" ? "selected" : "" ?>>Activos</option>
                <option value="inactivos" <?= $estado === "inactivos" ? "selected" : "" ?>>Inactivos</option>
                <option value="todos" <?= $estado === "todos" ? "selected" : "" ?>>Todos</option>
            </select>
        </div>
        <button type="submit" class="btn">Filtrar</button>
        <a href="clientes.php" class="btn btn-gris">Limpiar</a>
    </form>

    <div class="tabla-caja">
        <table class="tabla">
            <thead>
            <tr>
                <th>Código</th>
                <th>Nombre</th>
                <th>CI / NIT</th>
                <th>Teléfono</th>
                <th class="centro">Compras</th>
                <th class="derecha">Total comprado</th>
                <th>Estado</th>
                <th>Acciones</th>
            </tr>
            </thead>
            <tbody>
            <?php if (mysqli_num_rows($clientes) === 0) { ?>
                <tr><td colspan="8" class="sin-datos">No se encontraron clientes con ese filtro.</td></tr>
            <?php } ?>

            <?php while ($cliente = mysqli_fetch_assoc($clientes)) { ?>
                <tr>
                    <td><?= e($cliente["codigo"]) ?></td>
                    <td>
                        <a href="cliente_detalle.php?id=<?= (int) $cliente["id_cliente"] ?>">
                            <?= e($cliente["nombre"]) ?>
                        </a>
                    </td>
                    <td><?= e($cliente["ci_nit"]) ?></td>
                    <td><?= e($cliente["telefono"]) ?></td>
                    <td class="centro"><?= (int) $cliente["compras"] ?></td>
                    <td class="derecha">Bs <?= dinero($cliente["total_comprado"]) ?></td>
                    <td>
                        <span class="badge <?= $cliente["activo"] ? "" : "gris" ?>">
                            <?= $cliente["activo"] ? "Activo" : "Inactivo" ?>
                        </span>
                    </td>
                    <td>
                        <div class="acciones">
                            <a href="cliente_detalle.php?id=<?= (int) $cliente["id_cliente"] ?>"
                               class="btn btn-gris btn-pequeno">Ver</a>

                            <?php if (esAdmin()) { ?>
                                <a href="cliente_form.php?id=<?= (int) $cliente["id_cliente"] ?>"
                                   class="btn btn-gris btn-pequeno">Editar</a>

                                <form method="post" action="cliente_estado.php"
                                      onsubmit="return confirm('¿Seguro que quieres cambiar el estado de este cliente?');">
                                    <input type="hidden" name="id" value="<?= (int) $cliente["id_cliente"] ?>">
                                    <input type="hidden" name="accion" value="<?= $cliente["activo"] ? "inactivar" : "activar" ?>">
                                    <button type="submit" class="btn <?= $cliente["activo"] ? "btn-rojo" : "btn-verde" ?> btn-pequeno">
                                        <?= $cliente["activo"] ? "Inactivar" : "Activar" ?>
                                    </button>
                                </form>
                            <?php } ?>
                        </div>
                    </td>
                </tr>
            <?php } ?>
            </tbody>
        </table>
    </div>
</div>

<?php include "footer.php"; ?>

comprobante.phpMySQL
Script de practica.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirLogin();

$usuario = usuarioActual();
$id = isset($_GET["id"]) ? (int) $_GET["id"] : 0;

$consulta = mysqli_query($conexion,
    "SELECT v.*,
            COALESCE(c.nombre, 'Consumidor final') AS cliente,
            c.ci_nit AS cliente_documento,
            u.nombre AS vendedor
     FROM ventas v
     LEFT JOIN clientes c ON c.id_cliente = v.id_cliente
     INNER JOIN usuarios u ON u.id_usuario = v.id_usuario
     WHERE v.id_venta = $id
     LIMIT 1");
$venta = mysqli_fetch_assoc($consulta);

if (!$venta) {
    flash("error", "La venta solicitada no existe.");
    redirigir("ventas.php");
}

if (!esAdmin() && (int) $venta["id_usuario"] !== (int) $usuario["id_usuario"]) {
    flash("error", "No tienes permiso para ver este comprobante.");
    redirigir("ventas.php");
}

$detalles = mysqli_query($conexion,
    "SELECT * FROM detalle_ventas WHERE id_venta = $id ORDER BY id_detalle ASC");

$titulo = "Comprobante #" . $venta["id_venta"];
$activo = "ventas";
include "header.php";
?>

<div class="no-imprimir" style="display:flex; gap:10px; flex-wrap:wrap; margin-bottom:18px;">
    <button type="button" class="btn btn-verde" onclick="window.print();">Imprimir comprobante</button>
    <a href="venta_detalle.php?id=<?= (int) $venta["id_venta"] ?>" class="btn btn-gris">Ver detalle</a>
    <a href="ventas.php" class="btn btn-gris">Historial de ventas</a>
</div>

<div class="comprobante-wrapper">
    <div class="comprobante">
        <h2>TIENDA KEMAMADA</h2>
        <div class="negocio">
            Sistema de ventas<br>
            Comprobante simple de venta
        </div>

        <?php if ($venta["estado"] === "ANULADA") { ?>
            <div class="anulada">VENTA ANULADA</div>
        <?php } ?>

        <div style="display:flex; justify-content:space-between; font-size:12px;">
            <span><strong>N°:</strong> <?= str_pad((string) $venta["id_venta"], 6, "0", STR_PAD_LEFT) ?></span>
            <span><strong>Fecha:</strong> <?= fechaBonita($venta["fecha"]) ?></span>
        </div>

        <div class="linea"></div>

        <div style="font-size:12px; line-height:1.7;">
            <strong>Cliente:</strong> <?= e($venta["cliente"]) ?><br>
            <?php if ($venta["cliente_documento"]) { ?>
                <strong>CI / NIT:</strong> <?= e($venta["cliente_documento"]) ?><br>
            <?php } ?>
            <strong>Vendedor:</strong> <?= e($venta["vendedor"]) ?>
        </div>

        <div class="linea"></div>

        <table>
            <thead>
            <tr>
                <th style="width:12%;">Cant.</th>
                <th>Descripción</th>
                <th style="width:20%;" class="derecha">P. Unit.</th>
                <th style="width:20%;" class="derecha">Subtotal</th>
            </tr>
            </thead>
            <tbody>
            <?php while ($detalle = mysqli_fetch_assoc($detalles)) { ?>
                <tr>
                    <td><?= (int) $detalle["cantidad"] ?></td>
                    <td><?= e($detalle["producto_nombre"]) ?></td>
                    <td class="derecha"><?= dinero($detalle["precio_unitario"]) ?></td>
                    <td class="derecha"><?= dinero($detalle["subtotal"]) ?></td>
                </tr>
            <?php } ?>
            </tbody>
        </table>

        <div class="totales">
            <div>
                <span>Subtotal</span>
                <span>Bs <?= dinero($venta["subtotal"]) ?></span>
            </div>
            <div>
                <span>Descuento</span>
                <span>- Bs <?= dinero($venta["descuento"]) ?></span>
            </div>
            <div class="total-final">
                <span>TOTAL</span>
                <span>Bs <?= dinero($venta["total"]) ?></span>
            </div>
        </div>

        <div class="gracias">
            ¡Gracias por su compra!<br>
            Este documento es un comprobante interno.
        </div>
    </div>
</div>

<?php include "footer.php"; ?>

conexion.phpMySQL
Conexion a la base de datos.
Abrir
Ver codigo

<?php

$servidor  = "127.0.0.1";
$puerto    = 3307;
$usuario   = "ventas_user";
$clave     = "***";
$base_datos = "ventas_db";

$conexion = mysqli_connect($servidor, $usuario, $clave, $base_datos, $puerto);

mysqli_set_charset($conexion, "utf8mb4");

footer.php
Script de practica.
Abrir
Ver codigo

        </main>

        <footer class="pie">
            Sistema de ventas para una tienda &middot; Proyecto de Diseño y Programación Web 3
        </footer>
    </div>
</div>
</body>
</html>

funciones.phpMySQLSesionesRedireccion
Script de practica.
Abrir
Ver codigo

<?php

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

date_default_timezone_set("America/La_Paz");


function e($texto)
{
    return htmlspecialchars((string) $texto, ENT_QUOTES, "UTF-8");
}


function dinero($monto)
{
    return number_format((float) $monto, 2, ",", ".");
}


function fechaBonita($fecha)
{
    if (!$fecha) {
        return "-";
    }
    return date("d/m/Y H:i", strtotime($fecha));
}

function redirigir($pagina)
{
    header("Location: " . $pagina);
    exit;
}

function estaLogueado()
{
    return isset($_SESSION["usuario"]);
}

function usuarioActual()
{
    return $_SESSION["usuario"] ?? null;
}

function esAdmin()
{
    return estaLogueado() && $_SESSION["usuario"]["rol"] === "administrador";
}

function exigirLogin()
{
    if (!estaLogueado()) {
        redirigir("login.php");
    }
}

function exigirAdmin()
{
    exigirLogin();
    if (!esAdmin()) {
        flash("error", "No tienes permiso para entrar a esa opción.");
        redirigir("index.php");
    }
}


function flash($tipo, $mensaje)
{
    $_SESSION["flash"] = ["tipo" => $tipo, "mensaje" => $mensaje];
}

function mostrarFlash()
{
    if (isset($_SESSION["flash"])) {
        $tipo = $_SESSION["flash"]["tipo"];
        $mensaje = $_SESSION["flash"]["mensaje"];
        unset($_SESSION["flash"]);
        echo '<div class="aviso ' . e($tipo) . '">' . e($mensaje) . "</div>";
    }
}

function adminsActivos($conexion, $excluirId = 0)
{
    $excluirId = (int) $excluirId;
    $resultado = mysqli_query($conexion,
        "SELECT COUNT(*) AS total
         FROM usuarios
         WHERE rol = 'administrador' AND activo = 1 AND id_usuario <> $excluirId");
    $fila = mysqli_fetch_assoc($resultado);
    return (int) $fila["total"];
}

function siguienteCodigo($conexion, $tabla, $campo, $prefijo, $digitos)
{
    $sql = "SELECT MAX(CAST(SUBSTRING($campo, " . (strlen($prefijo) + 1) . ") AS UNSIGNED)) AS ultimo FROM $tabla";
    $resultado = mysqli_query($conexion, $sql);
    $fila = mysqli_fetch_assoc($resultado);
    $numero = ((int) ($fila["ultimo"] ?? 0)) + 1;

    return $prefijo . str_pad((string) $numero, $digitos, "0", STR_PAD_LEFT);
}

header.php
Script de practica.
Abrir
Ver codigo

<?php
require_once __DIR__ . "/funciones.php";
exigirLogin();

$titulo = $titulo ?? "Sistema de Ventas";
$activo = $activo ?? "";
$usuario = usuarioActual();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= e($titulo) ?> | Tienda KemaMada</title>
    <link rel="stylesheet" href="estilos.css">
</head>
<body>
<div class="layout">

    <aside class="sidebar">
        <div class="marca">
            <span class="marca-icono">KM</span>
            <div>
                <strong>Tienda KemaMada</strong>
                <small>Sistema de ventas</small>
            </div>
        </div>

        <nav class="menu">
            <a href="index.php" class="<?= $activo === "inicio" ? "activo" : "" ?>">Inicio</a>
            <a href="venta_nueva.php" class="<?= $activo === "nueva" ? "activo" : "" ?>">Nueva venta</a>
            <a href="ventas.php" class="<?= $activo === "ventas" ? "activo" : "" ?>">Historial de ventas</a>
            <a href="clientes.php" class="<?= $activo === "clientes" ? "activo" : "" ?>">Clientes</a>

            <?php if (esAdmin()) { ?>
                <span class="menu-titulo">Administración</span>
                <a href="productos.php" class="<?= $activo === "productos" ? "activo" : "" ?>">Productos</a>
                <a href="usuarios.php" class="<?= $activo === "usuarios" ? "activo" : "" ?>">Usuarios</a>
                <a href="reportes.php" class="<?= $activo === "reportes" ? "activo" : "" ?>">Reportes</a>
            <?php } ?>
        </nav>

        <div class="sidebar-pie">
            <a href="logout.php">Cerrar sesión</a>
        </div>
    </aside>

    <div class="contenido">
        <header class="topbar">
            <div>
                <h1><?= e($titulo) ?></h1>
                <p><?= date("d/m/Y") ?> &middot; <?= $usuario["rol"] === "administrador" ? "Administrador" : "Vendedor" ?></p>
            </div>
            <div class="usuario-caja">
                <span class="avatar"><?= e(strtoupper(substr($usuario["nombre"], 0, 1))) ?></span>
                <div>
                    <strong><?= e($usuario["nombre"]) ?></strong>
                    <small><?= e($usuario["usuario"]) ?></small>
                </div>
            </div>
        </header>

        <main class="principal">
            <?php mostrarFlash(); ?>

index.phpMySQL
Script de practica.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirLogin();

$usuario = usuarioActual();
$esAdmin = esAdmin();
$filtroUsuario = $esAdmin ? "" : " AND id_usuario = " . (int) $usuario["id_usuario"];


$hoy = mysqli_fetch_assoc(mysqli_query($conexion,
    "SELECT COUNT(*) AS cantidad, COALESCE(SUM(total), 0) AS monto
     FROM ventas
     WHERE estado = 'EMITIDA' AND DATE(fecha) = CURDATE()" . $filtroUsuario));

$mes = mysqli_fetch_assoc(mysqli_query($conexion,
    "SELECT COUNT(*) AS cantidad, COALESCE(SUM(total), 0) AS monto
     FROM ventas
     WHERE estado = 'EMITIDA'
       AND YEAR(fecha) = YEAR(CURDATE())
       AND MONTH(fecha) = MONTH(CURDATE())" . $filtroUsuario));

$productos = mysqli_fetch_assoc(mysqli_query($conexion,
    "SELECT COUNT(*) AS total FROM productos WHERE activo = 1"));

$clientes = mysqli_fetch_assoc(mysqli_query($conexion,
    "SELECT COUNT(*) AS total FROM clientes WHERE activo = 1"));

$stockBajo = mysqli_fetch_assoc(mysqli_query($conexion,
    "SELECT COUNT(*) AS total FROM productos
     WHERE activo = 1 AND stock <= stock_minimo"));

$ultimas = mysqli_query($conexion,
    "SELECT v.id_venta, v.fecha, v.total, v.estado,
            COALESCE(c.nombre, 'Consumidor final') AS cliente,
            u.nombre AS vendedor
     FROM ventas v
     LEFT JOIN clientes c ON c.id_cliente = v.id_cliente
     INNER JOIN usuarios u ON u.id_usuario = v.id_usuario
     WHERE 1 = 1" . ($esAdmin ? "" : " AND v.id_usuario = " . (int) $usuario["id_usuario"]) . "
     ORDER BY v.fecha DESC
     LIMIT 6");

$consultaDias = mysqli_query($conexion,
    "SELECT DATE(fecha) AS dia, SUM(total) AS monto
     FROM ventas
     WHERE estado = 'EMITIDA'
       AND fecha >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)" . $filtroUsuario . "
     GROUP BY DATE(fecha)");

$porDia = [];
while ($fila = mysqli_fetch_assoc($consultaDias)) {
    $porDia[$fila["dia"]] = (float) $fila["monto"];
}

$dias = [];
$maximo = 0;
for ($i = 6; $i >= 0; $i--) {
    $fecha = date("Y-m-d", strtotime("-$i day"));
    $monto = $porDia[$fecha] ?? 0;
    $dias[] = ["fecha" => $fecha, "monto" => $monto];
    if ($monto > $maximo) {
        $maximo = $monto;
    }
}


$bajoStock = null;
if ($esAdmin) {
    $bajoStock = mysqli_query($conexion,
        "SELECT codigo, nombre, stock, stock_minimo
         FROM productos
         WHERE activo = 1 AND stock <= stock_minimo
         ORDER BY stock ASC
         LIMIT 6");
}

$titulo = "Inicio";
$activo = "inicio";
include "header.php";
?>

<div class="tarjetas">
    <div class="tarjeta verde">
        <div class="etiqueta"><?= $esAdmin ? "Ventas de hoy" : "Mis ventas de hoy" ?></div>
        <div class="valor">Bs <?= dinero($hoy["monto"]) ?></div>
        <div class="nota"><?= (int) $hoy["cantidad"] ?> venta(s) registrada(s)</div>
    </div>

    <div class="tarjeta">
        <div class="etiqueta"><?= $esAdmin ? "Ventas del mes" : "Mis ventas del mes" ?></div>
        <div class="valor">Bs <?= dinero($mes["monto"]) ?></div>
        <div class="nota"><?= (int) $mes["cantidad"] ?> venta(s) en <?= date("m/Y") ?></div>
    </div>

    <div class="tarjeta">
        <div class="etiqueta">Productos activos</div>
        <div class="valor"><?= (int) $productos["total"] ?></div>
        <div class="nota">Disponibles para la venta</div>
    </div>

    <div class="tarjeta <?= $esAdmin && $stockBajo["total"] > 0 ? "roja" : "" ?>">
        <div class="etiqueta"><?= $esAdmin ? "Productos con bajo stock" : "Clientes activos" ?></div>
        <div class="valor"><?= $esAdmin ? (int) $stockBajo["total"] : (int) $clientes["total"] ?></div>
        <div class="nota"><?= $esAdmin ? "Requieren reposición" : "Registrados en el sistema" ?></div>
    </div>
</div>

<div class="dos-columnas">
    <div class="caja">
        <div class="caja-cabecera">
            <div>
                <h2>Últimas ventas</h2>
                <p>Movimiento reciente del negocio</p>
            </div>
            <a href="ventas.php" class="btn btn-gris btn-pequeno">Ver historial</a>
        </div>

        <div class="tabla-caja">
            <table class="tabla">
                <thead>
                <tr>
                    <th>N°</th>
                    <th>Fecha</th>
                    <th>Cliente</th>
                    <th class="derecha">Total</th>
                    <th>Estado</th>
                </tr>
                </thead>
                <tbody>
                <?php if (mysqli_num_rows($ultimas) === 0) { ?>
                    <tr><td colspan="5" class="sin-datos">Todavía no hay ventas registradas.</td></tr>
                <?php } ?>
                <?php while ($venta = mysqli_fetch_assoc($ultimas)) { ?>
                    <tr>
                        <td><a href="venta_detalle.php?id=<?= (int) $venta["id_venta"] ?>">#<?= (int) $venta["id_venta"] ?></a></td>
                        <td><?= fechaBonita($venta["fecha"]) ?></td>
                        <td><?= e($venta["cliente"]) ?></td>
                        <td class="derecha">Bs <?= dinero($venta["total"]) ?></td>
                        <td>
                            <span class="badge <?= $venta["estado"] === "ANULADA" ? "rojo" : "" ?>">
                                <?= e($venta["estado"]) ?>
                            </span>
                        </td>
                    </tr>
                <?php } ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="caja">
        <div class="caja-cabecera">
            <div>
                <h2>Ventas de los últimos 7 días</h2>
                <p>Monto vendido por día</p>
            </div>
        </div>

        <?php foreach ($dias as $dia) {
            $ancho = $maximo > 0 ? round(($dia["monto"] / $maximo) * 100) : 0;
            ?>
            <div style="display:flex; align-items:center; gap:10px; margin-bottom:10px;">
                <span style="width:70px; font-size:12px; color:#6b7c8c;"><?= date("d/m", strtotime($dia["fecha"])) ?></span>
                <div class="barra-fondo" style="flex:1;">
                    <div class="barra" style="width: <?= $ancho ?>%;"></div>
                </div>
                <span style="width:80px; text-align:right; font-size:12px;">Bs <?= dinero($dia["monto"]) ?></span>
            </div>
        <?php } ?>

        <div class="form-acciones" style="margin-top:22px;">
            <a href="venta_nueva.php" class="btn btn-verde">Registrar nueva venta</a>
            <a href="clientes.php" class="btn btn-gris">Consultar clientes</a>
        </div>
    </div>
</div>

<?php if ($esAdmin) { ?>
    <div class="caja">
        <div class="caja-cabecera">
            <div>
                <h2>Productos que necesitan reposición</h2>
                <p>Su stock está en el mínimo o por debajo</p>
            </div>
            <a href="productos.php?estado=bajo" class="btn btn-gris btn-pequeno">Ver todos</a>
        </div>

        <div class="tabla-caja">
            <table class="tabla">
                <thead>
                <tr>
                    <th>Código</th>
                    <th>Producto</th>
                    <th class="centro">Stock actual</th>
                    <th class="centro">Stock mínimo</th>
                    <th>Estado</th>
                </tr>
                </thead>
                <tbody>
                <?php if (mysqli_num_rows($bajoStock) === 0) { ?>
                    <tr><td colspan="5" class="sin-datos">Todo el inventario está por encima del mínimo.</td></tr>
                <?php } ?>
                <?php while ($producto = mysqli_fetch_assoc($bajoStock)) { ?>
                    <tr>
                        <td><?= e($producto["codigo"]) ?></td>
                        <td><?= e($producto["nombre"]) ?></td>
                        <td class="centro"><?= (int) $producto["stock"] ?></td>
                        <td class="centro"><?= (int) $producto["stock_minimo"] ?></td>
                        <td>
                            <span class="badge <?= $producto["stock"] == 0 ? "rojo" : "amarillo" ?>">
                                <?= $producto["stock"] == 0 ? "Sin stock" : "Reponer" ?>
                            </span>
                        </td>
                    </tr>
                <?php } ?>
                </tbody>
            </table>
        </div>
    </div>
<?php } ?>

<?php include "footer.php"; ?>

login.phpMySQL
Autenticacion de usuario.
Abrir
Ver codigo

<?php
require_once "funciones.php";
require_once "conexion.php";

if (estaLogueado()) {
    redirigir("index.php");
}

$error = "";

if (!isset($_SESSION["intentos"])) {
    $_SESSION["intentos"] = 0;
    $_SESSION["bloqueado_hasta"] = 0;
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (time() < $_SESSION["bloqueado_hasta"]) {
        $error = "Demasiados intentos fallidos. Espera un minuto e intenta de nuevo.";
    } else {
        $usuario = trim($_POST["usuario"] ?? "");
        $clave = $_POST["clave"] ?? "";

        if ($usuario === "" || $clave === "") {
            $error = "Escribe tu usuario y contraseña.";
        } else {
            $sql = "SELECT id_usuario, nombre, usuario, clave, rol
                    FROM usuarios
                    WHERE usuario = ? AND activo = 1
                    LIMIT 1";
            $sentencia = mysqli_prepare($conexion, $sql);
            mysqli_stmt_bind_param($sentencia, "s", $usuario);
            mysqli_stmt_execute($sentencia);
            $resultado = mysqli_stmt_get_result($sentencia);
            $fila = mysqli_fetch_assoc($resultado);

            if ($fila && password_verify($clave, $fila["clave"])) {
                session_regenerate_id(true);
                $_SESSION["usuario"] = [
                    "id_usuario" => $fila["id_usuario"],
                    "nombre" => $fila["nombre"],
                    "usuario" => $fila["usuario"],
                    "rol" => $fila["rol"]
                ];
                $_SESSION["intentos"] = 0;
                redirigir("index.php");
            } else {
                $_SESSION["intentos"]++;
                if ($_SESSION["intentos"] >= 5) {
                    $_SESSION["bloqueado_hasta"] = time() + 60;
                    $_SESSION["intentos"] = 0;
                    $error = "Demasiados intentos fallidos. Espera un minuto.";
                } else {
                    $error = "Usuario o contraseña incorrectos.";
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Iniciar sesión | Tienda KemaMada</title>
    <link rel="stylesheet" href="estilos.css">
</head>
<body>
<div class="login-fondo">
    <div class="login-caja">
        <h1>Tienda KemaMada</h1>
        <p class="subtitulo">Sistema de ventas</p>

        <?php if ($error !== "") { ?>
            <div class="aviso error"><?= e($error) ?></div>
        <?php } ?>

        <form method="post" action="login.php">
            <div class="campo">
                <label for="usuario">Usuario</label>
                <input type="text" name="usuario" id="usuario" required autofocus
                       value="<?= e($_POST["usuario"] ?? "") ?>">
            </div>

            <div class="campo">
                <label for="clave">Contraseña</label>
                <input type="password" name="clave" id="clave" required>
            </div>

            <button type="submit" class="btn btn-verde">Ingresar</button>
        </form>

        <div class="login-demo">
            <strong>Usuarios de prueba</strong><br>
            Administrador: <strong>admin / admin123</strong><br>
            Vendedor: <strong>vendedor / vendedor123</strong>
        </div>
    </div>
</div>
</body>
</html>

logout.php
Script de practica.
Abrir
Ver codigo

<?php
require_once "funciones.php";

$_SESSION = [];
session_destroy();

redirigir("login.php");

producto_estado.phpMySQL
Script de practica.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirAdmin();

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    redirigir("productos.php");
}

$id = (int) ($_POST["id"] ?? 0);
$accion = $_POST["accion"] ?? "";

if ($id <= 0 || !in_array($accion, ["activar", "inactivar"])) {
    flash("error", "Solicitud no válida.");
    redirigir("productos.php");
}

$nuevoEstado = $accion === "activar" ? 1 : 0;

$sentencia = mysqli_prepare($conexion,
    "UPDATE productos SET activo = ? WHERE id_producto = ?");
mysqli_stmt_bind_param($sentencia, "ii", $nuevoEstado, $id);
mysqli_stmt_execute($sentencia);

flash("exito", $nuevoEstado ? "Producto activado." : "Producto inactivado.");
redirigir("productos.php");

producto_form.phpMySQL
Formulario de entrada de datos.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirAdmin();

$id = isset($_GET["id"]) ? (int) $_GET["id"] : 0;
$producto = [
    "codigo" => siguienteCodigo($conexion, "productos", "codigo", "P", 3),
    "nombre" => "",
    "descripcion" => "",
    "precio" => "",
    "stock" => 0,
    "stock_minimo" => 5,
    "activo" => 1
];

if ($id > 0) {
    $consulta = mysqli_query($conexion, "SELECT * FROM productos WHERE id_producto = $id LIMIT 1");
    $encontrado = mysqli_fetch_assoc($consulta);
    if (!$encontrado) {
        flash("error", "El producto solicitado no existe.");
        redirigir("productos.php");
    }
    $producto = $encontrado;
}

$titulo = $id > 0 ? "Editar producto" : "Nuevo producto";
$activo = "productos";
include "header.php";
?>

<div class="caja formulario">
    <div class="caja-cabecera">
        <div>
            <h2><?= $id > 0 ? "Editar producto" : "Registrar producto" ?></h2>
            <p>Los campos con (*) son obligatorios</p>
        </div>
    </div>

    <form method="post" action="producto_guardar.php">
        <input type="hidden" name="id" value="<?= (int) $id ?>">

        <div class="campos">
            <div class="campo">
                <label for="codigo">Código *</label>
                <input type="text" name="codigo" id="codigo" required maxlength="20"
                       value="<?= e($producto["codigo"]) ?>">
            </div>

            <div class="campo">
                <label for="nombre">Nombre del producto *</label>
                <input type="text" name="nombre" id="nombre" required maxlength="150"
                       value="<?= e($producto["nombre"]) ?>">
            </div>

            <div class="campo campo-completo">
                <label for="descripcion">Descripción</label>
                <input type="text" name="descripcion" id="descripcion" maxlength="255"
                       value="<?= e($producto["descripcion"]) ?>">
            </div>

            <div class="campo">
                <label for="precio">Precio unitario (Bs) *</label>
                <input type="number" name="precio" id="precio" required min="0.01" step="0.01"
                       value="<?= e($producto["precio"]) ?>">
            </div>

            <div class="campo">
                <label for="stock">Stock actual *</label>
                <input type="number" name="stock" id="stock" required min="0" step="1"
                       value="<?= e($producto["stock"]) ?>">
            </div>

            <div class="campo">
                <label for="stock_minimo">Stock mínimo *</label>
                <input type="number" name="stock_minimo" id="stock_minimo" required min="0" step="1"
                       value="<?= e($producto["stock_minimo"]) ?>">
                <small>Se avisará cuando el stock llegue a este valor.</small>
            </div>
        </div>

        <div class="form-acciones">
            <button type="submit" class="btn btn-verde">Guardar producto</button>
            <a href="productos.php" class="btn btn-gris">Cancelar</a>
        </div>
    </form>
</div>

<?php include "footer.php"; ?>

producto_guardar.phpMySQL
Procesa el alta y guarda los datos.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirAdmin();

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    redirigir("productos.php");
}

$id = (int) ($_POST["id"] ?? 0);
$codigo = trim($_POST["codigo"] ?? "");
$nombre = trim($_POST["nombre"] ?? "");
$descripcion = trim($_POST["descripcion"] ?? "");
$precio = (float) ($_POST["precio"] ?? 0);
$stock = (int) ($_POST["stock"] ?? 0);
$stockMinimo = (int) ($_POST["stock_minimo"] ?? 0);

if ($codigo === "" || $nombre === "") {
    flash("error", "El código y el nombre del producto son obligatorios.");
    redirigir($id > 0 ? "producto_form.php?id=$id" : "producto_form.php");
}

if ($precio <= 0 || $stock < 0 || $stockMinimo < 0) {
    flash("error", "El precio debe ser mayor a cero y los stocks no pueden ser negativos.");
    redirigir($id > 0 ? "producto_form.php?id=$id" : "producto_form.php");
}

// Verificar que el código no esté repetido
$sentencia = mysqli_prepare($conexion,
    "SELECT id_producto FROM productos WHERE codigo = ? AND id_producto <> ? LIMIT 1");
mysqli_stmt_bind_param($sentencia, "si", $codigo, $id);
mysqli_stmt_execute($sentencia);
mysqli_stmt_store_result($sentencia);

if (mysqli_stmt_num_rows($sentencia) > 0) {
    flash("error", "Ya existe otro producto con el código $codigo.");
    redirigir($id > 0 ? "producto_form.php?id=$id" : "producto_form.php");
}
mysqli_stmt_close($sentencia);

if ($id > 0) {
    $sentencia = mysqli_prepare($conexion,
        "UPDATE productos
         SET codigo = ?, nombre = ?, descripcion = ?, precio = ?, stock = ?, stock_minimo = ?
         WHERE id_producto = ?");
    mysqli_stmt_bind_param($sentencia, "sssdiii",
        $codigo, $nombre, $descripcion, $precio, $stock, $stockMinimo, $id);
    mysqli_stmt_execute($sentencia);
    flash("exito", "Producto actualizado correctamente.");
} else {
    $sentencia = mysqli_prepare($conexion,
        "INSERT INTO productos (codigo, nombre, descripcion, precio, stock, stock_minimo)
         VALUES (?, ?, ?, ?, ?, ?)");
    mysqli_stmt_bind_param($sentencia, "sssdii",
        $codigo, $nombre, $descripcion, $precio, $stock, $stockMinimo);
    mysqli_stmt_execute($sentencia);
    flash("exito", "Producto registrado correctamente.");
}

redirigir("productos.php");

productos.phpMySQL
Script de practica.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirAdmin();

$buscar = trim($_GET["buscar"] ?? "");
$estado = $_GET["estado"] ?? "activos";

$condiciones = [];
if ($buscar !== "") {
    $buscarSeguro = mysqli_real_escape_string($conexion, $buscar);
    $condiciones[] = "(nombre LIKE '%$buscarSeguro%' OR codigo LIKE '%$buscarSeguro%')";
}

if ($estado === "activos") {
    $condiciones[] = "activo = 1";
} elseif ($estado === "inactivos") {
    $condiciones[] = "activo = 0";
} elseif ($estado === "bajo") {
    $condiciones[] = "activo = 1 AND stock <= stock_minimo";
}

$where = count($condiciones) > 0 ? "WHERE " . implode(" AND ", $condiciones) : "";
$productos = mysqli_query($conexion, "SELECT * FROM productos $where ORDER BY nombre ASC");

$titulo = "Productos";
$activo = "productos";
include "header.php";
?>

<div class="caja">
    <div class="caja-cabecera">
        <div>
            <h2>Catálogo de productos</h2>
            <p>Precios, existencias y stock mínimo</p>
        </div>
        <a href="producto_form.php" class="btn btn-verde">Nuevo producto</a>
    </div>

    <form method="get" action="productos.php" class="filtros">
        <div class="campo">
            <label for="buscar">Buscar</label>
            <input type="text" name="buscar" id="buscar" value="<?= e($buscar) ?>"
                   placeholder="Nombre o código">
        </div>
        <div class="campo">
            <label for="estado">Estado</label>
            <select name="estado" id="estado">
                <option value="activos" <?= $estado === "activos" ? "selected" : "" ?>>Activos</option>
                <option value="inactivos" <?= $estado === "inactivos" ? "selected" : "" ?>>Inactivos</option>
                <option value="bajo" <?= $estado === "bajo" ? "selected" : "" ?>>Bajo stock</option>
                <option value="todos" <?= $estado === "todos" ? "selected" : "" ?>>Todos</option>
            </select>
        </div>
        <button type="submit" class="btn">Filtrar</button>
        <a href="productos.php" class="btn btn-gris">Limpiar</a>
    </form>

    <div class="tabla-caja">
        <table class="tabla">
            <thead>
            <tr>
                <th>Código</th>
                <th>Producto</th>
                <th>Descripción</th>
                <th class="derecha">Precio</th>
                <th class="centro">Stock</th>
                <th class="centro">Mínimo</th>
                <th>Estado</th>
                <th>Acciones</th>
            </tr>
            </thead>
            <tbody>
            <?php if (mysqli_num_rows($productos) === 0) { ?>
                <tr><td colspan="8" class="sin-datos">No se encontraron productos con ese filtro.</td></tr>
            <?php } ?>

            <?php while ($producto = mysqli_fetch_assoc($productos)) { ?>
                <tr>
                    <td><?= e($producto["codigo"]) ?></td>
                    <td><strong><?= e($producto["nombre"]) ?></strong></td>
                    <td><?= e($producto["descripcion"]) ?></td>
                    <td class="derecha">Bs <?= dinero($producto["precio"]) ?></td>
                    <td class="centro">
                        <span class="badge <?= $producto["stock"] == 0 ? "rojo" : ($producto["stock"] <= $producto["stock_minimo"] ? "amarillo" : "") ?>">
                            <?= (int) $producto["stock"] ?>
                        </span>
                    </td>
                    <td class="centro"><?= (int) $producto["stock_minimo"] ?></td>
                    <td>
                        <span class="badge <?= $producto["activo"] ? "" : "gris" ?>">
                            <?= $producto["activo"] ? "Activo" : "Inactivo" ?>
                        </span>
                    </td>
                    <td>
                        <div class="acciones">
                            <a href="producto_form.php?id=<?= (int) $producto["id_producto"] ?>"
                               class="btn btn-gris btn-pequeno">Editar</a>

                            <form method="post" action="producto_estado.php"
                                  onsubmit="return confirm('¿Seguro que quieres cambiar el estado de este producto?');">
                                <input type="hidden" name="id" value="<?= (int) $producto["id_producto"] ?>">
                                <input type="hidden" name="accion" value="<?= $producto["activo"] ? "inactivar" : "activar" ?>">
                                <button type="submit" class="btn <?= $producto["activo"] ? "btn-rojo" : "btn-verde" ?> btn-pequeno">
                                    <?= $producto["activo"] ? "Inactivar" : "Activar" ?>
                                </button>
                            </form>
                        </div>
                    </td>
                </tr>
            <?php } ?>
            </tbody>
        </table>
    </div>
</div>

<?php include "footer.php"; ?>

reportes.phpMySQL
Generacion de reportes.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirAdmin();

$desde = trim($_GET["desde"] ?? date("Y-m-01"));
$hasta = trim($_GET["hasta"] ?? date("Y-m-d"));

if (!preg_match("/^\d{4}-\d{2}-\d{2}$/", $desde)) {
    $desde = date("Y-m-01");
}
if (!preg_match("/^\d{4}-\d{2}-\d{2}$/", $hasta)) {
    $hasta = date("Y-m-d");
}
if ($desde > $hasta) {
    $cambio = $desde;
    $desde = $hasta;
    $hasta = $cambio;
}

$desdeSeguro = mysqli_real_escape_string($conexion, $desde);
$hastaSeguro = mysqli_real_escape_string($conexion, $hasta);

$filtroFechas = "DATE(v.fecha) BETWEEN '$desdeSeguro' AND '$hastaSeguro' AND v.estado = 'EMITIDA'";

$resumen = mysqli_fetch_assoc(mysqli_query($conexion,
    "SELECT COUNT(*) AS cantidad,
            COALESCE(SUM(v.total), 0) AS total,
            COALESCE(SUM(v.descuento), 0) AS descuentos
     FROM ventas v
     WHERE $filtroFechas"));

$unidades = mysqli_fetch_assoc(mysqli_query($conexion,
    "SELECT COALESCE(SUM(d.cantidad), 0) AS total
     FROM detalle_ventas d
     INNER JOIN ventas v ON v.id_venta = d.id_venta
     WHERE $filtroFechas"));

$ticket = $resumen["cantidad"] > 0 ? $resumen["total"] / $resumen["cantidad"] : 0;

$porDia = mysqli_query($conexion,
    "SELECT DATE(v.fecha) AS dia, COUNT(*) AS cantidad, SUM(v.total) AS total
     FROM ventas v
     WHERE $filtroFechas
     GROUP BY DATE(v.fecha)
     ORDER BY dia DESC");

$datosDia = [];
$maximoDia = 0;
while ($fila = mysqli_fetch_assoc($porDia)) {
    $datosDia[] = $fila;
    if ((float) $fila["total"] > $maximoDia) {
        $maximoDia = (float) $fila["total"];
    }
}

$masVendidos = mysqli_query($conexion,
    "SELECT d.producto_nombre,
            SUM(d.cantidad) AS unidades,
            SUM(d.subtotal) AS total
     FROM detalle_ventas d
     INNER JOIN ventas v ON v.id_venta = d.id_venta
     WHERE $filtroFechas
     GROUP BY d.producto_nombre
     ORDER BY unidades DESC
     LIMIT 8");

$porVendedor = mysqli_query($conexion,
    "SELECT u.nombre, COUNT(*) AS cantidad, SUM(v.total) AS total
     FROM ventas v
     INNER JOIN usuarios u ON u.id_usuario = v.id_usuario
     WHERE $filtroFechas
     GROUP BY u.id_usuario, u.nombre
     ORDER BY total DESC");

$stockBajo = mysqli_query($conexion,
    "SELECT codigo, nombre, stock, stock_minimo
     FROM productos
     WHERE activo = 1 AND stock <= stock_minimo
     ORDER BY stock ASC");

$titulo = "Reportes";
$activo = "reportes";
include "header.php";
?>

<div class="caja">
    <div class="caja-cabecera">
        <div>
            <h2>Reporte de ventas</h2>
            <p>Del <?= date("d/m/Y", strtotime($desde)) ?> al <?= date("d/m/Y", strtotime($hasta)) ?></p>
        </div>
        <a href="reportes_csv.php?desde=<?= e($desde) ?>&hasta=<?= e($hasta) ?>" class="btn btn-gris">
            Exportar CSV
        </a>
    </div>

    <form method="get" action="reportes.php" class="filtros">
        <div class="campo">
            <label for="desde">Desde</label>
            <input type="date" name="desde" id="desde" value="<?= e($desde) ?>">
        </div>
        <div class="campo">
            <label for="hasta">Hasta</label>
            <input type="date" name="hasta" id="hasta" value="<?= e($hasta) ?>">
        </div>
        <button type="submit" class="btn">Generar reporte</button>
    </form>
</div>

<div class="tarjetas">
    <div class="tarjeta verde">
        <div class="etiqueta">Total vendido</div>
        <div class="valor">Bs <?= dinero($resumen["total"]) ?></div>
        <div class="nota"><?= (int) $resumen["cantidad"] ?> venta(s) emitida(s)</div>
    </div>
    <div class="tarjeta">
        <div class="etiqueta">Ticket promedio</div>
        <div class="valor">Bs <?= dinero($ticket) ?></div>
        <div class="nota">Promedio por venta</div>
    </div>
    <div class="tarjeta">
        <div class="etiqueta">Unidades vendidas</div>
        <div class="valor"><?= (int) $unidades["total"] ?></div>
        <div class="nota">Productos entregados</div>
    </div>
    <div class="tarjeta">
        <div class="etiqueta">Descuentos otorgados</div>
        <div class="valor">Bs <?= dinero($resumen["descuentos"]) ?></div>
        <div class="nota">Total descontado en el período</div>
    </div>
</div>

<div class="dos-columnas">
    <div class="caja">
        <div class="caja-cabecera">
            <div>
                <h2>Ventas por día</h2>
                <p>Monto y cantidad de ventas</p>
            </div>
        </div>

        <div class="tabla-caja">
            <table class="tabla">
                <thead>
                <tr>
                    <th>Fecha</th>
                    <th class="centro">Ventas</th>
                    <th class="derecha">Monto</th>
                    <th style="width:28%;">Participación</th>
                </tr>
                </thead>
                <tbody>
                <?php if (count($datosDia) === 0) { ?>
                    <tr><td colspan="4" class="sin-datos">No hay ventas en este período.</td></tr>
                <?php } ?>
                <?php foreach ($datosDia as $dia) {
                    $ancho = $maximoDia > 0 ? round(($dia["total"] / $maximoDia) * 100) : 0;
                    ?>
                    <tr>
                        <td><?= date("d/m/Y", strtotime($dia["dia"])) ?></td>
                        <td class="centro"><?= (int) $dia["cantidad"] ?></td>
                        <td class="derecha">Bs <?= dinero($dia["total"]) ?></td>
                        <td>
                            <div class="barra-fondo">
                                <div class="barra" style="width: <?= $ancho ?>%;"></div>
                            </div>
                        </td>
                    </tr>
                <?php } ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="caja">
        <div class="caja-cabecera">
            <div>
                <h2>Productos más vendidos</h2>
                <p>Ordenado por unidades</p>
            </div>
        </div>

        <div class="tabla-caja">
            <table class="tabla">
                <thead>
                <tr>
                    <th>Producto</th>
                    <th class="centro">Unidades</th>
                    <th class="derecha">Monto</th>
                </tr>
                </thead>
                <tbody>
                <?php if (mysqli_num_rows($masVendidos) === 0) { ?>
                    <tr><td colspan="3" class="sin-datos">No hay productos vendidos en este período.</td></tr>
                <?php } ?>
                <?php while ($producto = mysqli_fetch_assoc($masVendidos)) { ?>
                    <tr>
                        <td><?= e($producto["producto_nombre"]) ?></td>
                        <td class="centro"><?= (int) $producto["unidades"] ?></td>
                        <td class="derecha">Bs <?= dinero($producto["total"]) ?></td>
                    </tr>
                <?php } ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="dos-columnas">
    <div class="caja">
        <div class="caja-cabecera">
            <div>
                <h2>Ventas por vendedor</h2>
                <p>Rendimiento del período</p>
            </div>
        </div>

        <div class="tabla-caja">
            <table class="tabla">
                <thead>
                <tr>
                    <th>Vendedor</th>
                    <th class="centro">Ventas</th>
                    <th class="derecha">Monto</th>
                </tr>
                </thead>
                <tbody>
                <?php if (mysqli_num_rows($porVendedor) === 0) { ?>
                    <tr><td colspan="3" class="sin-datos">Sin ventas registradas.</td></tr>
                <?php } ?>
                <?php while ($vendedor = mysqli_fetch_assoc($porVendedor)) { ?>
                    <tr>
                        <td><?= e($vendedor["nombre"]) ?></td>
                        <td class="centro"><?= (int) $vendedor["cantidad"] ?></td>
                        <td class="derecha">Bs <?= dinero($vendedor["total"]) ?></td>
                    </tr>
                <?php } ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="caja">
        <div class="caja-cabecera">
            <div>
                <h2>Inventario con bajo stock</h2>
                <p>Necesitan reposición</p>
            </div>
        </div>

        <div class="tabla-caja">
            <table class="tabla">
                <thead>
                <tr>
                    <th>Código</th>
                    <th>Producto</th>
                    <th class="centro">Stock</th>
                    <th class="centro">Mínimo</th>
                </tr>
                </thead>
                <tbody>
                <?php if (mysqli_num_rows($stockBajo) === 0) { ?>
                    <tr><td colspan="4" class="sin-datos">Todo el inventario está en orden.</td></tr>
                <?php } ?>
                <?php while ($producto = mysqli_fetch_assoc($stockBajo)) { ?>
                    <tr>
                        <td><?= e($producto["codigo"]) ?></td>
                        <td><?= e($producto["nombre"]) ?></td>
                        <td class="centro">
                            <span class="badge <?= $producto["stock"] == 0 ? "rojo" : "amarillo" ?>">
                                <?= (int) $producto["stock"] ?>
                            </span>
                        </td>
                        <td class="centro"><?= (int) $producto["stock_minimo"] ?></td>
                    </tr>
                <?php } ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php include "footer.php"; ?>

reportes_csv.phpMySQLArchivos de texto
Generacion de reportes.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirAdmin();

$desde = trim($_GET["desde"] ?? date("Y-m-01"));
$hasta = trim($_GET["hasta"] ?? date("Y-m-d"));

if (!preg_match("/^\d{4}-\d{2}-\d{2}$/", $desde)) {
    $desde = date("Y-m-01");
}
if (!preg_match("/^\d{4}-\d{2}-\d{2}$/", $hasta)) {
    $hasta = date("Y-m-d");
}

$desdeSeguro = mysqli_real_escape_string($conexion, $desde);
$hastaSeguro = mysqli_real_escape_string($conexion, $hasta);

$ventas = mysqli_query($conexion,
    "SELECT v.id_venta, v.fecha, v.subtotal, v.descuento, v.total, v.estado,
            COALESCE(c.nombre, 'Consumidor final') AS cliente,
            u.nombre AS vendedor
     FROM ventas v
     LEFT JOIN clientes c ON c.id_cliente = v.id_cliente
     INNER JOIN usuarios u ON u.id_usuario = v.id_usuario
     WHERE DATE(v.fecha) BETWEEN '$desdeSeguro' AND '$hastaSeguro'
     ORDER BY v.fecha DESC");

$nombreArchivo = "ventas_" . $desde . "_" . $hasta . ".csv";

header("Content-Type: text/csv; charset=UTF-8");
header("Content-Disposition: attachment; filename=" . $nombreArchivo);
header("Pragma: no-cache");
header("Expires: 0");

$salida = fopen("php://output", "w");

fwrite($salida, "\xEF\xBB\xBF");

fputcsv($salida, ["N° venta", "Fecha", "Cliente", "Vendedor", "Subtotal",
    "Descuento", "Total", "Estado"]);

while ($venta = mysqli_fetch_assoc($ventas)) {
    fputcsv($salida, [
        $venta["id_venta"],
        fechaBonita($venta["fecha"]),
        $venta["cliente"],
        $venta["vendedor"],
        number_format((float) $venta["subtotal"], 2, ".", ""),
        number_format((float) $venta["descuento"], 2, ".", ""),
        number_format((float) $venta["total"], 2, ".", ""),
        $venta["estado"]
    ]);
}

fclose($salida);
exit;

usuario_estado.phpMySQL
Script de practica.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirAdmin();

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    redirigir("usuarios.php");
}

$id = (int) ($_POST["id"] ?? 0);
$accion = $_POST["accion"] ?? "";
$usuarioActual = usuarioActual();

if ($id <= 0 || !in_array($accion, ["activar", "inactivar"])) {
    flash("error", "Solicitud no válida.");
    redirigir("usuarios.php");
}

if ($accion === "inactivar" && $id === (int) $usuarioActual["id_usuario"]) {
    flash("error", "No puedes inactivar tu propia cuenta.");
    redirigir("usuarios.php");
}

$consulta = mysqli_query($conexion,
    "SELECT rol, activo FROM usuarios WHERE id_usuario = $id LIMIT 1");
$usuario = mysqli_fetch_assoc($consulta);

if (!$usuario) {
    flash("error", "El usuario no existe.");
    redirigir("usuarios.php");
}

if ($accion === "inactivar" && $usuario["rol"] === "administrador" &&
    adminsActivos($conexion, $id) === 0) {
    flash("error", "Debe quedar al menos un administrador activo.");
    redirigir("usuarios.php");
}

$nuevoEstado = $accion === "activar" ? 1 : 0;

$sentencia = mysqli_prepare($conexion,
    "UPDATE usuarios SET activo = ? WHERE id_usuario = ?");
mysqli_stmt_bind_param($sentencia, "ii", $nuevoEstado, $id);
mysqli_stmt_execute($sentencia);

flash("exito", $nuevoEstado ? "Usuario activado." : "Usuario inactivado.");
redirigir("usuarios.php");

usuario_form.phpMySQL
Formulario de entrada de datos.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirAdmin();

$id = isset($_GET["id"]) ? (int) $_GET["id"] : 0;
$usuarioEditado = [
    "nombre" => "",
    "usuario" => "",
    "rol" => "vendedor",
    "activo" => 1
];

if ($id > 0) {
    $consulta = mysqli_query($conexion,
        "SELECT * FROM usuarios WHERE id_usuario = $id LIMIT 1");
    $encontrado = mysqli_fetch_assoc($consulta);

    if (!$encontrado) {
        flash("error", "El usuario solicitado no existe.");
        redirigir("usuarios.php");
    }
    $usuarioEditado = $encontrado;
}

$titulo = $id > 0 ? "Editar usuario" : "Nuevo usuario";
$activo = "usuarios";
include "header.php";
?>

<div class="caja formulario">
    <div class="caja-cabecera">
        <div>
            <h2><?= $id > 0 ? "Editar usuario" : "Registrar usuario" ?></h2>
            <p>Los campos con (*) son obligatorios</p>
        </div>
    </div>

    <form method="post" action="usuario_guardar.php">
        <input type="hidden" name="id" value="<?= (int) $id ?>">

        <div class="campos">
            <div class="campo">
                <label for="nombre">Nombre completo *</label>
                <input type="text" name="nombre" id="nombre" required maxlength="100"
                       value="<?= e($usuarioEditado["nombre"]) ?>">
            </div>

            <div class="campo">
                <label for="usuario">Usuario de acceso *</label>
                <input type="text" name="usuario" id="usuario" required maxlength="50"
                       value="<?= e($usuarioEditado["usuario"]) ?>">
            </div>

            <div class="campo">
                <label for="clave">Contraseña <?= $id > 0 ? "" : "*" ?></label>
                <input type="password" name="clave" id="clave" minlength="6"
                       <?= $id > 0 ? "" : "required" ?>>
                <small><?= $id > 0 ? "Déjala vacía para conservar la contraseña actual." : "Mínimo 6 caracteres." ?></small>
            </div>

            <div class="campo">
                <label for="rol">Rol *</label>
                <select name="rol" id="rol" required>
                    <option value="vendedor" <?= $usuarioEditado["rol"] === "vendedor" ? "selected" : "" ?>>Vendedor</option>
                    <option value="administrador" <?= $usuarioEditado["rol"] === "administrador" ? "selected" : "" ?>>Administrador</option>
                </select>
            </div>
        </div>

        <div class="form-acciones">
            <button type="submit" class="btn btn-verde">Guardar usuario</button>
            <a href="usuarios.php" class="btn btn-gris">Cancelar</a>
        </div>
    </form>
</div>

<?php include "footer.php"; ?>

usuario_guardar.phpMySQL
Procesa el alta y guarda los datos.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirAdmin();

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    redirigir("usuarios.php");
}

$id = (int) ($_POST["id"] ?? 0);
$nombre = trim($_POST["nombre"] ?? "");
$usuario = trim($_POST["usuario"] ?? "");
$clave = $_POST["clave"] ?? "";
$rol = $_POST["rol"] ?? "vendedor";

if ($nombre === "" || $usuario === "") {
    flash("error", "El nombre y el usuario son obligatorios.");
    redirigir($id > 0 ? "usuario_form.php?id=$id" : "usuario_form.php");
}

if (!in_array($rol, ["administrador", "vendedor"])) {
    flash("error", "El rol seleccionado no es válido.");
    redirigir($id > 0 ? "usuario_form.php?id=$id" : "usuario_form.php");
}

if ($id === 0 && strlen($clave) < 6) {
    flash("error", "La contraseña debe tener al menos 6 caracteres.");
    redirigir("usuario_form.php");
}

if ($id > 0 && $clave !== "" && strlen($clave) < 6) {
    flash("error", "La nueva contraseña debe tener al menos 6 caracteres.");
    redirigir("usuario_form.php?id=$id");
}


$sentencia = mysqli_prepare($conexion,
    "SELECT id_usuario FROM usuarios WHERE usuario = ? AND id_usuario <> ? LIMIT 1");
mysqli_stmt_bind_param($sentencia, "si", $usuario, $id);
mysqli_stmt_execute($sentencia);
mysqli_stmt_store_result($sentencia);

if (mysqli_stmt_num_rows($sentencia) > 0) {
    flash("error", "El nombre de usuario '$usuario' ya está ocupado.");
    redirigir($id > 0 ? "usuario_form.php?id=$id" : "usuario_form.php");
}
mysqli_stmt_close($sentencia);


if ($rol !== "administrador" && adminsActivos($conexion, $id) === 0) {
    flash("error", "Debe existir al menos un administrador activo.");
    redirigir($id > 0 ? "usuario_form.php?id=$id" : "usuario_form.php");
}

if ($id > 0) {
    if ($clave !== "") {
        $claveSegura = password_hash($clave, PASSWORD_DEFAULT);
        $sentencia = mysqli_prepare($conexion,
            "UPDATE usuarios SET nombre = ?, usuario = ?, clave = ?, rol = ?
             WHERE id_usuario = ?");
        mysqli_stmt_bind_param($sentencia, "ssssi",
            $nombre, $usuario, $claveSegura, $rol, $id);
    } else {
        $sentencia = mysqli_prepare($conexion,
            "UPDATE usuarios SET nombre = ?, usuario = ?, rol = ?
             WHERE id_usuario = ?");
        mysqli_stmt_bind_param($sentencia, "sssi",
            $nombre, $usuario, $rol, $id);
    }

    mysqli_stmt_execute($sentencia);
    flash("exito", "Usuario actualizado correctamente.");

    if ($id === (int) $_SESSION["usuario"]["id_usuario"]) {
        $_SESSION["usuario"]["nombre"] = $nombre;
        $_SESSION["usuario"]["usuario"] = $usuario;
        $_SESSION["usuario"]["rol"] = $rol;
    }
} else {
    $claveSegura = password_hash($clave, PASSWORD_DEFAULT);
    $sentencia = mysqli_prepare($conexion,
        "INSERT INTO usuarios (nombre, usuario, clave, rol)
         VALUES (?, ?, ?, ?)");
    mysqli_stmt_bind_param($sentencia, "ssss",
        $nombre, $usuario, $claveSegura, $rol);
    mysqli_stmt_execute($sentencia);
    flash("exito", "Usuario registrado correctamente.");
}

redirigir("usuarios.php");

usuarios.phpMySQL
Script de practica.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirAdmin();

$usuarios = mysqli_query($conexion,
    "SELECT u.*,
            (SELECT COUNT(*) FROM ventas v WHERE v.id_usuario = u.id_usuario) AS ventas
     FROM usuarios u
     ORDER BY u.rol ASC, u.nombre ASC");

$titulo = "Usuarios";
$activo = "usuarios";
include "header.php";
?>

<div class="caja">
    <div class="caja-cabecera">
        <div>
            <h2>Cuentas de acceso</h2>
            <p>Administradores y vendedores del sistema</p>
        </div>
        <a href="usuario_form.php" class="btn btn-verde">Nuevo usuario</a>
    </div>

    <div class="tabla-caja">
        <table class="tabla">
            <thead>
            <tr>
                <th>Nombre</th>
                <th>Usuario</th>
                <th>Rol</th>
                <th class="centro">Ventas</th>
                <th>Estado</th>
                <th>Creado</th>
                <th>Acciones</th>
            </tr>
            </thead>
            <tbody>
            <?php while ($usuario = mysqli_fetch_assoc($usuarios)) { ?>
                <tr>
                    <td>
                        <strong><?= e($usuario["nombre"]) ?></strong>
                        <?php if ((int) $usuario["id_usuario"] === (int) usuarioActual()["id_usuario"]) { ?>
                            <span class="badge gris">Tú</span>
                        <?php } ?>
                    </td>
                    <td><?= e($usuario["usuario"]) ?></td>
                    <td>
                        <span class="badge <?= $usuario["rol"] === "administrador" ? "" : "gris" ?>">
                            <?= e($usuario["rol"]) ?>
                        </span>
                    </td>
                    <td class="centro"><?= (int) $usuario["ventas"] ?></td>
                    <td>
                        <span class="badge <?= $usuario["activo"] ? "" : "rojo" ?>">
                            <?= $usuario["activo"] ? "Activo" : "Inactivo" ?>
                        </span>
                    </td>
                    <td><?= date("d/m/Y", strtotime($usuario["fecha_creacion"])) ?></td>
                    <td>
                        <div class="acciones">
                            <a href="usuario_form.php?id=<?= (int) $usuario["id_usuario"] ?>"
                               class="btn btn-gris btn-pequeno">Editar</a>

                            <?php if ((int) $usuario["id_usuario"] !== (int) usuarioActual()["id_usuario"]) { ?>
                                <form method="post" action="usuario_estado.php"
                                      onsubmit="return confirm('¿Cambiar el estado de este usuario?');">
                                    <input type="hidden" name="id" value="<?= (int) $usuario["id_usuario"] ?>">
                                    <input type="hidden" name="accion" value="<?= $usuario["activo"] ? "inactivar" : "activar" ?>">
                                    <button type="submit" class="btn <?= $usuario["activo"] ? "btn-rojo" : "btn-verde" ?> btn-pequeno">
                                        <?= $usuario["activo"] ? "Inactivar" : "Activar" ?>
                                    </button>
                                </form>
                            <?php } ?>
                        </div>
                    </td>
                </tr>
            <?php } ?>
            </tbody>
        </table>
    </div>
</div>

<?php include "footer.php"; ?>

venta_anular.phpMySQL
Elimina o anula un registro.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirAdmin();

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    redirigir("ventas.php");
}

$id = (int) ($_POST["id"] ?? 0);
$usuario = usuarioActual();

if ($id <= 0) {
    flash("error", "Venta no válida.");
    redirigir("ventas.php");
}

mysqli_begin_transaction($conexion);

try {
    $sentencia = mysqli_prepare($conexion,
        "SELECT id_venta, estado FROM ventas WHERE id_venta = ? FOR UPDATE");
    mysqli_stmt_bind_param($sentencia, "i", $id);
    mysqli_stmt_execute($sentencia);
    $venta = mysqli_fetch_assoc(mysqli_stmt_get_result($sentencia));

    if (!$venta) {
        throw new Exception("La venta no existe.");
    }

    if ($venta["estado"] === "ANULADA") {
        throw new Exception("Esta venta ya fue anulada.");
    }


    $detalles = mysqli_query($conexion,
        "SELECT id_producto, cantidad FROM detalle_ventas WHERE id_venta = $id");

    while ($detalle = mysqli_fetch_assoc($detalles)) {
        $sentencia = mysqli_prepare($conexion,
            "UPDATE productos SET stock = stock + ? WHERE id_producto = ?");
        mysqli_stmt_bind_param($sentencia, "ii", $detalle["cantidad"], $detalle["id_producto"]);
        mysqli_stmt_execute($sentencia);
    }

    $sentencia = mysqli_prepare($conexion,
        "UPDATE ventas
         SET estado = 'ANULADA', anulada_en = NOW(), anulada_por = ?
         WHERE id_venta = ?");
    mysqli_stmt_bind_param($sentencia, "ii", $usuario["id_usuario"], $id);
    mysqli_stmt_execute($sentencia);

    mysqli_commit($conexion);
    flash("exito", "Venta #$id anulada y stock devuelto.");
} catch (Throwable $error) {
    mysqli_rollback($conexion);
    flash("error", $error->getMessage());
}

redirigir("venta_detalle.php?id=$id");

venta_detalle.phpMySQL
Script de practica.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirLogin();

$usuario = usuarioActual();
$id = isset($_GET["id"]) ? (int) $_GET["id"] : 0;

$consulta = mysqli_query($conexion,
    "SELECT v.*,
            COALESCE(c.nombre, 'Consumidor final') AS cliente,
            c.ci_nit AS cliente_documento,
            c.telefono AS cliente_telefono,
            u.nombre AS vendedor
     FROM ventas v
     LEFT JOIN clientes c ON c.id_cliente = v.id_cliente
     INNER JOIN usuarios u ON u.id_usuario = v.id_usuario
     WHERE v.id_venta = $id
     LIMIT 1");
$venta = mysqli_fetch_assoc($consulta);

if (!$venta) {
    flash("error", "La venta solicitada no existe.");
    redirigir("ventas.php");
}

if (!esAdmin() && (int) $venta["id_usuario"] !== (int) $usuario["id_usuario"]) {
    flash("error", "No tienes permiso para ver esta venta.");
    redirigir("ventas.php");
}

$detalles = mysqli_query($conexion,
    "SELECT * FROM detalle_ventas WHERE id_venta = $id ORDER BY id_detalle ASC");

$unidades = mysqli_fetch_assoc(mysqli_query($conexion,
    "SELECT COALESCE(SUM(cantidad), 0) AS total FROM detalle_ventas WHERE id_venta = $id"));

$titulo = "Venta #" . $venta["id_venta"];
$activo = "ventas";
include "header.php";
?>

<div class="caja">
    <div class="caja-cabecera">
        <div>
            <h2>Venta #<?= (int) $venta["id_venta"] ?></h2>
            <p><?= fechaBonita($venta["fecha"]) ?> &middot; <?= e($venta["vendedor"]) ?></p>
        </div>
        <div class="acciones">
            <a href="comprobante.php?id=<?= (int) $venta["id_venta"] ?>" class="btn btn-verde">Ver comprobante</a>
            <a href="ventas.php" class="btn btn-gris">Volver al historial</a>
        </div>
    </div>

    <div class="tarjetas">
        <div class="tarjeta">
            <div class="etiqueta">Cliente</div>
            <div class="valor" style="font-size:17px;"><?= e($venta["cliente"]) ?></div>
            <div class="nota"><?= e($venta["cliente_documento"] ?: "Sin documento") ?></div>
        </div>
        <div class="tarjeta">
            <div class="etiqueta">Estado</div>
            <div class="valor" style="font-size:18px;">
                <span class="badge <?= $venta["estado"] === "ANULADA" ? "rojo" : "" ?>">
                    <?= e($venta["estado"]) ?>
                </span>
            </div>
            <?php if ($venta["estado"] === "ANULADA") { ?>
                <div class="nota">Anulada el <?= fechaBonita($venta["anulada_en"]) ?></div>
            <?php } ?>
        </div>
        <div class="tarjeta">
            <div class="etiqueta">Unidades vendidas</div>
            <div class="valor"><?= (int) $unidades["total"] ?></div>
        </div>
        <div class="tarjeta verde">
            <div class="etiqueta">Total de la venta</div>
            <div class="valor">Bs <?= dinero($venta["total"]) ?></div>
        </div>
    </div>
</div>

<div class="caja">
    <div class="caja-cabecera">
        <div>
            <h2>Detalle de productos</h2>
            <p>Precios al momento de la venta</p>
        </div>
    </div>

    <div class="tabla-caja">
        <table class="tabla">
            <thead>
            <tr>
                <th>Producto</th>
                <th class="centro">Cantidad</th>
                <th class="derecha">Precio unitario</th>
                <th class="derecha">Subtotal</th>
            </tr>
            </thead>
            <tbody>
            <?php while ($detalle = mysqli_fetch_assoc($detalles)) { ?>
                <tr>
                    <td><?= e($detalle["producto_nombre"]) ?></td>
                    <td class="centro"><?= (int) $detalle["cantidad"] ?></td>
                    <td class="derecha">Bs <?= dinero($detalle["precio_unitario"]) ?></td>
                    <td class="derecha">Bs <?= dinero($detalle["subtotal"]) ?></td>
                </tr>
            <?php } ?>
            </tbody>
            <tfoot>
            <tr>
                <td colspan="3" class="derecha"><strong>Subtotal</strong></td>
                <td class="derecha">Bs <?= dinero($venta["subtotal"]) ?></td>
            </tr>
            <tr>
                <td colspan="3" class="derecha"><strong>Descuento</strong></td>
                <td class="derecha">- Bs <?= dinero($venta["descuento"]) ?></td>
            </tr>
            <tr>
                <td colspan="3" class="derecha"><strong>TOTAL</strong></td>
                <td class="derecha"><strong>Bs <?= dinero($venta["total"]) ?></strong></td>
            </tr>
            </tfoot>
        </table>
    </div>

    <?php if (esAdmin() && $venta["estado"] === "EMITIDA") { ?>
        <form method="post" action="venta_anular.php" style="margin-top:18px;"
              onsubmit="return confirm('¿Anular esta venta? El stock de los productos será devuelto.');">
            <input type="hidden" name="id" value="<?= (int) $venta["id_venta"] ?>">
            <button type="submit" class="btn btn-rojo">Anular venta</button>
        </form>
    <?php } ?>
</div>

<?php include "footer.php"; ?>

venta_guardar.phpMySQL
Procesa el alta y guarda los datos.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirLogin();

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    redirigir("venta_nueva.php");
}

$usuario = usuarioActual();
$idCliente = (int) ($_POST["id_cliente"] ?? 0);
$descuento = round((float) ($_POST["descuento"] ?? 0), 2);
$idsProductos = $_POST["id_producto"] ?? [];
$cantidades = $_POST["cantidad"] ?? [];

if (!is_array($idsProductos) || !is_array($cantidades)) {
    flash("error", "Los datos de la venta no son válidos.");
    redirigir("venta_nueva.php");
}

$pedido = [];
foreach ($idsProductos as $indice => $idProducto) {
    $idProducto = (int) $idProducto;
    $cantidad = (int) ($cantidades[$indice] ?? 0);

    if ($idProducto <= 0 || $cantidad <= 0) {
        continue;
    }

    if (!isset($pedido[$idProducto])) {
        $pedido[$idProducto] = 0;
    }
    $pedido[$idProducto] += $cantidad;
}

if (count($pedido) === 0) {
    flash("error", "Debes seleccionar al menos un producto con cantidad mayor a cero.");
    redirigir("venta_nueva.php");
}

if ($descuento < 0) {
    flash("error", "El descuento no puede ser negativo.");
    redirigir("venta_nueva.php");
}

mysqli_begin_transaction($conexion);

try {
    
    if ($idCliente > 0) {
        $sentencia = mysqli_prepare($conexion,
            "SELECT id_cliente FROM clientes WHERE id_cliente = ? AND activo = 1");
        mysqli_stmt_bind_param($sentencia, "i", $idCliente);
        mysqli_stmt_execute($sentencia);
        $resultado = mysqli_stmt_get_result($sentencia);

        if (mysqli_num_rows($resultado) === 0) {
            throw new Exception("El cliente seleccionado no existe o está inactivo.");
        }
    }

    $detalles = [];
    $subtotalVenta = 0;

    foreach ($pedido as $idProducto => $cantidad) {
        $sentencia = mysqli_prepare($conexion,
            "SELECT id_producto, nombre, precio, stock, activo
             FROM productos
             WHERE id_producto = ?
             FOR UPDATE");
        mysqli_stmt_bind_param($sentencia, "i", $idProducto);
        mysqli_stmt_execute($sentencia);
        $resultado = mysqli_stmt_get_result($sentencia);
        $producto = mysqli_fetch_assoc($resultado);

        if (!$producto) {
            throw new Exception("Uno de los productos ya no existe.");
        }

        if ((int) $producto["activo"] !== 1) {
            throw new Exception("El producto '" . $producto["nombre"] . "' está inactivo.");
        }

        if ($cantidad > (int) $producto["stock"]) {
            throw new Exception("Stock insuficiente de '" . $producto["nombre"] .
                "'. Disponible: " . $producto["stock"] . " unidad(es).");
        }

        $precio = (float) $producto["precio"];
        $subtotal = round($precio * $cantidad, 2);
        $subtotalVenta += $subtotal;

        $detalles[] = [
            "id_producto" => (int) $producto["id_producto"],
            "nombre" => $producto["nombre"],
            "cantidad" => $cantidad,
            "precio" => $precio,
            "subtotal" => $subtotal
        ];
    }

    $subtotalVenta = round($subtotalVenta, 2);

    if ($descuento > $subtotalVenta) {
        throw new Exception("El descuento no puede ser mayor al subtotal de la venta.");
    }

    $total = round($subtotalVenta - $descuento, 2);
    $idUsuario = (int) $usuario["id_usuario"];
    $clienteParaGuardar = $idCliente > 0 ? $idCliente : null;

 
    $sentencia = mysqli_prepare($conexion,
        "INSERT INTO ventas (id_cliente, id_usuario, fecha, subtotal, descuento, total)
         VALUES (?, ?, NOW(), ?, ?, ?)");
    mysqli_stmt_bind_param($sentencia, "iiddd",
        $clienteParaGuardar, $idUsuario, $subtotalVenta, $descuento, $total);
    mysqli_stmt_execute($sentencia);
    $idVenta = mysqli_insert_id($conexion);


    foreach ($detalles as $detalle) {
        $sentencia = mysqli_prepare($conexion,
            "INSERT INTO detalle_ventas
                (id_venta, id_producto, producto_nombre, cantidad, precio_unitario, subtotal)
             VALUES (?, ?, ?, ?, ?, ?)");
        mysqli_stmt_bind_param($sentencia, "iisidd",
            $idVenta, $detalle["id_producto"], $detalle["nombre"],
            $detalle["cantidad"], $detalle["precio"], $detalle["subtotal"]);
        mysqli_stmt_execute($sentencia);

        $sentencia = mysqli_prepare($conexion,
            "UPDATE productos SET stock = stock - ? WHERE id_producto = ?");
        mysqli_stmt_bind_param($sentencia, "ii", $detalle["cantidad"], $detalle["id_producto"]);
        mysqli_stmt_execute($sentencia);
    }

    mysqli_commit($conexion);

    flash("exito", "Venta #$idVenta registrada correctamente.");
    redirigir("comprobante.php?id=$idVenta");
} catch (Throwable $error) {
    mysqli_rollback($conexion);
    flash("error", $error->getMessage());
    redirigir("venta_nueva.php");
}

venta_nueva.phpMySQL
Script de practica.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirLogin();

$clientes = mysqli_query($conexion,
    "SELECT id_cliente, codigo, nombre FROM clientes WHERE activo = 1 ORDER BY nombre ASC");

$productos = mysqli_query($conexion,
    "SELECT id_producto, codigo, nombre, precio, stock
     FROM productos
     WHERE activo = 1
     ORDER BY nombre ASC");

$listaProductos = [];
while ($producto = mysqli_fetch_assoc($productos)) {
    $listaProductos[] = $producto;
}

$clienteElegido = isset($_GET["cliente"]) ? (int) $_GET["cliente"] : 0;

$titulo = "Nueva venta";
$activo = "nueva";
include "header.php";
?>

<?php if (count($listaProductos) === 0) { ?>
    <div class="aviso error">
        No hay productos activos. Un administrador debe registrar productos antes de vender.
    </div>
<?php } ?>

<form method="post" action="venta_guardar.php" id="formVenta">
    <div class="venta-grid">

        <div class="caja">
            <div class="caja-cabecera">
                <div>
                    <h2>Productos de la venta</h2>
                    <p>Selecciona los productos y las cantidades</p>
                </div>
                <button type="button" class="btn btn-gris" id="agregarFila">+ Agregar producto</button>
            </div>

            <div class="tabla-caja">
                <table class="tabla tabla-venta">
                    <thead>
                    <tr>
                        <th style="width:45%;">Producto</th>
                        <th style="width:18%;">Precio</th>
                        <th style="width:15%;">Cantidad</th>
                        <th style="width:15%;" class="derecha">Subtotal</th>
                        <th style="width:7%;"></th>
                    </tr>
                    </thead>
                    <tbody id="filas">
                    <tr class="fila-producto">
                        <td>
                            <select name="id_producto[]" class="producto">
                                <option value="">-- Seleccionar --</option>
                                <?php foreach ($listaProductos as $producto) { ?>
                                    <option value="<?= (int) $producto["id_producto"] ?>"
                                            data-precio="<?= $producto["precio"] ?>"
                                            data-stock="<?= (int) $producto["stock"] ?>"
                                            data-nombre="<?= e($producto["nombre"]) ?>"
                                            <?= (int) $producto["stock"] <= 0 ? "disabled" : "" ?>>
                                        <?= e($producto["codigo"] . " - " . $producto["nombre"]) ?>
                                        <?= (int) $producto["stock"] > 0
                                            ? "(stock " . (int) $producto["stock"] . ")"
                                            : "(sin stock)" ?>
                                    </option>
                                <?php } ?>
                            </select>
                        </td>
                        <td class="precio">Bs 0,00</td>
                        <td>
                            <input type="number" name="cantidad[]" class="cantidad" value="1" min="1" step="1">
                        </td>
                        <td class="subtotal derecha">Bs 0,00</td>
                        <td>
                            <button type="button" class="btn btn-rojo btn-pequeno quitar" title="Quitar fila">X</button>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>

            <p style="margin-top:14px; font-size:12px; color:#6b7c8c;">
                El sistema valida el stock disponible y descuenta las unidades al guardar la venta.
            </p>
        </div>

        <div class="resumen-venta">
            <h2>Resumen de la venta</h2>

            <div class="campo">
                <label for="id_cliente">Cliente</label>
                <select name="id_cliente" id="id_cliente">
                    <option value="0">Consumidor final</option>
                    <?php while ($cliente = mysqli_fetch_assoc($clientes)) { ?>
                        <option value="<?= (int) $cliente["id_cliente"] ?>"
                            <?= $clienteElegido === (int) $cliente["id_cliente"] ? "selected" : "" ?>>
                            <?= e($cliente["codigo"] . " - " . $cliente["nombre"]) ?>
                        </option>
                    <?php } ?>
                </select>
            </div>

            <div class="resumen-linea">
                <span>Subtotal</span>
                <strong id="textoSubtotal">Bs 0,00</strong>
            </div>

            <div class="campo">
                <label for="descuento">Descuento (Bs)</label>
                <input type="number" name="descuento" id="descuento" value="0" min="0" step="0.01">
            </div>

            <div class="resumen-total">
                <span>Total</span>
                <span id="textoTotal">Bs 0,00</span>
            </div>

            <button type="submit" class="btn btn-verde" style="margin-top:18px;"
                    <?= count($listaProductos) === 0 ? "disabled" : "" ?>>
                Registrar venta
            </button>

            <a href="index.php" class="btn btn-gris" style="width:100%; text-align:center; margin-top:8px;">
                Cancelar
            </a>
        </div>
    </div>
</form>

<script>
    const filas = document.getElementById("filas");
    const descuento = document.getElementById("descuento");

    function formato(monto) {
        return "Bs " + monto.toFixed(2).replace(".", ",");
    }

    function calcularFila(fila) {
        const select = fila.querySelector(".producto");
        const opcion = select.options[select.selectedIndex];
        const precio = opcion && opcion.dataset.precio ? parseFloat(opcion.dataset.precio) : 0;
        const stock = opcion && opcion.dataset.stock ? parseInt(opcion.dataset.stock) : 0;
        const cantidadInput = fila.querySelector(".cantidad");
        let cantidad = parseInt(cantidadInput.value) || 0;

        if (cantidad < 1) {
            cantidad = 1;
            cantidadInput.value = 1;
        }

        if (cantidad > stock && stock > 0) {
            cantidad = stock;
            cantidadInput.value = stock;
        }

        const subtotal = precio * cantidad;
        fila.querySelector(".precio").textContent = formato(precio) + (stock > 0 ? " (stock " + stock + ")" : "");
        fila.querySelector(".subtotal").textContent = formato(subtotal);

        return subtotal;
    }

    function calcularTotal() {
        let subtotal = 0;
        document.querySelectorAll(".fila-producto").forEach(function (fila) {
            subtotal += calcularFila(fila);
        });

        let desc = parseFloat(descuento.value) || 0;
        if (desc < 0) {
            desc = 0;
        }
        if (desc > subtotal) {
            desc = subtotal;
            descuento.value = desc.toFixed(2);
        }

        document.getElementById("textoSubtotal").textContent = formato(subtotal);
        document.getElementById("textoTotal").textContent = formato(subtotal - desc);
    }

    document.getElementById("agregarFila").addEventListener("click", function () {
        const primera = document.querySelector(".fila-producto");
        const nueva = primera.cloneNode(true);
        nueva.querySelector(".producto").value = "";
        nueva.querySelector(".cantidad").value = 1;
        filas.appendChild(nueva);
        calcularTotal();
    });

    filas.addEventListener("change", function (evento) {
        if (evento.target.classList.contains("producto") ||
            evento.target.classList.contains("cantidad")) {
            calcularTotal();
        }
    });

    filas.addEventListener("input", function (evento) {
        if (evento.target.classList.contains("cantidad")) {
            calcularTotal();
        }
    });

    filas.addEventListener("click", function (evento) {
        if (!evento.target.classList.contains("quitar")) {
            return;
        }
        if (document.querySelectorAll(".fila-producto").length === 1) {
            alert("Debe quedar al menos una fila.");
            return;
        }
        evento.target.closest("tr").remove();
        calcularTotal();
    });

    descuento.addEventListener("input", calcularTotal);

    document.getElementById("formVenta").addEventListener("submit", function (evento) {
        let hayProducto = false;
        document.querySelectorAll(".fila-producto").forEach(function (fila) {
            if (fila.querySelector(".producto").value !== "") {
                hayProducto = true;
            }
        });

        if (!hayProducto) {
            evento.preventDefault();
            alert("Selecciona al menos un producto.");
        }
    });

    calcularTotal();
</script>

<?php include "footer.php"; ?>

ventas.phpMySQL
Script de practica.
Abrir
Ver codigo

<?php
require_once "conexion.php";
require_once "funciones.php";
exigirLogin();

$usuario = usuarioActual();
$esAdmin = esAdmin();

$desde = trim($_GET["desde"] ?? "");
$hasta = trim($_GET["hasta"] ?? "");
$buscar = trim($_GET["buscar"] ?? "");
$estado = $_GET["estado"] ?? "todas";
$pagina = max(1, (int) ($_GET["pagina"] ?? 1));
$porPagina = 15;

$condiciones = [];
$condiciones[] = $esAdmin ? "1 = 1" : "v.id_usuario = " . (int) $usuario["id_usuario"];

if ($desde !== "" && preg_match("/^\d{4}-\d{2}-\d{2}$/", $desde)) {
    $desdeSeguro = mysqli_real_escape_string($conexion, $desde);
    $condiciones[] = "DATE(v.fecha) >= '$desdeSeguro'";
}

if ($hasta !== "" && preg_match("/^\d{4}-\d{2}-\d{2}$/", $hasta)) {
    $hastaSeguro = mysqli_real_escape_string($conexion, $hasta);
    $condiciones[] = "DATE(v.fecha) <= '$hastaSeguro'";
}

if ($buscar !== "") {
    $buscarSeguro = mysqli_real_escape_string($conexion, $buscar);
    $condiciones[] = "(c.nombre LIKE '%$buscarSeguro%' OR v.id_venta = '" . (int) $buscar . "')";
}

if ($estado === "EMITIDA" || $estado === "ANULADA") {
    $condiciones[] = "v.estado = '$estado'";
}

$where = "WHERE " . implode(" AND ", $condiciones);

$resumen = mysqli_fetch_assoc(mysqli_query($conexion,
    "SELECT COUNT(*) AS cantidad,
            COALESCE(SUM(CASE WHEN v.estado = 'EMITIDA' THEN v.total ELSE 0 END), 0) AS monto
     FROM ventas v
     LEFT JOIN clientes c ON c.id_cliente = v.id_cliente
     $where"));

$totalFilas = (int) $resumen["cantidad"];
$totalPaginas = max(1, (int) ceil($totalFilas / $porPagina));
if ($pagina > $totalPaginas) {
    $pagina = $totalPaginas;
}
$inicio = ($pagina - 1) * $porPagina;

$ventas = mysqli_query($conexion,
    "SELECT v.*,
            COALESCE(c.nombre, 'Consumidor final') AS cliente,
            u.nombre AS vendedor,
            (SELECT COUNT(*) FROM detalle_ventas d WHERE d.id_venta = v.id_venta) AS items
     FROM ventas v
     LEFT JOIN clientes c ON c.id_cliente = v.id_cliente
     INNER JOIN usuarios u ON u.id_usuario = v.id_usuario
     $where
     ORDER BY v.fecha DESC
     LIMIT $inicio, $porPagina");

$parametros = ["desde" => $desde, "hasta" => $hasta, "buscar" => $buscar, "estado" => $estado];

$titulo = "Historial de ventas";
$activo = "ventas";
include "header.php";
?>

<div class="tarjetas">
    <div class="tarjeta">
        <div class="etiqueta">Ventas encontradas</div>
        <div class="valor"><?= $totalFilas ?></div>
        <div class="nota">Según los filtros aplicados</div>
    </div>
    <div class="tarjeta verde">
        <div class="etiqueta">Monto vendido</div>
        <div class="valor">Bs <?= dinero($resumen["monto"]) ?></div>
        <div class="nota">Solo ventas emitidas</div>
    </div>
</div>

<div class="caja">
    <div class="caja-cabecera">
        <div>
            <h2>Ventas registradas</h2>
            <p><?= $esAdmin ? "Todas las ventas del negocio" : "Solamente tus ventas" ?></p>
        </div>
        <a href="venta_nueva.php" class="btn btn-verde">Nueva venta</a>
    </div>

    <form method="get" action="ventas.php" class="filtros">
        <div class="campo">
            <label for="desde">Desde</label>
            <input type="date" name="desde" id="desde" value="<?= e($desde) ?>">
        </div>
        <div class="campo">
            <label for="hasta">Hasta</label>
            <input type="date" name="hasta" id="hasta" value="<?= e($hasta) ?>">
        </div>
        <div class="campo">
            <label for="buscar">Cliente o N°</label>
            <input type="text" name="buscar" id="buscar" value="<?= e($buscar) ?>" placeholder="Nombre o número">
        </div>
        <div class="campo">
            <label for="estado">Estado</label>
            <select name="estado" id="estado">
                <option value="todas" <?= $estado === "todas" ? "selected" : "" ?>>Todas</option>
                <option value="EMITIDA" <?= $estado === "EMITIDA" ? "selected" : "" ?>>Emitidas</option>
                <option value="ANULADA" <?= $estado === "ANULADA" ? "selected" : "" ?>>Anuladas</option>
            </select>
        </div>
        <button type="submit" class="btn">Filtrar</button>
        <a href="ventas.php" class="btn btn-gris">Limpiar</a>
    </form>

    <div class="tabla-caja">
        <table class="tabla">
            <thead>
            <tr>
                <th>N°</th>
                <th>Fecha</th>
                <th>Cliente</th>
                <?php if ($esAdmin) { ?><th>Vendedor</th><?php } ?>
                <th class="centro">Ítems</th>
                <th class="derecha">Total</th>
                <th>Estado</th>
                <th>Acciones</th>
            </tr>
            </thead>
            <tbody>
            <?php if (mysqli_num_rows($ventas) === 0) { ?>
                <tr><td colspan="<?= $esAdmin ? 8 : 7 ?>" class="sin-datos">No hay ventas con esos filtros.</td></tr>
            <?php } ?>

            <?php while ($venta = mysqli_fetch_assoc($ventas)) { ?>
                <tr>
                    <td>#<?= (int) $venta["id_venta"] ?></td>
                    <td><?= fechaBonita($venta["fecha"]) ?></td>
                    <td><?= e($venta["cliente"]) ?></td>
                    <?php if ($esAdmin) { ?><td><?= e($venta["vendedor"]) ?></td><?php } ?>
                    <td class="centro"><?= (int) $venta["items"] ?></td>
                    <td class="derecha"><strong>Bs <?= dinero($venta["total"]) ?></strong></td>
                    <td>
                        <span class="badge <?= $venta["estado"] === "ANULADA" ? "rojo" : "" ?>">
                            <?= e($venta["estado"]) ?>
                        </span>
                    </td>
                    <td>
                        <div class="acciones">
                            <a href="venta_detalle.php?id=<?= (int) $venta["id_venta"] ?>"
                               class="btn btn-gris btn-pequeno">Ver</a>
                            <a href="comprobante.php?id=<?= (int) $venta["id_venta"] ?>"
                               class="btn btn-gris btn-pequeno">Comprobante</a>
                        </div>
                    </td>
                </tr>
            <?php } ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalPaginas > 1) { ?>
        <div class="paginacion">
            <?php for ($i = 1; $i <= $totalPaginas; $i++) {
                $parametros["pagina"] = $i;
                $enlace = "ventas.php?" . http_build_query($parametros);
                ?>
                <?php if ($i === $pagina) { ?>
                    <span class="actual"><?= $i ?></span>
                <?php } else { ?>
                    <a href="<?= e($enlace) ?>"><?= $i ?></a>
                <?php } ?>
            <?php } ?>
        </div>
    <?php } ?>
</div>

<?php include "footer.php"; ?>

leerqr

Lector de QR con subida de imagen.
autoload_qr.phpQR
Script de practica.
Abrir
Ver codigo

<?php
// autoload_qr.php
require_once __DIR__ . '/php-qrcode-detector-decoder/lib/Common/customFunctions.php';

spl_autoload_register(function ($clase) {
    $prefijo = 'Zxing\\';
    $directorioBase = __DIR__ . '/php-qrcode-detector-decoder/lib/';

    $largoPrefijo = strlen($prefijo);
    if (strncmp($prefijo, $clase, $largoPrefijo) !== 0) {
        return;
    }

    $claseRelativa = substr($clase, $largoPrefijo);
    $archivo = $directorioBase . str_replace('\\', '/', $claseRelativa) . '.php';

    if (file_exists($archivo)) {
        require $archivo;
    }
});
formulario.php
Formulario de entrada de datos.
Abrir
Ver codigo

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Leer codigo QR</title>
<style>
body{font-family:system-ui,sans-serif;max-width:42rem;margin:3rem auto;padding:0 1rem;color:#1f2328}
form{background:#f7f8fa;border:1px solid #d8dbe0;border-radius:8px;padding:1.5rem}
input{margin:.75rem 0}
button{background:#0b57d0;color:#fff;border:0;border-radius:6px;padding:.6rem 1.4rem;font-size:1rem;cursor:pointer}
button:hover{background:#0842a0}
p{color:#57606a;font-size:.9rem}
</style>
</head>
<body>
<h2>Sube una imagen con QR para leerlo</h2>
<form action="leerqr.php" method="post" enctype="multipart/form-data">
    <input type="file" name="imagenQR" accept="image/jpeg,image/png,image/gif,image/webp,image/bmp" required>
    <br>
    <button type="submit">SUBIR QR</button>
</form>
<p>Formatos permitidos: JPG, PNG, GIF, WebP y BMP. Tamaño máximo: 2&nbsp;MB.</p>
</body>
</html>

leerqr.phpSubida de archivosexec
Lee un codigo QR desde una imagen subida.
Abrir
Ver codigo

<?php
require 'autoload_qr.php';

use Zxing\QrReader;

header('Content-Type: text/html; charset=utf-8');

$directos = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp', 'image/x-ms-bmp'];

$convertibles = ['image/avif', 'image/heic', 'image/heif', 'image/tiff'];

$erroresSubida = [
    UPLOAD_ERR_INI_SIZE => 'El archivo supera el límite configurado en el servidor.',
    UPLOAD_ERR_FORM_SIZE => 'El archivo supera el límite permitido por el formulario.',
    UPLOAD_ERR_PARTIAL => 'La imagen solo se subió parcialmente.',
    UPLOAD_ERR_NO_FILE => 'No se seleccionó ningún archivo.',
    UPLOAD_ERR_NO_TMP_DIR => 'Falta el directorio temporal del servidor.',
    UPLOAD_ERR_CANT_WRITE => 'No se pudo escribir el archivo en el disco.',
    UPLOAD_ERR_EXTENSION => 'Una extensión del servidor detuvo la subida.',
];

function responder(string $titulo, string $mensaje, bool $ok = false): void
{
    $clase = $ok ? 'ok' : 'err';
    echo <<<HTML
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Leer codigo QR</title>
<style>
body{font-family:system-ui,sans-serif;max-width:42rem;margin:3rem auto;padding:0 1rem;color:#1f2328}
h2{margin-bottom:1rem}
.caja{padding:1rem 1.25rem;border-radius:8px;line-height:1.6}
.ok{background:#e6f4ea;border:1px solid #93c9a3}
.err{background:#fce8e6;border:1px solid #f2b8b5}
code{background:#f0f1f3;padding:.15em .4em;border-radius:4px;word-break:break-all}
a{color:#0b57d0}
</style>
</head>
<body>
<h2>{$titulo}</h2>
<div class="caja {$clase}">{$mensaje}</div>
<p><a href="formulario.php">Volver al formulario</a></p>
</body>
</html>
HTML;
    exit;
}

if (!isset($_FILES['imagenQR'])) {
    responder('Error al subir la imagen', 'No llegó ninguna imagen. Vuelve a intentarlo desde el <a href="formulario.php">formulario</a>.');
}

$subida = $_FILES['imagenQR'];

if ($subida['error'] !== UPLOAD_ERR_OK) {
    $detalle = $erroresSubida[$subida['error']] ?? 'Error desconocido al subir el archivo (código ' . (int) $subida['error'] . ').';
    responder('Error al subir la imagen', htmlspecialchars($detalle));
}

$info = @getimagesize($subida['tmp_name']);

if ($info === false || empty($info['mime'])) {
    responder('Imagen no válida', 'El archivo no es una imagen que el servidor pueda procesar.');
}

$mime = strtolower($info['mime']);

$directorio = __DIR__ . DIRECTORY_SEPARATOR . 'uploads';

if (!is_dir($directorio)) {
    @mkdir($directorio, 0777, true);
}

if (!is_writable($directorio)) {
    responder('Sin permisos de escritura', 'El directorio <code>uploads/</code> no permite escritura. Ejecuta:<br><code>chmod 777 uploads</code>');
}

$nombre = preg_replace('/[^A-Za-z0-9._-]+/', '_', pathinfo($subida['name'], PATHINFO_FILENAME));
$nombre = substr($nombre === '' ? 'qr' : $nombre, 0, 60);

$extension = strtolower(pathinfo($subida['name'], PATHINFO_EXTENSION));
if (!preg_match('/^[a-z0-9]{1,5}$/', $extension)) {
    $extension = 'img';
}

if (in_array($mime, $directos, true)) {
    $rutaFinal = $directorio . DIRECTORY_SEPARATOR . $nombre . '.' . $extension;
    if (!move_uploaded_file($subida['tmp_name'], $rutaFinal)) {
        responder('Error al subir la imagen', 'No se pudo guardar el archivo dentro de <code>uploads/</code>.');
    }
} elseif (in_array($mime, $convertibles, true)) {
    $rutaFinal = $directorio . DIRECTORY_SEPARATOR . $nombre . '.png';
    $salida = [];
    $codigo = 0;
    exec('convert ' . escapeshellarg($subida['tmp_name']) . ' -auto-orient ' . escapeshellarg($rutaFinal) . ' 2>&1', $salida, $codigo);
    if ($codigo !== 0 || !is_file($rutaFinal)) {
        $detalle = trim(implode("\n", $salida));
        $extra = $detalle !== '' ? '<br><code>' . htmlspecialchars($detalle) . '</code>' : '';
        responder('Formato no compatible', 'No se pudo convertir la imagen <strong>' . htmlspecialchars($mime) . '</strong>.' . $extra);
    }
} else {
    responder('Formato no compatible', 'El formato <strong>' . htmlspecialchars($mime) . '</strong> no está soportado. Usa JPG, PNG, GIF, WebP o BMP.');
}

if (!function_exists('mb_detect_encoding')) {
    responder(
        'Falta una extensión de PHP',
        'La extensión <code>mbstring</code> no está instalada y es necesaria para decodificar el texto del QR.<br><br>Instálala con:<br><code>sudo apt install -y php8.3-mbstring &amp;&amp; sudo systemctl restart php8.3-fpm</code>'
    );
}

try {
    $lector = new QrReader($rutaFinal);
    $texto = $lector->text();
} catch (Throwable $e) {
    $mensaje = $e->getMessage();

    if (str_contains($mensaje, 'mb_detect_encoding')) {
        responder(
            'Falta una extensión de PHP',
            'La extensión <code>mbstring</code> no está instalada y es necesaria para decodificar el texto del QR.<br><br>Instálala con:<br><code>sudo apt install -y php8.3-mbstring &amp;&amp; sudo systemctl restart php8.3-fpm</code>'
        );
    }

    if ($mensaje === 'Invalid image source.') {
        responder('No se pudo leer la imagen', 'El servidor no pudo abrir el archivo como imagen compatible. Prueba con un PNG o JPG.');
    }

    responder('No se pudo leer el código QR', htmlspecialchars($mensaje));
}

if (is_string($texto) && $texto !== '') {
    responder('Contenido del QR', htmlspecialchars($texto), true);
}

responder('No se encontró código QR', 'La imagen se subió correctamente, pero no contiene un código QR legible. Prueba con una foto más nítida y bien iluminada.');

ecs.php
Script de practica.
Abrir
Ver codigo

<?php

use Rector\Set\ValueObject\LevelSetList;
use PhpCsFixer\Fixer\Operator\ConcatSpaceFixer;
use Symplify\EasyCodingStandard\Config\ECSConfig;
use Symplify\EasyCodingStandard\ValueObject\Option;

use PhpCsFixer\Fixer\ArrayNotation\ArraySyntaxFixer;
use Symplify\EasyCodingStandard\ValueObject\Set\SetList;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ECSConfig $configurator): void {

  // alternative to CLI arguments, easier to maintain and extend
  $configurator->paths([__DIR__ . '/lib', __DIR__ . '/tests']);

  // choose 
  $configurator->sets([
    SetList::CLEAN_CODE, SetList::PSR_12//, LevelSetList::UP_TO_PHP_81 //, SymfonySetList::SYMFONY_60
  ]);

  $configurator->ruleWithConfiguration(ConcatSpaceFixer::class, [
    'spacing' => 'one'
  ]);

  // indent and tabs/spaces
  // [default: spaces]. BUT: tabs are superiour due to accessibility reasons
  $configurator->indentation('tab');
};

rector.php
Script de practica.
Abrir
Ver codigo

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Symfony\Set\SymfonySetList;
use Rector\Doctrine\Set\DoctrineSetList;
use Rector\Set\ValueObject\LevelSetList;
use Rector\DeadCode\Rector\ClassMethod\RemoveUselessParamTagRector;
use Rector\TypeDeclaration\Rector\Property\TypedPropertyFromAssignsRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnNewRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddReturnTypeDeclarationRector;
use Rector\CodeQuality\Rector\Class_\InlineConstructorDefaultToPropertyRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ParamTypeByParentCallTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictNewArrayRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddVoidReturnTypeWhereNoReturnRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddMethodCallBasedStrictParamTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictBoolReturnExprRector;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->paths([
        __DIR__ . '/lib'
    ]);

    $rectorConfig->symfonyContainerXml(__DIR__ . '/var/cache/dev/App_KernelDevDebugContainer.xml');

    $rectorConfig->sets([
        DoctrineSetList::ANNOTATIONS_TO_ATTRIBUTES,
        SymfonySetList::ANNOTATIONS_TO_ATTRIBUTES,
        SymfonySetList::SYMFONY_60,
        LevelSetList::UP_TO_PHP_81
    ]);

    // register a single rule
    $rectorConfig->rule(InlineConstructorDefaultToPropertyRector::class);
    $rectorConfig->rule(AddReturnTypeDeclarationRector::class);
    $rectorConfig->rules([
        AddMethodCallBasedStrictParamTypeRector::class,
        AddVoidReturnTypeWhereNoReturnRector::class,
        ParamTypeByMethodCallTypeRector::class,
        ParamTypeByParentCallTypeRector::class,
        RemoveUselessParamTagRector::class,
        ReturnTypeFromReturnNewRector::class,
        ReturnTypeFromStrictBoolReturnExprRector::class,
        ReturnTypeFromStrictNewArrayRector::class,
        TypedPropertyFromAssignsRector::class,
    ]);

    // define sets of rules
    //    $rectorConfig->sets([
    //        LevelSetList::UP_TO_PHP_80
    //    ]);
};

Binarizer.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing;

use Zxing\Common\BitArray;
use Zxing\Common\BitMatrix;

/**
 * This class hierarchy provides a set of methods to convert luminance data to 1 bit data.
 * It allows the algorithm to vary polymorphically, for example allowing a very expensive
 * thresholding technique for servers and a fast one for mobile. It also permits the implementation
 * to vary, e.g. a JNI version for Android and a Java fallback version for other platforms.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 */
abstract class Binarizer
{
	protected function __construct(private $source)
	{
	}

	/**
	 * @return LuminanceSource
	 */
	final public function getLuminanceSource()
	{
		return $this->source;
	}

	/**
	 * Converts one row of luminance data to 1 bit data. May actually do the conversion, or return
	 * cached data. Callers should assume this method is expensive and call it as seldom as possible.
	 * This method is intended for decoding 1D barcodes and may choose to apply sharpening.
	 * For callers which only examine one row of pixels at a time, the same BitArray should be reused
	 * and passed in with each call for performance. However it is legal to keep more than one row
	 * at a time if needed.
	 *
	 * @param int $y   The row to fetch, which must be in [0, bitmap height)
	 * @param BitArray|null $row An optional preallocated array. If null or too small, it will be ignored.
	 *            If used, the Binarizer will call BitArray.clear(). Always use the returned object.
	 *
	 * @return BitArray The array of bits for this row (true means black).
	 * @throws NotFoundException if row can't be binarized
	 */
	abstract public function getBlackRow(int $y, ?BitArray $row = null): BitArray;

	/**
	 * Converts a 2D array of luminance data to 1 bit data. As above, assume this method is expensive
	 * and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or
	 * may not apply sharpening. Therefore, a row from this matrix may not be identical to one
	 * fetched using getBlackRow(), so don't mix and match between them.
	 *
	 * @return BitMatrix The 2D array of bits for the image (true means black).
	 * @throws NotFoundException if image can't be binarized to make a matrix
	 */
	abstract public function getBlackMatrix();

	/**
	 * Creates a new object with the same type as this Binarizer implementation, but with pristine
	 * state. This is needed because Binarizer implementations may be stateful, e.g. keeping a cache
	 * of 1 bit data. See Effective Java for why we can't use Java's clone() method.
	 *
	 * @param $source The LuminanceSource this Binarizer will operate on.
	 *
	 * @return Binarizer A new concrete Binarizer implementation object.
	 */
	abstract public function createBinarizer($source);

	final public function getWidth()
	{
		return $this->source->getWidth();
	}

	final public function getHeight()
	{
		return $this->source->getHeight();
	}
}

BinaryBitmap.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing;

use Zxing\Common\BitMatrix;

/**
 * This class is the core bitmap class used by ZXing to represent 1 bit data. Reader objects
 * accept a BinaryBitmap and attempt to decode it.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 */
final class BinaryBitmap
{
	private readonly \Zxing\Binarizer $binarizer;
	private ?\Zxing\Common\BitMatrix $matrix = null;

	public function __construct(Binarizer $binarizer)
	{
		if ($binarizer === null) {
			throw new \InvalidArgumentException("Binarizer must be non-null.");
		}
		$this->binarizer = $binarizer;
	}

	/**
	 * @return int The width of the bitmap.
	 */
	public function getWidth()
	{
		return $this->binarizer->getWidth();
	}

	/**
	 * @return int The height of the bitmap.
	 */
	public function getHeight()
	{
		return $this->binarizer->getHeight();
	}

	/**
	 * Converts one row of luminance data to 1 bit data. May actually do the conversion, or return
	 * cached data. Callers should assume this method is expensive and call it as seldom as possible.
	 * This method is intended for decoding 1D barcodes and may choose to apply sharpening.
	 *
	 * @param $y   The row to fetch, which must be in [0, bitmap height)
	 * @param array|null $row An optional preallocated array. If null or too small, it will be ignored.
	 *            If used, the Binarizer will call BitArray.clear(). Always use the returned object.
	 *
	 * @return Common\BitArray The array of bits for this row (true means black).
	 *
	 * @throws NotFoundException if row can't be binarized
	 */
	public function getBlackRow($y, $row): Common\BitArray
	{
		return $this->binarizer->getBlackRow($y, $row);
	}

	/**
	 * @return bool Whether this bitmap can be cropped.
	 */
	public function isCropSupported()
	{
		return $this->binarizer->getLuminanceSource()->isCropSupported();
	}

	/**
	 * Returns a new object with cropped image data. Implementations may keep a reference to the
	 * original data rather than a copy. Only callable if isCropSupported() is true.
	 *
	 * @param $left   The left coordinate, which must be in [0,getWidth())
	 * @param $top    The top coordinate, which must be in [0,getHeight())
	 * @param $width  The width of the rectangle to crop.
	 * @param $height The height of the rectangle to crop.
	 *
	 * @return BinaryBitmap A cropped version of this object.
	 */
	public function crop($left, $top, $width, $height): \Zxing\BinaryBitmap
	{
		$newSource = $this->binarizer->getLuminanceSource()->crop($left, $top, $width, $height);

		return new BinaryBitmap($this->binarizer->createBinarizer($newSource));
	}

	/**
	 * @return bool this Whether bitmap supports counter-clockwise rotation.
	 */
	public function isRotateSupported()
	{
		return $this->binarizer->getLuminanceSource()->isRotateSupported();
	}

	/**
	 * Returns a new object with rotated image data by 90 degrees counterclockwise.
	 * Only callable if {@link #isRotateSupported()} is true.
	 *
	 * @return BinaryBitmap A rotated version of this object.
	 */
	public function rotateCounterClockwise(): \Zxing\BinaryBitmap
	{
		$newSource = $this->binarizer->getLuminanceSource()->rotateCounterClockwise();

		return new BinaryBitmap($this->binarizer->createBinarizer($newSource));
	}

	/**
	 * Returns a new object with rotated image data by 45 degrees counterclockwise.
	 * Only callable if {@link #isRotateSupported()} is true.
	 *
	 * @return BinaryBitmap A rotated version of this object.
	 */
	public function rotateCounterClockwise45(): \Zxing\BinaryBitmap
	{
		$newSource = $this->binarizer->getLuminanceSource()->rotateCounterClockwise45();

		return new BinaryBitmap($this->binarizer->createBinarizer($newSource));
	}

	public function toString(): string
	{
		try {
			return $this->getBlackMatrix()->toString();
		} catch (NotFoundException) {
		}

		return '';
	}

	/**
	 * Converts a 2D array of luminance data to 1 bit. As above, assume this method is expensive
	 * and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or
	 * may not apply sharpening. Therefore, a row from this matrix may not be identical to one
	 * fetched using getBlackRow(), so don't mix and match between them.
	 *
	 * @return BitMatrix The 2D array of bits for the image (true means black).
	 * @throws NotFoundException if image can't be binarized to make a matrix
	 */
	public function getBlackMatrix()
	{
		// The matrix is created on demand the first time it is requested, then cached. There are two
		// reasons for this:
		// 1. This work will never be done if the caller only installs 1D Reader objects, or if a
		//    1D Reader finds a barcode before the 2D Readers run.
		// 2. This work will only be done once even if the caller installs multiple 2D Readers.
		if ($this->matrix === null) {
			$this->matrix = $this->binarizer->getBlackMatrix();
		}

		return $this->matrix;
	}
}

ChecksumException.php
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing;

/**
 * Thrown when a barcode was successfully detected and decoded, but
 * was not returned because its checksum feature failed.
 *
 * @author Sean Owen
 */
final class ChecksumException extends ReaderException
{
	private static ?\Zxing\ChecksumException $instance = null;

	public static function getChecksumInstance($cause = ""): self
	{
		if (self::$isStackTrace) {
			return new ChecksumException($cause);
		} else {
			if (!self::$instance) {
				self::$instance = new ChecksumException($cause);
			}

			return self::$instance;
		}
	}
}

FormatException.php
Formulario de entrada de datos.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing;

/**
 * Thrown when a barcode was successfully detected, but some aspect of
 * the content did not conform to the barcode's format rules. This could have
 * been due to a mis-detection.
 *
 * @author Sean Owen
 */
final class FormatException extends ReaderException
{
	private static ?\Zxing\FormatException $instance = null;

	public function __construct($cause = null)
	{
		if ($cause) {
			parent::__construct($cause);
		}
	}

	public static function getFormatInstance($cause = null): self
	{
		if (!self::$instance) {
			self::$instance = new FormatException();
		}
		if (self::$isStackTrace) {
			return new FormatException($cause);
		} else {
			return self::$instance;
		}
	}
}

GDLuminanceSource.php
Script de practica.
Abrir
Ver codigo

<?php


namespace Zxing;

/**
 * This class is used to help decode images from files which arrive as GD Resource
 * It does not support rotation.
 *
 *
 *
 */
final class GDLuminanceSource extends LuminanceSource
{
	public $luminances;
	private $dataWidth;
	private $dataHeight;
	/**
  * @var mixed|int
  */
	private $left;
	/**
  * @var mixed|int
  */
	private $top;
	/**
  * @var mixed|null
  */
	private $gdImage;

	public function __construct(
		$gdImage,
		$dataWidth,
		$dataHeight,
		$left = null,
		$top = null,
		$width = null,
		$height = null
	) {
		if (!$left && !$top && !$width && !$height) {
			$this->GDLuminanceSource($gdImage, $dataWidth, $dataHeight);

			return;
		}
		parent::__construct($width, $height);
		if ($left + $width > $dataWidth || $top + $height > $dataHeight) {
			throw new \InvalidArgumentException("Crop rectangle does not fit within image data.");
		}
		$this->luminances = $gdImage;
		$this->dataWidth = $dataWidth;
		$this->dataHeight = $dataHeight;
		$this->left = $left;
		$this->top = $top;
	}

	public function GDLuminanceSource($gdImage, $width, $height): void
	{
		parent::__construct($width, $height);

		$this->dataWidth = $width;
		$this->dataHeight = $height;
		$this->left = 0;
		$this->top = 0;
		$this->gdImage = $gdImage;


		// In order to measure pure decoding speed, we convert the entire image to a greyscale array
		// up front, which is the same as the Y channel of the YUVLuminanceSource in the real app.
		$this->luminances = [];
		//$this->luminances = $this->grayScaleToBitmap($this->grayscale());

		$array = [];
		$rgb = [];

		for ($j = 0; $j < $height; $j++) {
			for ($i = 0; $i < $width; $i++) {
				$argb = imagecolorat($this->gdImage, $i, $j);
				$pixel = imagecolorsforindex($this->gdImage, $argb);
				$r = $pixel['red'];
				$g = $pixel['green'];
				$b = $pixel['blue'];
				if ($r == $g && $g == $b) {
					// Image is already greyscale, so pick any channel.

					$this->luminances[] = $r;//(($r + 128) % 256) - 128;
				} else {
					// Calculate luminance cheaply, favoring green.
					$this->luminances[] = ($r + 2 * $g + $b) / 4;//(((($r + 2 * $g + $b) / 4) + 128) % 256) - 128;
				}
			}
		}

		/*
		for ($y = 0; $y < $height; $y++) {
			$offset = $y * $width;
			for ($x = 0; $x < $width; $x++) {
				$pixel = $pixels[$offset + $x];
				$r = ($pixel >> 16) & 0xff;
				$g = ($pixel >> 8) & 0xff;
				$b = $pixel & 0xff;
				if ($r == $g && $g == $b) {
// Image is already greyscale, so pick any channel.

					$this->luminances[(int)($offset + $x)] = (($r+128) % 256) - 128;
				} else {
// Calculate luminance cheaply, favoring green.
					$this->luminances[(int)($offset + $x)] =  (((($r + 2 * $g + $b) / 4)+128)%256) - 128;
				}



			}
		*/
		//}
		//   $this->luminances = $this->grayScaleToBitmap($this->luminances);
	}

	
	public function getRow($y, $row = null)
	{
		if ($y < 0 || $y >= $this->getHeight()) {
			throw new \InvalidArgumentException('Requested row is outside the image: ' . $y);
		}
		$width = $this->getWidth();
		if ($row == null || (is_countable($row) ? count($row) : 0) < $width) {
			$row = [];
		}
		$offset = ($y + $this->top) * $this->dataWidth + $this->left;
		$row = arraycopy($this->luminances, $offset, $row, 0, $width);

		return $row;
	}

	
	public function getMatrix()
	{
		$width = $this->getWidth();
		$height = $this->getHeight();

		// If the caller asks for the entire underlying image, save the copy and give them the
		// original data. The docs specifically warn that result.length must be ignored.
		if ($width == $this->dataWidth && $height == $this->dataHeight) {
			return $this->luminances;
		}

		$area = $width * $height;
		$matrix = [];
		$inputOffset = $this->top * $this->dataWidth + $this->left;

		// If the width matches the full width of the underlying data, perform a single copy.
		if ($width == $this->dataWidth) {
			$matrix = arraycopy($this->luminances, $inputOffset, $matrix, 0, $area);

			return $matrix;
		}

		// Otherwise copy one cropped row at a time.
		$rgb = $this->luminances;
		for ($y = 0; $y < $height; $y++) {
			$outputOffset = $y * $width;
			$matrix = arraycopy($rgb, $inputOffset, $matrix, $outputOffset, $width);
			$inputOffset += $this->dataWidth;
		}

		return $matrix;
	}

	
	public function isCropSupported(): bool
	{
		return true;
	}

	
	public function crop($left, $top, $width, $height): \Zxing\GDLuminanceSource
	{
		return new GDLuminanceSource(
			$this->luminances,
			$this->dataWidth,
			$this->dataHeight,
			$this->left + $left,
			$this->top + $top,
			$width,
			$height
		);
	}

	public function rotateCounterClockwise(): void
	{
		throw new \RuntimeException("This LuminanceSource does not support rotateCounterClockwise");
	}

	public function rotateCounterClockwise45(): void
	{
		throw new \RuntimeException("This LuminanceSource does not support rotateCounterClockwise45");
	}
}

IMagickLuminanceSource.php
Script de practica.
Abrir
Ver codigo

<?php

namespace Zxing;

/**
 * This class is used to help decode images from files which arrive as GD Resource
 * It does not support rotation.
 */
final class IMagickLuminanceSource extends LuminanceSource
{
	public $luminances;
	private $dataWidth;
	private $dataHeight;
	/**
	 * @var mixed|int
	 */
	private $left;
	/**
	 * @var mixed|int
	 */
	private $top;
	private ?\Imagick $image = null;

	public function __construct(
		\Imagick $image,
		$dataWidth,
		$dataHeight,
		$left = null,
		$top = null,
		$width = null,
		$height = null
	) {
		if (!$left && !$top && !$width && !$height) {
			$this->_IMagickLuminanceSource($image, $dataWidth, $dataHeight);

			return;
		}
		parent::__construct($width, $height);
		if ($left + $width > $dataWidth || $top + $height > $dataHeight) {
			throw new \InvalidArgumentException("Crop rectangle does not fit within image data.");
		}
		$this->luminances = $image;
		$this->dataWidth = $dataWidth;
		$this->dataHeight = $dataHeight;
		$this->left = $left;
		$this->top = $top;
	}

	public function rotateCounterClockwise(): void
	{
		throw new \RuntimeException("This LuminanceSource does not support rotateCounterClockwise");
	}

	public function rotateCounterClockwise45(): void
	{
		throw new \RuntimeException("This LuminanceSource does not support rotateCounterClockwise45");
	}

	/**
	 * TODO: move to some utility class or something
	 * Converts shorthand memory notation value to bytes
	 * From http://php.net/manual/en/function.ini-get.php
	 *
	 * @param int $val Memory size shorthand notation string
	 */
	protected static function kmgStringToBytes(string $val)
	{
		$val = trim($val);
		$last = strtolower($val[strlen($val) - 1]);
		$val = substr($val, 0, -1);
		switch ($last) {
				// The 'G' modifier is available since PHP 5.1.0
			case 'g':
				$val *= 1024;
				// no break
			case 'm':
				$val *= 1024;
				// no break
			case 'k':
				$val *= 1024;
		}
		return $val;
	}

	public function _IMagickLuminanceSource(\Imagick $image, $width, $height): void
	{
		parent::__construct($width, $height);

		$this->dataWidth = $width;
		$this->dataHeight = $height;
		$this->left = 0;
		$this->top = 0;
		$this->image = $image;

		// In order to measure pure decoding speed, we convert the entire image to a greyscale array
		// up front, which is the same as the Y channel of the YUVLuminanceSource in the real app.
		$this->luminances = [];

		$image->setImageColorspace(\Imagick::COLORSPACE_GRAY);
		// Check that we actually have enough space to do it
		if (ini_get('memory_limit') != -1 && $width * $height * 16 * 3 > $this->kmgStringToBytes(ini_get('memory_limit'))) {
			throw new \RuntimeException("PHP Memory Limit does not allow pixel export.");
		}
		$pixels = $image->exportImagePixels(1, 1, $width, $height, "RGB", \Imagick::PIXEL_CHAR);

		$array = [];
		$rgb = [];

		$countPixels = count($pixels);
		for ($i = 0; $i < $countPixels; $i += 3) {
			$r = $pixels[$i] & 0xff;
			$g = $pixels[$i + 1] & 0xff;
			$b = $pixels[$i + 2] & 0xff;
			if ($r == $g && $g == $b) {
				// Image is already greyscale, so pick any channel.
				$this->luminances[] = $r; //(($r + 128) % 256) - 128;
			} else {
				// Calculate luminance cheaply, favoring green.
				$this->luminances[] = ($r + 2 * $g + $b) / 4; //(((($r + 2 * $g + $b) / 4) + 128) % 256) - 128;
			}
		}
	}


	public function getRow($y, $row = null)
	{
		if ($y < 0 || $y >= $this->getHeight()) {
			throw new \InvalidArgumentException('Requested row is outside the image: ' . $y);
		}
		$width = $this->getWidth();
		if ($row == null || (is_countable($row) ? count($row) : 0) < $width) {
			$row = [];
		}
		$offset = ($y + $this->top) * $this->dataWidth + $this->left;
		$row = arraycopy($this->luminances, $offset, $row, 0, $width);

		return $row;
	}


	public function getMatrix()
	{
		$width = $this->getWidth();
		$height = $this->getHeight();

		// If the caller asks for the entire underlying image, save the copy and give them the
		// original data. The docs specifically warn that result.length must be ignored.
		if ($width == $this->dataWidth && $height == $this->dataHeight) {
			return $this->luminances;
		}

		$area = $width * $height;
		$matrix = [];
		$inputOffset = $this->top * $this->dataWidth + $this->left;

		// If the width matches the full width of the underlying data, perform a single copy.
		if ($width == $this->dataWidth) {
			$matrix = arraycopy($this->luminances, $inputOffset, $matrix, 0, $area);

			return $matrix;
		}

		// Otherwise copy one cropped row at a time.
		$rgb = $this->luminances;
		for ($y = 0; $y < $height; $y++) {
			$outputOffset = $y * $width;
			$matrix = arraycopy($rgb, $inputOffset, $matrix, $outputOffset, $width);
			$inputOffset += $this->dataWidth;
		}

		return $matrix;
	}


	public function isCropSupported(): bool
	{
		return true;
	}


	public function crop($left, $top, $width, $height): LuminanceSource
	{
		return $this->luminances->cropImage($width, $height, $left, $top);

		return new GDLuminanceSource(
			$this->luminances,
			$this->dataWidth,
			$this->dataHeight,
			$this->left + $left,
			$this->top + $top,
			$width,
			$height
		);
	}
}

LuminanceSource.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing;

use Zxing\Common\BitMatrix;

/**
 * The purpose of this class hierarchy is to abstract different bitmap implementations across
 * platforms into a standard interface for requesting greyscale luminance values. The interface
 * only provides immutable methods; therefore crop and rotation create copies. This is to ensure
 * that one Reader does not modify the original luminance source and leave it in an unknown state
 * for other Readers in the chain.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 */
abstract class LuminanceSource
{
	public function __construct(private $width, private $height)
	{
	}

	/**
	 * Fetches luminance data for the underlying bitmap. Values should be fetched using:
	 * {@code int luminance = array[y * width + x] & 0xff}
	 *
	 * @return BitMatrix A row-major 2D array of luminance values. Do not use result.length as it may be
	 *         larger than width * height bytes on some platforms. Do not modify the contents
	 *         of the result.
	 */
	abstract public function getMatrix();

	/**
	 * @return float The width of the bitmap.
	 */
	final public function getWidth(): float
	{
		return $this->width;
	}

	/**
	 * @return float The height of the bitmap.
	 */
	final public function getHeight(): float
	{
		return $this->height;
	}

	/**
	 * @return bool Whether this subclass supports cropping.
	 */
	public function isCropSupported(): bool
	{
		return false;
	}

	/**
	 * Returns a new object with cropped image data. Implementations may keep a reference to the
	 * original data rather than a copy. Only callable if isCropSupported() is true.
	 *
	 * @param $left   The left coordinate, which must be in [0,getWidth())
	 * @param $top    The top coordinate, which must be in [0,getHeight())
	 * @param $width  The width of the rectangle to crop.
	 * @param $height The height of the rectangle to crop.
	 *
	 * @return mixed A cropped version of this object.
	 */
	abstract public function crop($left, $top, $width, $height): LuminanceSource;

	/**
	 * @return bool Whether this subclass supports counter-clockwise rotation.
	 */
	public function isRotateSupported(): bool
	{
		return false;
	}

	/**
	 * @return a wrapper of this {@code LuminanceSource} which inverts the luminances it returns -- black becomes
	 *  white and vice versa, and each value becomes (255-value).
	 */
	// public function invert()
	// {
	// 	return new InvertedLuminanceSource($this);
	// }

	/**
	 * Returns a new object with rotated image data by 90 degrees counterclockwise.
	 * Only callable if {@link #isRotateSupported()} is true.
	 *
	 * @return mixed A rotated version of this object.
	 */
	abstract public function rotateCounterClockwise(): void;

	/**
	 * Returns a new object with rotated image data by 45 degrees counterclockwise.
	 * Only callable if {@link #isRotateSupported()} is true.
	 *
	 * @return mixed A rotated version of this object.
	 */
	abstract public function rotateCounterClockwise45(): void;

	final public function toString(): string
	{
		$row = [];
		$result = '';
		for ($y = 0; $y < $this->height; $y++) {
			$row = $this->getRow($y, $row);
			for ($x = 0; $x < $this->width; $x++) {
				$luminance = $row[$x] & 0xFF;
				$c = '';
				if ($luminance < 0x40) {
					$c = '#';
				} elseif ($luminance < 0x80) {
					$c = '+';
				} elseif ($luminance < 0xC0) {
					$c = '.';
				} else {
					$c = ' ';
				}
				$result .= ($c);
			}
			$result .= ('\n');
		}

		return $result;
	}

	/**
	 * Fetches one row of luminance data from the underlying platform's bitmap. Values range from
	 * 0 (black) to 255 (white). Because Java does not have an unsigned byte type, callers will have
	 * to bitwise and with 0xff for each value. It is preferable for implementations of this method
	 * to only fetch this row rather than the whole image, since no 2D Readers may be installed and
	 * getMatrix() may never be called.
	 *
	 * @param $y   ; The row to fetch, which must be in [0,getHeight())
	 * @param $row ; An optional preallocated array. If null or too small, it will be ignored.
	 *             Always use the returned object, and ignore the .length of the array.
	 *
	 * @return array
	 * An array containing the luminance data.
	 */
	abstract public function getRow(int $y, array $row);
}

NotFoundException.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing;

/**
 * Thrown when a barcode was not found in the image. It might have been
 * partially detected but could not be confirmed.
 *
 * @author Sean Owen
 */
final class NotFoundException extends ReaderException
{
	private static ?\Zxing\NotFoundException $instance = null;

	public static function getNotFoundInstance(string $message = ""): self
	{
		if (!self::$instance) {
			self::$instance = new NotFoundException($message);
		}

		return self::$instance;
	}
}

PlanarYUVLuminanceSource.php
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2009 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing;

/**
 * This object extends LuminanceSource around an array of YUV data returned from the camera driver,
 * with the option to crop to a rectangle within the full data. This can be used to exclude
 * superfluous pixels around the perimeter and speed up decoding.
 *
 * It works for any pixel format where the Y channel is planar and appears first, including
 * YCbCr_420_SP and YCbCr_422_SP.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 */
final class PlanarYUVLuminanceSource extends LuminanceSource
{
	private static int $THUMBNAIL_SCALE_FACTOR = 2;
	private $dataWidth;
	private $dataHeight;
	private $left;
	private $top;

	public function __construct(
		private $yuvData,
		$dataWidth,
		$dataHeight,
		$left,
		$top,
		$width,
		$height,
		$reverseHorizontal
	) {
		parent::__construct($width, $height);

		if ($left + $width > $dataWidth || $top + $height > $dataHeight) {
			throw new \InvalidArgumentException("Crop rectangle does not fit within image data.");
		}
		$this->dataWidth = $dataWidth;
		$this->dataHeight = $dataHeight;
		$this->left = $left;
		$this->top = $top;
		if ($reverseHorizontal) {
			$this->reverseHorizontal($width, $height);
		}
	}

	public function rotateCounterClockwise(): void
	{
		throw new \RuntimeException("This LuminanceSource does not support rotateCounterClockwise");
	}

	public function rotateCounterClockwise45(): void
	{
		throw new \RuntimeException("This LuminanceSource does not support rotateCounterClockwise45");
	}

	public function getRow($y, $row = null)
	{
		if ($y < 0 || $y >= $this->getHeight()) {
			throw new \InvalidArgumentException("Requested row is outside the image: " + $y);
		}
		$width = $this->getWidth();
		if ($row == null || (is_countable($row) ? count($row) : 0) < $width) {
			$row = []; //new byte[width];
		}
		$offset = ($y + $this->top) * $this->dataWidth + $this->left;
		$row = arraycopy($this->yuvData, $offset, $row, 0, $width);

		return $row;
	}


	public function getMatrix()
	{
		$width = $this->getWidth();
		$height = $this->getHeight();

		// If the caller asks for the entire underlying image, save the copy and give them the
		// original data. The docs specifically warn that result.length must be ignored.
		if ($width == $this->dataWidth && $height == $this->dataHeight) {
			return $this->yuvData;
		}

		$area = $width * $height;
		$matrix = []; //new byte[area];
		$inputOffset = $this->top * $this->dataWidth + $this->left;

		// If the width matches the full width of the underlying data, perform a single copy.
		if ($width == $this->dataWidth) {
			$matrix = arraycopy($this->yuvData, $inputOffset, $matrix, 0, $area);

			return $matrix;
		}

		// Otherwise copy one cropped row at a time.
		$yuv = $this->yuvData;
		for ($y = 0; $y < $height; $y++) {
			$outputOffset = $y * $width;
			$matrix = arraycopy($this->yuvData, $inputOffset, $matrix, $outputOffset, $width);
			$inputOffset += $this->dataWidth;
		}

		return $matrix;
	}

	// @Override
	public function isCropSupported(): bool
	{
		return true;
	}

	// @Override
	public function crop($left, $top, $width, $height): \Zxing\PlanarYUVLuminanceSource
	{
		return new PlanarYUVLuminanceSource(
			$this->yuvData,
			$this->dataWidth,
			$this->dataHeight,
			$this->left + $left,
			$this->top + $top,
			$width,
			$height,
			false
		);
	}

	/**
	 * @return int[]
	 */
	public function renderThumbnail(): array
	{
		$width = (int)($this->getWidth() / self::$THUMBNAIL_SCALE_FACTOR);
		$height = (int)($this->getHeight() / self::$THUMBNAIL_SCALE_FACTOR);
		$pixels = []; //new int[width * height];
		$yuv = $this->yuvData;
		$inputOffset = $this->top * $this->dataWidth + $this->left;

		for ($y = 0; $y < $height; $y++) {
			$outputOffset = $y * $width;
			for ($x = 0; $x < $width; $x++) {
				$grey = ($yuv[$inputOffset + $x * self::$THUMBNAIL_SCALE_FACTOR] & 0xff);
				$pixels[$outputOffset + $x] = (0xFF000000 | ($grey * 0x00010101));
			}
			$inputOffset += $this->dataWidth * self::$THUMBNAIL_SCALE_FACTOR;
		}

		return $pixels;
	}

	/**
	 * @return width of image from {@link #renderThumbnail()}
	 */
	/*
  public int getThumbnailWidth() {
	return getWidth() / THUMBNAIL_SCALE_FACTOR;
  }*/

	/**
	 * @return height of image from {@link #renderThumbnail()}
	 */
	/**public function getThumbnailHeight(): int
	{
		return getHeight() / THUMBNAIL_SCALE_FACTOR;
	}*/

	/**
	 *
	 * @param int $width
	 * @param int $height
	 * @return void
	 */
	private function reverseHorizontal(int $width, int $height): void
	{
		$yuvData = $this->yuvData;
		for ($y = 0, $rowStart = $this->top * $this->dataWidth + $this->left; $y < $height; $y++, $rowStart += $this->dataWidth) {
			$middle = (int)round($rowStart + $width / 2);
			for ($x1 = $rowStart, $x2 = $rowStart + $width - 1; $x1 < $middle; $x1++, $x2--) {
				$temp = $yuvData[$x1];
				$yuvData[$x1] = $yuvData[$x2];
				$yuvData[$x2] = $temp;
			}
		}
	}
}

QrReader.phpArchivos de textoQR
Script de practica.
Abrir
Ver codigo

<?php

namespace Zxing;

use Exception;
use Zxing\Common\HybridBinarizer;
use Zxing\Qrcode\QRCodeReader;

final class QrReader
{
	/**
	 * @var string
	 */
	public const SOURCE_TYPE_FILE = 'file';
	/**
	 * @var string
	 */
	public const SOURCE_TYPE_BLOB = 'blob';
	/**
	 * @var string
	 */
	public const SOURCE_TYPE_RESOURCE = 'resource';

	private readonly \Zxing\BinaryBitmap $bitmap;
	private readonly \Zxing\Qrcode\QRCodeReader $reader;
	private \Zxing\Result|bool|null $result = null;
	private ?Exception $error = null;

	public function __construct($imgSource, $sourceType = QrReader::SOURCE_TYPE_FILE, $useImagickIfAvailable = true)
	{
		if (!in_array($sourceType, [
			self::SOURCE_TYPE_FILE,
			self::SOURCE_TYPE_BLOB,
			self::SOURCE_TYPE_RESOURCE,
		], true)) {
			throw new \InvalidArgumentException('Invalid image source.');
		}
		$im = null;
		switch ($sourceType) {
			case QrReader::SOURCE_TYPE_FILE:
				if ($useImagickIfAvailable && extension_loaded('imagick')) {
					$im = new \Imagick();
					$im->readImage($imgSource);
				} else {
					$image = file_get_contents($imgSource);
					$im = imagecreatefromstring($image);
				}
				break;

			case QrReader::SOURCE_TYPE_BLOB:
				if ($useImagickIfAvailable && extension_loaded('imagick')) {
					$im = new \Imagick();
					$im->readImageBlob($imgSource);
				} else {
					$im = imagecreatefromstring($imgSource);
				}
				break;

			case QrReader::SOURCE_TYPE_RESOURCE:
				$im = $imgSource;
				if ($useImagickIfAvailable && extension_loaded('imagick')) {
					$useImagickIfAvailable = true;
				} else {
					$useImagickIfAvailable = false;
				}
				break;
		}
		if ($useImagickIfAvailable && extension_loaded('imagick')) {
			if (!$im instanceof \Imagick) {
				throw new \InvalidArgumentException('Invalid image source.');
			}
			$width = $im->getImageWidth();
			$height = $im->getImageHeight();
			$source = new IMagickLuminanceSource($im, $width, $height);
		} else {
			if (!$im instanceof \GdImage && !is_object($im)) {
				throw new \InvalidArgumentException('Invalid image source.');
			}
			$width = imagesx($im);
			$height = imagesy($im);
			$source = new GDLuminanceSource($im, $width, $height);
		}
		$histo = new HybridBinarizer($source);
		$this->bitmap = new BinaryBitmap($histo);
		$this->reader = new QRCodeReader();
	}

	public function decode($hints = null): void
	{
		try {
			$this->result = $this->reader->decode($this->bitmap, $hints);
		} catch (NotFoundException | FormatException | ChecksumException $e) {
			$this->result = false;
			$this->error = $e;
		}
	}

	public function text($hints = null)
	{
		$this->decode($hints);

		if ($this->result !== false && method_exists($this->result, 'toString')) {
			return $this->result->toString();
		}

		return $this->result;
	}

	public function getResult(): bool|Result|null
	{
		return $this->result;
	}

	public function getError(): Exception|null
	{
		return $this->error;
	}
}

RGBLuminanceSource.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing;

/**
 * This class is used to help decode images from files which arrive as RGB data from
 * an ARGB pixel array. It does not support rotation.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 * @author Betaminos
 */
final class RGBLuminanceSource extends LuminanceSource
{
	public $luminances;
	private $dataWidth;
	private $dataHeight;
	/**
  * @var mixed|int
  */
	private $left;
	/**
  * @var mixed|int
  */
	private $top;
	/**
  * @var mixed|null
  */
	private $pixels;


	public function __construct(
		$pixels,
		$dataWidth,
		$dataHeight,
		$left = null,
		$top = null,
		$width = null,
		$height = null
	) {
		if (!$left && !$top && !$width && !$height) {
			$this->RGBLuminanceSource_($pixels, $dataWidth, $dataHeight);

			return;
		}
		parent::__construct($width, $height);
		if ($left + $width > $dataWidth || $top + $height > $dataHeight) {
			throw new \InvalidArgumentException("Crop rectangle does not fit within image data.");
		}
		$this->luminances = $pixels;
		$this->dataWidth = $dataWidth;
		$this->dataHeight = $dataHeight;
		$this->left = $left;
		$this->top = $top;
	}

	public function rotateCounterClockwise(): void
	{
		throw new \RuntimeException("This LuminanceSource does not support rotateCounterClockwise");
	}

	public function rotateCounterClockwise45(): void
	{
		throw new \RuntimeException("This LuminanceSource does not support rotateCounterClockwise45");
	}

	public function RGBLuminanceSource_($width, $height, $pixels): void
	{
		parent::__construct($width, $height);

		$this->dataWidth = $width;
		$this->dataHeight = $height;
		$this->left = 0;
		$this->top = 0;
		$this->pixels = $pixels;


		// In order to measure pure decoding speed, we convert the entire image to a greyscale array
		// up front, which is the same as the Y channel of the YUVLuminanceSource in the real app.
		$this->luminances = [];
		//$this->luminances = $this->grayScaleToBitmap($this->grayscale());

		foreach ($pixels as $key => $pixel) {
			$r = $pixel['red'];
			$g = $pixel['green'];
			$b = $pixel['blue'];

			/* if (($pixel & 0xFF000000) == 0) {
				 $pixel = 0xFFFFFFFF; // = white
			 }

			 // .229R + 0.587G + 0.114B (YUV/YIQ for PAL and NTSC)

			 $this->luminances[$key] =
				 (306 * (($pixel >> 16) & 0xFF) +
					 601 * (($pixel >> 8) & 0xFF) +
					 117 * ($pixel & 0xFF) +
					 0x200) >> 10;

			*/
			//$r = ($pixel >> 16) & 0xff;
			//$g = ($pixel >> 8) & 0xff;
			//$b = $pixel & 0xff;
			if ($r == $g && $g == $b) {
				// Image is already greyscale, so pick any channel.

				$this->luminances[$key] = $r;//(($r + 128) % 256) - 128;
			} else {
				// Calculate luminance cheaply, favoring green.
				$this->luminances[$key] = ($r + 2 * $g + $b) / 4;//(((($r + 2 * $g + $b) / 4) + 128) % 256) - 128;
			}
		}

		/*

		for ($y = 0; $y < $height; $y++) {
			$offset = $y * $width;
			for ($x = 0; $x < $width; $x++) {
				$pixel = $pixels[$offset + $x];
				$r = ($pixel >> 16) & 0xff;
				$g = ($pixel >> 8) & 0xff;
				$b = $pixel & 0xff;
				if ($r == $g && $g == $b) {
// Image is already greyscale, so pick any channel.

					$this->luminances[(int)($offset + $x)] = (($r+128) % 256) - 128;
				} else {
// Calculate luminance cheaply, favoring green.
					$this->luminances[(int)($offset + $x)] =  (((($r + 2 * $g + $b) / 4)+128)%256) - 128;
				}



			}
		*/
		//}
		//   $this->luminances = $this->grayScaleToBitmap($this->luminances);
	}

	/**
	 * @return (int|mixed)[]
	 *
	 * @psalm-return array<int|mixed>
	 */
	public function grayscale(): array
	{
		$width = $this->dataWidth;
		$height = $this->dataHeight;

		$ret = fill_array(0, $width * $height, 0);
		for ($y = 0; $y < $height; $y++) {
			for ($x = 0; $x < $width; $x++) {
				$gray = $this->getPixel($x, $y, $width, $height);

				$ret[$x + $y * $width] = $gray;
			}
		}

		return $ret;
	}

	public function getPixel(int $x, int $y, $width, $height): int
	{
		$image = $this->pixels;
		if ($width < $x) {
			die('error');
		}
		if ($height < $y) {
			die('error');
		}
		$point = ($x) + ($y * $width);

		$r = $image[$point]['red'];//($image[$point] >> 16) & 0xff;
		$g = $image[$point]['green'];//($image[$point] >> 8) & 0xff;
		$b = $image[$point]['blue'];//$image[$point] & 0xff;

		$p = (int)(($r * 33 + $g * 34 + $b * 33) / 100);


		return $p;
	}

	/**
	 * @return (int|mixed)[]
	 *
	 * @psalm-return array<int, 0|255|mixed>
	 */
	public function grayScaleToBitmap($grayScale): array
	{
		$middle = $this->getMiddleBrightnessPerArea($grayScale);
		$sqrtNumArea = is_countable($middle) ? count($middle) : 0;
		$areaWidth = floor($this->dataWidth / $sqrtNumArea);
		$areaHeight = floor($this->dataHeight / $sqrtNumArea);
		$bitmap = fill_array(0, $this->dataWidth * $this->dataHeight, 0);

		for ($ay = 0; $ay < $sqrtNumArea; $ay++) {
			for ($ax = 0; $ax < $sqrtNumArea; $ax++) {
				for ($dy = 0; $dy < $areaHeight; $dy++) {
					for ($dx = 0; $dx < $areaWidth; $dx++) {
						$bitmap[(int)($areaWidth * $ax + $dx + ($areaHeight * $ay + $dy) * $this->dataWidth)] = ($grayScale[(int)($areaWidth * $ax + $dx + ($areaHeight * $ay + $dy) * $this->dataWidth)] < $middle[$ax][$ay]) ? 0 : 255;
					}
				}
			}
		}

		return $bitmap;
	}

	/**
  * @return float[]&mixed[][]
  */
	public function getMiddleBrightnessPerArea($image): array
	{
		$numSqrtArea = 4;
		//obtain middle brightness((min + max) / 2) per area
		$areaWidth = floor($this->dataWidth / $numSqrtArea);
		$areaHeight = floor($this->dataHeight / $numSqrtArea);
		$minmax = fill_array(0, $numSqrtArea, 0);
		for ($i = 0; $i < $numSqrtArea; $i++) {
			$minmax[$i] = fill_array(0, $numSqrtArea, 0);
			for ($i2 = 0; $i2 < $numSqrtArea; $i2++) {
				$minmax[$i][$i2] = [0, 0];
			}
		}
		for ($ay = 0; $ay < $numSqrtArea; $ay++) {
			for ($ax = 0; $ax < $numSqrtArea; $ax++) {
				$minmax[$ax][$ay][0] = 0xFF;
				for ($dy = 0; $dy < $areaHeight; $dy++) {
					for ($dx = 0; $dx < $areaWidth; $dx++) {
						$target = $image[(int)($areaWidth * $ax + $dx + ($areaHeight * $ay + $dy) * $this->dataWidth)];
						if ($target < $minmax[$ax][$ay][0]) {
							$minmax[$ax][$ay][0] = $target;
						}
						if ($target > $minmax[$ax][$ay][1]) {
							$minmax[$ax][$ay][1] = $target;
						}
					}
				}
				//minmax[ax][ay][0] = (minmax[ax][ay][0] + minmax[ax][ay][1]) / 2;
			}
		}
		$middle = [];
		for ($i3 = 0; $i3 < $numSqrtArea; $i3++) {
			$middle[$i3] = [];
		}
		for ($ay = 0; $ay < $numSqrtArea; $ay++) {
			for ($ax = 0; $ax < $numSqrtArea; $ax++) {
				$middle[$ax][$ay] = floor(($minmax[$ax][$ay][0] + $minmax[$ax][$ay][1]) / 2);
				//Console.out.print(middle[ax][ay] + ",");
			}
			//Console.out.println("");
		}

		//Console.out.println("");

		return $middle;
	}

	
	public function getRow($y, $row = null)
	{
		if ($y < 0 || $y >= $this->getHeight()) {
			throw new \InvalidArgumentException("Requested row is outside the image: " + $y);
		}
		$width = $this->getWidth();
		if ($row == null || (is_countable($row) ? count($row) : 0) < $width) {
			$row = [];
		}
		$offset = ($y + $this->top) * $this->dataWidth + $this->left;
		$row = arraycopy($this->luminances, $offset, $row, 0, $width);

		return $row;
	}

	
	public function getMatrix()
	{
		$width = $this->getWidth();
		$height = $this->getHeight();

		// If the caller asks for the entire underlying image, save the copy and give them the
		// original data. The docs specifically warn that result.length must be ignored.
		if ($width == $this->dataWidth && $height == $this->dataHeight) {
			return $this->luminances;
		}

		$area = $width * $height;
		$matrix = [];
		$inputOffset = $this->top * $this->dataWidth + $this->left;

		// If the width matches the full width of the underlying data, perform a single copy.
		if ($width == $this->dataWidth) {
			$matrix = arraycopy($this->luminances, $inputOffset, $matrix, 0, $area);

			return $matrix;
		}

		// Otherwise copy one cropped row at a time.
		$rgb = $this->luminances;
		for ($y = 0; $y < $height; $y++) {
			$outputOffset = $y * $width;
			$matrix = arraycopy($rgb, $inputOffset, $matrix, $outputOffset, $width);
			$inputOffset += $this->dataWidth;
		}

		return $matrix;
	}

	
	public function isCropSupported(): bool
	{
		return true;
	}

	
	public function crop($left, $top, $width, $height): \Zxing\RGBLuminanceSource
	{
		return new RGBLuminanceSource(
			$this->luminances,
			$this->dataWidth,
			$this->dataHeight,
			$this->left + $left,
			$this->top + $top,
			$width,
			$height
		);
	}
}

Reader.php
Script de practica.
Abrir
Ver codigo

<?php

namespace Zxing;

interface Reader
{
	public function decode(BinaryBitmap $image);

	public function reset();
}

ReaderException.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing;

/**
 * The general exception class throw when something goes wrong during decoding of a barcode.
 * This includes, but is not limited to, failing checksums / error correction algorithms, being
 * unable to locate finder timing patterns, and so on.
 *
 * @author Sean Owen
 */
abstract class ReaderException extends \Exception
{
	// disable stack traces when not running inside test units
	//protected static  $isStackTrace = System.getProperty("surefire.test.class.path") != null;
	protected static bool $isStackTrace = false;

	public function ReaderException($cause = null): void
	{
		if ($cause) {
			parent::__construct($cause);
		}
	}


	// Prevent stack traces from being taken
	// srowen says: huh, my IDE is saying this is not an override. native methods can't be overridden?
	// This, at least, does not hurt. Because we use a singleton pattern here, it doesn't matter anyhow.

	final public function fillInStackTrace()
	{
		return null;
	}
}

Result.php
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing;

/**
 * <p>Encapsulates the result of decoding a barcode within an image.</p>
 *
 * @author Sean Owen
 */
final class Result
{
	/**
  * @var mixed[]|mixed
  */
	private $resultMetadata = null;
	private $timestamp;

	public function __construct(
		private $text,
		private $rawBytes,
		private $resultPoints,
		private $format,
		$timestamp = ''
	) {
		$this->timestamp = $timestamp ?: time();
	}

	/**
	 * @return string raw text encoded by the barcode
	 */
	public function getText()
	{
		return $this->text;
	}

	/**
	 * @return array|string raw bytes encoded by the barcode, if applicable, otherwise {@code null}
	 */
	public function getRawBytes()
	{
		return $this->rawBytes;
	}

	/**
	 * @return array points related to the barcode in the image. These are typically points
	 *         identifying finder patterns or the corners of the barcode. The exact meaning is
	 *         specific to the type of barcode that was decoded.
	 */
	public function getResultPoints()
	{
		return $this->resultPoints;
	}

	/**
	 * @return {@link BarcodeFormat} representing the format of the barcode that was decoded
	 */
	public function getBarcodeFormat()
	{
		return $this->format;
	}

	/**
	 * @return {@link Map} mapping {@link ResultMetadataType} keys to values. May be
	 *   {@code null}. This contains optional metadata about what was detected about the barcode,
	 *   like orientation.
	 */
	public function getResultMetadata()
	{
		return $this->resultMetadata;
	}

	public function putMetadata(string $type, $value): void
	{
		$resultMetadata = [];
		if ($this->resultMetadata === null) {
			$this->resultMetadata = [];
		}
		$resultMetadata[$type] = $value;
	}

	public function putAllMetadata($metadata): void
	{
		if ($metadata !== null) {
			if ($this->resultMetadata === null) {
				$this->resultMetadata = $metadata;
			} else {
				$this->resultMetadata = array_merge($this->resultMetadata, $metadata);
			}
		}
	}

	public function addResultPoints($newPoints): void
	{
		$oldPoints = $this->resultPoints;
		if ($oldPoints === null) {
			$this->resultPoints = $newPoints;
		} elseif ($newPoints !== null && (is_countable($newPoints) ? count($newPoints) : 0) > 0) {
			$allPoints = fill_array(0, (is_countable($oldPoints) ? count($oldPoints) : 0) + (is_countable($newPoints) ? count($newPoints) : 0), 0);
			$allPoints = arraycopy($oldPoints, 0, $allPoints, 0, is_countable($oldPoints) ? count($oldPoints) : 0);
			$allPoints = arraycopy($newPoints, 0, $allPoints, is_countable($oldPoints) ? count($oldPoints) : 0, is_countable($newPoints) ? count($newPoints) : 0);
			$this->resultPoints = $allPoints;
		}
	}

	public function getTimestamp()
	{
		return $this->timestamp;
	}

	public function toString()
	{
		return $this->text;
	}
}

ResultPoint.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing;

use Zxing\Common\Detector\MathUtils;

/**
 * <p>Encapsulates a point of interest in an image containing a barcode. Typically, this
 * would be the location of a finder pattern or the corner of the barcode, for example.</p>
 *
 * @author Sean Owen
 */
class ResultPoint
{
	private float $x;
	private float $y;

	public function __construct($x, $y)
	{
		$this->x = (float)($x);
		$this->y = (float)($y);
	}

	/**
	 * Orders an array of three ResultPoints in an order [A,B,C] such that AB is less than AC
	 * and BC is less than AC, and the angle between BC and BA is less than 180 degrees.
	 *
	 * @param array $patterns of three {@code ResultPoint} to order
	 */
	public static function orderBestPatterns(array $patterns): array
	{

// Find distances between pattern centers
		$zeroOneDistance = self::distance($patterns[0], $patterns[1]);
		$oneTwoDistance = self::distance($patterns[1], $patterns[2]);
		$zeroTwoDistance = self::distance($patterns[0], $patterns[2]);

		$pointA = '';
		$pointB = '';
		$pointC = '';
		// Assume one closest to other two is B; A and C will just be guesses at first
		if ($oneTwoDistance >= $zeroOneDistance && $oneTwoDistance >= $zeroTwoDistance) {
			$pointB = $patterns[0];
			$pointA = $patterns[1];
			$pointC = $patterns[2];
		} elseif ($zeroTwoDistance >= $oneTwoDistance && $zeroTwoDistance >= $zeroOneDistance) {
			$pointB = $patterns[1];
			$pointA = $patterns[0];
			$pointC = $patterns[2];
		} else {
			$pointB = $patterns[2];
			$pointA = $patterns[0];
			$pointC = $patterns[1];
		}

		// Use cross product to figure out whether A and C are correct or flipped.
		// This asks whether BC x BA has a positive z component, which is the arrangement
		// we want for A, B, C. If it's negative, then we've got it flipped around and
		// should swap A and C.
		if (self::crossProductZ($pointA, $pointB, $pointC) < 0.0) {
			$temp = $pointA;
			$pointA = $pointC;
			$pointC = $temp;
		}

		$patterns[0] = $pointA;
		$patterns[1] = $pointB;
		$patterns[2] = $pointC;

		return $patterns;
	}

	/**
	 * @param ResultPoint $pattern1 first pattern
	 * @param ResultPoint $pattern2 second pattern
	 *
	 * @return float distance between two points
	 */
	public static function distance($pattern1, $pattern2)
	{
		return MathUtils::distance($pattern1->x, $pattern1->y, $pattern2->x, $pattern2->y);
	}

	

	/**
	 * Returns the z component of the cross product between vectors BC and BA.
	 */
	private static function crossProductZ(
		$pointA,
		$pointB,
		$pointC
	) {
		$bX = $pointB->x;
		$bY = $pointB->y;

		return (($pointC->x - $bX) * ($pointA->y - $bY)) - (($pointC->y - $bY) * ($pointA->x - $bX));
	}

	

	final public function getX(): float
	{
		return (float)($this->x);
	}

	

	final public function getY(): float
	{
		return (float)($this->y);
	}

	final public function equals($other): bool
	{
		if ($other instanceof ResultPoint) {
			$otherPoint = $other;

			return $this->x == $otherPoint->x && $this->y == $otherPoint->y;
		}

		return false;
	}

	final public function hashCode()
	{
		return 31 * floatToIntBits($this->x) + floatToIntBits($this->y);
	}

	final public function toString(): string
	{
		$result = '';
		$result .= ('(');
		$result .= ($this->x);
		$result .= (',');
		$result .= ($this->y);
		$result .= (')');

		return $result;
	}
}

AbstractEnum.php
Script de practica.
Abrir
Ver codigo

<?php

namespace Zxing\Common;

use ReflectionClass;

/**
 * A general enum implementation until we got SplEnum.
 */
final class AbstractEnum implements \Stringable
{
	/**
  * Default value.
  * @var null
  */
	public const __default = null;
	/**
	 * Current value.
	 *
	 * @var mixed
	 */
	private $value;
	/**
  * Cache of constants.
  *
  * @var array<string, mixed>|null
  */
	private ?array $constants = null;

	/**
	 * Creates a new enum.
	 *
	 * @param mixed   $initialValue
	 * @param boolean $strict
	 */
	public function __construct($initialValue = null, private $strict = false)
	{
		$this->change($initialValue);
	}

	/**
	 * Changes the value of the enum.
	 *
	 * @param  mixed $value
	 *
	 * @return void
	 */
	public function change($value)
	{
		if (!in_array($value, $this->getConstList(), $this->strict)) {
			throw new \UnexpectedValueException('Value not a const in enum ' . $this::class);
		}
		$this->value = $value;
	}

	/**
  * Gets all constants (possible values) as an array.
  *
  *
  * @return array
  */
	public function getConstList(bool $includeDefault = true)
	{
		$constants = [];
		if ($this->constants === null) {
			$reflection = new ReflectionClass($this);
			$this->constants = $reflection->getConstants();
		}
		if ($includeDefault) {
			return $this->constants;
		}
		$constants = $this->constants;
		unset($constants['__default']);

		return $constants;
	}

	/**
	 * Gets current value.
	 *
	 * @return mixed
	 */
	public function get()
	{
		return $this->value;
	}

	/**
	 * Gets the name of the enum.
	 *
	 * @return string
	 */
	public function __toString(): string
	{
		return (string)array_search($this->value, $this->getConstList());
	}
}

BitArray.php
Script de practica.
Abrir
Ver codigo

<?php
/**
 * Created by PhpStorm.
 * User: Ashot
 * Date: 3/25/15
 * Time: 11:51
 */

/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Common;

/**
 * <p>A simple, fast array of bits, represented compactly by an array of ints internally.</p>
 *
 * @author Sean Owen
 */

final class BitArray
{
	/**
  * @var mixed[]|int[]|null
  */
	private $bits;
	/**
  * @var mixed|null
  */
	private $size;


	public function __construct($bits = [], $size = 0)
	{
		if (!$bits && !$size) {
			$this->$size = 0;
			$this->bits = [];
		} elseif ($bits && !$size) {
			$this->size = $bits;
			$this->bits = self::makeArray($bits);
		} else {
			$this->bits = $bits;
			$this->size = $size;
		}
	}

	/**
	 * @psalm-return array<empty, empty>
	 */
	private static function makeArray($size): array
	{
		return [];
	}

	public function getSize()
	{
		return $this->size;
	}

	public function getSizeInBytes()
	{
		return ($this->size + 7) / 8;
	}

	/**
	 * Sets bit i.
	 *
	 * @param int $i bit to set
	 */
	public function set($i): void
	{
		$this->bits[(int)($i / 32)] |= 1 << ($i & 0x1F);
		$this->bits[(int)($i / 32)] = ($this->bits[(int)($i / 32)]);
	}

	/**
	 * Flips bit i.
	 *
	 * @param int $i bit to set
	 */
	public function flip($i): void
	{
		$this->bits[(int)($i / 32)] ^= 1 << ($i & 0x1F);
		$this->bits[(int)($i / 32)] = ($this->bits[(int)($i / 32)]);
	}

	/**
	 * @param int $from first bit to check
	 *
	 * @return int index of first bit that is set, starting from the given index, or size if none are set
	 *  at or beyond this given index
	 * @see #getNextUnset(int)
	 */
	public function getNextSet($from)
	{
		if ($from >= $this->size) {
			return $this->size;
		}
		$bitsOffset = (int)($from / 32);
		$currentBits = (int)$this->bits[$bitsOffset];
		// mask off lesser bits first
		$currentBits &= ~((1 << ($from & 0x1F)) - 1);
		while ($currentBits == 0) {
			if (++$bitsOffset == (is_countable($this->bits) ? count($this->bits) : 0)) {
				return $this->size;
			}
			$currentBits = $this->bits[$bitsOffset];
		}
		$result = ($bitsOffset * 32) + numberOfTrailingZeros($currentBits); //numberOfTrailingZeros

		return $result > $this->size ? $this->size : $result;
	}

	/**
	 * @param int $from index to start looking for unset bit
	 *
	 * @return int index of next unset bit, or {@code size} if none are unset until the end
	 * @see #getNextSet(int)
	 */
	public function getNextUnset($from)
	{
		if ($from >= $this->size) {
			return $this->size;
		}
		$bitsOffset = (int)($from / 32);
		$currentBits = ~$this->bits[$bitsOffset];
		// mask off lesser bits first
		$currentBits &= ~((1 << ($from & 0x1F)) - 1);
		while ($currentBits == 0) {
			if (++$bitsOffset == (is_countable($this->bits) ? count($this->bits) : 0)) {
				return $this->size;
			}
			$currentBits = (~$this->bits[$bitsOffset]);
		}
		$result = ($bitsOffset * 32) + numberOfTrailingZeros($currentBits);

		return $result > $this->size ? $this->size : $result;
	}

	/**
	 * Sets a block of 32 bits, starting at bit i.
	 *
	 * @param int $i first  bit to set
	 * @param int $newBits the new value of the next 32 bits. Note again that the least-significant bit
	 *                corresponds to bit i, the next-least-significant to i+1, and so on.
	 */
	public function setBulk($i, $newBits): void
	{
		$this->bits[(int)($i / 32)] = $newBits;
	}

	/**
	 * Sets a range of bits.
	 *
	 * @param int $start start of range, inclusive.
	 * @param int $end end   of range, exclusive
	 *
	 * @return void
	 */
	public function setRange($start, $end)
	{
		if ($end < $start) {
			throw new \InvalidArgumentException();
		}
		if ($end == $start) {
			return;
		}
		$end--; // will be easier to treat this as the last actually set bit -- inclusive
		$firstInt = (int)($start / 32);
		$lastInt = (int)($end / 32);
		for ($i = $firstInt; $i <= $lastInt; $i++) {
			$firstBit = $i > $firstInt ? 0 : $start & 0x1F;
			$lastBit = $i < $lastInt ? 31 : $end & 0x1F;
			$mask = 0;
			if ($firstBit == 0 && $lastBit == 31) {
				$mask = -1;
			} else {
				$mask = 0;
				for ($j = $firstBit; $j <= $lastBit; $j++) {
					$mask |= 1 << $j;
				}
			}
			$this->bits[$i] = ($this->bits[$i] | $mask);
		}
	}

	/**
	 * Clears all bits (sets to false).
	 */
	public function clear(): void
	{
		$max = is_countable($this->bits) ? count($this->bits) : 0;
		for ($i = 0; $i < $max; $i++) {
			$this->bits[$i] = 0;
		}
	}

	/**
	 * Efficient method to check if a range of bits is set, or not set.
	 *
	 * @param int $start start of range, inclusive.
	 * @param int $end end   of range, exclusive
	 * @param bool $value if true, checks that bits in range are set, otherwise checks that they are not set
	 *
	 * @return bool iff all bits are set or not set in range, according to value argument
	 *
	 * @throws \InvalidArgumentException if end is less than or equal to start
	 */
	public function isRange($start, $end, $value): bool
	{
		if ($end < $start) {
			throw new \InvalidArgumentException();
		}
		if ($end == $start) {
			return true; // empty range matches
		}
		$end--; // will be easier to treat this as the last actually set bit -- inclusive
		$firstInt = (int)($start / 32);
		$lastInt = (int)($end / 32);
		for ($i = $firstInt; $i <= $lastInt; $i++) {
			$firstBit = $i > $firstInt ? 0 : $start & 0x1F;
			$lastBit = $i < $lastInt ? 31 : $end & 0x1F;
			$mask = 0;
			if ($firstBit == 0 && $lastBit == 31) {
				$mask = -1;
			} else {
				$mask = 0;
				for ($j = $firstBit; $j <= $lastBit; $j++) {
					$mask = ($mask | (1 << $j));
				}
			}

			// Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is,
			// equals the mask, or we're looking for 0s and the masked portion is not all 0s
			if (($this->bits[$i] & $mask) != ($value ? $mask : 0)) {
				return false;
			}
		}

		return true;
	}

	/**
	 * Appends the least-significant bits, from value, in order from most-significant to
	 * least-significant. For example, appending 6 bits from 0x000001E will append the bits
	 * 0, 1, 1, 1, 1, 0 in that order.
	 *
	 * @param int $value   {@code int} containing bits to append
	 * @param int $numBits bits from value to append
	 */
	public function appendBits($value, $numBits): void
	{
		if ($numBits < 0 || $numBits > 32) {
			throw new \InvalidArgumentException("Num bits must be between 0 and 32");
		}
		$this->ensureCapacity($this->size + $numBits);
		for ($numBitsLeft = $numBits; $numBitsLeft > 0; $numBitsLeft--) {
			$this->appendBit((($value >> ($numBitsLeft - 1)) & 0x01) == 1);
		}
	}

	private function ensureCapacity($size): void
	{
		if ($size > (is_countable($this->bits) ? count($this->bits) : 0) * 32) {
			$newBits = self::makeArray($size);
			$newBits = arraycopy($this->bits, 0, $newBits, 0, is_countable($this->bits) ? count($this->bits) : 0);
			$this->bits = $newBits;
		}
	}

	public function appendBit(bool $bit): void
	{
		$this->ensureCapacity($this->size + 1);
		if ($bit) {
			$this->bits[(int)($this->size / 32)] |= 1 << ($this->size & 0x1F);
		}
		$this->size++;
	}

	public function appendBitArray($other): void
	{
		$otherSize = $other->size;
		$this->ensureCapacity($this->size + $otherSize);
		for ($i = 0; $i < $otherSize; $i++) {
			$this->appendBit($other->get($i));
		}
	}

	public function _xor($other): void
	{
		if ((is_countable($this->bits) ? count($this->bits) : 0) !== (is_countable($other->bits) ? count($other->bits) : 0)) {
			throw new \InvalidArgumentException("Sizes don't match");
		}
		$count = is_countable($this->bits) ? count($this->bits) : 0;
		for ($i = 0; $i < $count; $i++) {
			// The last byte could be incomplete (i.e. not have 8 bits in
			// it) but there is no problem since 0 XOR 0 == 0.
			$this->bits[$i] ^= $other->bits[$i];
		}
	}

	/**
	 *
	 * @param int $bitOffset first bit to start writing
	 * @param array     $array to write into. Bytes are written most-significant byte first. This is the opposite
	 *                  of the internal representation, which is exposed by {@link #getBitArray()}
	 * @param int $offset position    in array to start writing
	 * @param int $numBytes how  many bytes to write
	 */
	public function toBytes($bitOffset, array &$array, $offset, $numBytes): void
	{
		for ($i = 0; $i < $numBytes; $i++) {
			$theByte = 0;
			for ($j = 0; $j < 8; $j++) {
				if ($this->get($bitOffset)) {
					$theByte |= 1 << (7 - $j);
				}
				$bitOffset++;
			}
			$array[(int)($offset + $i)] = $theByte;
		}
	}

	/**
	 * @param $i ; bit to get
	 * @param float|int first $i
	 *
	 * @return bool iff bit i is set
	 */
	public function get(int|float $i): bool
	{
		$key = (int)($i / 32);

		return ($this->bits[$key] & (1 << ($i & 0x1F))) != 0;
	}

	/**
	 * @return (int|mixed)[]|null underlying array of ints. The first element holds the first 32 bits, and the least significant bit is bit 0.
	 *
	 * @psalm-return array<int|mixed>|null
	 */
	public function getBitArray(): array|null
	{
		return $this->bits;
	}

	/**
	 * Reverses all bits in the array.
	 */
	public function reverse(): void
	{
		$newBits = [];
		// reverse all int's first
		$len = (($this->size - 1) / 32);
		$oldBitsLen = $len + 1;
		for ($i = 0; $i < $oldBitsLen; $i++) {
			$x = $this->bits[$i];/*
			 $x = (($x >>  1) & 0x55555555L) | (($x & 0x55555555L) <<  1);
				  $x = (($x >>  2) & 0x33333333L) | (($x & 0x33333333L) <<  2);
				  $x = (($x >>  4) & 0x0f0f0f0fL) | (($x & 0x0f0f0f0fL) <<  4);
				  $x = (($x >>  8) & 0x00ff00ffL) | (($x & 0x00ff00ffL) <<  8);
				  $x = (($x >> 16) & 0x0000ffffL) | (($x & 0x0000ffffL) << 16);*/
			$x = (($x >> 1) & 0x55555555) | (($x & 0x55555555) << 1);
			$x = (($x >> 2) & 0x33333333) | (($x & 0x33333333) << 2);
			$x = (($x >> 4) & 0x0f0f0f0f) | (($x & 0x0f0f0f0f) << 4);
			$x = (($x >> 8) & 0x00ff00ff) | (($x & 0x00ff00ff) << 8);
			$x = (($x >> 16) & 0x0000ffff) | (($x & 0x0000ffff) << 16);
			$newBits[(int)$len - $i] = (int)$x;
		}
		// now correct the int's if the bit size isn't a multiple of 32
		if ($this->size != $oldBitsLen * 32) {
			$leftOffset = $oldBitsLen * 32 - $this->size;
			$mask = 1;
			for ($i = 0; $i < 31 - $leftOffset; $i++) {
				$mask = ($mask << 1) | 1;
			}
			$currentInt = ($newBits[0] >> $leftOffset) & $mask;
			for ($i = 1; $i < $oldBitsLen; $i++) {
				$nextInt = $newBits[$i];
				$currentInt |= $nextInt << (32 - $leftOffset);
				$newBits[(int)($i) - 1] = $currentInt;
				$currentInt = ($nextInt >> $leftOffset) & $mask;
			}
			$newBits[(int)($oldBitsLen) - 1] = $currentInt;
		}
		//        $bits = $newBits;
	}

	public function equals($o): bool
	{
		if (!($o instanceof BitArray)) {
			return false;
		}
		$other = $o;

		return $this->size == $other->size && $this->bits === $other->bits;
	}

	public function hashCode()
	{
		return 31 * $this->size + hashCode($this->bits);
	}

	public function toString(): string
	{
		$result = '';
		for ($i = 0; $i < $this->size; $i++) {
			if (($i & 0x07) == 0) {
				$result .= ' ';
			}
			$result .= ($this->get($i) ? 'X' : '.');
		}

		return (string)$result;
	}

	public function _clone(): \Zxing\Common\BitArray
	{
		return new BitArray($this->bits, $this->size);
	}
}

BitMatrix.php
Script de practica.
Abrir
Ver codigo

<?php

namespace Zxing\Common;

final class BitMatrix
{
	private $width;
	private $height;
	private $rowSize;
	/**
  * @var mixed|int[]
  */
	private $bits;

	public function __construct($width, $height = false, $rowSize = false, $bits = false)
	{
		if (!$height) {
			$height = $width;
		}
		if (!$rowSize) {
			$rowSize = (int)(($width + 31) / 32);
		}
		if (!$bits) {
			$bits = fill_array(0, $rowSize * $height, 0);
			//            [];//new int[rowSize * height];
		}
		$this->width = $width;
		$this->height = $height;
		$this->rowSize = $rowSize;
		$this->bits = $bits;
	}

	public static function parse($stringRepresentation, $setString, $unsetString): self
	{
		if (!$stringRepresentation) {
			throw new \InvalidArgumentException();
		}
		$bits = [];
		$bitsPos = 0;
		$rowStartPos = 0;
		$rowLength = -1;
		$nRows = 0;
		$pos = 0;
		while ($pos < strlen((string) $stringRepresentation)) {
			if ($stringRepresentation[$pos] == '\n' ||
				$stringRepresentation->{$pos} == '\r') {
				if ($bitsPos > $rowStartPos) {
					if ($rowLength == -1) {
						$rowLength = $bitsPos - $rowStartPos;
					} elseif ($bitsPos - $rowStartPos != $rowLength) {
						throw new \InvalidArgumentException("row lengths do not match");
					}
					$rowStartPos = $bitsPos;
					$nRows++;
				}
				$pos++;
			} elseif (substr((string) $stringRepresentation, $pos, strlen((string) $setString)) == $setString) {
				$pos += strlen((string) $setString);
				$bits[$bitsPos] = true;
				$bitsPos++;
			} elseif (substr((string) $stringRepresentation, $pos + strlen((string) $unsetString)) == $unsetString) {
				$pos += strlen((string) $unsetString);
				$bits[$bitsPos] = false;
				$bitsPos++;
			} else {
				throw new \InvalidArgumentException(
					"illegal character encountered: " . substr((string) $stringRepresentation, $pos)
				);
			}
		}

		// no EOL at end?
		if ($bitsPos > $rowStartPos) {
			if ($rowLength == -1) {
				$rowLength = $bitsPos - $rowStartPos;
			} elseif ($bitsPos - $rowStartPos != $rowLength) {
				throw new \InvalidArgumentException("row lengths do not match");
			}
			$nRows++;
		}

		$matrix = new BitMatrix($rowLength, $nRows);
		for ($i = 0; $i < $bitsPos; $i++) {
			if ($bits[$i]) {
				$matrix->set($i % $rowLength, $i / $rowLength);
			}
		}

		return $matrix;
	}

	/**
	 * <p>Sets the given bit to true.</p>
	 *
	 * @param $x ;  The horizontal component (i.e. which column)
	 * @param $y ;   The vertical component (i.e. which row)
	 * @param float|int $x
	 * @param float|int $y
	 */
	public function set(int|float $x, int|float $y): void
	{
		$offset = (int)($y * $this->rowSize + ($x / 32));
		if (!isset($this->bits[$offset])) {
			$this->bits[$offset] = 0;
		}
		//$this->bits[$offset] = $this->bits[$offset];

		//  if($this->bits[$offset]>200748364){
		//$this->bits= array(0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-16777216,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-1090519040,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,1056964608,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,-1358954496,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,117440512,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,50331648,-1,-1,-1,-1,65535,0,0,0,0,0,0,0,33554432,-1,-1,536870911,-4096,65279,0,0,0,0,0,0,0,0,-1,-1,65535,-4096,65535,0,0,0,0,0,0,0,0,-193,536870911,0,-4096,65279,0,0,0,0,0,0,0,0,-254,32767,0,-4096,61951,0,0,0,0,0,0,0,0,20913920,0,0,-4096,50175,0,0,0,0,0,0,0,0,0,0,0,-4096,60159,0,0,0,0,0,0,0,0,0,0,0,-4096,64255,0,0,0,0,0,0,0,0,0,0,0,-8192,56319,0,0,0,0,0,0,0,0,0,0,0,-4096,16777215,0,0,0,0,0,0,0,0,0,0,0,-4096,16777215,0,0,0,0,0,0,0,0,0,0,0,-4096,16777215,0,0,0,0,0,0,0,0,0,0,0,-4096,16777215,0,0,0,0,0,0,0,0,0,0,0,-4096,16777215,0,0,0,0,0,0,0,0,0,0,0,-4096,16777215,0,0,0,0,0,0,0,0,0,0,0,-4096,16777215,0,0,0,0,0,0,0,0,0,0,0,-4096,16777215,0,0,0,0,0,0,0,251658240,0,0,0,-4096,-1,255,0,256,0,0,0,0,117440512,0,0,0,-4096,-1,255,0,512,0,0,0,0,117440512,0,0,0,-4096,-1,255,0,1024,0,0,0,0,117440512,0,0,0,-4096,-1,223,0,256,0,0,0,0,117440512,0,0,33030144,-4096,-1,191,0,256,0,0,0,0,117440512,0,0,33554428,-4096,-1,255,0,768,0,0,0,0,117440512,0,402849792,67108862,-8192,-1,255,0,768,0,0,0,0,117440512,0,470278396,63045630,-8192,-1,255,0,256,0,0,0,0,251658240,-8388608,470278399,58720286,-8192,-1,2686975,0,3842,0,0,0,0,251658240,-131072,1007149567,58720286,-8192,-1,2031615,0,3879,0,0,0,0,251658240,536739840,1007092192,58720286,-8192,-1,851967,0,3840,0,0,0,0,251658240,917504,1007092192,58720284,-8192,-1,2031615,0,3968,0,0,0,0,251658240,917504,1007092160,59244060,-8192,-1,65535,0,7936,0,0,0,0,251658240,917504,1009779136,59244060,-8192,-1,9371647,0,1792,0,0,0,0,251658240,917504,946921920,59244060,-8192,-1,8585215,0,1792,0,0,0,0,117440512,-15859712,477159875,59244060,-8192,-1,65535,0,12032,0,0,0,0,251658240,-15859712,52490691,59244060,-8192,-1,-1,0,65408,0,0,0,0,251658240,-15859712,58778051,59244060,-8192,-1,-1,0,65473,0,0,0,0,251658240,-15859712,125886915,59244060,-8192,-1,-1,0,65472,0,0,0,0,251658240,-15859712,58778051,59244060,-8192,-1,-1,0,65408,0,0,0,0,251658240,-15859712,8380867,59244060,-8192,-1,-1,0,65473,0,0,0,0,251658240,-15859712,8380867,59244060,-8192,-1,-1,0,131011,0,0,0,0,251658240,-15859712,8380867,58720284,-8192,-1,-1,0,130947,0,0,0,0,251658240,-15859712,2089411,58720284,-8192,-1,-1,0,130947,0,0,0,0,251658240,-32636928,449,58720284,-8192,-1,-1,33554431,131015,0,0,0,0,251658240,786432,448,62914588,-8192,-1,-1,16777215,131015,0,0,0,0,251658240,786432,448,67108860,-8192,-1,-1,553648127,131015,0,0,0,0,251658240,786432,946864576,67108860,-8192,-1,-1,32505855,131015,0,0,0,0,251658240,786432,946921976,8388604,-8192,-1,-1,8191999,131015,0,0,0,0,251658240,-262144,946921983,248,-8192,-1,-1,8126463,196551,0,0,0,0,251658240,-262144,7397887,0,-8192,-1,-1,16777215,262087,0,0,0,0,251658240,-262144,8257543,0,-8192,-1,-1,-2121269249,262095,0,0,0,0,520093696,0,8257536,0,-8192,-1,-1,-201326593,262095,0,0,0,0,520290304,0,8257536,117963776,-8192,-1,-1,-201326593,262095,0,0,0,0,520093696,0,-2140143616,118488579,-8192,-1,-1,-201326593,131023,0,0,0,0,520093696,0,-2131697280,118488579,-8192,-1,-1,-503316481,131023,0,0,0,0,520093696,2145386496,-2131631232,118484995,-16384,-1,-1,-469762049,262095,0,0,0,0,520093696,2147221504,552649600,118481344,-16384,-1,-1,-469762049,131023,0,0,0,0,520290304,2147221504,2029002240,118481344,-16384,-1,-1,-469762049,262031,0,0,0,0,520290304,-266600448,2029001791,125952960,-16384,-1,-1,-469762049,262031,0,0,0,0,1057423360,-266600448,2027953215,133177312,-16384,-1,-1,-134217729,262111,0,0,0,0,1058471936,-266600448,-119531393,133177343,-16384,-1,-1,-134217729,262111,0,0,0,0,1058471936,-2145648640,-253754369,66068479,-16384,-1,-1,-134217729,262111,0,0,0,0,1058471936,236716032,-253754369,15729663,-16384,-1,-1,-134217729,262095,0,0,0,0,1057947648,236716032,-253754369,6348807,-16384,-1,-1,-134217729,262095,0,0,0,0,524222464,236716032,-253690305,6348803,-16384,-1,-1,-134217729,262111,0,0,0,0,521076736,2115764224,-253625344,14737411,-16384,-1,-1,-134217729,262095,0,0,0,0,522125312,2115764224,-253625344,14743555,-16384,-1,-1,-134217729,262111,0,0,16772608,0,1073676288,-31719424,-2014283776,14810115,-16384,-1,-1,-1,262143,0,0,16776704,0,1065287680,-1642594304,-1879178880,14810115,-16384,-1,-1,-1,524287,0,0,16776192,0,2139029504,264241152,-2013396089,14809091,-16384,-1,-1,-1,262095,0,0,16776192,0,2139029504,264241152,-2080636025,14803335,-16384,-1,-1,-1,262087,0,0,16776192,0,2147418112,264241152,-2132803581,14803847,-16384,-1,-1,-402653185,524259,0,0,8386048,0,2147418112,0,-2132688896,123783,-16384,-1,-1,1207959551,262112,0,0,16775168,0,2147418112,0,14794752,1046535,-16384,-1,-1,268435455,262128,0,0,16775168,0,2147418112,0,14712832,1047615,-16384,-1,-1,536870911,524284,0,0,16776705,0,2147418112,0,14680832,1047615,-16384,-1,-1,-1,524287,0,0,16776704,0,2147418112,-1048576,14681087,1046591,-32768,-1,-1,-1,524287,0,0,16776704,0,2147418112,-524288,-2132802561,2080831,-32768,-1,-1,-1,524287,0,0,16776705,0,2147418112,-524288,-31718401,2080831,-32768,-1,-1,-1,1048575,0,0,16776193,0,2147418112,3670016,-31718528,2080831,-32768,-1,-1,-1,524287,0,0,16776195,0,2147418112,3670016,-31718528,134086719,-32768,-1,-1,-1,524287,0,0,16776195,0,2147418112,3670016,253494144,268173368,-32768,-1,-1,-1,524287,0,0,16775171,0,2147418112,3670016,268174208,268173368,-32768,-1,-1,-1,1048575,0,0,16771072,0,2147418112,-63438848,268174223,31457328,-32768,-1,-1,-1,1048575,0,0,10418176,0,-65536,-63438848,133957519,14807040,-32768,-1,-1,-1,2097151,0,0,15923200,0,2147418112,-63438848,1968015,14809095,-32768,-1,-1,-1,1048575,0,0,12808192,0,2147418112,-63438848,2082703,12711943,-32768,-1,-1,-1,2097151,0,0,6420480,0,2147418112,-63438848,2082703,14343,-32768,-1,-1,-1,2097151,0,0,15202304,0,-65536,-63438848,2082703,1849351,-32768,-1,-1,-1,2097151,0,0,15464448,0,-65536,-63438848,264472335,1849351,-32768,-1,-1,-1,4194303,0,0,16371712,0,-65536,-63438848,264472335,14343,-32768,-1,-1,-1,8388607,0,0,0,0,-65536,-63438848,532907791,235010048,-32768,-1,-1,-1,16777215,0,0,0,0,-65536,-63438848,-1603833,235010160,-32768,-1,-1,-1,16777215,0,0,0,0,-65536,3670016,-30976,67238000,-32768,-1,-1,-1,16777215,0,0,0,0,-65536,3670016,-30976,48,-32768,-1,-1,-1,16777215,0,0,0,0,-65536,3670016,-29391104,768,-32768,-1,-1,-1,16777215,0,0,0,0,-65536,3670016,-29391104,768,-32768,-1,-1,-1,16777215,0,0,0,0,-65536,-524287,-65042433,768,-32768,-1,-1,-1,16777215,0,0,0,0,-65536,-524287,2082441215,0,-65536,-1,-1,-1,16777215,0,0,0,0,-13697024,-524287,511,0,-65536,-1,-1,-1,16777215,0,0,0,0,-12648448,1,0,0,-65536,-1,-1,-1,14680063,0,0,0,0,-12648448,1,0,0,-65536,-1,-1,-1,16777215,0,0,0,0,-65536,1,0,0,-65536,-1,-1,-1,14680063,0,0,0,0,-8454144,1,0,0,-65536,-1,-1,-1,12582911,0,0,0,0,-12648448,1,0,0,-65536,-1,-1,-1,2097151,0,0,0,0,-12648448,1,0,0,-65536,-1,-1,-1,1048575,0,0,0,0,-14745600,1,0,0,-65536,-1,-1,-1,3145727,0,0,0,0,1056964608,1,0,0,-65536,-1,-1,-1,1048575,0,0,0,0,1056964608,1,0,0,-65536,-1,-1,-1,1048575,0,0,0,0,1056964608,1,0,0,-65536,-1,-1,-1,524287,0,0,0,0,2130706432,1,0,0,-65536,-1,-1,-1,1048575,0,0,0,0,1056964608,1,0,0,-65536,-1,-1,-1,524287,0,0,0,0,2130706432,1,0,0,-65536,-1,-1,-1,524287,0,0,0,0,2130706432,1,0,0,-65536,-1,-1,-1,1048575,0,0,0,0,2130706432,1,0,0,-65536,-1,-1,-1,1048575,0,0,0,0,50331648,1,0,0,-65536,-1,-1,-1,1048575,0,0,0,0,117440512,1,0,-268435456,-1,-1,-1,-1,524287,0,0,0,0,251658240,1,0,-320,-1,-1,-1,-1,262143,0,0,0,0,520093696,1,-2048,-1,-1,-1,-1,-1,262143,0,0,0,0,1056964608,-16777213,-1,-1,-1,-1,-1,-1,131071,0,0,0,0,-16777216,-121,-1,-1,-1,-1,-1,-1,131071,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,131071,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,131071,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,131071,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,65535,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,65535,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,131071,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,262143,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,524287,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,524287,0,0,0,0,-16777216,-1,-1,-1,-1,-1,-1,-1,589823,0,0,0,0,0,-1,-1,-1,-1,-1,-1,-1,8179,0,0,0,0,50331648,-1,-1,-1,-1,-1,-1,-1,4080,0,0,0,0,117440512,-1,-1,-1,-1,-1,-1,-1,1016,0,0,0,0,251658240,-1,-1,-1,-1,-1,-1,1073741823,1020,0,0,0,0,50331648,-1,-1,-1,-1,-1,-1,536870911,254,0,0,0,0,50331648,-1,-1,-1,-1,-1,-1,536870911,255,0,0,0,0,50331648,-1,-1,-1,-1,-1,-1,-1879048193,127,0,0,0,0,50331648,-1,-1,-1,-1,-1,-1,-469762049,63,0,0,0,0,1191182336,-1,-1,-1,-1,1023999,0,-520093712,15,0,0,0,0,-218103808,-1,-1,-1,-1,0,-8454144,-260046849,7,0,0,0,0,0,-193,-1,-1,-1057947649,-2147483648,-1,-58720257,1,0,0,0,0,0,-251,-1,-1,-1057423361,-2074,-1,-1,0,0,0,0,0,0,-59648,-1,-1,-1,-1,-1,1073741823,0,0,0,0,0,0,-65536,-1,-1,-1,-1,-1,268435455,0,0,0,0,0,0,-65536,-1,-1,-1,-1,-1,67108863,0,0,0,0,0,0,-65536,-1,-1,-1,-1,-1,8388607,0,0,0,0,0,0,0,-403603456,-1,-1,-1,-1,262143,0,0,0,8388656,0,0,0,-1891434496,-1,-1,-1,-1,16383,0,0,0,8388608,0,0,0,-1612513280,-1,-1,-1,-1,63,0,0,0,0,0,0,0,-24320,-1,-1,-1,8388607,0,0,0,0,0,0,0,0,-256,-1,-1,1073741823,1,0,0,0,0,0,0,0,1610612736,-15,-1,-1,16383,0,0,0,0,0,0,0,0,-16646144,-1,-1,251658239,0,0,0,0,0,0,0,0,0,-51200,-1,-1,40959,0,0,0,0,0,0,268419584,103809024,-12713984,-1,-2147483137,4194303,0,0,0,0,0,0,0,402620416,-2144010240,-13631487,-32513,3,20480,0,0,0,0,0,0,0,419299328,0,-262144,-1,0,0,0,0,0,0,0,0,0,0,0,-5832704,268049407,0,0,0,0,0,0,0,0,0,0,0,0,33030144,0,0,0,0,0,0,0,0,0,0,0,0,3670016,0,0,0,0,0,0,0,0,0,0,0,0,1572864,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,458752,0,0,0,0,0,0,0,0,0,0,0,0,229376,0,0,0,0,0,0,0,0,0,0,0,0,32768,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8192,0,0,0,0,0,0,0,0,0,0,0,0,8192,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,31744,0,0,0,0,0,0,0,0,0,0,0,0,31744,0,0,0,0,0,0,0,0,0,0,0,0,64512,0,0,0,0,0,0,0,0,0,0,0,0,15872,0,0,0,0,0,0,0,0,0,0,0,0,3584,0,0,0,0,0,0,0,0,0,0,0,0,7680,0,0,0,0,0,0,0,0,0,0,0,0,512,0,0,0,0,0,0,0,0,0,0,0,0,3968,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3840,0,0,0,0,0,0,0,0,0,0,0,0,1855,0,0,0,0,0,0,0,0,0,0,0,0,63,0,0,0,0,0,0,0,0,0,0,0,0,15,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,134217728,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,124,0,0,0,0,0,0,0,0,0,0,0,-260046848,63,0,0,0,0,0,0,0,0,0,0,0,-17301504,127,0,0,0,0,0,0,0,0,0,0,0,-524288,127,0,0,0,0,0,0,0,0,0,0,0,-262144,127,0,0,0,0,0,0,0,0,0,0,0,-262144,63,0,0,0,0,0,0,0,0,0,0,0,-262144,63,0,0,0,0,0,0,0,0,0,0,0,-262144,63,0,0,0,0,0,0,0,0,0,0,0,-262144,31,0,0,0,0,0,0,0,0,0,0,0,-262144,63,0,0,0,0,3,0,0,0,0,0,0,-262144,63,0,0,0,0,7,0,0,0,0,0,0,-262144,63,0,0,0,0,63,0,0,0,0,0,0,-262144,63,0,0,0,0,511,0,0,0,0,0,0,-524288,31,0,0,0,0,8191,0,0,0,0,0,0,-1048576,63,0,0,0,0,131071,0,0,0,0,0,0,-524288,63,0,0,0,0,262143,0,0,0,0,0,0,-524288,63,0,0,0,0,131071,0,0,0,0,0,0,-1048576,63,0,0,0,0,262143,0,0,0,0,0,0,-1048576,63,0,0,0,0,262143,0,0,0,0,0,0,-1048576,63,0,0,0,0,262143,0,0,0,0,0,0,-1048576,63,0,0,0,0,262143,0,0,0,0,0,0,-2097152,127,0,0,0,0,262143,0,0,0,0,0,0,-2097152,127,0,0,0,0,262143,0,0,0,0,0,0,-1048576,127,0,0,0,0,262143,0,0,0,0,0,0,-1048576,127,0,0,0,0,262143,0,0,0,0,0,0,-2097152,255,0,0,0,0,262143,0,0,0,0,0,0,-2097152,255,0,0,0,0,262142,0,0,0,0,0,0,-2097152,255,0,0,0,0,262142,0,0,0,0,0,0,-2097152,255,0,0,0,0,262142,0,0,0,0,0,0,-2097152,255,0,0,0,0,262140,0,0,0,0,0,0,-2097152,255,0,0,0,0,131068,0,0,0,0,0,0,-4194304,255,0,0,0,0,131068,0,0,0,0,0,0,-4194304,255,0,0,0,0,65528,0,0,0,0,0,0,-8388608,255,0,0,0,0,65528,0,0,0,0,0,0,-8388608,255,0,0,0,0,65528,0,0,0,0,0,0,-8388608,255,0,0,0,0,32760,0,0,0,0,0,0,-8388608,255,0,0,0,0,32760,0,0,0,0,0,0,-16777216,255,0,0,-2147483648,255,16368,0,0,0,0,0,0,-16777216,255,0,0,-536870912,1023,16368,0,0,0,0,0,0,-33554432,255,0,0,-16777216,4095,16352,0,0,0,0,0,0,-33554432,255,0,0,-8388608,262143,16352,0,0,0,0,0,0,-33554432,255,0,0,-1048576,2097151,16352,0,0,0,0,0,0,-67108864,255,0,0,-524288,8388607,16352,0,0,0,0,0,0,-67108864,255,0,0,-262144,16777215,16320,0,0,0,0,0,0,-67108864,255,0,0,-131072,16777215,100679648,0,0,0,0,0,0,-67108864,255,0,0,-16384,16776959,125861824,0,0,0,0,0,0,-134217728,255,0,0,-4096,16773121,62930880,0,0,0,0,0,0,-134217728,127,0,0,2147482624,16252928,32704,0,0,0,0,0,0,-134217728,127,0,0,268435200,14680064,16320,0,0,0,0,0,0,-134217728,127,0,0,134217600,0,32704,0,0,0,0,0,0,-33554432,127,0,1056964608,67108736,0,32704,0,0,0,0,0,0,-33554432,127,0,2130706432,33554368,0,65408,0,0,0,0,0,0,-33554432,127,0,-16777216,8388576,0,32640,0,0,0,0,0,0,-134217728,127,0,-16777216,2097136,0,32640,0,0,0,0,0,0,-134217728,63,0,-16776960,1048573,0,32640,0,0,0,0,0,0,-536870912,63,0,-16776448,1048575,0,32640,0,0,0,0,0,0,-536870912,63,0,-33553664,6291455,66752,32640,0,0,0,0,0,0,-536870912,63,0,2013266688,2097148,229376,32640,0,0,0,0,0,0,-536870912,63,0,256,4194300,229376,32640,0,0,0,0,0,0,-536870912,63,0,0,524280,196608,32512,0,0,8,0,0,0,-1073741824,63,0,0,-200,15,65280,0,0,24,0,0,0,-1073741824,63,0,0,-1867768,127,32512,0,0,56,0,0,0,-1073741824,63,0,0,-1056768,4095,32512,0,0,124,0,0,0,-1073741824,63,0,0,-1050624,8191,32512,0,0,508,0,0,0,-2147483648,31,0,0,-7866368,8191,32512,0,0,1020,0,0,0,-2147483648,31,0,0,-33030656,8095,32512,0,0,2046,0,0,0,-2147483648,63,0,0,-66586624,771,32512,0,0,4094,0,0,0,0,63,0,0,-134184960,1,32256,0,0,8190,0,0,0,0,63,0,0,1610612736,0,32256,0,0,16382,0,0,0,-2147483648,63,0,0,0,0,15872,0,0,32767,0,0,0,-2147483648,31,0,0,0,0,15872,0,-2147483648,65535,0,0,0,-2147483648,31,0,0,0,0,7680,0,0,65535,0,0,0,-2147483648,31,0,0,134217728,0,7680,0,-2147483648,65535,0,0,0,-2147483648,31,0,0,0,0,7680,0,-2147483648,65535,0,0,0,-2147483648,31,0,0,0,0,7680,0,-1073741824,65535,0,0,0,-2147483648,31,0,0,0,0,3072,0,-1073741824,65535,0,0,0,-2147483648,31,0,0,0,0,3072,0,-1073741824,65535,0,0,0,-2147483648,31,0,0,0,0,0,0,-2147483648,65535,0,0,0,-2147483648,31,0,0,0,0,0,0,-1073741824,65535,0,0,0,0,31,0,0,0,0,0,0,-1073741824,65535,0,0,0,0,31,0,0,0,0,0,0,-2147483648,65535,0,0,0,0,30,0,0,0,0,0,0,-1073741824,65535,0,0,0,0,30,0,0,0,0,0,0,-2147483648,65535,0,0,0,0,30,0,0,0,0,0,0,0,65535,0,0,0,0,28,0,0,0,0,0,0,0,65535,0,0,0,0,28,0,0,0,0,0,0,0,65535,0,0,0,0,28,0,0,0,0,0,0,0,65535,0,0,0,0,24,0,0,0,0,0,0,-2147483648,65535,0,0,0,0,0,0,0,0,0,0,0,-536870912,65535);//[$offset] |= intval32bits(1 << ($x & 0x1f));
		$bob = $this->bits[$offset];
		$bob |= 1 << ($x & 0x1f);
		$this->bits[$offset] |= ($bob);
		//$this->bits[$offset] = intval32bits($this->bits[$offset]);

		//}
//16777216
	}

	public function _unset($x, $y): void
	{//было unset, php не позволяет использовать unset
		$offset = (int)($y * $this->rowSize + ($x / 32));
		$this->bits[$offset] &= ~(1 << ($x & 0x1f));
	}

	/**1 << (249 & 0x1f)
	 * <p>Flips the given bit.</p>
	 *
	 * @param $x ;  The horizontal component (i.e. which column)
	 * @param $y ;  The vertical component (i.e. which row)
	 */
	/**
	 * @psalm-param 0|positive-int $x
	 * @psalm-param 0|positive-int $y
	 */
	public function flip(int $x, int $y): void
	{
		$offset = $y * $this->rowSize + (int)($x / 32);

		$this->bits[$offset] = ($this->bits[$offset] ^ (1 << ($x & 0x1f)));
	}

	/**
	 * Exclusive-or (XOR): Flip the bit in this {@code BitMatrix} if the corresponding
	 * mask bit is set.
	 *
	 * @param $mask ;  XOR mask
	 */
	public function _xor($mask): void
	{//было xor, php не позволяет использовать xor
		if ($this->width != $mask->getWidth() || $this->height != $mask->getHeight()
			|| $this->rowSize != $mask->getRowSize()) {
			throw new \InvalidArgumentException("input matrix dimensions do not match");
		}
		$rowArray = new BitArray($this->width / 32 + 1);
		for ($y = 0; $y < $this->height; $y++) {
			$offset = $y * $this->rowSize;
			$row = $mask->getRow($y, $rowArray)->getBitArray();
			for ($x = 0; $x < $this->rowSize; $x++) {
				$this->bits[$offset + $x] ^= $row[$x];
			}
		}
	}

	/**
	 * Clears all bits (sets to false).
	 */
	public function clear(): void
	{
		$max = is_countable($this->bits) ? count($this->bits) : 0;
		for ($i = 0; $i < $max; $i++) {
			$this->bits[$i] = 0;
		}
	}

	/**
	 * <p>Sets a square region of the bit matrix to true.</p>
	 *
	 * @param $left   ;  The horizontal position to begin at (inclusive)
	 * @param $top    ;  The vertical position to begin at (inclusive)
	 * @param $width  ;  The width of the region
	 * @param $height ;  The height of the region
	 *
	 * @psalm-param 0|6|9 $left
	 * @psalm-param 0|6|9 $top
	 */
	public function setRegion(int $left, int $top, int $width, int $height): void
	{
		if ($top < 0 || $left < 0) {
			throw new \InvalidArgumentException("Left and top must be nonnegative");
		}
		if ($height < 1 || $width < 1) {
			throw new \InvalidArgumentException("Height and width must be at least 1");
		}
		$right = $left + $width;
		$bottom = $top + $height;
		if ($bottom > $this->height || $right > $this->width) { //> this.height || right > this.width
			throw new \InvalidArgumentException("The region must fit inside the matrix");
		}
		for ($y = $top; $y < $bottom; $y++) {
			$offset = $y * $this->rowSize;
			for ($x = $left; $x < $right; $x++) {
				$this->bits[$offset + (int)($x / 32)] = ($this->bits[$offset + (int)($x / 32)] |= 1 << ($x & 0x1f));
			}
		}
	}

	/**
	 * Modifies this {@code BitMatrix} to represent the same but rotated 180 degrees
	 */
	public function rotate180(): void
	{
		$width = $this->getWidth();
		$height = $this->getHeight();
		$topRow = new BitArray($width);
		$bottomRow = new BitArray($width);
		for ($i = 0; $i < ($height + 1) / 2; $i++) {
			$topRow = $this->getRow($i, $topRow);
			$bottomRow = $this->getRow($height - 1 - $i, $bottomRow);
			$topRow->reverse();
			$bottomRow->reverse();
			$this->setRow($i, $bottomRow);
			$this->setRow($height - 1 - $i, $topRow);
		}
	}

	/**
	 * @return float The width of the matrix
	 */
	public function getWidth()
	{
		return $this->width;
	}

	/**
	 * A fast method to retrieve one row of data from the matrix as a BitArray.
	 *
	 * @param $y   ;  The row to retrieve
	 * @param $row ;  An optional caller-allocated BitArray, will be allocated if null or too small
	 * @param float|int $y
	 *
	 * @psalm-param 0|float|positive-int $y
	 */
	public function getRow(int|float $y, BitArray $row): BitArray
	{
		if ($row == null || $row->getSize() < $this->width) {
			$row = new BitArray($this->width);
		} else {
			$row->clear();
		}
		$offset = $y * $this->rowSize;
		for ($x = 0; $x < $this->rowSize; $x++) {
			$row->setBulk($x * 32, $this->bits[$offset + $x]);
		}

		return $row;
	}

	/**
	 * @param $y   ;  row to set
	 * @param $row ;  {@link BitArray} to copy from
	 * @param float|int $y
	 *
	 * @psalm-param 0|float|positive-int $y
	 */
	public function setRow(int|float $y, BitArray $row): void
	{
		$this->bits = arraycopy($row->getBitArray(), 0, $this->bits, $y * $this->rowSize, $this->rowSize);
	}

	/**
	 * This is useful in detecting the enclosing rectangle of a 'pure' barcode.
	 *
	 * @return (int|mixed)[]|null
	 *
	 * @psalm-return array{0: int|mixed, 1: 0|mixed|positive-int, 2: mixed, 3: mixed}|null
	 */
	public function getEnclosingRectangle(): array|null
	{
		$left = $this->width;
		$top = $this->height;
		$right = -1;
		$bottom = -1;

		for ($y = 0; $y < $this->height; $y++) {
			for ($x32 = 0; $x32 < $this->rowSize; $x32++) {
				$theBits = $this->bits[$y * $this->rowSize + $x32];
				if ($theBits != 0) {
					if ($y < $top) {
						$top = $y;
					}
					if ($y > $bottom) {
						$bottom = $y;
					}
					if ($x32 * 32 < $left) {
						$bit = 0;
						while (($theBits << (31 - $bit)) == 0) {
							$bit++;
						}
						if (($x32 * 32 + $bit) < $left) {
							$left = $x32 * 32 + $bit;
						}
					}
					if ($x32 * 32 + 31 > $right) {
						$bit = 31;
						while ((sdvig3($theBits, $bit)) == 0) {//>>>
							$bit--;
						}
						if (($x32 * 32 + $bit) > $right) {
							$right = $x32 * 32 + $bit;
						}
					}
				}
			}
		}

		$width = $right - $left;
		$height = $bottom - $top;

		if ($width < 0 || $height < 0) {
			return null;
		}

		return [$left, $top, $width, $height];
	}

	/**
	 * This is useful in detecting a corner of a 'pure' barcode.
	 *
	 * @psalm-return array{0: mixed, 1: mixed}|null
	 */
	public function getTopLeftOnBit(): array|null
	{
		$bitsOffset = 0;
		while ($bitsOffset < (is_countable($this->bits) ? count($this->bits) : 0) && $this->bits[$bitsOffset] == 0) {
			$bitsOffset++;
		}
		if ($bitsOffset == (is_countable($this->bits) ? count($this->bits) : 0)) {
			return null;
		}
		$y = $bitsOffset / $this->rowSize;
		$x = ($bitsOffset % $this->rowSize) * 32;

		$theBits = $this->bits[$bitsOffset];
		$bit = 0;
		while (($theBits << (31 - $bit)) == 0) {
			

... (vista previa truncada) ...
BitSource.php
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Common;

/**
 * <p>This provides an easy abstraction to read bits at a time from a sequence of bytes, where the
 * number of bits read is not often a multiple of 8.</p>
 *
 * <p>This class is thread-safe but not reentrant -- unless the caller modifies the bytes array
 * it passed in, in which case all bets are off.</p>
 *
 * @author Sean Owen
 */
final class BitSource
{
	private int $byteOffset = 0;
	private int $bitOffset = 0;

	/**
	 * @param array $bytes bytes from which this will read bits. Bits will be read from the first byte first.
	 *              Bits are read within a byte from most-significant to least-significant bit.
	 */
	public function __construct(private array $bytes)
	{
	}

	/**
	 * @return int of next bit in current byte which would be read by the next call to {@link #readBits(int)}.
	 */
	public function getBitOffset(): int
	{
		return $this->bitOffset;
	}

	/**
	 * @return int of next byte in input byte array which would be read by the next call to {@link #readBits(int)}.
	 */
	public function getByteOffset(): int
	{
		return $this->byteOffset;
	}

	/**
	 * @param int $numBits number of bits to read
	 *
	 * @return int representing the bits read. The bits will appear as the least-significant
	 *         bits of the int
	 * @throws \InvalidArgumentException if numBits isn't in [1,32] or more than is available
	 */
	public function readBits($numBits)
	{
		if ($numBits < 1 || $numBits > 32 || $numBits > $this->available()) {
			throw new \InvalidArgumentException(strval($numBits));
		}

		$result = 0;

		// First, read remainder from current byte
		if ($this->bitOffset > 0) {
			$bitsLeft = 8 - $this->bitOffset;
			$toRead = $numBits < $bitsLeft ? $numBits : $bitsLeft;
			$bitsToNotRead = $bitsLeft - $toRead;
			$mask = (0xFF >> (8 - $toRead)) << $bitsToNotRead;
			$result = ($this->bytes[$this->byteOffset] & $mask) >> $bitsToNotRead;
			$numBits -= $toRead;
			$this->bitOffset += $toRead;
			if ($this->bitOffset == 8) {
				$this->bitOffset = 0;
				$this->byteOffset++;
			}
		}

		// Next read whole bytes
		if ($numBits > 0) {
			while ($numBits >= 8) {
				$result = ($result << 8) | ($this->bytes[$this->byteOffset] & 0xFF);
				$this->byteOffset++;
				$numBits -= 8;
			}

			// Finally read a partial byte
			if ($numBits > 0) {
				$bitsToNotRead = 8 - $numBits;
				$mask = (0xFF >> $bitsToNotRead) << $bitsToNotRead;
				$result = ($result << $numBits) | (($this->bytes[$this->byteOffset] & $mask) >> $bitsToNotRead);
				$this->bitOffset += $numBits;
			}
		}

		return $result;
	}

	/**
	 * @return int of bits that can be read successfully
	 */
	public function available(): int
	{
		return 8 * ((is_countable($this->bytes) ? count($this->bytes) : 0) - $this->byteOffset) - $this->bitOffset;
	}
}

CharacterSetECI.php
Script de practica.
Abrir
Ver codigo

<?php

namespace Zxing\Common;

/**
 * Encapsulates a Character Set ECI, according to "Extended Channel
 * Interpretations" 5.3.1.1 of ISO 18004.
 */
final class CharacterSetECI
{
	/**#@+
  * Character set constants.
  */
	/**
	 * @var int
	 */
	public const CP437 = 0;
	/**
  * @var int
  */
	public const ISO8859_1 = 1;
	/**
  * @var int
  */
	public const ISO8859_2 = 4;
	/**
  * @var int
  */
	public const ISO8859_3 = 5;
	/**
  * @var int
  */
	public const ISO8859_4 = 6;
	/**
  * @var int
  */
	public const ISO8859_5 = 7;
	/**
  * @var int
  */
	public const ISO8859_6 = 8;
	/**
  * @var int
  */
	public const ISO8859_7 = 9;
	/**
  * @var int
  */
	public const ISO8859_8 = 10;
	/**
  * @var int
  */
	public const ISO8859_9 = 11;
	/**
  * @var int
  */
	public const ISO8859_10 = 12;
	/**
  * @var int
  */
	public const ISO8859_11 = 13;
	/**
  * @var int
  */
	public const ISO8859_12 = 14;
	/**
  * @var int
  */
	public const ISO8859_13 = 15;
	/**
  * @var int
  */
	public const ISO8859_14 = 16;
	/**
  * @var int
  */
	public const ISO8859_15 = 17;
	/**
  * @var int
  */
	public const ISO8859_16 = 18;
	/**
  * @var int
  */
	public const SJIS = 20;
	/**
  * @var int
  */
	public const CP1250 = 21;
	/**
  * @var int
  */
	public const CP1251 = 22;
	/**
  * @var int
  */
	public const CP1252 = 23;
	/**
  * @var int
  */
	public const CP1256 = 24;
	/**
  * @var int
  */
	public const UNICODE_BIG_UNMARKED = 25;
	/**
  * @var int
  */
	public const UTF8 = 26;
	/**
  * @var int
  */
	public const ASCII = 27;
	/**
  * @var int
  */
	public const BIG5 = 28;
	/**
  * @var int
  */
	public const GB18030 = 29;
	/**
  * @var int
  */
	public const EUC_KR = 30;
	/**
  * Map between character names and their ECI values.
  */
	private static array $nameToEci = [
		'ISO-8859-1' => self::ISO8859_1,
		'ISO-8859-2' => self::ISO8859_2,
		'ISO-8859-3' => self::ISO8859_3,
		'ISO-8859-4' => self::ISO8859_4,
		'ISO-8859-5' => self::ISO8859_5,
		'ISO-8859-6' => self::ISO8859_6,
		'ISO-8859-7' => self::ISO8859_7,
		'ISO-8859-8' => self::ISO8859_8,
		'ISO-8859-9' => self::ISO8859_9,
		'ISO-8859-10' => self::ISO8859_10,
		'ISO-8859-11' => self::ISO8859_11,
		'ISO-8859-12' => self::ISO8859_12,
		'ISO-8859-13' => self::ISO8859_13,
		'ISO-8859-14' => self::ISO8859_14,
		'ISO-8859-15' => self::ISO8859_15,
		'ISO-8859-16' => self::ISO8859_16,
		'SHIFT-JIS' => self::SJIS,
		'WINDOWS-1250' => self::CP1250,
		'WINDOWS-1251' => self::CP1251,
		'WINDOWS-1252' => self::CP1252,
		'WINDOWS-1256' => self::CP1256,
		'UTF-16BE' => self::UNICODE_BIG_UNMARKED,
		'UTF-8' => self::UTF8,
		'ASCII' => self::ASCII,
		'GBK' => self::GB18030,
		'EUC-KR' => self::EUC_KR,
	];
	/**#@-*/
	/**
	 * Additional possible values for character sets.
	 */
	private static array $additionalValues = [
		self::CP437 => 2,
		self::ASCII => 170,
	];
	private static int|string|null $name = null;

	/**
  * Gets character set ECI by value.
  *
  *
  * @return CharacterSetEci|null
  */
	public static function getCharacterSetECIByValue(string $value)
	{
		if ($value < 0 || $value >= 900) {
			throw new \InvalidArgumentException('Value must be between 0 and 900');
		}
		if (false !== ($key = array_search($value, self::$additionalValues))) {
			$value = $key;
		}
		array_search($value, self::$nameToEci);
		try {
			self::setName($value);

			return new self($value);
		} catch (\UnexpectedValueException) {
			return null;
		}
	}

	/**
	 * @param (int|string) $value
	 *
	 * @psalm-param array-key $value
	 *
	 * @return null|true
	 */
	private static function setName($value)
	{
		foreach (self::$nameToEci as $name => $key) {
			if ($key == $value) {
				self::$name = $name;

				return true;
			}
		}
		if (self::$name == null) {
			foreach (self::$additionalValues as $name => $key) {
				if ($key == $value) {
					self::$name = $name;

					return true;
				}
			}
		}
	}

	/**
	 * Gets character set ECI name.
	 *
	 * @return int|null|string set ECI name|null
	 */
	public static function name(): string|int|null
	{
		return self::$name;
	}

	/**
  * Gets character set ECI by name.
  *
  *
  * @return CharacterSetEci|null
  */
	public static function getCharacterSetECIByName(string $name)
	{
		$name = strtoupper($name);
		if (isset(self::$nameToEci[$name])) {
			return new self(self::$nameToEci[$name]);
		}

		return null;
	}
}

DecoderResult.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Common;

/**
 * <p>Encapsulates the result of decoding a matrix of bits. This typically
 * applies to 2D barcode formats. For now it contains the raw bytes obtained,
 * as well as a String interpretation of those bytes, if applicable.</p>
 *
 * @author Sean Owen
 */
final class DecoderResult
{
	/**
  * @var mixed|null
  */
	private $errorsCorrected;
	/**
  * @var mixed|null
  */
	private $erasures;
	/**
  * @var mixed|null
  */
	private $other;


	public function __construct(private $rawBytes, private $text, private $byteSegments, private $ecLevel, private $structuredAppendSequenceNumber = -1, private $structuredAppendParity = -1)
	{
	}

	public function getRawBytes()
	{
		return $this->rawBytes;
	}

	public function getText()
	{
		return $this->text;
	}

	public function getByteSegments()
	{
		return $this->byteSegments;
	}

	public function getECLevel()
	{
		return $this->ecLevel;
	}

	public function getErrorsCorrected()
	{
		return $this->errorsCorrected;
	}

	public function setErrorsCorrected($errorsCorrected): void
	{
		$this->errorsCorrected = $errorsCorrected;
	}

	public function getErasures()
	{
		return $this->erasures;
	}

	public function setErasures($erasures): void
	{
		$this->erasures = $erasures;
	}

	public function getOther()
	{
		return $this->other;
	}

	public function setOther(\Zxing\Qrcode\Decoder\QRCodeDecoderMetaData $other): void
	{
		$this->other = $other;
	}

	public function hasStructuredAppend(): bool
	{
		return $this->structuredAppendParity >= 0 && $this->structuredAppendSequenceNumber >= 0;
	}

	public function getStructuredAppendParity()
	{
		return $this->structuredAppendParity;
	}

	public function getStructuredAppendSequenceNumber()
	{
		return $this->structuredAppendSequenceNumber;
	}
}

DefaultGridSampler.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Common;

use Zxing\NotFoundException;

/**
 * @author Sean Owen
 */
final class DefaultGridSampler extends GridSampler
{
	/**
	 * @return BitMatrix
	 */
	public function sampleGrid(
		$image,
		$dimensionX,
		$dimensionY,
		$p1ToX,
		$p1ToY,
		$p2ToX,
		$p2ToY,
		$p3ToX,
		$p3ToY,
		$p4ToX,
		$p4ToY,
		$p1FromX,
		$p1FromY,
		$p2FromX,
		$p2FromY,
		$p3FromX,
		$p3FromY,
		$p4FromX,
		$p4FromY
	) {
		$transform = PerspectiveTransform::quadrilateralToQuadrilateral(
			$p1ToX,
			$p1ToY,
			$p2ToX,
			$p2ToY,
			$p3ToX,
			$p3ToY,
			$p4ToX,
			$p4ToY,
			$p1FromX,
			$p1FromY,
			$p2FromX,
			$p2FromY,
			$p3FromX,
			$p3FromY,
			$p4FromX,
			$p4FromY
		);

		return $this->sampleGrid_($image, $dimensionX, $dimensionY, $transform);
	}


	/**
	 * @return BitMatrix
	 */
	public function sampleGrid_(
		BitMatrix $image,
		int $dimensionX,
		int $dimensionY,
		PerspectiveTransform $transform
	): BitMatrix {
		if ($dimensionX <= 0 || $dimensionY <= 0) {
			throw new NotFoundException("X or Y dimensions smaller than zero");
		}
		$bits = new BitMatrix($dimensionX, $dimensionY);
		$points = fill_array(0, 2 * $dimensionX, 0.0);
		for ($y = 0; $y < $dimensionY; $y++) {
			$max = is_countable($points) ? count($points) : 0;
			$iValue = (float)$y + 0.5;
			for ($x = 0; $x < $max; $x += 2) {
				$points[$x] = (float)($x / 2) + 0.5;
				$points[$x + 1] = $iValue;
			}
			$transform->transformPoints($points);
			// Quick check to see if points transformed to something inside the image;
			// sufficient to check the endpoints
			self::checkAndNudgePoints($image, $points);
			try {
				for ($x = 0; $x < $max; $x += 2) {
					if ($image->get((int)$points[$x], (int)$points[$x + 1])) {
						// Black(-ish) pixel
						$bits->set($x / 2, $y);
					}
				}
			} catch (\Exception) { //ArrayIndexOutOfBoundsException
				// This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting
				// transform gets "twisted" such that it maps a straight line of points to a set of points
				// whose endpoints are in bounds, but others are not. There is probably some mathematical
				// way to detect this about the transformation that I don't know yet.
				// This results in an ugly runtime exception despite our clever checks above -- can't have
				// that. We could check each point's coordinates but that feels duplicative. We settle for
				// catching and wrapping ArrayIndexOutOfBoundsException.
				throw new NotFoundException("ArrayIndexOutOfBoundsException");
			}
		}

		return $bits;
	}
}

DetectorResult.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Common;

/**
 * <p>Encapsulates the result of detecting a barcode in an image. This includes the raw
 * matrix of black/white pixels corresponding to the barcode, and possibly points of interest
 * in the image, like the location of finder patterns or corners of the barcode in the image.</p>
 *
 * @author Sean Owen
 */
class DetectorResult
{
	public function __construct(private $bits, private $points)
	{
	}

	final public function getBits()
	{
		return $this->bits;
	}

	final public function getPoints()
	{
		return $this->points;
	}
}

GlobalHistogramBinarizer.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Common;

use Zxing\Binarizer;
use Zxing\NotFoundException;

/**
 * This Binarizer implementation uses the old ZXing global histogram approach. It is suitable
 * for low-end mobile devices which don't have enough CPU or memory to use a local thresholding
 * algorithm. However, because it picks a global black point, it cannot handle difficult shadows
 * and gradients.
 *
 * Faster mobile devices and all desktop applications should probably use HybridBinarizer instead.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 * @author Sean Owen
 */
class GlobalHistogramBinarizer extends Binarizer
{
	private static int $LUMINANCE_BITS = 5;
	private static int $LUMINANCE_SHIFT = 3;
	private static int $LUMINANCE_BUCKETS = 32;

	private static array $EMPTY = [];

	private array $luminances = [];
	private array $buckets = [];
	/**
  * @var mixed|\Zxing\LuminanceSource
  */
	private $source = [];

	public function __construct($source)
	{
		self::$LUMINANCE_SHIFT = 8 - self::$LUMINANCE_BITS;
		self::$LUMINANCE_BUCKETS = 1 << self::$LUMINANCE_BITS;

		parent::__construct($source);

		$this->luminances = self::$EMPTY;
		$this->buckets = fill_array(0, self::$LUMINANCE_BUCKETS, 0);
		$this->source = $source;
	}

	// Applies simple sharpening to the row data to improve performance of the 1D Readers.
	public function getBlackRow(int $y, ?BitArray $row = null): BitArray
	{
		$this->source = $this->getLuminanceSource();
		$width = $this->source->getWidth();
		if ($row == null || $row->getSize() < $width) {
			$row = new BitArray($width);
		} else {
			$row->clear();
		}

		$this->initArrays($width);
		$localLuminances = $this->source->getRow($y, $this->luminances);
		$localBuckets = $this->buckets;
		for ($x = 0; $x < $width; $x++) {
			$pixel = $localLuminances[$x] & 0xff;
			$localBuckets[$pixel >> self::$LUMINANCE_SHIFT]++;
		}
		$blackPoint = self::estimateBlackPoint($localBuckets);

		$left = $localLuminances[0] & 0xff;
		$center = $localLuminances[1] & 0xff;
		for ($x = 1; $x < $width - 1; $x++) {
			$right = $localLuminances[$x + 1] & 0xff;
			// A simple -1 4 -1 box filter with a weight of 2.
			$luminance = (($center * 4) - $left - $right) / 2;
			if ($luminance < $blackPoint) {
				$row->set($x);
			}
			$left = $center;
			$center = $right;
		}

		return $row;
	}

	// Does not sharpen the data, as this call is intended to only be used by 2D Readers.
	private function initArrays(float $luminanceSize): void
	{
		if (count($this->luminances) < $luminanceSize) {
			$this->luminances = [];
		}
		for ($x = 0; $x < self::$LUMINANCE_BUCKETS; $x++) {
			$this->buckets[$x] = 0;
		}
	}

	private static function estimateBlackPoint(array $buckets): int
	{
		// Find the tallest peak in the histogram.
		$numBuckets = is_countable($buckets) ? count($buckets) : 0;
		$maxBucketCount = 0;
		$firstPeak = 0;
		$firstPeakSize = 0;
		for ($x = 0; $x < $numBuckets; $x++) {
			if ($buckets[$x] > $firstPeakSize) {
				$firstPeak = $x;
				$firstPeakSize = $buckets[$x];
			}
			if ($buckets[$x] > $maxBucketCount) {
				$maxBucketCount = $buckets[$x];
			}
		}

		// Find the second-tallest peak which is somewhat far from the tallest peak.
		$secondPeak = 0;
		$secondPeakScore = 0;
		for ($x = 0; $x < $numBuckets; $x++) {
			$distanceToBiggest = $x - $firstPeak;
			// Encourage more distant second peaks by multiplying by square of distance.
			$score = $buckets[$x] * $distanceToBiggest * $distanceToBiggest;
			if ($score > $secondPeakScore) {
				$secondPeak = $x;
				$secondPeakScore = $score;
			}
		}

		// Make sure firstPeak corresponds to the black peak.
		if ($firstPeak > $secondPeak) {
			$temp = $firstPeak;
			$firstPeak = $secondPeak;
			$secondPeak = $temp;
		}

		// If there is too little contrast in the image to pick a meaningful black point, throw rather
		// than waste time trying to decode the image, and risk false positives.
		if ($secondPeak - $firstPeak <= $numBuckets / 16) {
			throw new NotFoundException("too little contrast in the image to pick a meaningful black point");
		}

		// Find a valley between them that is low and closer to the white peak.
		$bestValley = $secondPeak - 1;
		$bestValleyScore = -1;
		for ($x = $secondPeak - 1; $x > $firstPeak; $x--) {
			$fromFirst = $x - $firstPeak;
			$score = $fromFirst * $fromFirst * ($secondPeak - $x) * ($maxBucketCount - $buckets[$x]);
			if ($score > $bestValleyScore) {
				$bestValley = $x;
				$bestValleyScore = $score;
			}
		}

		return $bestValley << self::$LUMINANCE_SHIFT;
	}

	public function getBlackMatrix()
	{
		$source = $this->getLuminanceSource();
		$width = $source->getWidth();
		$height = $source->getHeight();
		$matrix = new BitMatrix($width, $height);

		// Quickly calculates the histogram by sampling four rows from the image. This proved to be
		// more robust on the blackbox tests than sampling a diagonal as we used to do.
		$this->initArrays($width);
		$localBuckets = $this->buckets;
		for ($y = 1; $y < 5; $y++) {
			$row = (int)($height * $y / 5);
			$localLuminances = $source->getRow($row, $this->luminances);
			$right = (int)(($width * 4) / 5);
			for ($x = (int)($width / 5); $x < $right; $x++) {
				$pixel = ($localLuminances[(int)($x)] & 0xff);
				$localBuckets[($pixel >> self::$LUMINANCE_SHIFT)]++;
			}
		}
		$blackPoint = self::estimateBlackPoint($localBuckets);

		// We delay reading the entire image luminance until the black point estimation succeeds.
		// Although we end up reading four rows twice, it is consistent with our motto of
		// "fail quickly" which is necessary for continuous scanning.
		$localLuminances = $source->getMatrix();
		for ($y = 0; $y < $height; $y++) {
			$offset = $y * $width;
			for ($x = 0; $x < $width; $x++) {
				$pixel = (int)($localLuminances[$offset + $x] & 0xff);
				if ($pixel < $blackPoint) {
					$matrix->set($x, $y);
				}
			}
		}

		return $matrix;
	}

	public function createBinarizer($source): \Zxing\Common\GlobalHistogramBinarizer
	{
		return new GlobalHistogramBinarizer($source);
	}
}

GridSampler.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Common;

use Zxing\NotFoundException;

/**
 * Implementations of this class can, given locations of finder patterns for a QR code in an
 * image, sample the right points in the image to reconstruct the QR code, accounting for
 * perspective distortion. It is abstracted since it is relatively expensive and should be allowed
 * to take advantage of platform-specific optimized implementations, like Sun's Java Advanced
 * Imaging library, but which may not be available in other environments such as J2ME, and vice
 * versa.
 *
 * The implementation used can be controlled by calling {@link #setGridSampler(GridSampler)}
 * with an instance of a class which implements this interface.
 *
 * @author Sean Owen
 */
abstract class GridSampler
{
	/**
	 * @var GridSampler|null
	 */
	private static $gridSampler;

	/**
	 * Sets the implementation of GridSampler used by the library. One global
	 * instance is stored, which may sound problematic. But, the implementation provided
	 * ought to be appropriate for the entire platform, and all uses of this library
	 * in the whole lifetime of the JVM. For instance, an Android activity can swap in
	 * an implementation that takes advantage of native platform libraries.
	 *
	 * @param GridSampler $newGridSampler The platform-specific object to install.
	 */
	public static function setGridSampler($newGridSampler): void
	{
		self::$gridSampler = $newGridSampler;
	}

	/**
	 * @return GridSampler the current implementation of GridSampler
	 */
	public static function getInstance()
	{
		if (!self::$gridSampler) {
			self::$gridSampler = new DefaultGridSampler();
		}

		return self::$gridSampler;
	}

	/**
	 * <p>Checks a set of points that have been transformed to sample points on an image against
	 * the image's dimensions to see if the point are even within the image.</p>
	 *
	 * <p>This method will actually "nudge" the endpoints back onto the image if they are found to be
	 * barely (less than 1 pixel) off the image. This accounts for imperfect detection of finder
	 * patterns in an image where the QR Code runs all the way to the image border.</p>
	 *
	 * <p>For efficiency, the method will check points from either end of the line until one is found
	 * to be within the image. Because the set of points are assumed to be linear, this is valid.</p>
	 *
	 * @param BitMatrix $image  image into which the points should map
	 * @param array $points actual points in x1,y1,...,xn,yn form
	 * @param float[] $points
	 *
	 * @throws NotFoundException if an endpoint is lies outside the image boundaries
	 *
	 * @psalm-param array<int, float> $points
	 */
	protected static function checkAndNudgePoints(
		BitMatrix $image,
		array $points
	): void {
		$width = $image->getWidth();
		$height = $image->getHeight();
		// Check and nudge points from start until we see some that are OK:
		$nudged = true;
		for ($offset = 0; $offset < (is_countable($points) ? count($points) : 0) && $nudged; $offset += 2) {
			$x = (int)$points[$offset];
			$y = (int)$points[$offset + 1];
			if ($x < -1 || $x > $width || $y < -1 || $y > $height) {
				throw new NotFoundException("Endpoint ($x, $y) lies outside the image boundaries ($width, $height)");
			}
			$nudged = false;
			if ($x == -1) {
				$points[$offset] = 0.0;
				$nudged = true;
			} elseif ($x == $width) {
				$points[$offset] = $width - 1;
				$nudged = true;
			}
			if ($y == -1) {
				$points[$offset + 1] = 0.0;
				$nudged = true;
			} elseif ($y == $height) {
				$points[$offset + 1] = $height - 1;
				$nudged = true;
			}
		}
		// Check and nudge points from end:
		$nudged = true;
		for ($offset = (is_countable($points) ? count($points) : 0) - 2; $offset >= 0 && $nudged; $offset -= 2) {
			$x = (int)$points[$offset];
			$y = (int)$points[$offset + 1];
			if ($x < -1 || $x > $width || $y < -1 || $y > $height) {
				throw new NotFoundException("Endpoint ($x, $y) lies outside the image boundaries ($width, $height)");
			}
			$nudged = false;
			if ($x == -1) {
				$points[$offset] = 0.0;
				$nudged = true;
			} elseif ($x == $width) {
				$points[$offset] = $width - 1;
				$nudged = true;
			}
			if ($y == -1) {
				$points[$offset + 1] = 0.0;
				$nudged = true;
			} elseif ($y == $height) {
				$points[$offset + 1] = $height - 1;
				$nudged = true;
			}
		}
	}

	/**
	 * Samples an image for a rectangular matrix of bits of the given dimension. The sampling
	 * transformation is determined by the coordinates of 4 points, in the original and transformed
	 * image space.
	 *
	 * @param BitMatrix $image      image to sample
	 * @param int $dimensionX width of {@link BitMatrix} to sample from image
	 * @param int $dimensionY height of {@link BitMatrix} to sample from image
	 * @param float      $p1ToX point 1 preimage X
	 * @param float      $p1ToY point 1 preimage Y
	 * @param float      $p2ToX point 2 preimage X
	 * @param float      $p2ToY point 2 preimage Y
	 * @param float      $p3ToX point 3 preimage X
	 * @param float      $p3ToY point 3 preimage Y
	 * @param float      $p4ToX point 4 preimage X
	 * @param float      $p4ToY point 4 preimage Y
	 * @param float    $p1FromX point 1 image X
	 * @param float    $p1FromY point 1 image Y
	 * @param float    $p2FromX point 2 image X
	 * @param float    $p2FromY point 2 image Y
	 * @param float    $p3FromX point 3 image X
	 * @param float    $p3FromY point 3 image Y
	 * @param float    $p4FromX point 4 image X
	 * @param float    $p4FromY point 4 image Y
	 *
	 * @return {@link BitMatrix} representing a grid of points sampled from the image within a region
	 *   defined by the "from" parameters
	 * @throws NotFoundException if image can't be sampled, for example, if the transformation defined
	 *   by the given points is invalid or results in sampling outside the image boundaries
	 */
	abstract public function sampleGrid(
		$image,
		$dimensionX,
		$dimensionY,
		$p1ToX,
		$p1ToY,
		$p2ToX,
		$p2ToY,
		$p3ToX,
		$p3ToY,
		$p4ToX,
		$p4ToY,
		$p1FromX,
		$p1FromY,
		$p2FromX,
		$p2FromY,
		$p3FromX,
		$p3FromY,
		$p4FromX,
		$p4FromY
	);

	abstract public function sampleGrid_(
		BitMatrix $image,
		int $dimensionX,
		int $dimensionY,
		PerspectiveTransform $transform
	): BitMatrix;
}

HybridBinarizer.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Common;

use Zxing\Binarizer;

/**
 * This class implements a local thresholding algorithm, which while slower than the
 * GlobalHistogramBinarizer, is fairly efficient for what it does. It is designed for
 * high frequency images of barcodes with black data on white backgrounds. For this application,
 * it does a much better job than a global blackpoint with severe shadows and gradients.
 * However it tends to produce artifacts on lower frequency images and is therefore not
 * a good general purpose binarizer for uses outside ZXing.
 *
 * This class extends GlobalHistogramBinarizer, using the older histogram approach for 1D readers,
 * and the newer local approach for 2D readers. 1D decoding using a per-row histogram is already
 * inherently local, and only fails for horizontal gradients. We can revisit that problem later,
 * but for now it was not a win to use local blocks for 1D.
 *
 * This Binarizer is the default for the unit tests and the recommended class for library users.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 */
final class HybridBinarizer extends GlobalHistogramBinarizer
{
	// This class uses 5x5 blocks to compute local luminance, where each block is 8x8 pixels.
	// So this is the smallest dimension in each axis we can accept.
	private static int $BLOCK_SIZE_POWER = 3;
	private static int $BLOCK_SIZE = 8; // ...0100...00
	private static int $BLOCK_SIZE_MASK = 7;   // ...0011...11
	private static int $MINIMUM_DIMENSION = 40;
	private static int $MIN_DYNAMIC_RANGE = 24;

	private ?\Zxing\Common\BitMatrix $matrix = null;

	public function __construct($source)
	{
		parent::__construct($source);
		self::$BLOCK_SIZE_POWER = 3;
		self::$BLOCK_SIZE = 1 << self::$BLOCK_SIZE_POWER; // ...0100...00
		self::$BLOCK_SIZE_MASK = self::$BLOCK_SIZE - 1;   // ...0011...11
		self::$MINIMUM_DIMENSION = self::$BLOCK_SIZE * 5;
		self::$MIN_DYNAMIC_RANGE = 24;
	}

	/**
	 * Calculates the final BitMatrix once for all requests. This could be called once from the
	 * constructor instead, but there are some advantages to doing it lazily, such as making
	 * profiling easier, and not doing heavy lifting when callers don't expect it.
	 */
	public function getBlackMatrix()
	{
		if ($this->matrix !== null) {
			return $this->matrix;
		}
		$source = $this->getLuminanceSource();
		$width = $source->getWidth();
		$height = $source->getHeight();
		if ($width >= self::$MINIMUM_DIMENSION && $height >= self::$MINIMUM_DIMENSION) {
			$luminances = $source->getMatrix();
			$subWidth = $width >> self::$BLOCK_SIZE_POWER;
			if (($width & self::$BLOCK_SIZE_MASK) != 0) {
				$subWidth++;
			}
			$subHeight = $height >> self::$BLOCK_SIZE_POWER;
			if (($height & self::$BLOCK_SIZE_MASK) != 0) {
				$subHeight++;
			}
			$blackPoints = self::calculateBlackPoints($luminances, $subWidth, $subHeight, $width, $height);

			$newMatrix = new BitMatrix($width, $height);
			self::calculateThresholdForBlock($luminances, $subWidth, $subHeight, $width, $height, $blackPoints, $newMatrix);
			$this->matrix = $newMatrix;
		} else {
			// If the image is too small, fall back to the global histogram approach.
			$this->matrix = parent::getBlackMatrix();
		}

		return $this->matrix;
	}

	/**
	 * Calculates a single black point for each block of pixels and saves it away.
	 * See the following thread for a discussion of this algorithm:
	 *  http://groups.google.com/group/zxing/browse_thread/thread/d06efa2c35a7ddc0
	 *
	 * @return ((int|mixed)[]|mixed)[]
	 *
	 * @psalm-return array<int, array<int, int|mixed>|mixed>
	 */
	private static function calculateBlackPoints(
		array|BitMatrix $luminances,
		float $subWidth,
		float $subHeight,
		float $width,
		float $height
	): array {
		$blackPoints = fill_array(0, $subHeight, 0);
		foreach ($blackPoints as $key => $point) {
			$blackPoints[$key] = fill_array(0, $subWidth, 0);
		}
		for ($y = 0; $y < $subHeight; $y++) {
			$yoffset = ($y << self::$BLOCK_SIZE_POWER);
			$maxYOffset = $height - self::$BLOCK_SIZE;
			if ($yoffset > $maxYOffset) {
				$yoffset = $maxYOffset;
			}
			for ($x = 0; $x < $subWidth; $x++) {
				$xoffset = ($x << self::$BLOCK_SIZE_POWER);
				$maxXOffset = $width - self::$BLOCK_SIZE;
				if ($xoffset > $maxXOffset) {
					$xoffset = $maxXOffset;
				}
				$sum = 0;
				$min = 0xFF;
				$max = 0;
				for ($yy = 0, $offset = $yoffset * $width + $xoffset; $yy < self::$BLOCK_SIZE; $yy++, $offset += $width) {
					for ($xx = 0; $xx < self::$BLOCK_SIZE; $xx++) {
						$pixel = ((int)($luminances[(int)($offset + $xx)]) & 0xFF);
						$sum += $pixel;
						// still looking for good contrast
						if ($pixel < $min) {
							$min = $pixel;
						}
						if ($pixel > $max) {
							$max = $pixel;
						}
					}
					// short-circuit min/max tests once dynamic range is met
					if ($max - $min > self::$MIN_DYNAMIC_RANGE) {
						// finish the rest of the rows quickly
						for ($yy++, $offset += $width; $yy < self::$BLOCK_SIZE; $yy++, $offset += $width) {
							for ($xx = 0; $xx < self::$BLOCK_SIZE; $xx++) {
								$sum += (((int)$luminances[(int)round($offset + $xx)]) & 0xFF);
							}
						}
					}
				}

				// The default estimate is the average of the values in the block.
				$average = ($sum >> (self::$BLOCK_SIZE_POWER * 2));
				if ($max - $min <= self::$MIN_DYNAMIC_RANGE) {
					// If variation within the block is low, assume this is a block with only light or only
					// dark pixels. In that case we do not want to use the average, as it would divide this
					// low contrast area into black and white pixels, essentially creating data out of noise.
					//
					// The default assumption is that the block is light/background. Since no estimate for
					// the level of dark pixels exists locally, use half the min for the block.
					$average = (int)($min / 2);

					if ($y > 0 && $x > 0) {
						// Correct the "white background" assumption for blocks that have neighbors by comparing
						// the pixels in this block to the previously calculated black points. This is based on
						// the fact that dark barcode symbology is always surrounded by some amount of light
						// background for which reasonable black point estimates were made. The bp estimated at
						// the boundaries is used for the interior.

						// The (min < bp) is arbitrary but works better than other heuristics that were tried.
						$averageNeighborBlackPoint =
							(int)(($blackPoints[$y - 1][$x] + (2 * $blackPoints[$y][$x - 1]) + $blackPoints[$y - 1][$x - 1]) / 4);
						if ($min < $averageNeighborBlackPoint) {
							$average = $averageNeighborBlackPoint;
						}
					}
				}
				$blackPoints[$y][$x] = (int)($average);
			}
		}

		return $blackPoints;
	}

	/**
	 * For each block in the image, calculate the average black point using a 5x5 grid
	 * of the blocks around it. Also handles the corner cases (fractional blocks are computed based
	 * on the last pixels in the row/column which are also used in the previous block).
	 *
	 * @param ((int|mixed)[]|mixed)[] $blackPoints
	 *
	 * @psalm-param array<int, array<int, int|mixed>|mixed> $blackPoints
	 */
	private static function calculateThresholdForBlock(
		array|BitMatrix $luminances,
		float $subWidth,
		float $subHeight,
		float $width,
		float $height,
		array $blackPoints,
		BitMatrix $matrix
	): void {
		for ($y = 0; $y < $subHeight; $y++) {
			$yoffset = ($y << self::$BLOCK_SIZE_POWER);
			$maxYOffset = $height - self::$BLOCK_SIZE;
			if ($yoffset > $maxYOffset) {
				$yoffset = $maxYOffset;
			}
			for ($x = 0; $x < $subWidth; $x++) {
				$xoffset = ($x << self::$BLOCK_SIZE_POWER);
				$maxXOffset = $width - self::$BLOCK_SIZE;
				if ($xoffset > $maxXOffset) {
					$xoffset = $maxXOffset;
				}
				$left = self::cap($x, 2, $subWidth - 3);
				$top = self::cap($y, 2, $subHeight - 3);
				$sum = 0;
				for ($z = -2; $z <= 2; $z++) {
					$blackRow = $blackPoints[$top + $z];
					$sum += $blackRow[$left - 2] + $blackRow[$left - 1] + $blackRow[$left] + $blackRow[$left + 1] + $blackRow[$left + 2];
				}
				$average = (int)($sum / 25);

				self::thresholdBlock($luminances, $xoffset, $yoffset, $average, $width, $matrix);
			}
		}
	}

	/**
	 * @psalm-param 0|positive-int $value
	 * @psalm-param 2 $min
	 *
	 * @return float|int
	 *
	 * @psalm-return float|int<2, max>
	 */
	private static function cap(int $value, int $min, float $max): int|float
	{
		if ($value < $min) {
			return $min;
		} elseif ($value > $max) {
			return $max;
		} else {
			return $value;
		}
	}

	/**
	 * Applies a single threshold to a block of pixels.
	 *
	 * @param BitMatrix|array $luminances
	 * @param float|int $xoffset
	 * @param float|int $yoffset
	 */
	private static function thresholdBlock(
		array|BitMatrix $luminances,
		int|float $xoffset,
		int|float $yoffset,
		int $threshold,
		float $stride,
		BitMatrix $matrix
	): void {
		for ($y = 0, $offset = $yoffset * $stride + $xoffset; $y < self::$BLOCK_SIZE; $y++, $offset += $stride) {
			for ($x = 0; $x < self::$BLOCK_SIZE; $x++) {
				// Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0.
				if ((((int)$luminances[(int)round($offset + $x)]) & 0xFF) <= $threshold) {
					$matrix->set($xoffset + $x, $yoffset + $y);
				}
			}
		}
	}

	public function createBinarizer($source): \Zxing\Common\HybridBinarizer
	{
		return new HybridBinarizer($source);
	}
}

PerspectiveTransform.php
Formulario de entrada de datos.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Common;

/**
 * <p>This class implements a perspective transform in two dimensions. Given four source and four
 * destination points, it will compute the transformation implied between them. The code is based
 * directly upon section 3.4.2 of George Wolberg's "Digital Image Warping"; see pages 54-56.</p>
 *
 * @author Sean Owen
 */
final class PerspectiveTransform
{
	private function __construct(private $a11, private $a21, private $a31, private $a12, private $a22, private $a32, private $a13, private $a23, private $a33)
	{
	}

	public static function quadrilateralToQuadrilateral(
		float $x0,
		float $y0,
		float $x1,
		float $y1,
		float $x2,
		float $y2,
		float $x3,
		float $y3,
		float $x0p,
		float $y0p,
		float $x1p,
		float $y1p,
		float $x2p,
		float $y2p,
		float $x3p,
		float $y3p
	): self {
		$qToS = self::quadrilateralToSquare($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3);
		$sToQ = self::squareToQuadrilateral($x0p, $y0p, $x1p, $y1p, $x2p, $y2p, $x3p, $y3p);

		return $sToQ->times($qToS);
	}

	public static function quadrilateralToSquare(
		float $x0,
		float $y0,
		float $x1,
		float $y1,
		float $x2,
		float $y2,
		float $x3,
		float $y3
	): self {
		// Here, the adjoint serves as the inverse:
		return self::squareToQuadrilateral($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3)->buildAdjoint();
	}

	public function buildAdjoint(): \Zxing\Common\PerspectiveTransform
	{
		// Adjoint is the transpose of the cofactor matrix:
		return new PerspectiveTransform(
			$this->a22 * $this->a33 - $this->a23 * $this->a32,
			$this->a23 * $this->a31 - $this->a21 * $this->a33,
			$this->a21 * $this->a32 - $this->a22 * $this->a31,
			$this->a13 * $this->a32 - $this->a12 * $this->a33,
			$this->a11 * $this->a33 - $this->a13 * $this->a31,
			$this->a12 * $this->a31 - $this->a11 * $this->a32,
			$this->a12 * $this->a23 - $this->a13 * $this->a22,
			$this->a13 * $this->a21 - $this->a11 * $this->a23,
			$this->a11 * $this->a22 - $this->a12 * $this->a21
		);
	}

	public static function squareToQuadrilateral(
		float $x0,
		float $y0,
		float $x1,
		float $y1,
		float $x2,
		float $y2,
		float $x3,
		float $y3
	): \Zxing\Common\PerspectiveTransform {
		$dx3 = $x0 - $x1 + $x2 - $x3;
		$dy3 = $y0 - $y1 + $y2 - $y3;
		if ($dx3 == 0.0 && $dy3 == 0.0) {
			// Affine
			return new PerspectiveTransform(
				$x1 - $x0,
				$x2 - $x1,
				$x0,
				$y1 - $y0,
				$y2 - $y1,
				$y0,
				0.0,
				0.0,
				1.0
			);
		} else {
			$dx1 = $x1 - $x2;
			$dx2 = $x3 - $x2;
			$dy1 = $y1 - $y2;
			$dy2 = $y3 - $y2;
			$denominator = $dx1 * $dy2 - $dx2 * $dy1;
			$a13 = ($dx3 * $dy2 - $dx2 * $dy3) / $denominator;
			$a23 = ($dx1 * $dy3 - $dx3 * $dy1) / $denominator;

			return new PerspectiveTransform(
				$x1 - $x0 + $a13 * $x1,
				$x3 - $x0 + $a23 * $x3,
				$x0,
				$y1 - $y0 + $a13 * $y1,
				$y3 - $y0 + $a23 * $y3,
				$y0,
				$a13,
				$a23,
				1.0
			);
		}
	}

	public function times(self $other): \Zxing\Common\PerspectiveTransform
	{
		return new PerspectiveTransform(
			$this->a11 * $other->a11 + $this->a21 * $other->a12 + $this->a31 * $other->a13,
			$this->a11 * $other->a21 + $this->a21 * $other->a22 + $this->a31 * $other->a23,
			$this->a11 * $other->a31 + $this->a21 * $other->a32 + $this->a31 * $other->a33,
			$this->a12 * $other->a11 + $this->a22 * $other->a12 + $this->a32 * $other->a13,
			$this->a12 * $other->a21 + $this->a22 * $other->a22 + $this->a32 * $other->a23,
			$this->a12 * $other->a31 + $this->a22 * $other->a32 + $this->a32 * $other->a33,
			$this->a13 * $other->a11 + $this->a23 * $other->a12 + $this->a33 * $other->a13,
			$this->a13 * $other->a21 + $this->a23 * $other->a22 + $this->a33 * $other->a23,
			$this->a13 * $other->a31 + $this->a23 * $other->a32 + $this->a33 * $other->a33
		);
	}

	/**
	 * @param (float|mixed)[] $points
	 *
	 * @psalm-param array<int, float|mixed> $points
	 */
	public function transformPoints(array &$points, &$yValues = 0): void
	{
		if ($yValues) {
			$this->transformPoints_($points, $yValues);

			return;
		}
		$max = is_countable($points) ? count($points) : 0;
		$a11 = $this->a11;
		$a12 = $this->a12;
		$a13 = $this->a13;
		$a21 = $this->a21;
		$a22 = $this->a22;
		$a23 = $this->a23;
		$a31 = $this->a31;
		$a32 = $this->a32;
		$a33 = $this->a33;
		for ($i = 0; $i < $max; $i += 2) {
			$x = $points[$i];
			$y = $points[$i + 1];
			$denominator = $a13 * $x + $a23 * $y + $a33;
			// TODO: think what we do if $denominator == 0 (division by zero)
			if ($denominator != 0.0) {
				$points[$i] = ($a11 * $x + $a21 * $y + $a31) / $denominator;
				$points[$i + 1] = ($a12 * $x + $a22 * $y + $a32) / $denominator;
			}
		}
	}

	/**
	 * @param (float|mixed)[] $xValues
	 *
	 * @psalm-param array<int, float|mixed> $xValues
	 */
	public function transformPoints_(array &$xValues, &$yValues): void
	{
		$n = is_countable($xValues) ? count($xValues) : 0;
		for ($i = 0; $i < $n; $i++) {
			$x = $xValues[$i];
			$y = $yValues[$i];
			$denominator = $this->a13 * $x + $this->a23 * $y + $this->a33;
			$xValues[$i] = ($this->a11 * $x + $this->a21 * $y + $this->a31) / $denominator;
			$yValues[$i] = ($this->a12 * $x + $this->a22 * $y + $this->a32) / $denominator;
		}
	}
}

customFunctions.php
Script de practica.
Abrir
Ver codigo

<?php

if (!function_exists('arraycopy')) {
	function arraycopy($srcArray, $srcPos, $destArray, $destPos, $length): array
	{
		$srcArrayToCopy = array_slice($srcArray, $srcPos, $length);
		array_splice($destArray, $destPos, $length, $srcArrayToCopy);

		return $destArray;
	}
}

if (!function_exists('hashCode')) {
	function hashCode($s): int
	{
		$h = 0;
		$len = strlen((string) $s);
		for ($i = 0; $i < $len; $i++) {
			$h = (31 * $h + ord($s[$i]));
		}

		return $h;
	}
}

if (!function_exists('numberOfTrailingZeros')) {
	/**
	 * @psalm-return 0|32|positive-int
	 */
	function numberOfTrailingZeros($i): int
	{
		if ($i == 0) {
			return 32;
		}
		$num = 0;
		while (($i & 1) == 0) {
			$i >>= 1;
			$num++;
		}

		return $num;
	}
}

if (!function_exists('uRShift')) {
	function uRShift($a, $b)
	{
		static $mask = (8 * PHP_INT_SIZE - 1);
		if ($b === 0) {
			return $a;
		}

		return ($a >> $b) & ~(1 << $mask >> ($b - 1));
	}
}

/*
function sdvig3($num,$count=1){//>>> 32 bit
	$s = decbin($num);

	$sarray  = str_split($s,1);
	$sarray = array_slice($sarray,-32);//32bit

	for($i=0;$i<=1;$i++) {
		array_pop($sarray);
		array_unshift($sarray, '0');
	}
	return bindec(implode($sarray));
}
*/

if (!function_exists('sdvig3')) {
	function sdvig3($a, $b): float|int
	{
		if ($a >= 0) {
			return bindec(decbin($a >> $b)); //simply right shift for positive number
		}

		$bin = decbin($a >> $b);

		$bin = substr($bin, $b); // zero fill on the left side

		return bindec($bin);
	}
}

if (!function_exists('floatToIntBits')) {
	function floatToIntBits($float_val)
	{
		$int = unpack('i', pack('f', $float_val));

		return $int[1];
	}
}


if (!function_exists('fill_array')) {
	/**
	 * @psalm-return array<int, mixed>
	 */
	function fill_array($index, $count, $value): array
	{
		if ($count <= 0) {
			return [0];
		}

		return array_fill($index, $count, $value);
	}
}

GenericGF.php
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Common\Reedsolomon;

/**
 * <p>This class contains utility methods for performing mathematical operations over
 * the Galois Fields. Operations use a given primitive polynomial in calculations.</p>
 *
 * <p>Throughout this package, elements of the GF are represented as an {@code int}
 * for convenience and speed (but at the cost of memory).
 * </p>
 *
 * @author Sean Owen
 * @author David Olivier
 */
final class GenericGF
{
	public static $AZTEC_DATA_12;
	public static $AZTEC_DATA_10;
	public static $AZTEC_DATA_6;
	public static $AZTEC_PARAM;
	public static $QR_CODE_FIELD_256;
	public static $DATA_MATRIX_FIELD_256;
	public static $AZTEC_DATA_8;
	public static $MAXICODE_FIELD_64;

	private array $expTable = [];
	private array $logTable = [];
	private readonly \Zxing\Common\Reedsolomon\GenericGFPoly $zero;
	private readonly \Zxing\Common\Reedsolomon\GenericGFPoly $one;

	/**
 * Create a representation of GF(size) using the given primitive polynomial.
 *
 * @param int $primitive irreducible polynomial whose coefficients are represented by
 *                  the bits of an int, where the least-significant bit represents the constant
 *                  coefficient
 * @param int $size      the size of the field
  * @param int $generatorBase the factor b in the generator polynomial can be 0- or 1-based
				  (g(x) = (x+a^b)(x+a^(b+1))...(x+a^(b+2t-1))).
				  In most cases it should be 1, but for QR code it is 0.
 */
	public function __construct(private $primitive, private $size, private $generatorBase)
	{
		$x = 1;
		for ($i = 0; $i < $size; $i++) {
			$this->expTable[$i] = $x;
			$x *= 2; // we're assuming the generator alpha is 2
			if ($x >= $size) {
				$x ^= $primitive;
				$x &= $size - 1;
			}
		}
		for ($i = 0; $i < $size - 1; $i++) {
			$this->logTable[$this->expTable[$i]] = $i;
		}
		// logTable[0] == 0 but this should never be used
		$this->zero = new GenericGFPoly($this, [0]);
		$this->one = new GenericGFPoly($this, [1]);
	}

	public static function Init(): void
	{
		self::$AZTEC_DATA_12 = new GenericGF(0x1069, 4096, 1); // x^12 + x^6 + x^5 + x^3 + 1
		self::$AZTEC_DATA_10 = new GenericGF(0x409, 1024, 1); // x^10 + x^3 + 1
		self::$AZTEC_DATA_6 = new GenericGF(0x43, 64, 1); // x^6 + x + 1
		self::$AZTEC_PARAM = new GenericGF(0x13, 16, 1); // x^4 + x + 1
		self::$QR_CODE_FIELD_256 = new GenericGF(0x011D, 256, 0); // x^8 + x^4 + x^3 + x^2 + 1
		self::$DATA_MATRIX_FIELD_256 = new GenericGF(0x012D, 256, 1); // x^8 + x^5 + x^3 + x^2 + 1
		self::$AZTEC_DATA_8 = self::$DATA_MATRIX_FIELD_256;
		self::$MAXICODE_FIELD_64 = self::$AZTEC_DATA_6;
	}

	/**
	 * Implements both addition and subtraction -- they are the same in GF(size).
	 *
	 * @return float|int sum/difference of a and b
	 *
	 * @param float|int|null $b
	 */
	public static function addOrSubtract(int $a, int|float|null $b)
	{
		return $a ^ $b;
	}

	public function getZero(): GenericGFPoly
	{
		return $this->zero;
	}

	public function getOne(): GenericGFPoly
	{
		return $this->one;
	}

	/**
	 * @return GenericGFPoly  the monomial representing coefficient * x^degree
	 */
	public function buildMonomial($degree, int $coefficient)
	{
		if ($degree < 0) {
			throw new \InvalidArgumentException();
		}
		if ($coefficient == 0) {
			return $this->zero;
		}
		$coefficients = fill_array(0, $degree + 1, 0);//new int[degree + 1];
		$coefficients[0] = $coefficient;

		return new GenericGFPoly($this, $coefficients);
	}

	/**
	 * @return 2 to the power of a in GF(size)
	 */
	public function exp($a)
	{
		return $this->expTable[$a];
	}

	/**
	 * @return float base 2 log of a in GF(size)
	 */
	public function log(float|int|null $a)
	{
		if ($a == 0) {
			throw new \InvalidArgumentException();
		}

		return $this->logTable[$a];
	}

	/**
	 * @return float multiplicative inverse of a
	 */
	public function inverse($a)
	{
		if ($a == 0) {
			throw new \Exception();
		}

		return $this->expTable[$this->size - $this->logTable[$a] - 1];
	}

	/**
	 * @return int product of a and b in GF(size)
	 *
	 * @param float|int|null $b
	 * @param float|int|null $a
	 */
	public function multiply(int|float|null $a, int|float|null $b)
	{
		if ($a == 0 || $b == 0) {
			return 0;
		}

		return $this->expTable[($this->logTable[$a] + $this->logTable[$b]) % ($this->size - 1)];
	}

	public function getSize()
	{
		return $this->size;
	}

	public function getGeneratorBase()
	{
		return $this->generatorBase;
	}

	// @Override
	public function toString(): string
	{
		return "GF(0x" . dechex((int)($this->primitive)) . ',' . $this->size . ')';
	}
}

GenericGF::Init();

GenericGFPoly.php
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Common\Reedsolomon;

/**
 * <p>Represents a polynomial whose coefficients are elements of a GF.
 * Instances of this class are immutable.</p>
 *
 * <p>Much credit is due to William Rucklidge since portions of this code are an indirect
 * port of his C++ Reed-Solomon implementation.</p>
 *
 * @author Sean Owen
 */
final class GenericGFPoly
{
	/**
  * @var int[]|float[]|null
  */
	private $coefficients;

	/**
	 * @param GenericGF $field {@link GenericGF} the        instance representing the field to use
	 * to perform computations
	 * @param array $coefficients coefficients as ints representing elements of GF(size), arranged
	 *                     from most significant (highest-power term) coefficient to least significant
	 *
	 * @throws \InvalidArgumentException if argument is null or empty,
	 * or if leading coefficient is 0 and this is not a
	 * constant polynomial (that is, it is not the monomial "0")
	 */
	public function __construct(private $field, $coefficients)
	{
		if (count($coefficients) == 0) {
			throw new \InvalidArgumentException();
		}
		$coefficientsLength = count($coefficients);
		if ($coefficientsLength > 1 && $coefficients[0] == 0) {
			// Leading term must be non-zero for anything except the constant polynomial "0"
			$firstNonZero = 1;
			while ($firstNonZero < $coefficientsLength && $coefficients[$firstNonZero] == 0) {
				$firstNonZero++;
			}
			if ($firstNonZero == $coefficientsLength) {
				$this->coefficients = [0];
			} else {
				$this->coefficients = fill_array(0, $coefficientsLength - $firstNonZero, 0);
				$this->coefficients = arraycopy(
					$coefficients,
					$firstNonZero,
					$this->coefficients,
					0,
					is_countable($this->coefficients) ? count($this->coefficients) : 0
				);
			}
		} else {
			$this->coefficients = $coefficients;
		}
	}

	/**
	 * @return (float|int)[]|null
	 *
	 * @psalm-return array<float|int>|null
	 */
	public function getCoefficients(): array|null
	{
		return $this->coefficients;
	}

	/**
	 * @return float|int|null evaluation of this polynomial at a given point
	 */
	public function evaluateAt($a): int|float|null
	{
		if ($a == 0) {
			// Just return the x^0 coefficient
			return $this->getCoefficient(0);
		}
		$size = is_countable($this->coefficients) ? count($this->coefficients) : 0;
		if ($a == 1) {
			// Just the sum of the coefficients
			$result = 0;
			foreach ($this->coefficients as $coefficient) {
				$result = GenericGF::addOrSubtract($result, $coefficient);
			}

			return $result;
		}
		$result = $this->coefficients[0];
		for ($i = 1; $i < $size; $i++) {
			$result = GenericGF::addOrSubtract($this->field->multiply($a, $result), $this->coefficients[$i]);
		}

		return $result;
	}

	/**
	 * @return float|int|null coefficient of x^degree term in this polynomial
	 *
	 * @param float|int $degree
	 */
	public function getCoefficient(int|float $degree): int|float|null
	{
		return $this->coefficients[(is_countable($this->coefficients) ? count($this->coefficients) : 0) - 1 - $degree];
	}

	public function multiply($other): self
	{
		$aCoefficients = [];
		$bCoefficients = [];
		$aLength = null;
		$bLength = null;
		$product = [];
		if (is_int($other)) {
			return $this->multiply_($other);
		}
		if ($this->field !== $other->field) {
			throw new \InvalidArgumentException("GenericGFPolys do not have same GenericGF field");
		}
		if ($this->isZero() || $other->isZero()) {
			return $this->field->getZero();
		}
		$aCoefficients = $this->coefficients;
		$aLength = count($aCoefficients);
		$bCoefficients = $other->coefficients;
		$bLength = count($bCoefficients);
		$product = fill_array(0, $aLength + $bLength - 1, 0);
		for ($i = 0; $i < $aLength; $i++) {
			$aCoeff = $aCoefficients[$i];
			for ($j = 0; $j < $bLength; $j++) {
				$product[$i + $j] = GenericGF::addOrSubtract(
					$product[$i + $j],
					$this->field->multiply($aCoeff, $bCoefficients[$j])
				);
			}
		}

		return new GenericGFPoly($this->field, $product);
	}

	public function multiply_(int $scalar): self
	{
		if ($scalar == 0) {
			return $this->field->getZero();
		}
		if ($scalar == 1) {
			return $this;
		}
		$size = is_countable($this->coefficients) ? count($this->coefficients) : 0;
		$product = fill_array(0, $size, 0);
		for ($i = 0; $i < $size; $i++) {
			$product[$i] = $this->field->multiply($this->coefficients[$i], $scalar);
		}

		return new GenericGFPoly($this->field, $product);
	}

	/**
	 * @return bool iff this polynomial is the monomial "0"
	 */
	public function isZero(): bool
	{
		return $this->coefficients[0] == 0;
	}

	public function multiplyByMonomial($degree, $coefficient): self
	{
		if ($degree < 0) {
			throw new \InvalidArgumentException();
		}
		if ($coefficient == 0) {
			return $this->field->getZero();
		}
		$size = is_countable($this->coefficients) ? count($this->coefficients) : 0;
		$product = fill_array(0, $size + $degree, 0);
		for ($i = 0; $i < $size; $i++) {
			$product[$i] = $this->field->multiply($this->coefficients[$i], $coefficient);
		}

		return new GenericGFPoly($this->field, $product);
	}

	/**
	 * @psalm-return array{0: mixed, 1: mixed}
	 */
	public function divide($other): array
	{
		if ($this->field !== $other->field) {
			throw new \InvalidArgumentException("GenericGFPolys do not have same GenericGF field");
		}
		if ($other->isZero()) {
			throw new \InvalidArgumentException("Divide by 0");
		}

		$quotient = $this->field->getZero();
		$remainder = $this;

		$denominatorLeadingTerm = $other->getCoefficient($other->getDegree());
		$inverseDenominatorLeadingTerm = $this->field->inverse($denominatorLeadingTerm);

		while ($remainder->getDegree() >= $other->getDegree() && !$remainder->isZero()) {
			$degreeDifference = $remainder->getDegree() - $other->getDegree();
			$scale = $this->field->multiply($remainder->getCoefficient($remainder->getDegree()), $inverseDenominatorLeadingTerm);
			$term = $other->multiplyByMonomial($degreeDifference, $scale);
			$iterationQuotient = $this->field->buildMonomial($degreeDifference, $scale);
			$quotient = $quotient->addOrSubtract($iterationQuotient);
			$remainder = $remainder->addOrSubtract($term);
		}

		return [$quotient, $remainder];
	}

	/**
	 * @return int of this polynomial
	 */
	public function getDegree(): int
	{
		return (is_countable($this->coefficients) ? count($this->coefficients) : 0) - 1;
	}

	public function addOrSubtract(self $other): self
	{
		$smallerCoefficients = [];
		$largerCoefficients = [];
		$sumDiff = [];
		$lengthDiff = null;
		$countLargerCoefficients = null;
		if ($this->field !== $other->field) {
			throw new \InvalidArgumentException("GenericGFPolys do not have same GenericGF field");
		}
		if ($this->isZero()) {
			return $other;
		}
		if ($other->isZero()) {
			return $this;
		}

		$smallerCoefficients = $this->coefficients;
		$largerCoefficients = $other->coefficients;
		if (count($smallerCoefficients) > count($largerCoefficients)) {
			$temp = $smallerCoefficients;
			$smallerCoefficients = $largerCoefficients;
			$largerCoefficients = $temp;
		}
		$sumDiff = fill_array(0, count($largerCoefficients), 0);
		$lengthDiff = count($largerCoefficients) - count($smallerCoefficients);
		// Copy high-order terms only found in higher-degree polynomial's coefficients
		$sumDiff = arraycopy($largerCoefficients, 0, $sumDiff, 0, $lengthDiff);

		$countLargerCoefficients = count($largerCoefficients);
		for ($i = $lengthDiff; $i < $countLargerCoefficients; $i++) {
			$sumDiff[$i] = GenericGF::addOrSubtract($smallerCoefficients[$i - $lengthDiff], $largerCoefficients[$i]);
		}

		return new GenericGFPoly($this->field, $sumDiff);
	}

	

	public function toString(): string
	{
		$result = '';
		for ($degree = $this->getDegree(); $degree >= 0; $degree--) {
			$coefficient = $this->getCoefficient($degree);
			if ($coefficient != 0) {
				if ($coefficient < 0) {
					$result .= " - ";
					$coefficient = -$coefficient;
				} else {
					if (strlen((string) $result) > 0) {
						$result .= " + ";
					}
				}
				if ($degree == 0 || $coefficient != 1) {
					$alphaPower = $this->field->log($coefficient);
					if ($alphaPower == 0) {
						$result .= '1';
					} elseif ($alphaPower == 1) {
						$result .= 'a';
					} else {
						$result .= "a^";
						$result .= ($alphaPower);
					}
				}
				if ($degree != 0) {
					if ($degree == 1) {
						$result .= 'x';
					} else {
						$result .= "x^";
						$result .= $degree;
					}
				}
			}
		}

		return $result;
	}
}

ReedSolomonDecoder.php
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Common\Reedsolomon;

/**
 * <p>Implements Reed-Solomon decoding, as the name implies.</p>
 *
 * <p>The algorithm will not be explained here, but the following references were helpful
 * in creating this implementation:</p>
 *
 * <ul>
 * <li>Bruce Maggs.
 * <a href="http://www.cs.cmu.edu/afs/cs.cmu.edu/project/pscico-guyb/realworld/www/rs_decode.ps">
 * "Decoding Reed-Solomon Codes"</a> (see discussion of Forney's Formula)</li>
 * <li>J.I. Hall. <a href="www.mth.msu.edu/~jhall/classes/codenotes/GRS.pdf">
 * "Chapter 5. Generalized Reed-Solomon Codes"</a>
 * (see discussion of Euclidean algorithm)</li>
 * </ul>
 *
 * <p>Much credit is due to William Rucklidge since portions of this code are an indirect
 * port of his C++ Reed-Solomon implementation.</p>
 *
 * @author Sean Owen
 * @author William Rucklidge
 * @author sanfordsquires
 */
final class ReedSolomonDecoder
{
	public function __construct(private $field)
	{
	}

	/**
	 * <p>Decodes given set of received codewords, which include both data and error-correction
	 * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
	 * in the input.</p>
	 *
	 * @param array $received data and error-correction codewords
	 * @param int|float $twoS number     of error-correction codewords available
	 *
	 * @throws ReedSolomonException if decoding fails for any reason
	 *
	 * @return void
	 */
	public function decode(&$received, $twoS)
	{
		$poly = new GenericGFPoly($this->field, $received);
		$syndromeCoefficients = fill_array(0, $twoS, 0);
		$noError = true;
		for ($i = 0; $i < $twoS; $i++) {
			$eval = $poly->evaluateAt($this->field->exp($i + $this->field->getGeneratorBase()));
			$syndromeCoefficients[(is_countable($syndromeCoefficients) ? count($syndromeCoefficients) : 0) - 1 - $i] = $eval;
			if ($eval != 0) {
				$noError = false;
			}
		}
		if ($noError) {
			return;
		}
		$syndrome = new GenericGFPoly($this->field, $syndromeCoefficients);
		$sigmaOmega =
			$this->runEuclideanAlgorithm($this->field->buildMonomial($twoS, 1), $syndrome, $twoS);
		$sigma = $sigmaOmega[0];
		$omega = $sigmaOmega[1];
		$errorLocations = $this->findErrorLocations($sigma);
		$errorMagnitudes = $this->findErrorMagnitudes($omega, $errorLocations);
		$errorLocationsCount = is_countable($errorLocations) ? count($errorLocations) : 0;
		for ($i = 0; $i < $errorLocationsCount; $i++) {
			$position = (is_countable($received) ? count($received) : 0) - 1 - $this->field->log($errorLocations[$i]);
			if ($position < 0) {
				throw new ReedSolomonException("Bad error location");
			}
			$received[$position] = GenericGF::addOrSubtract($received[$position], $errorMagnitudes[$i]);
		}
	}

	/**
	 * @psalm-return array{0: mixed, 1: mixed}
	 */
	private function runEuclideanAlgorithm($a, \Zxing\Common\Reedsolomon\GenericGFPoly $b, int|float $R): array
	{
		// Assume a's degree is >= b's
		if ($a->getDegree() < $b->getDegree()) {
			$temp = $a;
			$a = $b;
			$b = $temp;
		}

		$rLast = $a;
		$r = $b;
		$tLast = $this->field->getZero();
		$t = $this->field->getOne();

		// Run Euclidean algorithm until r's degree is less than R/2
		while ($r->getDegree() >= $R / 2) {
			$rLastLast = $rLast;
			$tLastLast = $tLast;
			$rLast = $r;
			$tLast = $t;

			// Divide rLastLast by rLast, with quotient in q and remainder in r
			if ($rLast->isZero()) {
				// Oops, Euclidean algorithm already terminated?
				throw new ReedSolomonException("r_{i-1} was zero");
			}
			$r = $rLastLast;
			$q = $this->field->getZero();
			$denominatorLeadingTerm = $rLast->getCoefficient($rLast->getDegree());
			$dltInverse = $this->field->inverse($denominatorLeadingTerm);
			while ($r->getDegree() >= $rLast->getDegree() && !$r->isZero()) {
				$degreeDiff = $r->getDegree() - $rLast->getDegree();
				$scale = $this->field->multiply($r->getCoefficient($r->getDegree()), $dltInverse);
				$q = $q->addOrSubtract($this->field->buildMonomial($degreeDiff, $scale));
				$r = $r->addOrSubtract($rLast->multiplyByMonomial($degreeDiff, $scale));
			}

			$t = $q->multiply($tLast)->addOrSubtract($tLastLast);

			if ($r->getDegree() >= $rLast->getDegree()) {
				throw new ReedSolomonException("Division algorithm failed to reduce polynomial?");
			}
		}

		$sigmaTildeAtZero = $t->getCoefficient(0);
		if ($sigmaTildeAtZero == 0) {
			throw new ReedSolomonException("sigmaTilde(0) was zero");
		}

		$inverse = $this->field->inverse($sigmaTildeAtZero);
		$sigma = $t->multiply($inverse);
		$omega = $r->multiply($inverse);

		return [$sigma, $omega];
	}

	/**
	 * @psalm-return array<int, mixed>
	 */
	private function findErrorLocations($errorLocator): array
	{
		// This is a direct application of Chien's search
		$numErrors = $errorLocator->getDegree();
		if ($numErrors == 1) { // shortcut
			return [$errorLocator->getCoefficient(1)];
		}
		$result = fill_array(0, $numErrors, 0);
		$e = 0;
		for ($i = 1; $i < $this->field->getSize() && $e < $numErrors; $i++) {
			if ($errorLocator->evaluateAt($i) == 0) {
				$result[$e] = $this->field->inverse($i);
				$e++;
			}
		}
		if ($e != $numErrors) {
			throw new ReedSolomonException("Error locator degree does not match number of roots");
		}

		return $result;
	}

	/**
	 * @psalm-return array<int, mixed>
	 * @psalm-param array<int, mixed> $errorLocations
	 */
	private function findErrorMagnitudes($errorEvaluator, array $errorLocations): array
	{
		// This is directly applying Forney's Formula
		$s = is_countable($errorLocations) ? count($errorLocations) : 0;
		$result = fill_array(0, $s, 0);
		for ($i = 0; $i < $s; $i++) {
			$xiInverse = $this->field->inverse($errorLocations[$i]);
			$denominator = 1;
			for ($j = 0; $j < $s; $j++) {
				if ($i != $j) {
					//denominator = field.multiply(denominator,
					//    GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)));
					// Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
					// Below is a funny-looking workaround from Steven Parkes
					$term = $this->field->multiply($errorLocations[$j], $xiInverse);
					$termPlus1 = ($term & 0x1) == 0 ? $term | 1 : $term & ~1;
					$denominator = $this->field->multiply($denominator, $termPlus1);
				}
			}
			$result[$i] = $this->field->multiply(
				$errorEvaluator->evaluateAt($xiInverse),
				$this->field->inverse($denominator)
			);
			if ($this->field->getGeneratorBase() != 0) {
				$result[$i] = $this->field->multiply($result[$i], $xiInverse);
			}
		}

		return $result;
	}
}

ReedSolomonException.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Common\Reedsolomon;

/**
 * <p>Thrown when an exception occurs during Reed-Solomon decoding, such as when
 * there are too many errors to correct.</p>
 *
 * @author Sean Owen
 */
final class ReedSolomonException extends \Exception
{
}

MathUtils.php
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2012 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Common\Detector;

final class MathUtils
{
	private function __construct()
	{
	}

	/**
	 * Ends up being a bit faster than {@link Math#round(float)}. This merely rounds its
	 * argument to the nearest int, where x.5 rounds up to x+1. Semantics of this shortcut
	 * differ slightly from {@link Math#round(float)} in that half rounds down for negative
	 * values. -2.5 rounds to -3, not -2. For purposes here it makes no difference.
	 *
	 * @param float $d real value to round
	 *
	 * @return int {@code int}
	 */
	public static function round(float $d)
	{
		return (int)($d + ($d < 0.0 ? -0.5 : 0.5));
	}

	public static function distance(float|int $aX, float|int $aY, float $bX, float $bY): float
	{
		$xDiff = $aX - $bX;
		$yDiff = $aY - $bY;

		return (float)sqrt($xDiff * $xDiff + $yDiff * $yDiff);
	}
}

MonochromeRectangleDetector.php
Script de practica.
Abrir
Ver codigo

<?php
/**
 * Created by PhpStorm.
 * User: Ashot
 * Date: 3/24/15
 * Time: 21:23
 */

namespace Zxing\Common\Detector;

use Zxing\BinaryBitmap;
use Zxing\NotFoundException;
use Zxing\ResultPoint;

/*
 *
 *
import com.google.zxing.NotFoundException;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.BitMatrix;

 */
//require_once('./lib/NotFoundException.php');
//require_once('./lib/ResultPoint.php');
//require_once('./lib/common/BitMatrix.php');


/**
 * <p>A somewhat generic detector that looks for a barcode-like rectangular region within an image.
 * It looks within a mostly white region of an image for a region of black and white, but mostly
 * black. It returns the four corners of the region, as best it can determine.</p>
 *
 * @author Sean Owen
 * @port   Ashot Khanamiryan
 */
class MonochromeRectangleDetector
{
	private static int $MAX_MODULES = 32;

	public function __construct(private readonly BinaryBitmap $image)
	{
	}

	/**
	 * <p>Detects a rectangular region of black and white -- mostly black -- with a region of mostly
	 * white, in an image.</p>
	 *
	 * @return {@link ResultPoint}[] describing the corners of the rectangular region. The first and
	 *  last points are opposed on the diagonal, as are the second and third. The first point will be
	 *  the topmost point and the last, the bottommost. The second point will be leftmost and the
	 *  third, the rightmost
	 * @throws NotFoundException if no Data Matrix Code can be found
	 */
	public function detect(): \Zxing\ResultPoint
	{
		$height = $this->image->getHeight();
		$width = $this->image->getWidth();
		$halfHeight = $height / 2;
		$halfWidth = $width / 2;

		$deltaY = max(1, $height / (self::$MAX_MODULES * 8));
		$deltaX = max(1, $width / (self::$MAX_MODULES * 8));


		$top = 0;
		$bottom = $height;
		$left = 0;
		$right = $width;
		$pointA = $this->findCornerFromCenter(
			$halfWidth,
			0,
			$left,
			$right,
			$halfHeight,
			-$deltaY,
			$top,
			$bottom,
			$halfWidth / 2
		);
		$top = (int)$pointA->getY() - 1;
		$pointB = $this->findCornerFromCenter(
			$halfWidth,
			-$deltaX,
			$left,
			$right,
			$halfHeight,
			0,
			$top,
			$bottom,
			$halfHeight / 2
		);
		$left = (int)$pointB->getX() - 1;
		$pointC = $this->findCornerFromCenter(
			$halfWidth,
			$deltaX,
			$left,
			$right,
			$halfHeight,
			0,
			$top,
			$bottom,
			$halfHeight / 2
		);
		$right = (int)$pointC->getX() + 1;
		$pointD = $this->findCornerFromCenter(
			$halfWidth,
			0,
			$left,
			$right,
			$halfHeight,
			$deltaY,
			$top,
			$bottom,
			$halfWidth / 2
		);
		$bottom = (int)$pointD->getY() + 1;

		// Go try to find po$A again with better information -- might have been off at first.
		$pointA = $this->findCornerFromCenter(
			$halfWidth,
			0,
			$left,
			$right,
			$halfHeight,
			-$deltaY,
			$top,
			$bottom,
			$halfWidth / 4
		);

		return new ResultPoint($pointA, $pointB, $pointC, $pointD);
	}


	/**
	 * Attempts to locate a corner of the barcode by scanning up, down, left or right from a center
	 * point which should be within the barcode.
	 *
	 * @param float $centerX     center's x component (horizontal)
	 * @param float $deltaX      same as deltaY but change in x per step instead
	 * @param int $left
	 * @param int $right
	 * @param float $centerY     center's y component (vertical)
	 * @param float $deltaY      change in y per step. If scanning up this is negative; down, positive;
	 *                    left or right, 0
	 * @param int $top
	 * @param int $bottom
	 * @param float $maxWhiteRun maximum run of white pixels that can still be considered to be within
	 *                    the barcode
	 *
	 * @return ResultPoint {@link com.google.zxing.ResultPoint} encapsulating the corner that was found
	 *
	 * @throws NotFoundException if such a point cannot be found
	 */
	private function findCornerFromCenter(
		int|float $centerX,
		int|float $deltaX,
		int $left,
		int $right,
		int|float $centerY,
		float|int $deltaY,
		int $top,
		int $bottom,
		int|float $maxWhiteRun
	): \Zxing\ResultPoint {
		$lastRange = null;
		for ($y = $centerY, $x = $centerX;
			 $y < $bottom && $y >= $top && $x < $right && $x >= $left;
			 $y += $deltaY, $x += $deltaX) {
			$range = 0;
			if ($deltaX == 0) {
				// horizontal slices, up and down
				$range = $this->blackWhiteRange($y, $maxWhiteRun, $left, $right, true);
			} else {
				// vertical slices, left and right
				$range = $this->blackWhiteRange($x, $maxWhiteRun, $top, $bottom, false);
			}
			if ($range == null) {
				if ($lastRange == null) {
					throw new NotFoundException("No corner from center found");
				}
				// lastRange was found
				if ($deltaX == 0) {
					$lastY = $y - $deltaY;
					if ($lastRange[0] < $centerX) {
						if ($lastRange[1] > $centerX) {
							// straddle, choose one or the other based on direction
							return new ResultPoint($deltaY > 0 ? $lastRange[0] : $lastRange[1], $lastY);
						}

						return new ResultPoint($lastRange[0], $lastY);
					} else {
						return new ResultPoint($lastRange[1], $lastY);
					}
				} else {
					$lastX = $x - $deltaX;
					if ($lastRange[0] < $centerY) {
						if ($lastRange[1] > $centerY) {
							return new ResultPoint($lastX, $deltaX < 0 ? $lastRange[0] : $lastRange[1]);
						}

						return new ResultPoint($lastX, $lastRange[0]);
					} else {
						return new ResultPoint($lastX, $lastRange[1]);
					}
				}
			}
			$lastRange = $range;
		}
		throw new NotFoundException("No corner from center found");
	}


	/**
	 * Computes the start and end of a region of pixels, either horizontally or vertically, that could
	 * be part of a Data Matrix barcode.
	 *
	 * @param float|int $fixedDimension
	 * @param float|int $maxWhiteRun
	 * @param int $minDim
	 * @param int $maxDim
	 * @param bool $horizontal
	 *
	 * @return (float|int)[]|null with start and end of found range, or null if no such range is found (e.g. only white was found)
	 *
	 * @psalm-return array{0: float|int, 1: float|int}|null
	 */
	private function blackWhiteRange(float|int $fixedDimension, int|float $maxWhiteRun, int $minDim, int $maxDim, bool $horizontal): array|null
	{
		$center = ($minDim + $maxDim) / 2;

		// Scan left/up first
		$start = $center;
		while ($start >= $minDim) {
			if ($horizontal ? $this->image->get($start, $fixedDimension) : $this->image->get($fixedDimension, $start)) {
				$start--;
			} else {
				$whiteRunStart = $start;
				do {
					$start--;
				} while ($start >= $minDim && !($horizontal ? $this->image->get($start, $fixedDimension) :
					$this->image->get($fixedDimension, $start)));
				$whiteRunSize = $whiteRunStart - $start;
				if ($start < $minDim || $whiteRunSize > $maxWhiteRun) {
					$start = $whiteRunStart;
					break;
				}
			}
		}
		$start++;

		// Then try right/down
		$end = $center;
		while ($end < $maxDim) {
			if ($horizontal ? $this->image->get($end, $fixedDimension) : $this->image->get($fixedDimension, $end)) {
				$end++;
			} else {
				$whiteRunStart = $end;
				do {
					$end++;
				} while ($end < $maxDim && !($horizontal ? $this->image->get($end, $fixedDimension) :
					$this->image->get($fixedDimension, $end)));
				$whiteRunSize = $end - $whiteRunStart;
				if ($end >= $maxDim || $whiteRunSize > $maxWhiteRun) {
					$end = $whiteRunStart;
					break;
				}
			}
		}
		$end--;

		return $end > $start ? [$start, $end] : null;
	}
}

QRCodeReader.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode;

use Zxing\BinaryBitmap;
use Zxing\ChecksumException;
use Zxing\Common\BitMatrix;
use Zxing\FormatException;
use Zxing\NotFoundException;
use Zxing\Qrcode\Decoder\Decoder;
use Zxing\Qrcode\Detector\Detector;
use Zxing\Reader;
use Zxing\Result;

/**
 * This implementation can detect and decode QR Codes in an image.
 *
 * @author Sean Owen
 */
class QRCodeReader implements Reader
{
	private static array $NO_POINTS = [];
	private readonly Decoder $decoder;

	public function __construct()
	{
		$this->decoder = new Decoder();
	}

	/**
  * @param null         $hints
  *
  * @return Result
  * @throws \Zxing\FormatException
  * @throws \Zxing\NotFoundException
  */
	public function decode(BinaryBitmap $image, $hints = null)
	{
		$decoderResult = null;
		if ($hints !== null && array_key_exists('PURE_BARCODE', $hints) && $hints['PURE_BARCODE']) {
			$bits = self::extractPureBits($image->getBlackMatrix());
			$decoderResult = $this->decoder->decode($bits, $hints);
			$points = self::$NO_POINTS;
		} else {
			$detector = new Detector($image->getBlackMatrix());
			$detectorResult = $detector->detect($hints);

			$decoderResult = $this->decoder->decode($detectorResult->getBits(), $hints);
			$points = $detectorResult->getPoints();
		}
		$result = new Result($decoderResult->getText(), $decoderResult->getRawBytes(), $points, 'QR_CODE');//BarcodeFormat.QR_CODE

		$byteSegments = $decoderResult->getByteSegments();
		if ($byteSegments !== null) {
			$result->putMetadata('BYTE_SEGMENTS', $byteSegments);//ResultMetadataType.BYTE_SEGMENTS
		}
		$ecLevel = $decoderResult->getECLevel();
		if ($ecLevel !== null) {
			$result->putMetadata('ERROR_CORRECTION_LEVEL', $ecLevel);//ResultMetadataType.ERROR_CORRECTION_LEVEL
		}
		if ($decoderResult->hasStructuredAppend()) {
			$result->putMetadata(
				'STRUCTURED_APPEND_SEQUENCE',//ResultMetadataType.STRUCTURED_APPEND_SEQUENCE
				$decoderResult->getStructuredAppendSequenceNumber()
			);
			$result->putMetadata(
				'STRUCTURED_APPEND_PARITY',//ResultMetadataType.STRUCTURED_APPEND_PARITY
				$decoderResult->getStructuredAppendParity()
			);
		}

		return $result;
	}

	/**
	 * Locates and decodes a QR code in an image.
	 * This method detects a code in a "pure" image -- that is, pure monochrome image
	 * which contains only an unrotated, unskewed, image of a code, with some white border
	 * around it. This is a specialized method that works exceptionally fast in this special
	 * case.
	 *
	 * @return BitMatrix a String representing the content encoded by the QR code
	 * @throws NotFoundException if a QR code cannot be found
	 * @throws FormatException if a QR code cannot be decoded
	 * @throws ChecksumException if error correction fails
	 *
	 * @see com.google.zxing.datamatrix.DataMatrixReader#extractPureBits(BitMatrix)
	 */
	private static function extractPureBits(BitMatrix $image): BitMatrix
	{
		$leftTopBlack = $image->getTopLeftOnBit();
		$rightBottomBlack = $image->getBottomRightOnBit();
		if ($leftTopBlack === null || $rightBottomBlack == null) {
			throw new NotFoundException("Top left or bottom right on bit not found");
		}

		$moduleSize = self::moduleSize($leftTopBlack, $image);

		$top = $leftTopBlack[1];
		$bottom = $rightBottomBlack[1];
		$left = $leftTopBlack[0];
		$right = $rightBottomBlack[0];

		// Sanity check!
		if ($left >= $right || $top >= $bottom) {
			throw new NotFoundException("Left vs. right ($left >= $right) or top vs. bottom ($top >= $bottom) sanity violated.");
		}

		if ($bottom - $top != $right - $left) {
			// Special case, where bottom-right module wasn't black so we found something else in the last row
			// Assume it's a square, so use height as the width
			$right = $left + ($bottom - $top);
		}

		$matrixWidth = round(($right - $left + 1) / $moduleSize);
		$matrixHeight = round(($bottom - $top + 1) / $moduleSize);
		if ($matrixWidth <= 0 || $matrixHeight <= 0) {
			throw new NotFoundException("Matrix dimensions <= 0 ($matrixWidth, $matrixHeight)");
		}
		if ($matrixHeight != $matrixWidth) {
			// Only possibly decode square regions
			throw new NotFoundException("Matrix height  $matrixHeight != matrix width $matrixWidth");
		}

		// Push in the "border" by half the module width so that we start
		// sampling in the middle of the module. Just in case the image is a
		// little off, this will help recover.
		$nudge = (int)($moduleSize / 2.0);// $nudge = (int) ($moduleSize / 2.0f);
		$top += $nudge;
		$left += $nudge;

		// But careful that this does not sample off the edge
		// "right" is the farthest-right valid pixel location -- right+1 is not necessarily
		// This is positive by how much the inner x loop below would be too large
		$nudgedTooFarRight = $left + (int)(($matrixWidth - 1) * $moduleSize) - $right;
		if ($nudgedTooFarRight > 0) {
			if ($nudgedTooFarRight > $nudge) {
				// Neither way fits; abort
				throw new NotFoundException("Nudge too far right ($nudgedTooFarRight > $nudge), no fit found");
			}
			$left -= $nudgedTooFarRight;
		}
		// See logic above
		$nudgedTooFarDown = $top + (int)(($matrixHeight - 1) * $moduleSize) - $bottom;
		if ($nudgedTooFarDown > 0) {
			if ($nudgedTooFarDown > $nudge) {
				// Neither way fits; abort
				throw new NotFoundException("Nudge too far down ($nudgedTooFarDown > $nudge), no fit found");
			}
			$top -= $nudgedTooFarDown;
		}

		// Now just read off the bits
		$bits = new BitMatrix($matrixWidth, $matrixHeight);
		for ($y = 0; $y < $matrixHeight; $y++) {
			$iOffset = (int)($top + (int)($y * $moduleSize));
			for ($x = 0; $x < $matrixWidth; $x++) {
				if ($image->get((int)($left + (int)($x * $moduleSize)), $iOffset)) {
					$bits->set($x, $y);
				}
			}
		}

		return $bits;
	}

	/**
	 * @psalm-param array{0: mixed, 1: mixed} $leftTopBlack
	 */
	private static function moduleSize(array $leftTopBlack, BitMatrix $image)
	{
		$height = $image->getHeight();
		$width = $image->getWidth();
		$x = $leftTopBlack[0];
		$y = $leftTopBlack[1];
		/*$x           = $leftTopBlack[0];
		$y           = $leftTopBlack[1];*/
		$inBlack = true;
		$transitions = 0;
		while ($x < $width && $y < $height) {
			if ($inBlack != $image->get((int)round($x), (int)round($y))) {
				if (++$transitions == 5) {
					break;
				}
				$inBlack = !$inBlack;
			}
			$x++;
			$y++;
		}
		if ($x == $width || $y == $height) {
			throw new NotFoundException("$x == $width || $y == $height");
		}

		return ($x - $leftTopBlack[0]) / 7.0; //return ($x - $leftTopBlack[0]) / 7.0f;
	}

	public function reset(): void
	{
		// do nothing
	}

	final protected function getDecoder(): Decoder
	{
		return $this->decoder;
	}
}

BitMatrixParser.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Decoder;

use Zxing\Common\BitMatrix;
use Zxing\FormatException;

/**
 * @author Sean Owen
 */
final class BitMatrixParser
{
	private $bitMatrix;
	/**
  * @var mixed|null
  */
	private $parsedVersion;
	private $parsedFormatInfo;
	private $mirror;

	/**
	 * @param $bitMatrix {@link BitMatrix} to parse
	 *
	 * @throws FormatException if dimension is not >= 21 and 1 mod 4
	 */
	public function __construct($bitMatrix)
	{
		$dimension = $bitMatrix->getHeight();
		if ($dimension < 21 || ($dimension & 0x03) != 1) {
			throw new FormatException();
		}
		$this->bitMatrix = $bitMatrix;
	}

	/**
	 * <p>Reads the bits in the {@link BitMatrix} representing the finder pattern in the
	 * correct order in order to reconstruct the codewords bytes contained within the
	 * QR Code.</p>
	 *
	 * @return array bytes encoded within the QR Code
	 * @throws FormatException if the exact number of bytes expected is not read
	 */
	public function readCodewords()
	{
		$formatInfo = $this->readFormatInformation();
		$version = $this->readVersion();

		// Get the data mask for the format used in this QR Code. This will exclude
		// some bits from reading as we wind through the bit matrix.
		$dataMask = DataMask::forReference($formatInfo->getDataMask());
		$dimension = $this->bitMatrix->getHeight();
		$dataMask->unmaskBitMatrix($this->bitMatrix, $dimension);

		$functionPattern = $version->buildFunctionPattern();

		$readingUp = true;
		if ($version->getTotalCodewords()) {
			$result = fill_array(0, $version->getTotalCodewords(), 0);
		} else {
			$result = [];
		}
		$resultOffset = 0;
		$currentByte = 0;
		$bitsRead = 0;
		// Read columns in pairs, from right to left
		for ($j = $dimension - 1; $j > 0; $j -= 2) {
			if ($j == 6) {
				// Skip whole column with vertical alignment pattern;
				// saves time and makes the other code proceed more cleanly
				$j--;
			}
			// Read alternatingly from bottom to top then top to bottom
			for ($count = 0; $count < $dimension; $count++) {
				$i = $readingUp ? $dimension - 1 - $count : $count;
				for ($col = 0; $col < 2; $col++) {
					// Ignore bits covered by the function pattern
					if (!$functionPattern->get($j - $col, $i)) {
						// Read a bit
						$bitsRead++;
						$currentByte <<= 1;
						if ($this->bitMatrix->get($j - $col, $i)) {
							$currentByte |= 1;
						}
						// If we've made a whole byte, save it off
						if ($bitsRead == 8) {
							$result[$resultOffset++] = $currentByte; //(byte)
							$bitsRead = 0;
							$currentByte = 0;
						}
					}
				}
			}
			$readingUp ^= true; // readingUp = !readingUp; // switch directions
		}
		if ($resultOffset != $version->getTotalCodewords()) {
			throw new FormatException();
		}

		return $result;
	}

	/**
	 * <p>Reads format information from one of its two locations within the QR Code.</p>
	 *
	 * @return {@link FormatInformation} encapsulating the QR Code's format info
	 * @throws FormatException if both format information locations cannot be parsed as
	 * the valid encoding of format information
	 */
	public function readFormatInformation()
	{
		if ($this->parsedFormatInfo != null) {
			return $this->parsedFormatInfo;
		}

		// Read top-left format info bits
		$formatInfoBits1 = 0;
		for ($i = 0; $i < 6; $i++) {
			$formatInfoBits1 = $this->copyBit($i, 8, $formatInfoBits1);
		}
		// .. and skip a bit in the timing pattern ...
		$formatInfoBits1 = $this->copyBit(7, 8, $formatInfoBits1);
		$formatInfoBits1 = $this->copyBit(8, 8, $formatInfoBits1);
		$formatInfoBits1 = $this->copyBit(8, 7, $formatInfoBits1);
		// .. and skip a bit in the timing pattern ...
		for ($j = 5; $j >= 0; $j--) {
			$formatInfoBits1 = $this->copyBit(8, $j, $formatInfoBits1);
		}

		// Read the top-right/bottom-left pattern too
		$dimension = $this->bitMatrix->getHeight();
		$formatInfoBits2 = 0;
		$jMin = $dimension - 7;
		for ($j = $dimension - 1; $j >= $jMin; $j--) {
			$formatInfoBits2 = $this->copyBit(8, $j, $formatInfoBits2);
		}
		for ($i = $dimension - 8; $i < $dimension; $i++) {
			$formatInfoBits2 = $this->copyBit($i, 8, $formatInfoBits2);
		}

		$parsedFormatInfo = FormatInformation::decodeFormatInformation($formatInfoBits1, $formatInfoBits2);
		if ($parsedFormatInfo != null) {
			return $parsedFormatInfo;
		}
		throw new FormatException();
	}

	/**
	 * @psalm-param 0 $versionBits
	 *
	 * @psalm-return 0|1
	 */
	private function copyBit(int|float $i, int|float $j, int $versionBits): int
	{
		$bit = $this->mirror ? $this->bitMatrix->get($j, $i) : $this->bitMatrix->get($i, $j);

		return $bit ? ($versionBits << 1) | 0x1 : $versionBits << 1;
	}

	/**
	 * <p>Reads version information from one of its two locations within the QR Code.</p>
	 *
	 * @return {@link Version} encapsulating the QR Code's version
	 * @throws FormatException if both version information locations cannot be parsed as
	 * the valid encoding of version information
	 */
	public function readVersion()
	{
		if ($this->parsedVersion != null) {
			return $this->parsedVersion;
		}

		$dimension = $this->bitMatrix->getHeight();

		$provisionalVersion = ($dimension - 17) / 4;
		if ($provisionalVersion <= 6) {
			return Version::getVersionForNumber($provisionalVersion);
		}

		// Read top-right version info: 3 wide by 6 tall
		$versionBits = 0;
		$ijMin = $dimension - 11;
		for ($j = 5; $j >= 0; $j--) {
			for ($i = $dimension - 9; $i >= $ijMin; $i--) {
				$versionBits = $this->copyBit($i, $j, $versionBits);
			}
		}

		$theParsedVersion = Version::decodeVersionInformation($versionBits);
		if ($theParsedVersion != null && $theParsedVersion->getDimensionForVersion() == $dimension) {
			$this->parsedVersion = $theParsedVersion;

			return $theParsedVersion;
		}

		// Hmm, failed. Try bottom left: 6 wide by 3 tall
		$versionBits = 0;
		for ($i = 5; $i >= 0; $i--) {
			for ($j = $dimension - 9; $j >= $ijMin; $j--) {
				$versionBits = $this->copyBit($i, $j, $versionBits);
			}
		}

		$theParsedVersion = Version::decodeVersionInformation($versionBits);
		if ($theParsedVersion != null && $theParsedVersion->getDimensionForVersion() == $dimension) {
			$this->parsedVersion = $theParsedVersion;

			return $theParsedVersion;
		}
		throw new FormatException("both version information locations cannot be parsed as the valid encoding of version information");
	}

	/**
	 * Revert the mask removal done while reading the code words. The bit matrix should revert to its original state.
	 */
	public function remask(): void
	{
		if ($this->parsedFormatInfo == null) {
			return; // We have no format information, and have no data mask
		}
		$dataMask = DataMask::forReference($this->parsedFormatInfo->getDataMask());
		$dimension = $this->bitMatrix->getHeight();
		$dataMask->unmaskBitMatrix($this->bitMatrix, $dimension);
	}

	/**
	 * Prepare the parser for a mirrored operation.
	 * This flag has effect only on the {@link #readFormatInformation()} and the
	 * {@link #readVersion()}. Before proceeding with {@link #readCodewords()} the
	 * {@link #mirror()} method should be called.
	 *
	 * @param bool $mirror Whether to read version and format information mirrored.
	 */
	public function setMirror($mirror): void
	{
		$parsedVersion = null;
		$parsedFormatInfo = null;
		$this->mirror = $mirror;
	}

	/** Mirror the bit matrix in order to attempt a second reading. */
	public function mirror(): void
	{
		for ($x = 0; $x < $this->bitMatrix->getWidth(); $x++) {
			for ($y = $x + 1; $y < $this->bitMatrix->getHeight(); $y++) {
				if ($this->bitMatrix->get($x, $y) != $this->bitMatrix->get($y, $x)) {
					$this->bitMatrix->flip($y, $x);
					$this->bitMatrix->flip($x, $y);
				}
			}
		}
	}
}

DataBlock.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Decoder;

/**
 * <p>Encapsulates a block of data within a QR Code. QR Codes may split their data into
 * multiple blocks, each of which is a unit of data and error-correction codewords. Each
 * is represented by an instance of this class.</p>
 *
 * @author Sean Owen
 */
final class DataBlock
{
	//byte[]

	private function __construct(private $numDataCodewords, private $codewords)
	{
	}

	/**
	 * <p>When QR Codes use multiple data blocks, they are actually interleaved.
	 * That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This
	 * method will separate the data into original blocks.</p>
	 *
	 * @param array $rawCodewords as read directly from the QR Code
	 * @param Version $version of the QR Code
	 * @param ErrorCorrectionLevel $ecLevel error-correction level of the QR Code
	 *
	 * @return \Zxing\Qrcode\Decoder\DataBlock[] DataBlocks containing original bytes, "de-interleaved" from representation in the
		 QR Code
	 */
	public static function getDataBlocks(
		$rawCodewords,
		Version $version,
		ErrorCorrectionLevel $ecLevel
	): array {
		if ((is_countable($rawCodewords) ? count($rawCodewords) : 0) != $version->getTotalCodewords()) {
			throw new \InvalidArgumentException();
		}

		// Figure out the number and size of data blocks used by this version and
		// error correction level
		$ecBlocks = $version->getECBlocksForLevel($ecLevel);

		// First count the total number of data blocks
		$totalBlocks = 0;
		$ecBlockArray = $ecBlocks->getECBlocks();
		foreach ($ecBlockArray as $ecBlock) {
			$totalBlocks += $ecBlock->getCount();
		}

		// Now establish DataBlocks of the appropriate size and number of data codewords
		$result = []; //new DataBlock[$totalBlocks];
		$numResultBlocks = 0;
		foreach ($ecBlockArray as $ecBlock) {
			$ecBlockCount = $ecBlock->getCount();
			for ($i = 0; $i < $ecBlockCount; $i++) {
				$numDataCodewords = $ecBlock->getDataCodewords();
				$numBlockCodewords = $ecBlocks->getECCodewordsPerBlock() + $numDataCodewords;
				$result[$numResultBlocks++] = new DataBlock($numDataCodewords, fill_array(0, $numBlockCodewords, 0));
			}
		}

		// All blocks have the same amount of data, except that the last n
		// (where n may be 0) have 1 more byte. Figure out where these start.
		$shorterBlocksTotalCodewords = is_countable($result[0]->codewords) ? count($result[0]->codewords) : 0;
		$longerBlocksStartAt = count($result) - 1;
		while ($longerBlocksStartAt >= 0) {
			$numCodewords = is_countable($result[$longerBlocksStartAt]->codewords) ? count($result[$longerBlocksStartAt]->codewords) : 0;
			if ($numCodewords == $shorterBlocksTotalCodewords) {
				break;
			}
			$longerBlocksStartAt--;
		}
		$longerBlocksStartAt++;

		$shorterBlocksNumDataCodewords = $shorterBlocksTotalCodewords - $ecBlocks->getECCodewordsPerBlock();
		// The last elements of result may be 1 element longer;
		// first fill out as many elements as all of them have
		$rawCodewordsOffset = 0;
		for ($i = 0; $i < $shorterBlocksNumDataCodewords; $i++) {
			for ($j = 0; $j < $numResultBlocks; $j++) {
				$result[$j]->codewords[$i] = $rawCodewords[$rawCodewordsOffset++];
			}
		}
		// Fill out the last data block in the longer ones
		for ($j = $longerBlocksStartAt; $j < $numResultBlocks; $j++) {
			$result[$j]->codewords[$shorterBlocksNumDataCodewords] = $rawCodewords[$rawCodewordsOffset++];
		}
		// Now add in error correction blocks
		$max = is_countable($result[0]->codewords) ? count($result[0]->codewords) : 0;
		for ($i = $shorterBlocksNumDataCodewords; $i < $max; $i++) {
			for ($j = 0; $j < $numResultBlocks; $j++) {
				$iOffset = $j < $longerBlocksStartAt ? $i : $i + 1;
				$result[$j]->codewords[$iOffset] = $rawCodewords[$rawCodewordsOffset++];
			}
		}

		return $result;
	}

	public function getNumDataCodewords()
	{
		return $this->numDataCodewords;
	}

	public function getCodewords()
	{
		return $this->codewords;
	}
}

DataMask.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Decoder;

use Zxing\Common\BitMatrix;

/**
 * <p>Encapsulates data masks for the data bits in a QR code, per ISO 18004:2006 6.8. Implementations
 * of this class can un-mask a raw BitMatrix. For simplicity, they will unmask the entire BitMatrix,
 * including areas used for finder patterns, timing patterns, etc. These areas should be unused
 * after the point they are unmasked anyway.</p>
 *
 * <p>Note that the diagram in section 6.8.1 is misleading since it indicates that i is column position
 * and j is row position. In fact, as the text says, i is row position and j is column position.</p>
 *
 * @author Sean Owen
 */
abstract class DataMask
{
	/**
	 * See ISO 18004:2006 6.8.1
	 */
	private static array $DATA_MASKS = [];

	public function __construct()
	{
	}

	public static function Init(): void
	{
		self::$DATA_MASKS = [
			new DataMask000(),
			new DataMask001(),
			new DataMask010(),
			new DataMask011(),
			new DataMask100(),
			new DataMask101(),
			new DataMask110(),
			new DataMask111(),
		];
	}

	/**
	 * @param int $reference a value between 0 and 7 indicating one of the eight possible
	 *                  data mask patterns a QR Code may use
	 *
	 * @return DataMask encapsulating the data mask pattern
	 */
	public static function forReference($reference)
	{
		if ($reference < 0 || $reference > 7) {
			throw new \InvalidArgumentException();
		}

		return self::$DATA_MASKS[$reference];
	}

	/**
	 * <p>Implementations of this method reverse the data masking process applied to a QR Code and
	 * make its bits ready to read.</p>
	 *
	 * @param BitMatrix $bits representation      of QR Code bits
	 * @param int $dimension dimension of QR Code, represented by bits, being unmasked
	 */
	final public function unmaskBitMatrix($bits, $dimension): void
	{
		for ($i = 0; $i < $dimension; $i++) {
			for ($j = 0; $j < $dimension; $j++) {
				if ($this->isMasked($i, $j)) {
					$bits->flip($j, $i);
				}
			}
		}
	}

	/**
	 * @psalm-param 0|positive-int $i
	 * @psalm-param 0|positive-int $j
	 */
	abstract public function isMasked(int $i, int $j);
}

DataMask::Init();

/**
 * 000: mask bits for which (x + y) mod 2 == 0
 */
final class DataMask000 extends DataMask
{
	// @Override
	public function isMasked($i, $j): bool
	{
		return (($i + $j) & 0x01) == 0;
	}
}

/**
 * 001: mask bits for which x mod 2 == 0
 */
final class DataMask001 extends DataMask
{
	public function isMasked($i, $j): bool
	{
		return ($i & 0x01) == 0;
	}
}

/**
 * 010: mask bits for which y mod 3 == 0
 */
final class DataMask010 extends DataMask
{
	public function isMasked($i, $j): bool
	{
		return $j % 3 == 0;
	}
}

/**
 * 011: mask bits for which (x + y) mod 3 == 0
 */
final class DataMask011 extends DataMask
{
	public function isMasked($i, $j): bool
	{
		return ($i + $j) % 3 == 0;
	}
}

/**
 * 100: mask bits for which (x/2 + y/3) mod 2 == 0
 */
final class DataMask100 extends DataMask
{
	public function isMasked($i, $j): bool
	{
		return (int)(((int)($i / 2) + (int)($j / 3)) & 0x01) == 0;
	}
}

/**
 * 101: mask bits for which xy mod 2 + xy mod 3 == 0
 */
final class DataMask101 extends DataMask
{
	public function isMasked($i, $j): bool
	{
		$temp = $i * $j;

		return ($temp & 0x01) + ($temp % 3) == 0;
	}
}

/**
 * 110: mask bits for which (xy mod 2 + xy mod 3) mod 2 == 0
 */
final class DataMask110 extends DataMask
{
	public function isMasked($i, $j): bool
	{
		$temp = $i * $j;

		return ((($temp & 0x01) + ($temp % 3)) & 0x01) == 0;
	}
}

/**
 * 111: mask bits for which ((x+y)mod 2 + xy mod 3) mod 2 == 0
 */
final class DataMask111 extends DataMask
{
	public function isMasked($i, $j): bool
	{
		return (((($i + $j) & 0x01) + (($i * $j) % 3)) & 0x01) == 0;
	}
}

DecodedBitStreamParser.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Decoder;

use ValueError;
use Zxing\Common\BitSource;
use Zxing\Common\CharacterSetECI;
use Zxing\Common\DecoderResult;
use Zxing\FormatException;

/**
 * <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes
 * in one QR Code. This class decodes the bits back into text.</p>
 *
 * <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p>
 *
 * @author Sean Owen
 */
final class DecodedBitStreamParser
{
	/**
	 * See ISO 18004:2006, 6.4.4 Table 5
	 */
	private static array $ALPHANUMERIC_CHARS = [
		'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
		'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
		'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
		' ', '$', '%', '*', '+', '-', '.', '/', ':',
	];
	private static int $GB2312_SUBSET = 1;

	/**
	 * @psalm-param array<int, mixed> $bytes
	 */
	public static function decode(
		array $bytes,
		Version $version,
		ErrorCorrectionLevel $ecLevel,
		array|null $hints
	): \Zxing\Common\DecoderResult {
		$bits = new BitSource($bytes);
		$result = ''; //new StringBuilder(50);
		$byteSegments = [];
		$symbolSequence = -1;
		$parityData = -1;

		try {
			$currentCharacterSetECI = null;
			$fc1InEffect = false;
			$mode = '';
			do {
				// While still another segment to read...
				if ($bits->available() < 4) {
					// OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
					$mode = Mode::$TERMINATOR;
				} else {
					$mode = Mode::forBits($bits->readBits(4)); // mode is encoded by 4 bits
				}
				if ($mode != Mode::$TERMINATOR) {
					if ($mode == Mode::$FNC1_FIRST_POSITION || $mode == Mode::$FNC1_SECOND_POSITION) {
						// We do little with FNC1 except alter the parsed result a bit according to the spec
						$fc1InEffect = true;
					} elseif ($mode == Mode::$STRUCTURED_APPEND) {
						if ($bits->available() < 16) {
							throw new FormatException("Bits available < 16");
						}
						// sequence number and parity is added later to the result metadata
						// Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue
						$symbolSequence = $bits->readBits(8);
						$parityData = $bits->readBits(8);
					} elseif ($mode == Mode::$ECI) {
						// Count doesn't apply to ECI
						$value = self::parseECIValue($bits);
						$currentCharacterSetECI = CharacterSetECI::getCharacterSetECIByValue($value);
						if ($currentCharacterSetECI == null) {
							throw new FormatException("Current character set ECI is null");
						}
					} else {
						// First handle Hanzi mode which does not start with character count
						if ($mode == Mode::$HANZI) {
							//chinese mode contains a sub set indicator right after mode indicator
							$subset = $bits->readBits(4);
							$countHanzi = $bits->readBits($mode->getCharacterCountBits($version));
							if ($subset == self::$GB2312_SUBSET) {
								self::decodeHanziSegment($bits, $result, $countHanzi);
							}
						} else {
							// "Normal" QR code modes:
							// How many characters will follow, encoded in this mode?
							$count = $bits->readBits($mode->getCharacterCountBits($version));
							if ($mode == Mode::$NUMERIC) {
								self::decodeNumericSegment($bits, $result, $count);
							} elseif ($mode == Mode::$ALPHANUMERIC) {
								self::decodeAlphanumericSegment($bits, $result, $count, $fc1InEffect);
							} elseif ($mode == Mode::$BYTE) {
								self::decodeByteSegment($bits, $result, $count, $currentCharacterSetECI, $byteSegments, $hints);
							} elseif ($mode == Mode::$KANJI) {
								self::decodeKanjiSegment($bits, $result, $count);
							} else {
								throw new FormatException("Unknown mode $mode to decode");
							}
						}
					}
				}
			} while ($mode != Mode::$TERMINATOR);
		} catch (\InvalidArgumentException $e) {
			// from readBits() calls
			throw new FormatException("Invalid argument exception when formatting: " . $e->getMessage());
		}

		return new DecoderResult(
			$bytes,
			$result,
			empty($byteSegments) ? null : $byteSegments,
			$ecLevel == null ? null : 'L', //ErrorCorrectionLevel::toString($ecLevel),
			$symbolSequence,
			$parityData
		);
	}

	private static function parseECIValue(BitSource $bits): int
	{
		$firstByte = $bits->readBits(8);
		if (($firstByte & 0x80) == 0) {
			// just one byte
			return $firstByte & 0x7F;
		}
		if (($firstByte & 0xC0) == 0x80) {
			// two bytes
			$secondByte = $bits->readBits(8);

			return (($firstByte & 0x3F) << 8) | $secondByte;
		}
		if (($firstByte & 0xE0) == 0xC0) {
			// three bytes
			$secondThirdBytes = $bits->readBits(16);

			return (($firstByte & 0x1F) << 16) | $secondThirdBytes;
		}
		throw new FormatException("ECI Value parsing failed.");
	}

	/**
	 * See specification GBT 18284-2000
	 *
	 * @psalm-param '' $result
	 */
	private static function decodeHanziSegment(
		BitSource $bits,
		string &$result,
		int $count
	): void {
		// Don't crash trying to read more bits than we have available.
		if ($count * 13 > $bits->available()) {
			throw new FormatException("Trying to read more bits than we have available");
		}

		// Each character will require 2 bytes. Read the characters as 2-byte pairs
		// and decode as GB2312 afterwards
		$buffer = fill_array(0, 2 * $count, 0);
		$offset = 0;
		while ($count > 0) {
			// Each 13 bits encodes a 2-byte character
			$twoBytes = $bits->readBits(13);
			$assembledTwoBytes = (($twoBytes / 0x060) << 8) | ($twoBytes % 0x060);
			if ($assembledTwoBytes < 0x003BF) {
				// In the 0xA1A1 to 0xAAFE range
				$assembledTwoBytes += 0x0A1A1;
			} else {
				// In the 0xB0A1 to 0xFAFE range
				$assembledTwoBytes += 0x0A6A1;
			}
			$buffer[$offset] = (($assembledTwoBytes >> 8) & 0xFF); //(byte)
			$buffer[$offset + 1] = ($assembledTwoBytes & 0xFF); //(byte)
			$offset += 2;
			$count--;
		}
		$result .= iconv('GB2312', 'UTF-8', implode($buffer));
	}

	private static function decodeNumericSegment(
		BitSource $bits,
		string &$result,
		int $count
	): void {
		// Read three digits at a time
		while ($count >= 3) {
			// Each 10 bits encodes three digits
			if ($bits->available() < 10) {
				throw new FormatException("Not enough bits available");
			}
			$threeDigitsBits = $bits->readBits(10);
			if ($threeDigitsBits >= 1000) {
				throw new FormatException("Too many three digit bits");
			}
			$result .= (self::toAlphaNumericChar(intdiv($threeDigitsBits, 100)));
			$result .= (self::toAlphaNumericChar(intdiv($threeDigitsBits, 10) % 10));
			$result .= (self::toAlphaNumericChar($threeDigitsBits % 10));
			$count -= 3;
		}
		if ($count == 2) {
			// Two digits left over to read, encoded in 7 bits
			if ($bits->available() < 7) {
				throw new FormatException("Two digits left over to read, encoded in 7 bits, but only " . $bits->available() . ' bits available');
			}
			$twoDigitsBits = $bits->readBits(7);
			if ($twoDigitsBits >= 100) {
				throw new FormatException("Too many bits: $twoDigitsBits expected < 100");
			}
			$result .= (self::toAlphaNumericChar(intdiv($twoDigitsBits, 10)));
			$result .= (self::toAlphaNumericChar($twoDigitsBits % 10));
		} elseif ($count == 1) {
			// One digit left over to read
			if ($bits->available() < 4) {
				throw new FormatException("One digit left to read, but < 4 bits available");
			}
			$digitBits = $bits->readBits(4);
			if ($digitBits >= 10) {
				throw new FormatException("Too many bits: $digitBits expected < 10");
			}
			$result .= (self::toAlphaNumericChar($digitBits));
		}
	}

	/**
	 * @param float|int $value
	 */
	private static function toAlphaNumericChar(int|float $value)
	{
		$intVal = (int) $value;
		if ($intVal >= count(self::$ALPHANUMERIC_CHARS)) {
			throw new FormatException("$intVal is too many alphanumeric chars");
		}

		return self::$ALPHANUMERIC_CHARS[(int)($intVal)];
	}

	private static function decodeAlphanumericSegment(
		BitSource $bits,
		string &$result,
		int $count,
		bool $fc1InEffect
	): void {
		// Read two characters at a time
		$start = strlen((string) $result);
		while ($count > 1) {
			if ($bits->available() < 11) {
				throw new FormatException("Not enough bits available to read two expected characters");
			}
			$nextTwoCharsBits = $bits->readBits(11);
			$result .= (self::toAlphaNumericChar(intdiv($nextTwoCharsBits, 45)));
			$result .= (self::toAlphaNumericChar($nextTwoCharsBits % 45));
			$count -= 2;
		}
		if ($count == 1) {
			// special case: one character left
			if ($bits->available() < 6) {
				throw new FormatException("Not enough bits available to read one expected character");
			}
			$result .= self::toAlphaNumericChar($bits->readBits(6));
		}
		// See section 6.4.8.1, 6.4.8.2
		if ($fc1InEffect) {
			// We need to massage the result a bit if in an FNC1 mode:
			for ($i = $start; $i < strlen((string) $result); $i++) {
				if ($result[$i] == '%') {
					if ($i < strlen((string) $result) - 1 && $result[$i + 1] == '%') {
						// %% is rendered as %
						$result = substr_replace($result, '', $i + 1, 1); //deleteCharAt(i + 1);
					} else {
						// In alpha mode, % should be converted to FNC1 separator 0x1D
						$result[$i] = chr(0x1D);
					}
				}
			}
		}
	}

	private static function decodeByteSegment(
		BitSource $bits,
		string &$result,
		int $count,
		CharacterSetECI|null $currentCharacterSetECI,
		array &$byteSegments,
		array|null $hints
	): void {
		// Don't crash trying to read more bits than we have available.
		if (8 * $count > $bits->available()) {
			throw new FormatException("Trying to read more bits than we have available");
		}

		$readBytes = fill_array(0, $count, 0);
		for ($i = 0; $i < $count; $i++) {
			$readBytes[$i] = $bits->readBits(8); //(byte)
		}
		$text = implode(array_map('chr', $readBytes));
        if ($hints !== null && array_key_exists('BINARY_MODE', $hints) && $hints['BINARY_MODE']) {
            $result .= $text;
        } else {
            $encoding = '';
            if ($currentCharacterSetECI == null) {
                // The spec isn't clear on this mode; see
                // section 6.4.5: t does not say which encoding to assuming
                // upon decoding. I have seen ISO-8859-1 used as well as
                // Shift_JIS -- without anything like an ECI designator to
                // give a hint.

                try {
                    $encoding = mb_detect_encoding($text, $hints);
                } catch (ValueError $e) {
                    $encoding = mb_detect_encoding($text, mb_detect_order(), false);
                }
            } else {
                $encoding = $currentCharacterSetECI->name();
            }
            $result .= mb_convert_encoding($text, $encoding); //(new String(readBytes, encoding));
        }

		$byteSegments = array_merge($byteSegments, $readBytes);
	}

	private static function decodeKanjiSegment(
		BitSource $bits,
		string &$result,
		int $count
	): void {
		// Don't crash trying to read more bits than we have available.
		if ($count * 13 > $bits->available()) {
			throw new FormatException("Trying to read more bits than we have available");
		}

		// Each character will require 2 bytes. Read the characters as 2-byte pairs
		// and decode as Shift_JIS afterwards
		$buffer = [0, 2 * $count, 0];
		$offset = 0;
		while ($count > 0) {
			// Each 13 bits encodes a 2-byte character
			$twoBytes = $bits->readBits(13);
			$assembledTwoBytes = (($twoBytes / 0x0C0) << 8) | ($twoBytes % 0x0C0);
			if ($assembledTwoBytes < 0x01F00) {
				// In the 0x8140 to 0x9FFC range
				$assembledTwoBytes += 0x08140;
			} else {
				// In the 0xE040 to 0xEBBF range
				$assembledTwoBytes += 0x0C140;
			}
			$buffer[$offset] = ($assembledTwoBytes >> 8); //(byte)
			$buffer[$offset + 1] = $assembledTwoBytes; //(byte)
			$offset += 2;
			$count--;
		}
		// Shift_JIS may not be supported in some environments:

		$result .= iconv('shift-jis', 'utf-8', implode($buffer));
	}

	private function DecodedBitStreamParser(): void
	{
	}
}

Decoder.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Decoder;

use Zxing\ChecksumException;
use Zxing\Common\BitMatrix;
use Zxing\Common\DecoderResult;
use Zxing\Common\Reedsolomon\GenericGF;
use Zxing\Common\Reedsolomon\ReedSolomonDecoder;
use Zxing\Common\Reedsolomon\ReedSolomonException;
use Zxing\FormatException;

/**
 * <p>The main class which implements QR Code decoding -- as opposed to locating and extracting
 * the QR Code from an image.</p>
 *
 * @author Sean Owen
 */
final class Decoder
{
	private readonly \Zxing\Common\Reedsolomon\ReedSolomonDecoder $rsDecoder;

	public function __construct()
	{
		$this->rsDecoder = new ReedSolomonDecoder(GenericGF::$QR_CODE_FIELD_256);
	}

	public function decode(BitMatrix|BitMatrixParser $variable, array|null $hints = null): string|DecoderResult
	{
		if (is_array($variable)) {
			return $this->decodeImage($variable, $hints);
		} elseif ($variable instanceof BitMatrix) {
			return $this->decodeBits($variable, $hints);
		} elseif ($variable instanceof BitMatrixParser) {
			return $this->decodeParser($variable, $hints);
		}
		die('decode error Decoder.php');
	}

	/**
	 * <p>Convenience method that can decode a QR Code represented as a 2D array of booleans.
	 * "true" is taken to mean a black module.</p>
	 *
	 * @param array $image booleans representing white/black QR Code modules
	 * @param array|null $hints       decoding  hints that should be used to influence decoding
	 *
	 * @return DecoderResult|string text and bytes encoded within the QR Code
	 *
	 * @throws FormatException if the QR Code cannot be decoded
	 * @throws ChecksumException if error correction fails
	 */
	public function decodeImage(array $image, $hints = null): string|DecoderResult
	{
		$dimension = is_countable($image) ? count($image) : 0;
		$bits = new BitMatrix($dimension);
		for ($i = 0; $i < $dimension; $i++) {
			for ($j = 0; $j < $dimension; $j++) {
				if ($image[$i][$j]) {
					$bits->set($j, $i);
				}
			}
		}

		return $this->decode($bits, $hints);
	}


	/**
	 * <p>Decodes a QR Code represented as a {@link BitMatrix}. A 1 or "true" is taken to mean a black module.</p>
	 *
	 * @param BitMatrix $bits booleans representing white/black QR Code modules
	 * @param array|null          $hints decoding hints that should be used to influence decoding
	 *
	 * @return DecoderResult|string string text and bytes encoded within the QR Code
	 *
	 * @throws FormatException if the QR Code cannot be decoded
	 * @throws ChecksumException if error correction fails
	 */
	public function decodeBits(\Zxing\Common\BitMatrix $bits, $hints = null): string|DecoderResult
	{

		// Construct a parser and read version, error-correction level
		$parser = new BitMatrixParser($bits);
		$fe = null;
		$ce = null;
		try {
			return $this->decode($parser, $hints);
		} catch (FormatException $e) {
			$fe = $e;
		} catch (ChecksumException $e) {
			$ce = $e;
		}

		try {

			// Revert the bit matrix
			$parser->remask();

			// Will be attempting a mirrored reading of the version and format info.
			$parser->setMirror(true);

			// Preemptively read the version.
			$parser->readVersion();

			// Preemptively read the format information.
			$parser->readFormatInformation();

			/*
			* Since we're here, this means we have successfully detected some kind
			* of version and format information when mirrored. This is a good sign,
			* that the QR code may be mirrored, and we should try once more with a
			* mirrored content.
			*/
			// Prepare for a mirrored reading.
			$parser->mirror();

			$result = $this->decode($parser, $hints);

			// Success! Notify the caller that the code was mirrored.
			$result->setOther(new QRCodeDecoderMetaData(true));

			return $result;
		} catch (FormatException $e) { // catch (FormatException | ChecksumException e) {
			// Throw the exception from the original reading
			if ($fe != null) {
				throw $fe;
			}
			if ($ce != null) {
				throw $ce;
			}
			throw $e;
		}
	}

	private function decodeParser(\Zxing\Qrcode\Decoder\BitMatrixParser $parser, ?array $hints = null): DecoderResult
	{
		$version = $parser->readVersion();
		$ecLevel = $parser->readFormatInformation()->getErrorCorrectionLevel();

		// Read codewords
		$codewords = $parser->readCodewords();
		// Separate into data blocks
		$dataBlocks = DataBlock::getDataBlocks($codewords, $version, $ecLevel);

		// Count total number of data bytes
		$totalBytes = 0;
		foreach ($dataBlocks as $dataBlock) {
			$totalBytes += $dataBlock->getNumDataCodewords();
		}
		$resultBytes = fill_array(0, $totalBytes, 0);
		$resultOffset = 0;

		// Error-correct and copy data blocks together into a stream of bytes
		foreach ($dataBlocks as $dataBlock) {
			$codewordBytes = $dataBlock->getCodewords();
			$numDataCodewords = $dataBlock->getNumDataCodewords();
			$this->correctErrors($codewordBytes, $numDataCodewords);
			for ($i = 0; $i < $numDataCodewords; $i++) {
				$resultBytes[$resultOffset++] = $codewordBytes[$i];
			}
		}

		// Decode the contents of that stream of bytes
		return DecodedBitStreamParser::decode($resultBytes, $version, $ecLevel, $hints);
	}

	/**
	 * <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to
	 * correct the errors in-place using Reed-Solomon error correction.</p>
	 *
	 * @param array $codewordBytes and error correction codewords
	 * @param int $numDataCodewords of codewords that are data bytes
	 *
	 * @throws ChecksumException if error correction fails
	 */
	private function correctErrors(&$codewordBytes, int $numDataCodewords): void
	{
		$numCodewords = is_countable($codewordBytes) ? count($codewordBytes) : 0;
		// First read into an array of ints
		$codewordsInts = fill_array(0, $numCodewords, 0);
		for ($i = 0; $i < $numCodewords; $i++) {
			$codewordsInts[$i] = $codewordBytes[$i] & 0xFF;
		}
		$numECCodewords = (is_countable($codewordBytes) ? count($codewordBytes) : 0) - $numDataCodewords;
		try {
			$this->rsDecoder->decode($codewordsInts, $numECCodewords);
		} catch (ReedSolomonException) {
			throw ChecksumException::getChecksumInstance();
		}
		// Copy back into array of bytes -- only need to worry about the bytes that were data
		// We don't care about errors in the error-correction codewords
		for ($i = 0; $i < $numDataCodewords; $i++) {
			$codewordBytes[$i] = $codewordsInts[$i];
		}
	}
}

ErrorCorrectionLevel.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Decoder;

/**
 * <p>See ISO 18004:2006, 6.5.1. This enum encapsulates the four error correction levels
 * defined by the QR code standard.</p>
 *
 * @author Sean Owen
 */
class ErrorCorrectionLevel
{
	/**
  * @var \Zxing\Qrcode\Decoder\ErrorCorrectionLevel[]|null
  */
	private static ?array $FOR_BITS = null;

	public function __construct(private $bits, private $ordinal = 0)
	{
	}

	public static function Init(): void
	{
		self::$FOR_BITS = [


			new ErrorCorrectionLevel(0x00, 1), //M
			new ErrorCorrectionLevel(0x01, 0), //L
			new ErrorCorrectionLevel(0x02, 3), //H
			new ErrorCorrectionLevel(0x03, 2), //Q

		];
	}
	/** L = ~7% correction */
	//  self::$L = new ErrorCorrectionLevel(0x01);
	/** M = ~15% correction */
	//self::$M = new ErrorCorrectionLevel(0x00);
	/** Q = ~25% correction */
	//self::$Q = new ErrorCorrectionLevel(0x03);
	/** H = ~30% correction */
	//self::$H = new ErrorCorrectionLevel(0x02);
	/**
	 * @param int $bits containing the two bits encoding a QR Code's error correction level
	 *
	 * @return null|self representing the encoded error correction level
	 */
	public static function forBits(int $bits): self|null
	{
		if ($bits < 0 || $bits >= (is_countable(self::$FOR_BITS) ? count(self::$FOR_BITS) : 0)) {
			throw new \InvalidArgumentException();
		}
		$level = self::$FOR_BITS[$bits];

		// $lev = self::$$bit;
		return $level;
	}


	public function getBits()
	{
		return $this->bits;
	}

	public function toString()
	{
		return $this->bits;
	}

	public function getOrdinal()
	{
		return $this->ordinal;
	}
}

ErrorCorrectionLevel::Init();

FormatInformation.phpQR
Formulario de entrada de datos.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Decoder;

/**
 * <p>Encapsulates a QR Code's format information, including the data mask used and
 * error correction level.</p>
 *
 * @author Sean Owen
 * @see    DataMask
 * @see    ErrorCorrectionLevel
 */
final class FormatInformation
{
	public static $FORMAT_INFO_MASK_QR;

	/**
	 * See ISO 18004:2006, Annex C, Table C.1
	 */
	public static $FORMAT_INFO_DECODE_LOOKUP;
	/**
  * Offset i holds the number of 1 bits in the binary representation of i
  * @var int[]|null
  */
	private static ?array $BITS_SET_IN_HALF_BYTE = null;

	private readonly \Zxing\Qrcode\Decoder\ErrorCorrectionLevel $errorCorrectionLevel;
	private readonly int $dataMask;

	private function __construct($formatInfo)
	{
		// Bits 3,4
		$this->errorCorrectionLevel = ErrorCorrectionLevel::forBits(($formatInfo >> 3) & 0x03);
		// Bottom 3 bits
		$this->dataMask = ($formatInfo & 0x07);//(byte)
	}

	public static function Init(): void
	{
		self::$FORMAT_INFO_MASK_QR = 0x5412;
		self::$BITS_SET_IN_HALF_BYTE = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4];
		self::$FORMAT_INFO_DECODE_LOOKUP = [
			[0x5412, 0x00],
			[0x5125, 0x01],
			[0x5E7C, 0x02],
			[0x5B4B, 0x03],
			[0x45F9, 0x04],
			[0x40CE, 0x05],
			[0x4F97, 0x06],
			[0x4AA0, 0x07],
			[0x77C4, 0x08],
			[0x72F3, 0x09],
			[0x7DAA, 0x0A],
			[0x789D, 0x0B],
			[0x662F, 0x0C],
			[0x6318, 0x0D],
			[0x6C41, 0x0E],
			[0x6976, 0x0F],
			[0x1689, 0x10],
			[0x13BE, 0x11],
			[0x1CE7, 0x12],
			[0x19D0, 0x13],
			[0x0762, 0x14],
			[0x0255, 0x15],
			[0x0D0C, 0x16],
			[0x083B, 0x17],
			[0x355F, 0x18],
			[0x3068, 0x19],
			[0x3F31, 0x1A],
			[0x3A06, 0x1B],
			[0x24B4, 0x1C],
			[0x2183, 0x1D],
			[0x2EDA, 0x1E],
			[0x2BED, 0x1F],
		];
	}

	/**
	 * @param $maskedFormatInfo1 ; format info indicator, with mask still applied
	 * @param $maskedFormatInfo2 ; second copy of same info; both are checked at the same time
	 *                          to establish best match
	 *
	 * @return FormatInformation|null information about the format it specifies, or {@code null}
	 *  if doesn't seem to match any known pattern
	 *
	 * @psalm-param 0|1 $maskedFormatInfo1
	 * @psalm-param 0|1 $maskedFormatInfo2
	 */
	public static function decodeFormatInformation(int $maskedFormatInfo1, int $maskedFormatInfo2)
	{
		$formatInfo = self::doDecodeFormatInformation($maskedFormatInfo1, $maskedFormatInfo2);
		if ($formatInfo != null) {
			return $formatInfo;
		}
		// Should return null, but, some QR codes apparently
		// do not mask this info. Try again by actually masking the pattern
		// first
		return self::doDecodeFormatInformation(
			$maskedFormatInfo1 ^ self::$FORMAT_INFO_MASK_QR,
			$maskedFormatInfo2 ^ self::$FORMAT_INFO_MASK_QR
		);
	}

	/**
	 * @psalm-param 0|1 $maskedFormatInfo1
	 * @psalm-param 0|1 $maskedFormatInfo2
	 */
	private static function doDecodeFormatInformation(int $maskedFormatInfo1, int $maskedFormatInfo2): self|null
	{
		// Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing
		$bestDifference = PHP_INT_MAX;
		$bestFormatInfo = 0;
		foreach (self::$FORMAT_INFO_DECODE_LOOKUP as $decodeInfo) {
			$targetInfo = $decodeInfo[0];
			if ($targetInfo == $maskedFormatInfo1 || $targetInfo == $maskedFormatInfo2) {
				// Found an exact match
				return new FormatInformation($decodeInfo[1]);
			}
			$bitsDifference = self::numBitsDiffering($maskedFormatInfo1, $targetInfo);
			if ($bitsDifference < $bestDifference) {
				$bestFormatInfo = $decodeInfo[1];
				$bestDifference = $bitsDifference;
			}
			if ($maskedFormatInfo1 != $maskedFormatInfo2) {
				// also try the other option
				$bitsDifference = self::numBitsDiffering($maskedFormatInfo2, $targetInfo);
				if ($bitsDifference < $bestDifference) {
					$bestFormatInfo = $decodeInfo[1];
					$bestDifference = $bitsDifference;
				}
			}
		}
		// Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits
		// differing means we found a match
		if ($bestDifference <= 3) {
			return new FormatInformation($bestFormatInfo);
		}

		return null;
	}

	/**
	 * @psalm-param 0|1 $a
	 */
	public static function numBitsDiffering(int $a, $b): int
	{
		$a ^= $b; // a now has a 1 bit exactly where its bit differs with b's
		// Count bits set quickly with a series of lookups:
		return self::$BITS_SET_IN_HALF_BYTE[$a & 0x0F] +
			self::$BITS_SET_IN_HALF_BYTE[(int)(uRShift($a, 4) & 0x0F)] +
			self::$BITS_SET_IN_HALF_BYTE[(uRShift($a, 8) & 0x0F)] +
			self::$BITS_SET_IN_HALF_BYTE[(uRShift($a, 12) & 0x0F)] +
			self::$BITS_SET_IN_HALF_BYTE[(uRShift($a, 16) & 0x0F)] +
			self::$BITS_SET_IN_HALF_BYTE[(uRShift($a, 20) & 0x0F)] +
			self::$BITS_SET_IN_HALF_BYTE[(uRShift($a, 24) & 0x0F)] +
			self::$BITS_SET_IN_HALF_BYTE[(uRShift($a, 28) & 0x0F)];
	}

	public function getErrorCorrectionLevel(): ErrorCorrectionLevel
	{
		return $this->errorCorrectionLevel;
	}

	public function getDataMask(): int
	{
		return $this->dataMask;
	}

	
	public function hashCode()
	{
		return ($this->errorCorrectionLevel->ordinal() << 3) | (int)($this->dataMask);
	}

	
	public function equals($o): bool
	{
		if (!($o instanceof FormatInformation)) {
			return false;
		}
		$other = $o;

		return $this->errorCorrectionLevel == $other->errorCorrectionLevel &&
			$this->dataMask == $other->dataMask;
	}
}

FormatInformation::Init();

Mode.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Decoder;

/**
 * <p>See ISO 18004:2006, 6.4.1, Tables 2 and 3. This enum encapsulates the various modes in which
 * data can be encoded to bits in the QR code standard.</p>
 *
 * @author Sean Owen
 */
class Mode
{
	public static $TERMINATOR;
	public static $NUMERIC;
	public static $ALPHANUMERIC;
	public static $STRUCTURED_APPEND;
	public static $BYTE;
	public static $ECI;
	public static $KANJI;
	public static $FNC1_FIRST_POSITION;
	public static $FNC1_SECOND_POSITION;
	public static $HANZI;

	public function __construct(private $characterCountBitsForVersions, private $bits)
	{
	}

	public static function Init(): void
	{
		self::$TERMINATOR = new Mode([0, 0, 0], 0x00); // Not really a mode...
		self::$NUMERIC = new Mode([10, 12, 14], 0x01);
		self::$ALPHANUMERIC = new Mode([9, 11, 13], 0x02);
		self::$STRUCTURED_APPEND = new Mode([0, 0, 0], 0x03); // Not supported
		self::$BYTE = new Mode([8, 16, 16], 0x04);
		self::$ECI = new Mode([0, 0, 0], 0x07); // character counts don't apply
		self::$KANJI = new Mode([8, 10, 12], 0x08);
		self::$FNC1_FIRST_POSITION = new Mode([0, 0, 0], 0x05);
		self::$FNC1_SECOND_POSITION = new Mode([0, 0, 0], 0x09);
		/** See GBT 18284-2000; "Hanzi" is a transliteration of this mode name. */
		self::$HANZI = new Mode([8, 10, 12], 0x0D);
	}

	/**
	 * @param int $bits four bits encoding a QR Code data mode
	 *
	 * @return Mode encoded by these bits
	 * @throws \InvalidArgumentException if bits do not correspond to a known mode
	 */
	public static function forBits($bits)
	{
		return match ($bits) {
			0x0 => self::$TERMINATOR,
			0x1 => self::$NUMERIC,
			0x2 => self::$ALPHANUMERIC,
			0x3 => self::$STRUCTURED_APPEND,
			0x4 => self::$BYTE,
			0x5 => self::$FNC1_FIRST_POSITION,
			0x7 => self::$ECI,
			0x8 => self::$KANJI,
			0x9 => self::$FNC1_SECOND_POSITION,
			0xD => self::$HANZI,
			default => throw new \InvalidArgumentException(),
		};
	}

	/**
	 * @param version $version in question
	 *
	 * @return int number of bits used, in this QR Code symbol {@link Version}, to encode the
	 *         count of characters that will follow encoded in this Mode
	 */
	public function getCharacterCountBits(\Zxing\Qrcode\Decoder\version $version)
	{
		$number = $version->getVersionNumber();
		$offset = 0;
		if ($number <= 9) {
			$offset = 0;
		} elseif ($number <= 26) {
			$offset = 1;
		} else {
			$offset = 2;
		}

		return $this->characterCountBitsForVersions[$offset];
	}

	public function getBits()
	{
		return $this->bits;
	}
}

Mode::Init();

QRCodeDecoderMetaData.phpQR
Script de practica.
Abrir
Ver codigo

<?php

namespace Zxing\Qrcode\Decoder;

class QRCodeDecoderMetaData
{
	/**
	 * QRCodeDecoderMetaData constructor.
	 * @param bool $mirrored
	 */
	public function __construct(private $mirrored)
	{
	}

	public function isMirrored(): bool
	{
		return $this->mirrored;
	}
}

Version.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Qrcode\Decoder;

use Zxing\Common\BitMatrix;
use Zxing\FormatException;

/**
 * See ISO 18004:2006 Annex D
 *
 * @author Sean Owen
 */
class Version
{
	/**
	 * See ISO 18004:2006 Annex D.
	 * Element i represents the raw version bits that specify version i + 7
	 */
	private static array $VERSION_DECODE_INFO = [
		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
	];

	/**
  * @var mixed|null
  */
	private static $VERSIONS;
	private readonly float|int $totalCodewords;

	public function __construct(
		private $versionNumber,
		private $alignmentPatternCenters,
		private $ecBlocks
	) {
		$total = 0;
		if (is_array($ecBlocks)) {
			$ecCodewords = $ecBlocks[0]->getECCodewordsPerBlock();
			$ecbArray = $ecBlocks[0]->getECBlocks();
		} else {
			$ecCodewords = $ecBlocks->getECCodewordsPerBlock();
			$ecbArray = $ecBlocks->getECBlocks();
		}
		foreach ($ecbArray as $ecBlock) {
			$total += $ecBlock->getCount() * ($ecBlock->getDataCodewords() + $ecCodewords);
		}
		$this->totalCodewords = $total;
	}
	public function getVersionNumber()
	{
		return $this->versionNumber;
	}

	public function getAlignmentPatternCenters()
	{
		return $this->alignmentPatternCenters;
	}

	public function getTotalCodewords(): int|float
	{
		return $this->totalCodewords;
	}

	public function getDimensionForVersion()
	{
		return 17 + 4 * $this->versionNumber;
	}

	public function getECBlocksForLevel(ErrorCorrectionLevel $ecLevel)
	{
		return $this->ecBlocks[$ecLevel->getOrdinal()];
	}

	/**
	 * <p>Deduces version information purely from QR Code dimensions.</p>
	 *
	 * @param int $dimension dimension in modules
	 * @return Version for a QR Code of that dimension
	 * @throws FormatException if dimension is not 1 mod 4
	 */
	public static function getProvisionalVersionForDimension($dimension)
	{
		if ($dimension % 4 != 1) {
			throw new FormatException();
		}
		try {
			return self::getVersionForNumber(($dimension - 17) / 4);
		} catch (\InvalidArgumentException) {
			throw new FormatException();
		}
	}

	/**
	 * @param float|int $versionNumber
	 */
	public static function getVersionForNumber(int|float $versionNumber)
	{
		if ($versionNumber < 1 || $versionNumber > 40) {
			throw new \InvalidArgumentException();
		}
		if (!self::$VERSIONS) {
			self::$VERSIONS = self::buildVersions();
		}
		return self::$VERSIONS[$versionNumber - 1];
	}

	/**
	 * @psalm-param 0|1 $versionBits
	 */
	public static function decodeVersionInformation(int $versionBits)
	{
		$bestDifference = PHP_INT_MAX;
		$bestVersion = 0;
		for ($i = 0; $i < count(self::$VERSION_DECODE_INFO); $i++) {
			$targetVersion = self::$VERSION_DECODE_INFO[$i];
			// Do the version info bits match exactly? done.
			if ($targetVersion == $versionBits) {
				return self::getVersionForNumber($i + 7);
			}
			// Otherwise see if this is the closest to a real version info bit string
			// we have seen so far
			$bitsDifference = FormatInformation::numBitsDiffering($versionBits, $targetVersion);
			if ($bitsDifference < $bestDifference) {
				$bestVersion = $i + 7;
				$bestDifference = $bitsDifference;
			}
		}
		// We can tolerate up to 3 bits of error since no two version info codewords will
		// differ in less than 8 bits.
		if ($bestDifference <= 3) {
			return self::getVersionForNumber($bestVersion);
		}
		// If we didn't find a close enough match, fail
		return null;
	}

	/**
	 * See ISO 18004:2006 Annex E
	 */
	public function buildFunctionPattern(): BitMatrix
	{
		$dimension = self::getDimensionForVersion();
		$bitMatrix = new BitMatrix($dimension);

		// Top left finder pattern + separator + format
		$bitMatrix->setRegion(0, 0, 9, 9);
		// Top right finder pattern + separator + format
		$bitMatrix->setRegion($dimension - 8, 0, 8, 9);
		// Bottom left finder pattern + separator + format
		$bitMatrix->setRegion(0, $dimension - 8, 9, 8);

		// Alignment patterns
		$max = is_countable($this->alignmentPatternCenters) ? count($this->alignmentPatternCenters) : 0;
		for ($x = 0; $x < $max; $x++) {
			$i = $this->alignmentPatternCenters[$x] - 2;
			for ($y = 0; $y < $max; $y++) {
				if (($x == 0 && ($y == 0 || $y == $max - 1)) || ($x == $max - 1 && $y == 0)) {
					// No alignment patterns near the three finder paterns
					continue;
				}
				$bitMatrix->setRegion($this->alignmentPatternCenters[$y] - 2, $i, 5, 5);
			}
		}

		// Vertical timing pattern
		$bitMatrix->setRegion(6, 9, 1, $dimension - 17);
		// Horizontal timing pattern
		$bitMatrix->setRegion(9, 6, $dimension - 17, 1);

		if ($this->versionNumber > 6) {
			// Version info, top right
			$bitMatrix->setRegion($dimension - 11, 0, 3, 6);
			// Version info, bottom left
			$bitMatrix->setRegion(0, $dimension - 11, 6, 3);
		}

		return $bitMatrix;
	}
	/**
	 * See ISO 18004:2006 6.5.1 Table 9
	 *
	 * @return self[]
	 *
	 * @psalm-return array{0: self, 1: self, 2: self, 3: self, 4: self, 5: self, 6: self, 7: self, 8: self, 9: self, 10: self, 11: self, 12: self, 13: self, 14: self, 15: self, 16: self, 17: self, 18: self, 19: self, 20: self, 21: self, 22: self, 23: self, 24: self, 25: self, 26: self, 27: self, 28: self, 29: self, 30: self, 31: self, 32: self, 33: self, 34: self, 35: self, 36: self, 37: self, 38: self, 39: self}
	 */
	private static function buildVersions(): array
	{
		return [
			new Version(
				1,
				[],
				[new ECBlocks(7, [new ECB(1, 19)]),
					new ECBlocks(10, [new ECB(1, 16)]),
					new ECBlocks(13, [new ECB(1, 13)]),
					new ECBlocks(17, [new ECB(1, 9)])]
			),
			new Version(
				2,
				[6, 18],
				[new ECBlocks(10, [new ECB(1, 34)]),
					new ECBlocks(16, [new ECB(1, 28)]),
					new ECBlocks(22, [new ECB(1, 22)]),
					new ECBlocks(28, [new ECB(1, 16)])]
			),
			new Version(
				3,
				[6, 22],
				[ new ECBlocks(15, [new ECB(1, 55)]),
					new ECBlocks(26, [new ECB(1, 44)]),
					new ECBlocks(18, [new ECB(2, 17)]),
					new ECBlocks(22, [new ECB(2, 13)])]
			),
			new Version(
				4,
				[6, 26],
				[new ECBlocks(20, [new ECB(1, 80)]),
					new ECBlocks(18, [new ECB(2, 32)]),
					new ECBlocks(26, [new ECB(2, 24)]),
					new ECBlocks(16, [new ECB(4, 9)])]
			),
			new Version(
				5,
				[6, 30],
				[new ECBlocks(26, [new ECB(1, 108)]),
					new ECBlocks(24, [new ECB(2, 43)]),
					new ECBlocks(18, [new ECB(2, 15),
						new ECB(2, 16)]),
					new ECBlocks(22, [new ECB(2, 11),
						new ECB(2, 12)])]
			),
			new Version(
				6,
				[6, 34],
				[new ECBlocks(18, [new ECB(2, 68)]),
					new ECBlocks(16, [new ECB(4, 27)]),
					new ECBlocks(24, [new ECB(4, 19)]),
					new ECBlocks(28, [new ECB(4, 15)])]
			),
			new Version(
				7,
				[6, 22, 38],
				[new ECBlocks(20, [new ECB(2, 78)]),
					new ECBlocks(18, [new ECB(4, 31)]),
					new ECBlocks(18, [new ECB(2, 14),
						new ECB(4, 15)]),
					new ECBlocks(26, [new ECB(4, 13),
						new ECB(1, 14)])]
			),
			new Version(
				8,
				[6, 24, 42],
				[new ECBlocks(24, [new ECB(2, 97)]),
					new ECBlocks(22, [new ECB(2, 38),
						new ECB(2, 39)]),
					new ECBlocks(22, [new ECB(4, 18),
						new ECB(2, 19)]),
					new ECBlocks(26, [new ECB(4, 14),
						new ECB(2, 15)])]
			),
			new Version(
				9,
				[6, 26, 46],
				[new ECBlocks(30, [new ECB(2, 116)]),
					new ECBlocks(22, [new ECB(3, 36),
						new ECB(2, 37)]),
					new ECBlocks(20, [new ECB(4, 16),
						new ECB(4, 17)]),
					new ECBlocks(24, [new ECB(4, 12),
						new ECB(4, 13)])]
			),
			new Version(
				10,
				[6, 28, 50],
				[new ECBlocks(18, [new ECB(2, 68),
					new ECB(2, 69)]),
					new ECBlocks(26, [new ECB(4, 43),
						new ECB(1, 44)]),
					new ECBlocks(24, [new ECB(6, 19),
						new ECB(2, 20)]),
					new ECBlocks(28, [new ECB(6, 15),
						new ECB(2, 16)])]
			),
			new Version(
				11,
				[6, 30, 54],
				[new ECBlocks(20, [new ECB(4, 81)]),
					new ECBlocks(30, [new ECB(1, 50),
						new ECB(4, 51)]),
					new ECBlocks(28, [new ECB(4, 22),
						new ECB(4, 23)]),
					new ECBlocks(24, [new ECB(3, 12),
						new ECB(8, 13)])]
			),
			new Version(
				12,
				[6, 32, 58],
				[new ECBlocks(24, [new ECB(2, 92),
					new ECB(2, 93)]),
					new ECBlocks(22, [new ECB(6, 36),
						new ECB(2, 37)]),
					new ECBlocks(26, [new ECB(4, 20),
						new ECB(6, 21)]),
					new ECBlocks(28, [new ECB(7, 14),
						new ECB(4, 15)])]
			),
			new Version(
				13,
				[6, 34, 62],
				[new ECBlocks(26, [new ECB(4, 107)]),
					new ECBlocks(22, [new ECB(8, 37),
						new ECB(1, 38)]),
					new ECBlocks(24, [new ECB(8, 20),
						new ECB(4, 21)]),
					new ECBlocks(22, [new ECB(12, 11),
						new ECB(4, 12)])]
			),
			new Version(
				14,
				[6, 26, 46, 66],
				[new ECBlocks(30, [new ECB(3, 115),
					new ECB(1, 116)]),
					new ECBlocks(24, [new ECB(4, 40),
						new ECB(5, 41)]),
					new ECBlocks(20, [new ECB(11, 16),
						new ECB(5, 17)]),
					new ECBlocks(24, [new ECB(11, 12),
						new ECB(5, 13)])]
			),
			new Version(
				15,
				[6, 26, 48, 70],
				[new ECBlocks(22, [new ECB(5, 87),
					new ECB(1, 88)]),
					new ECBlocks(24, [new ECB(5, 41),
						new ECB(5, 42)]),
					new ECBlocks(30, [new ECB(5, 24),
						new ECB(7, 25)]),
					new ECBlocks(24, [new ECB(11, 12),
						new ECB(7, 13)])]
			),
			new Version(
				16,
				[6, 26, 50, 74],
				[new ECBlocks(24, [new ECB(5, 98),
					new ECB(1, 99)]),
					new ECBlocks(28, [new ECB(7, 45),
						new ECB(3, 46)]),
					new ECBlocks(24, [new ECB(15, 19),
						new ECB(2, 20)]),
					new ECBlocks(30, [new ECB(3, 15),
						new ECB(13, 16)])]
			),
			new Version(
				17,
				[6, 30, 54, 78],
				[new ECBlocks(28, [new ECB(1, 107),
					new ECB(5, 108)]),
					new ECBlocks(28, [new ECB(10, 46),
						new ECB(1, 47)]),
					new ECBlocks(28, [new ECB(1, 22),
						new ECB(15, 23)]),
					new ECBlocks(28, [new ECB(2, 14),
						new ECB(17, 15)])]
			),
			new Version(
				18,
				[6, 30, 56, 82],
				[new ECBlocks(30, [new ECB(5, 120),
					new ECB(1, 121)]),
					new ECBlocks(26, [new ECB(9, 43),
						new ECB(4, 44)]),
					new ECBlocks(28, [new ECB(17, 22),
						new ECB(1, 23)]),
					new ECBlocks(28, [new ECB(2, 14),
						new ECB(19, 15)])]
			),
			new Version(
				19,
				[6, 30, 58, 86],
				[new ECBlocks(28, [new ECB(3, 113),
					new ECB(4, 114)]),
					new ECBlocks(26, [new ECB(3, 44),
						new ECB(11, 45)]),
					new ECBlocks(26, [new ECB(17, 21),
						new ECB(4, 22)]),
					new ECBlocks(26, [new ECB(9, 13),
						new ECB(16, 14)])]
			),
			new Version(
				20,
				[6, 34, 62, 90],
				[new ECBlocks(28, [new ECB(3, 107),
					new ECB(5, 108)]),
					new ECBlocks(26, [new ECB(3, 41),
						new ECB(13, 42)]),
					new ECBlocks(30, [new ECB(15, 24),
						new ECB(5, 25)]),
					new ECBlocks(28, [new ECB(15, 15),
						new ECB(10, 16)])]
			),
			new Version(
				21,
				[6, 28, 50, 72, 94],
				[ new ECBlocks(28, [new ECB(4, 116),
					new ECB(4, 117)]),
					new ECBlocks(26, [new ECB(17, 42)]),
					new ECBlocks(28, [new ECB(17, 22),
						new ECB(6, 23)]),
					new ECBlocks(30, [new ECB(19, 16),
						new ECB(6, 17)])]
			),
			new Version(
				22,
				[6, 26, 50, 74, 98],
				[new ECBlocks(28, [new ECB(2, 111),
					new ECB(7, 112)]),
					new ECBlocks(28, [new ECB(17, 46)]),
					new ECBlocks(30, [new ECB(7, 24),
						new ECB(16, 25)]),
					new ECBlocks(24, [new ECB(34, 13)])]
			),
			new Version(
				23,
				[6, 30, 54, 78, 102],
				new ECBlocks(30, [new ECB(4, 121),
					new ECB(5, 122)]),
				new ECBlocks(28, [new ECB(4, 47),
					new ECB(14, 48)]),
				new ECBlocks(30, [new ECB(11, 24),
					new ECB(14, 25)]),
				new ECBlocks(30, [new ECB(16, 15),
					new ECB(14, 16)])
			),
			new Version(
				24,
				[6, 28, 54, 80, 106],
				[new ECBlocks(30, [new ECB(6, 117),
					new ECB(4, 118)]),
					new ECBlocks(28, [new ECB(6, 45),
						new ECB(14, 46)]),
					new ECBlocks(30, [new ECB(11, 24),
						new ECB(16, 25)]),
					new ECBlocks(30, [new ECB(30, 16),
						new ECB(2, 17)])]
			),
			new Version(
				25,
				[6, 32, 58, 84, 110],
				[new ECBlocks(26, [new ECB(8, 106),
					new ECB(4, 107)]),
					new ECBlocks(28, [new ECB(8, 47),
						new ECB(13, 48)]),
					new ECBlocks(30, [new ECB(7, 24),
						new ECB(22, 25)]),
					new ECBlocks(30, [new ECB(22, 15),
						new ECB(13, 16)])]
			),
			new Version(
				26,
				[6, 30, 58, 86, 114],
				[new ECBlocks(28, [new ECB(10, 114),
					new ECB(2, 115)]),
					new ECBlocks(28, [new ECB(19, 46),
						new ECB(4, 47)]),
					new ECBlocks(28, [new ECB(28, 22),
						new ECB(6, 23)]),
					new ECBlocks(30, [new ECB(33, 16),
						new ECB(4, 17)])]
			),
			new Version(
				27,
				[6, 34, 62, 90, 118],
				[new ECBlocks(30, [new ECB(8, 122),
					new ECB(4, 123)]),
					new ECBlocks(28, [new ECB(22, 45),
						new ECB(3, 46)]),
					new ECBlocks(30, [new ECB(8, 23),
						new ECB(26, 24)]),
					new ECBlocks(30, [new ECB(12, 15),
						new ECB(28, 16)])]
			),
			new Version(
				28,
				[6, 26, 50, 74, 98, 122],
				[new ECBlocks(30, [new ECB(3, 117),
					new ECB(10, 118)]),
					new ECBlocks(28, [new ECB(3, 45),
						new ECB(23, 46)]),
					new ECBlocks(30, [new ECB(4, 24),
						new ECB(31, 25)]),
					new ECBlocks(30, [new ECB(11, 15),
						new ECB(31, 16)])]
			),
			new Version(
				29,
				[6, 30, 54, 78, 102, 126],
				[new ECBlocks(30, [new ECB(7, 116),
					new ECB(7, 117)]),
					new ECBlocks(28, [new ECB(21, 45),
						new ECB(7, 46)]),
					new ECBlocks(30, [new ECB(1, 23),
						new ECB(37, 24)]),
					new ECBlocks(30, [new ECB(19, 15),
						new ECB(26, 16)])]
			),
			new Version(
				30,
				[6, 26, 52, 78, 104, 130],
				[new ECBlocks(30, [new ECB(5, 115),
					new ECB(10, 116)]),
					new ECBlocks(28, [new ECB(19, 47),
						new ECB(10, 48)]),
					new ECBlocks(30, [new ECB(15, 24),
						new ECB(25, 25)]),
					new ECBlocks(30, [new ECB(23, 15),
						new ECB(25, 16)])]
			),
			new Version(
				31,
				[6, 30, 56, 82, 108, 134],
				[new ECBlocks(30, [new ECB(13, 115),
					new ECB(3, 116)]),
					new ECBlocks(28, [new ECB(2, 46),
						new ECB(29, 47)]),
					new ECBlocks(30, [new ECB(42, 24),
						new ECB(1, 25)]),
					new ECBlocks(30, [new ECB(23, 15),
						new ECB(28, 16)])]
			),
			new Version(
				32,
				[6, 34, 60, 86, 112, 138],
				[new ECBlocks(30, [new ECB(17, 115)]),
					new ECBlocks(28, [new ECB(10, 46),
						new ECB(23, 47)]),
					new ECBlocks(30, [new ECB(10, 24),
						new ECB(35, 25)]),
					new ECBlocks(30, [new ECB(19, 15),
						new ECB(35, 16)])]
			),
			new Version(
				33,
				[6, 30, 58, 86, 114, 142],
				[new ECBlocks(30, [new ECB(17, 115),
					new ECB(1, 116)]),
					new ECBlocks(28, [new ECB(14, 46),
						new ECB(21, 47)]),
					new ECBlocks(30, [new ECB(29, 24),
						new ECB(19, 25)]),
					new ECBlocks(30, [new ECB(11, 15),
						new ECB(46, 16)])]
			),
			new Version(
				34,
				[6, 34, 62, 90, 118, 146],
				[new ECBlocks(30, [new ECB(13, 115),
					new ECB(6, 116)]),
					new ECBlocks(28, [new ECB(14, 46),
						new ECB(23, 47)]),
					new ECBlocks(30, [new ECB(44, 24),
						new ECB(7, 25)]),
					new ECBlocks(30, [new ECB(59, 16),
						new ECB(1, 17)])]
			),
			new Version(
				35,
				[6, 30, 54, 78, 102, 126, 150],
				[new ECBlocks(30, [new ECB(12, 121),
					new ECB(7, 122)]),
					new ECBlocks(28, [new ECB(12, 47),
						new ECB(26, 48)]),
					new ECBlocks(30, [new ECB(39, 24),
						new ECB(14, 25)]),
					new ECBlocks(30, [new ECB(22, 15),
						new ECB(41, 16)])]
			),
			new Version(
				36,
				[6, 24, 50, 76, 102, 128, 154],
				[new ECBlocks(30, [new ECB(6, 121),
					new ECB(14, 122)]),
					new ECBlocks(28, [new ECB(6, 47),
						new ECB(34, 48)]),
					new ECBlocks(30, [new ECB(46, 24),
						new ECB(10, 25)]),
					new ECBlocks(30, [new ECB(2, 15),
						new ECB(64, 16)])]
			),
			new Version(
				37,
				[6, 28, 54, 80, 106, 132, 158],
				[new ECBlocks(30, [new ECB(17, 122),
					new ECB(4, 123)]),
					new ECBlocks(28, [new ECB(29, 46),
						new ECB(14, 47)]),
					new ECBlocks(30, [new ECB(49, 24),
						new ECB(10, 25)]),
					new ECBlocks(30, [new ECB(24, 15),
						new ECB(46, 16)])]
			),
			new Version(
				38,
				[6, 32, 58, 84, 110, 136, 162],
				[new ECBlocks(30, [new ECB(4, 122),
					new ECB(18, 123)]),
					new ECBlocks(28, [new ECB(13, 46),
						new ECB(32, 47)]),
					new ECBlocks(30, [new ECB(48, 24),
						new ECB(14, 25)]),
					new ECBlocks(30, [new ECB(42, 15),
						new ECB(32, 16)])]
			),
			new Version(
				39,
				[6, 26, 54, 82, 110, 138, 166],
				[new ECBlocks(30, [new ECB(20, 117),
					new ECB(4, 118)]),
					new ECBlocks(28, [new ECB(40, 47),
						new ECB(7, 48)]),
					new ECBlocks(30, [new ECB(43, 24),
						new ECB(22, 25)]),
					new ECBlocks(30, [new ECB(10, 15),
						new ECB(67, 16)])]
			),
			new Version(
				40,
				[6, 30, 58, 86, 114, 142, 170],
				[new ECBlocks(30, [new ECB(19, 118),
					new ECB(6, 119)]),
					new ECBlocks(28, [new ECB(18, 47),
						new ECB(31, 48)]),
					new ECBlocks(30, [new ECB(34, 24),
						new ECB(34, 25)]),
					new ECBlocks(30, [new ECB(20, 15),
						new ECB(61, 16)])]
			)
		];
	}
}

/**
 * <p>Encapsulates a set of error-correction blocks in one symbol version. Most versions will
 * use blocks of differing sizes within one version, so, this encapsulates the parameters for
 * each set of blocks. It also holds the number of error-correction codewords per block since it
 * will be the same across all blocks within one version.</p>
 */
final class ECBlocks
{
	public function __construct(private $ecCodewordsPerBlock, private $ecBlocks)
	{
	}

	public function getECCodewordsPerBlock()
	{
		return $this->ecCodewordsPerBlock;
	}

	public function getNumBlocks()
	{
		$total = 0;
		foreach ($this->ecBlocks as $ecBlock) {
			$total += $ecBlock->getCount();
		}
		return $total;
	}

	public function getTotalECCodewords()
	{
		return $this->ecCodewordsPerBlock * $this->getNumBlocks();
	}

	public function getECBlocks()
	{
		return $this->ecBlocks;
	}
}

/**
 * <p>Encapsualtes the parameters for one error-correction block in one symbol version.
 * This includes the number of data codewords, and the number of times a block with these
 * parameters is used consecutively in the QR code version's format.</p>
 */
final class ECB
{
	public function __construct(private $count, private $dataCodewords)
	{
	}

	public function getCount()
	{
		return $this->count;
	}

	public function getDataCodewords()
	{
		return $this->dataCodewords;
	}

	public function toString(): string
	{
		die('Version ECB toString()');
		//  return parent::$versionNumber;
	}
}

AlignmentPattern.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Detector;

use Zxing\ResultPoint;

/**
 * <p>Encapsulates an alignment pattern, which are the smaller square patterns found in
 * all but the simplest QR Codes.</p>
 *
 * @author Sean Owen
 */
final class AlignmentPattern extends ResultPoint
{
	public function __construct($posX, $posY, private $estimatedModuleSize)
	{
		parent::__construct($posX, $posY);
	}

	/**
	 * <p>Determines if this alignment pattern "about equals" an alignment pattern at the stated
	 * position and size -- meaning, it is at nearly the same center with nearly the same size.</p>
	 */
	public function aboutEquals($moduleSize, $i, $j): bool
	{
		if (abs($i - $this->getY()) <= $moduleSize && abs($j - $this->getX()) <= $moduleSize) {
			$moduleSizeDiff = abs($moduleSize - $this->estimatedModuleSize);

			return $moduleSizeDiff <= 1.0 || $moduleSizeDiff <= $this->estimatedModuleSize;
		}

		return false;
	}

	/**
	 * Combines this object's current estimate of a finder pattern position and module size
	 * with a new estimate. It returns a new {@code FinderPattern} containing an average of the two.
	 */
	public function combineEstimate($i, $j, $newModuleSize): \Zxing\Qrcode\Detector\AlignmentPattern
	{
		$combinedX = ($this->getX() + $j) / 2.0;
		$combinedY = ($this->getY() + $i) / 2.0;
		$combinedModuleSize = ($this->estimatedModuleSize + $newModuleSize) / 2.0;

		return new AlignmentPattern($combinedX, $combinedY, $combinedModuleSize);
	}
}

AlignmentPatternFinder.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Detector;

use Zxing\NotFoundException;

/**
 * <p>This class attempts to find alignment patterns in a QR Code. Alignment patterns look like finder
 * patterns but are smaller and appear at regular intervals throughout the image.</p>
 *
 * <p>At the moment this only looks for the bottom-right alignment pattern.</p>
 *
 * <p>This is mostly a simplified copy of {@link FinderPatternFinder}. It is copied,
 * pasted and stripped down here for maximum performance but does unfortunately duplicate
 * some code.</p>
 *
 * <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.</p>
 *
 * @author Sean Owen
 */
final class AlignmentPatternFinder
{
	private array $possibleCenters = [];
	private array $crossCheckStateCount = [];

	/**
	 * <p>Creates a finder that will look in a portion of the whole image.</p>
	 *
	 * @param \Imagick image      $image to search
	 * @param int left     $startX column from which to start searching
	 * @param int top     $startY row from which to start searching
	 * @param float width      $width of region to search
	 * @param float height     $height of region to search
	 * @param float estimated $moduleSize module size so far
	 */
	public function __construct(private $image, private $startX, private $startY, private $width, private $height, private $moduleSize, private $resultPointCallback)
	{
	}

	/**
	 * <p>This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since
	 * it's pretty performance-critical and so is written to be fast foremost.</p>
	 *
	 * @return {@link AlignmentPattern} if found
	 * @throws NotFoundException if not found
	 */
	public function find()
	{
		$startX = $this->startX;
		$height = $this->height;
		$maxJ = $startX + $this->width;
		$middleI = $this->startY + ($height / 2);
		// We are looking for black/white/black modules in 1:1:1 ratio;
		// this tracks the number of black/white/black modules seen so far
		$stateCount = [];
		for ($iGen = 0; $iGen < $height; $iGen++) {
			// Search from middle outwards
			$i = $middleI + (($iGen & 0x01) == 0 ? ($iGen + 1) / 2 : -(($iGen + 1) / 2));
			$i = (int)($i);
			$stateCount[0] = 0;
			$stateCount[1] = 0;
			$stateCount[2] = 0;
			$j = $startX;
			// Burn off leading white pixels before anything else; if we start in the middle of
			// a white run, it doesn't make sense to count its length, since we don't know if the
			// white run continued to the left of the start point
			while ($j < $maxJ && !$this->image->get($j, $i)) {
				$j++;
			}
			$currentState = 0;
			while ($j < $maxJ) {
				if ($this->image->get($j, $i)) {
					// Black pixel
					if ($currentState == 1) { // Counting black pixels
						$stateCount[$currentState]++;
					} else { // Counting white pixels
						if ($currentState == 2) { // A winner?
							if ($this->foundPatternCross($stateCount)) { // Yes
								$confirmed = $this->handlePossibleCenter($stateCount, $i, $j);
								if ($confirmed != null) {
									return $confirmed;
								}
							}
							$stateCount[0] = $stateCount[2];
							$stateCount[1] = 1;
							$stateCount[2] = 0;
							$currentState = 1;
						} else {
							$stateCount[++$currentState]++;
						}
					}
				} else { // White pixel
					if ($currentState == 1) { // Counting black pixels
						$currentState++;
					}
					$stateCount[$currentState]++;
				}
				$j++;
			}
			if ($this->foundPatternCross($stateCount)) {
				$confirmed = $this->handlePossibleCenter($stateCount, $i, $maxJ);
				if ($confirmed != null) {
					return $confirmed;
				}
			}
		}

		// Hmm, nothing we saw was observed and confirmed twice. If we had
		// any guess at all, return it.
		if (count($this->possibleCenters)) {
			return $this->possibleCenters[0];
		}

		throw  new NotFoundException("Bottom right alignment pattern not found");
	}

	/**
	 * @param int $stateCount count of black/white/black pixels just read
	 *
	 * @return bool iff the proportions of the counts is close enough to the 1/1/1 ratios used by alignment patterns to be considered a match
	 */
	private function foundPatternCross($stateCount): bool
	{
		$moduleSize = $this->moduleSize;
		$maxVariance = $moduleSize / 2.0;
		for ($i = 0; $i < 3; $i++) {
			if (abs($moduleSize - $stateCount[$i]) >= $maxVariance) {
				return false;
			}
		}

		return true;
	}

	/**
	 * <p>This is called when a horizontal scan finds a possible alignment pattern. It will
	 * cross check with a vertical scan, and if successful, will see if this pattern had been
	 * found on a previous horizontal scan. If so, we consider it confirmed and conclude we have
	 * found the alignment pattern.</p>
	 *
	 * @param array $stateCount state module counts from horizontal scan
	 * @param int $i where alignment pattern may be found
	 * @param int $j number of possible alignment pattern in row
	 *
	 * @return {@link AlignmentPattern} if we have found the same pattern twice, or null if not
	 */
	private function handlePossibleCenter($stateCount, $i, $j)
	{
		$stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2];
		$centerJ = self::centerFromEnd($stateCount, $j);
		$centerI = $this->crossCheckVertical($i, (int)$centerJ, 2 * $stateCount[1], $stateCountTotal);
		if (!is_nan($centerI)) {
			$estimatedModuleSize = (float)($stateCount[0] + $stateCount[1] + $stateCount[2]) / 3.0;
			foreach ($this->possibleCenters as $center) {
				// Look for about the same center and module size:
				if ($center->aboutEquals($estimatedModuleSize, $centerI, $centerJ)) {
					return $center->combineEstimate($centerI, $centerJ, $estimatedModuleSize);
				}
			}
			// Hadn't found this before; save it
			$point = new AlignmentPattern($centerJ, $centerI, $estimatedModuleSize);
			$this->possibleCenters[] = $point;
			if ($this->resultPointCallback != null) {
				$this->resultPointCallback->foundPossibleResultPoint($point);
			}
		}

		return null;
	}

	/**
	 * Given a count of black/white/black pixels just seen and an end position,
	 * figures the location of the center of this black/white/black run.
	 */
	private static function centerFromEnd(array $stateCount, int $end)
	{
		return (float)($end - $stateCount[2]) - $stateCount[1] / 2.0;
	}

	/**
	 * <p>After a horizontal scan finds a potential alignment pattern, this method
	 * "cross-checks" by scanning down vertically through the center of the possible
	 * alignment pattern to see if the same proportion is detected.</p>
	 *
	 * @param int $startI row   where an alignment pattern was detected
	 * @param float $centerJ center  of the section that appears to cross an alignment pattern
	 * @param int $maxCount maximum reasonable number of modules that should be
	 *                 observed in any reading state, based on the results of the horizontal scan
	 *
	 * @return float vertical center of alignment pattern, or {@link Float#NaN} if not found
	 */
	private function crossCheckVertical(
		int $startI,
		int $centerJ,
		$maxCount,
		$originalStateCountTotal
	) {
		$image = $this->image;

		$maxI = $image->getHeight();
		$stateCount = $this->crossCheckStateCount;
		$stateCount[0] = 0;
		$stateCount[1] = 0;
		$stateCount[2] = 0;

		// Start counting up from center
		$i = $startI;
		while ($i >= 0 && $image->get($centerJ, $i) && $stateCount[1] <= $maxCount) {
			$stateCount[1]++;
			$i--;
		}
		// If already too many modules in this state or ran off the edge:
		if ($i < 0 || $stateCount[1] > $maxCount) {
			return NAN;
		}
		while ($i >= 0 && !$image->get($centerJ, $i) && $stateCount[0] <= $maxCount) {
			$stateCount[0]++;
			$i--;
		}
		if ($stateCount[0] > $maxCount) {
			return NAN;
		}

		// Now also count down from center
		$i = $startI + 1;
		while ($i < $maxI && $image->get($centerJ, $i) && $stateCount[1] <= $maxCount) {
			$stateCount[1]++;
			$i++;
		}
		if ($i == $maxI || $stateCount[1] > $maxCount) {
			return NAN;
		}
		while ($i < $maxI && !$image->get($centerJ, $i) && $stateCount[2] <= $maxCount) {
			$stateCount[2]++;
			$i++;
		}
		if ($stateCount[2] > $maxCount) {
			return NAN;
		}

		$stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2];
		if (5 * abs($stateCountTotal - $originalStateCountTotal) >= 2 * $originalStateCountTotal) {
			return NAN;
		}

		return $this->foundPatternCross($stateCount) ? self::centerFromEnd($stateCount, $i) : NAN;
	}
}

Detector.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Qrcode\Detector;

use Zxing\Common\BitMatrix;
use Zxing\Common\Detector\MathUtils;
use Zxing\Common\DetectorResult;
use Zxing\Common\GridSampler;
use Zxing\Common\PerspectiveTransform;
use Zxing\DecodeHintType;
use Zxing\FormatException;
use Zxing\NotFoundException;
use Zxing\Qrcode\Decoder\Version;
use Zxing\ResultPoint;
use Zxing\ResultPointCallback;

/**
 * <p>Encapsulates logic that can detect a QR Code in an image, even if the QR Code
 * is rotated or skewed, or partially obscured.</p>
 *
 * @author Sean Owen
 */
class Detector
{
	private $resultPointCallback;

	public function __construct(private BitMatrix $image)
	{
	}

	/**
	 * <p>Detects a QR Code in an image.</p>
	 *
	 * @param array|null optional $hints hints to detector
	 *
	 * @return {@link DetectorResult} encapsulating results of detecting a QR Code
	 * @throws NotFoundException if QR Code cannot be found
	 * @throws FormatException if a QR Code cannot be decoded
	 */
	final public function detect(?array $hints = null): DetectorResult
	{/*Map<DecodeHintType,?>*/

		$resultPointCallback = ($hints !== null && array_key_exists('NEED_RESULT_POINT_CALLBACK', $hints)) ?
			$hints['NEED_RESULT_POINT_CALLBACK'] : null;
		/* resultPointCallback = hints == null ? null :
				(ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);*/
		$finder = new FinderPatternFinder($this->image, $resultPointCallback);
		$info = $finder->find($hints);

		return $this->processFinderPatternInfo($info);
	}

	final protected function processFinderPatternInfo(FinderPatternInfo $info): \Zxing\Common\DetectorResult
	{
		$topLeft = $info->getTopLeft();
		$topRight = $info->getTopRight();
		$bottomLeft = $info->getBottomLeft();

		$moduleSize = (float)$this->calculateModuleSize($topLeft, $topRight, $bottomLeft);
		if ($moduleSize < 1.0) {
			throw new NotFoundException("Module size $moduleSize < 1.0");
		}
		$dimension = (int)self::computeDimension($topLeft, $topRight, $bottomLeft, $moduleSize);
		$provisionalVersion = \Zxing\Qrcode\Decoder\Version::getProvisionalVersionForDimension($dimension);
		$modulesBetweenFPCenters = $provisionalVersion->getDimensionForVersion() - 7;

		$alignmentPattern = null;
		// Anything above version 1 has an alignment pattern
		if ((is_countable($provisionalVersion->getAlignmentPatternCenters()) ? count($provisionalVersion->getAlignmentPatternCenters()) : 0) > 0) {

			// Guess where a "bottom right" finder pattern would have been
			$bottomRightX = $topRight->getX() - $topLeft->getX() + $bottomLeft->getX();
			$bottomRightY = $topRight->getY() - $topLeft->getY() + $bottomLeft->getY();

			// Estimate that alignment pattern is closer by 3 modules
			// from "bottom right" to known top left location
			$correctionToTopLeft = 1.0 - 3.0 / (float)$modulesBetweenFPCenters;
			$estAlignmentX = (int)round($topLeft->getX() + $correctionToTopLeft * ($bottomRightX - $topLeft->getX()));
			$estAlignmentY = (int)round($topLeft->getY() + $correctionToTopLeft * ($bottomRightY - $topLeft->getY()));

			// Kind of arbitrary -- expand search radius before giving up
			for ($i = 4; $i <= 16; $i = $i << 1) { //??????????
				try {
					$alignmentPattern = $this->findAlignmentInRegion(
						$moduleSize,
						$estAlignmentX,
						$estAlignmentY,
						(float)$i
					);
					break;
				} catch (NotFoundException $e) {
					// try next round
					$alignmentPattern = null;
				}
			}
			// If we didn't find alignment pattern... well try anyway without it
		}

		$transform = self::createTransform($topLeft, $topRight, $bottomLeft, $alignmentPattern, $dimension);

		$bits = self::sampleGrid($this->image, $transform, $dimension);

		$points = [];
		if ($alignmentPattern == null) {
			$points = [$bottomLeft, $topLeft, $topRight];
		} else {
			// die('$points = new ResultPoint[]{bottomLeft, topLeft, topRight, alignmentPattern};');
			$points = [$bottomLeft, $topLeft, $topRight, $alignmentPattern];
		}

		return new DetectorResult($bits, $points);
	}

	/**
	 * <p>Detects a QR Code in an image.</p>
	 *
	 * @return {@link DetectorResult} encapsulating results of detecting a QR Code
	 * @throws NotFoundException if QR Code cannot be found
	 * @throws FormatException if a QR Code cannot be decoded
	 */

	/**
	 * <p>Computes an average estimated module size based on estimated derived from the positions
	 * of the three finder patterns.</p>
	 *
	 * @param FinderPattern $topLeft detected    top-left finder pattern center
	 * @param FinderPattern $topRight detected   top-right finder pattern center
	 * @param FinderPattern $bottomLeft detected bottom-left finder pattern center
	 *
	 * @return float estimated module size
	 */
	final protected function calculateModuleSize($topLeft, $topRight, $bottomLeft): float
	{
		// Take the average
		return ($this->calculateModuleSizeOneWay($topLeft, $topRight) +
			$this->calculateModuleSizeOneWay($topLeft, $bottomLeft)) / 2.0;
	}

	/**
	 * <p>Estimates module size based on two finder patterns -- it uses
	 * {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the
	 * width of each, measuring along the axis between their centers.</p>
	 */
	private function calculateModuleSizeOneWay(FinderPattern $pattern, FinderPattern $otherPattern): float
	{
		$moduleSizeEst1 = $this->sizeOfBlackWhiteBlackRunBothWays(
			(int)$pattern->getX(),
			(int)$pattern->getY(),
			(int)$otherPattern->getX(),
			(int)$otherPattern->getY()
		);
		$moduleSizeEst2 = $this->sizeOfBlackWhiteBlackRunBothWays(
			(int)$otherPattern->getX(),
			(int)$otherPattern->getY(),
			(int)$pattern->getX(),
			(int)$pattern->getY()
		);
		if (is_nan($moduleSizeEst1)) {
			return $moduleSizeEst2 / 7.0;
		}
		if (is_nan($moduleSizeEst2)) {
			return $moduleSizeEst1 / 7.0;
		}
		// Average them, and divide by 7 since we've counted the width of 3 black modules,
		// and 1 white and 1 black module on either side. Ergo, divide sum by 14.
		return ($moduleSizeEst1 + $moduleSizeEst2) / 14.0;
	}

	/**
	 * See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of
	 * a finder pattern by looking for a black-white-black run from the center in the direction
	 * of another po$(another finder pattern center), and in the opposite direction too.</p>
	 */
	private function sizeOfBlackWhiteBlackRunBothWays(int $fromX, int $fromY, int $toX, int $toY): float
	{
		$result = $this->sizeOfBlackWhiteBlackRun($fromX, $fromY, $toX, $toY);

		// Now count other way -- don't run off image though of course
		$scale = 1.0;
		$otherToX = $fromX - ($toX - $fromX);
		if ($otherToX < 0) {
			$scale = (float)$fromX / (float)($fromX - $otherToX);
			$otherToX = 0;
		} elseif ($otherToX >= $this->image->getWidth()) {
			$scale = (float)($this->image->getWidth() - 1 - $fromX) / (float)($otherToX - $fromX);
			$otherToX = $this->image->getWidth() - 1;
		}
		$otherToY = (int)($fromY - ($toY - $fromY) * $scale);

		$scale = 1.0;
		if ($otherToY < 0) {
			$scale = (float)$fromY / (float)($fromY - $otherToY);
			$otherToY = 0;
		} elseif ($otherToY >= $this->image->getHeight()) {
			$scale = (float)($this->image->getHeight() - 1 - $fromY) / (float)($otherToY - $fromY);
			$otherToY = $this->image->getHeight() - 1;
		}
		$otherToX = (int)($fromX + ($otherToX - $fromX) * $scale);

		$result += $this->sizeOfBlackWhiteBlackRun($fromX, $fromY, $otherToX, $otherToY);

		// Middle pixel is double-counted this way; subtract 1
		return $result - 1.0;
	}

	/**
	 * <p>This method traces a line from a po$in the image, in the direction towards another point.
	 * It begins in a black region, and keeps going until it finds white, then black, then white again.
	 * It reports the distance from the start to this point.</p>
	 *
	 * <p>This is used when figuring out how wide a finder pattern is, when the finder pattern
	 * may be skewed or rotated.</p>
	 */
	private function sizeOfBlackWhiteBlackRun(int $fromX, int $fromY, int $toX, int|float $toY): float
	{
		// Mild variant of Bresenham's algorithm;
		// see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
		$steep = abs($toY - $fromY) > abs($toX - $fromX);
		if ($steep) {
			$temp = $fromX;
			$fromX = $fromY;
			$fromY = $temp;
			$temp = $toX;
			$toX = $toY;
			$toY = $temp;
		}

		$dx = abs($toX - $fromX);
		$dy = abs($toY - $fromY);
		$error = -$dx / 2;
		$xstep = $fromX < $toX ? 1 : -1;
		$ystep = $fromY < $toY ? 1 : -1;

		// In black pixels, looking for white, first or second time.
		$state = 0;
		// Loop up until x == toX, but not beyond
		$xLimit = $toX + $xstep;
		for ($x = $fromX, $y = $fromY; $x != $xLimit; $x += $xstep) {
			$realX = $steep ? $y : $x;
			$realY = $steep ? $x : $y;

			// Does current pixel mean we have moved white to black or vice versa?
			// Scanning black in state 0,2 and white in state 1, so if we find the wrong
			// color, advance to next state or end if we are in state 2 already
			if (($state == 1) == $this->image->get($realX, $realY)) {
				if ($state == 2) {
					return MathUtils::distance($x, $y, $fromX, $fromY);
				}
				$state++;
			}

			$error += $dy;
			if ($error > 0) {
				if ($y == $toY) {
					break;
				}
				$y += $ystep;
				$error -= $dx;
			}
		}
		// Found black-white-black; give the benefit of the doubt that the next pixel outside the image
		// is "white" so this last po$at (toX+xStep,toY) is the right ending. This is really a
		// small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this.
		if ($state == 2) {
			return MathUtils::distance($toX + $xstep, $toY, $fromX, $fromY);
		}

		// else we didn't find even black-white-black; no estimate is really possible
		return NAN;
	}

	/**
	 * <p>Computes the dimension (number of modules on a size) of the QR Code based on the position
	 * of the finder patterns and estimated module size.</p>
	 */
	private static function computeDimension(
		$topLeft,
		$topRight,
		$bottomLeft,
		float $moduleSize
	): int {
		$tltrCentersDimension = MathUtils::round(ResultPoint::distance($topLeft, $topRight) / $moduleSize);
		$tlblCentersDimension = MathUtils::round(ResultPoint::distance($topLeft, $bottomLeft) / $moduleSize);
		$dimension = (int)round((($tltrCentersDimension + $tlblCentersDimension) / 2) + 7);
		switch ($dimension & 0x03) { // mod 4
			case 0:
				$dimension++;
				break;
				// 1? do nothing
			case 2:
				$dimension--;
				break;
			case 3:
				throw new NotFoundException("Dimension ($dimension) mod 4 == 3 unusable");
		}

		return (int)round($dimension);
	}

	/**
	 * <p>Attempts to locate an alignment pattern in a limited region of the image, which is
	 * guessed to contain it. This method uses {@link AlignmentPattern}.</p>
	 *
	 * @param float $overallEstModuleSize module size so far
	 * @param int $estAlignmentX coordinate of center of area probably containing alignment pattern
	 * @param int $estAlignmentY coordinate of above
	 * @param float      $allowanceFactor of pixels in all directions to search from the center
	 *
	 * @return {@link AlignmentPattern} if found, or null otherwise
	 * @throws NotFoundException if an unexpected error occurs during detection
	 */
	final protected function findAlignmentInRegion(
		float $overallEstModuleSize,
		int $estAlignmentX,
		int $estAlignmentY,
		float $allowanceFactor
	) {
		// Look for an alignment pattern (3 modules in size) around where it
		// should be
		$allowance = (int)($allowanceFactor * $overallEstModuleSize);
		$alignmentAreaLeftX = max(0, $estAlignmentX - $allowance);
		$alignmentAreaRightX = min($this->image->getWidth() - 1, $estAlignmentX + $allowance);
		if ($alignmentAreaRightX - $alignmentAreaLeftX < $overallEstModuleSize * 3) {
			throw new NotFoundException("Alignment area right smaller than overall module size: $alignmentAreaRightX - $alignmentAreaLeftX < $overallEstModuleSize * 3. Allowance: $allowance, estimage of x: $estAlignmentX");
		}

		$alignmentAreaTopY = max(0, $estAlignmentY - $allowance);
		$alignmentAreaBottomY = min($this->image->getHeight() - 1, $estAlignmentY + $allowance);
		if ($alignmentAreaBottomY - $alignmentAreaTopY < $overallEstModuleSize * 3) {
			throw new NotFoundException("Alignment area bottom smaller than overall module size: $alignmentAreaBottomY - $alignmentAreaTopY < $overallEstModuleSize * 3. Allowance: $allowance, estimage of y: $estAlignmentY");
		}

		$alignmentFinder =
			new AlignmentPatternFinder(
				$this->image,
				$alignmentAreaLeftX,
				$alignmentAreaTopY,
				$alignmentAreaRightX - $alignmentAreaLeftX,
				$alignmentAreaBottomY - $alignmentAreaTopY,
				$overallEstModuleSize,
				$this->resultPointCallback
			);

		return $alignmentFinder->find();
	}

	private static function createTransform(
		$topLeft,
		$topRight,
		$bottomLeft,
		$alignmentPattern,
		int $dimension
	): PerspectiveTransform {
		$dimMinusThree = (float)$dimension - 3.5;
		$bottomRightX = 0.0;
		$bottomRightY = 0.0;
		$sourceBottomRightX = 0.0;
		$sourceBottomRightY = 0.0;
		if ($alignmentPattern != null) {
			$bottomRightX = $alignmentPattern->getX();
			$bottomRightY = $alignmentPattern->getY();
			$sourceBottomRightX = $dimMinusThree - 3.0;
			$sourceBottomRightY = $sourceBottomRightX;
		} else {
			// Don't have an alignment pattern, just make up the bottom-right point
			$bottomRightX = ($topRight->getX() - $topLeft->getX()) + $bottomLeft->getX();
			$bottomRightY = ($topRight->getY() - $topLeft->getY()) + $bottomLeft->getY();
			$sourceBottomRightX = $dimMinusThree;
			$sourceBottomRightY = $dimMinusThree;
		}

		return PerspectiveTransform::quadrilateralToQuadrilateral(
			3.5,
			3.5,
			$dimMinusThree,
			3.5,
			$sourceBottomRightX,
			$sourceBottomRightY,
			3.5,
			$dimMinusThree,
			$topLeft->getX(),
			$topLeft->getY(),
			$topRight->getX(),
			$topRight->getY(),
			$bottomRightX,
			$bottomRightY,
			$bottomLeft->getX(),
			$bottomLeft->getY()
		);
	}

	private static function sampleGrid(
		$image,
		PerspectiveTransform $transform,
		int $dimension
	): \Zxing\Common\BitMatrix {
		$sampler = GridSampler::getInstance();

		return $sampler->sampleGrid_($image, $dimension, $dimension, $transform);
	}

	final protected function getImage()
	{
		return $this->image;
	}

	final protected function getResultPointCallback()
	{
		return $this->resultPointCallback;
	}
}

FinderPattern.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Detector;

use  Zxing\ResultPoint;

/**
 * <p>Encapsulates a finder pattern, which are the three square patterns found in
 * the corners of QR Codes. It also encapsulates a count of similar finder patterns,
 * as a convenience to the finder's bookkeeping.</p>
 *
 * @author Sean Owen
 */
final class FinderPattern extends ResultPoint
{
	public function __construct($posX, $posY, private $estimatedModuleSize, private $count = 1)
	{
		parent::__construct($posX, $posY);
	}

	public function getEstimatedModuleSize()
	{
		return $this->estimatedModuleSize;
	}

	public function getCount()
	{
		return $this->count;
	}

	/*
	void incrementCount() {
	  this.count++;
	}
	 */

	/**
	 * <p>Determines if this finder pattern "about equals" a finder pattern at the stated
	 * position and size -- meaning, it is at nearly the same center with nearly the same size.</p>
	 */
	public function aboutEquals($moduleSize, $i, $j): bool
	{
		if (abs($i - $this->getY()) <= $moduleSize && abs($j - $this->getX()) <= $moduleSize) {
			$moduleSizeDiff = abs($moduleSize - $this->estimatedModuleSize);

			return $moduleSizeDiff <= 1.0 || $moduleSizeDiff <= $this->estimatedModuleSize;
		}

		return false;
	}

	/**
	 * Combines this object's current estimate of a finder pattern position and module size
	 * with a new estimate. It returns a new {@code FinderPattern} containing a weighted average
	 * based on count.
	 */
	public function combineEstimate($i, $j, $newModuleSize): \Zxing\Qrcode\Detector\FinderPattern
	{
		$combinedCount = $this->count + 1;
		$combinedX = ($this->count * $this->getX() + $j) / $combinedCount;
		$combinedY = ($this->count * $this->getY() + $i) / $combinedCount;
		$combinedModuleSize = ($this->count * $this->estimatedModuleSize + $newModuleSize) / $combinedCount;

		return new FinderPattern($combinedX, $combinedY, $combinedModuleSize, $combinedCount);
	}
}

FinderPatternFinder.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Zxing\Qrcode\Detector;

use Zxing\Common\BitMatrix;
use Zxing\NotFoundException;
use Zxing\ResultPoint;

/**
 * <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square
 * markers at three corners of a QR Code.</p>
 *
 * <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.
 *
 * @author Sean Owen
 */
class FinderPatternFinder
{
	protected static int $MIN_SKIP = 3;
	protected static int $MAX_MODULES = 57; // 1 pixel/module times 3 modules/center
	private static int $CENTER_QUORUM = 2;
	private ?float $average = null;
	private array $possibleCenters = []; //private final List<FinderPattern> possibleCenters;
	private bool $hasSkipped = false;
	/**
	 * @var mixed|int[]
	 */
	private $crossCheckStateCount;

	/**
	 * <p>Creates a finder that will search the image for three finder patterns.</p>
	 *
	 * @param BitMatrix $image image to search
	 */
	public function __construct(private $image, private $resultPointCallback = null)
	{
		//new ArrayList<>();
		$this->crossCheckStateCount = fill_array(0, 5, 0);
	}

	final public function find(array|null $hints): \Zxing\Qrcode\Detector\FinderPatternInfo
	{/*final FinderPatternInfo find(Map<DecodeHintType,?> hints) throws NotFoundException {*/
		$tryHarder = $hints != null && array_key_exists('TRY_HARDER', $hints) && $hints['TRY_HARDER'];
		$pureBarcode = $hints != null && array_key_exists('PURE_BARCODE', $hints) && $hints['PURE_BARCODE'];
		$nrOfRowsSkippable = $hints != null && array_key_exists('NR_ALLOW_SKIP_ROWS', $hints) ? $hints['NR_ALLOW_SKIP_ROWS'] : ($tryHarder ? 0 : null);
		$allowedDeviation = $hints != null && array_key_exists('ALLOWED_DEVIATION', $hints) ? $hints['ALLOWED_DEVIATION'] : 0.05;
		$maxVariance = $hints != null && array_key_exists('MAX_VARIANCE', $hints) ? $hints['MAX_VARIANCE'] : 0.5;
		$maxI = $this->image->getHeight();
		$maxJ = $this->image->getWidth();
		// We are looking for black/white/black/white/black modules in
		// 1:1:3:1:1 ratio; this tracks the number of such modules seen so far

		// Let's assume that the maximum version QR Code we support takes up 1/4 the height of the
		// image, and then account for the center being 3 modules in size. This gives the smallest
		// number of pixels the center could be, so skip this often. When trying harder, look for all
		// QR versions regardless of how dense they are.
		$iSkip = (int)((3 * $maxI) / (4 * self::$MAX_MODULES));
		if ($iSkip < self::$MIN_SKIP || $tryHarder) {
			$iSkip = self::$MIN_SKIP;
		}

		$done = false;
		$stateCount = [];
		for ($i = $iSkip - 1; $i < $maxI && !$done; $i += $iSkip) {
			// Get a row of black/white values
			$stateCount[0] = 0;
			$stateCount[1] = 0;
			$stateCount[2] = 0;
			$stateCount[3] = 0;
			$stateCount[4] = 0;
			$currentState = 0;
			for ($j = 0; $j < $maxJ; $j++) {
				if ($this->image->get($j, $i)) {
					// Black pixel
					if (($currentState & 1) == 1) { // Counting white pixels
						$currentState++;
					}
					$stateCount[$currentState]++;
				} else { // White pixel
					if (($currentState & 1) == 0) { // Counting black pixels
						if ($currentState == 4) { // A winner?
							if (self::foundPatternCross($stateCount, $maxVariance)) { // Yes
								$confirmed = $this->handlePossibleCenter($stateCount, $i, $j, $pureBarcode);
								if ($confirmed) {
									// Start examining every other line. Checking each line turned out to be too
									// expensive and didn't improve performance.
									$iSkip = 3;
									if ($this->hasSkipped) {
										$done = $this->haveMultiplyConfirmedCenters($allowedDeviation);
									} else {
										$rowSkip = $nrOfRowsSkippable === null ? $this->findRowSkip() : $nrOfRowsSkippable;
										if ($rowSkip > $stateCount[2]) {
											// Skip rows between row of lower confirmed center
											// and top of presumed third confirmed center
											// but back up a bit to get a full chance of detecting
											// it, entire width of center of finder pattern

											// Skip by rowSkip, but back off by $stateCount[2] (size of last center
											// of pattern we saw) to be conservative, and also back off by iSkip which
											// is about to be re-added
											$i += $rowSkip - $stateCount[2] - $iSkip;
											$j = $maxJ - 1;
										}
									}
								} else {
									$stateCount[0] = $stateCount[2];
									$stateCount[1] = $stateCount[3];
									$stateCount[2] = $stateCount[4];
									$stateCount[3] = 1;
									$stateCount[4] = 0;
									$currentState = 3;
									continue;
								}
								// Clear state to start looking again
								$currentState = 0;
								$stateCount[0] = 0;
								$stateCount[1] = 0;
								$stateCount[2] = 0;
								$stateCount[3] = 0;
								$stateCount[4] = 0;
							} else { // No, shift counts back by two
								$stateCount[0] = $stateCount[2];
								$stateCount[1] = $stateCount[3];
								$stateCount[2] = $stateCount[4];
								$stateCount[3] = 1;
								$stateCount[4] = 0;
								$currentState = 3;
							}
						} else {
							$stateCount[++$currentState]++;
						}
					} else { // Counting white pixels
						$stateCount[$currentState]++;
					}
				}
			}
			if (self::foundPatternCross($stateCount, $maxVariance)) {
				$confirmed = $this->handlePossibleCenter($stateCount, $i, $maxJ, $pureBarcode);
				if ($confirmed) {
					$iSkip = $stateCount[0];
					if ($this->hasSkipped) {
						// Found a third one
						$done = $this->haveMultiplyConfirmedCenters($allowedDeviation);
					}
				}
			}
		}

		$patternInfo = $this->selectBestPatterns();
		$patternInfo = ResultPoint::orderBestPatterns($patternInfo);

		return new FinderPatternInfo($patternInfo);
	}

	/**
	 * @param $stateCount ; count of black/white/black/white/black pixels just read
	 * @param int[] $stateCount
	 *
	 * @return bool iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios used by finder patterns to be considered a match
	 *
	 * @psalm-param array<0|positive-int, int> $stateCount
	 */
	protected static function foundPatternCross(array $stateCount, float $maxVariance = 0.5): bool
	{
		$totalModuleSize = 0;
		for ($i = 0; $i < 5; $i++) {
			$count = $stateCount[$i];
			if ($count == 0) {
				return false;
			}
			$totalModuleSize += $count;
		}
		if ($totalModuleSize < 7) {
			return false;
		}
		$moduleSize = $totalModuleSize / 7.0;
		$maxVariance = $moduleSize * $maxVariance;

		// Allow less than 50% variance from 1-1-3-1-1 proportions
		return
			abs($moduleSize - $stateCount[0]) < $maxVariance &&
			abs($moduleSize - $stateCount[1]) < $maxVariance &&
			abs(3.0 * $moduleSize - $stateCount[2]) < 3 * $maxVariance &&
			abs($moduleSize - $stateCount[3]) < $maxVariance &&
			abs($moduleSize - $stateCount[4]) < $maxVariance;
	}

	/**
	 * <p>This is called when a horizontal scan finds a possible alignment pattern. It will
	 * cross check with a vertical scan, and if successful, will, ah, cross-cross-check
	 * with another horizontal scan. This is needed primarily to locate the real horizontal
	 * center of the pattern in cases of extreme skew.
	 * And then we cross-cross-cross check with another diagonal scan.</p>
	 *
	 * <p>If that succeeds the finder pattern location is added to a list that tracks
	 * the number of times each location has been nearly-matched as a finder pattern.
	 * Each additional find is more evidence that the location is in fact a finder
	 * pattern center
	 *
	 * @param array $stateCount reading state module counts from horizontal scan
	 * @param int $i row           where finder pattern may be found
	 * @param int $j end           of possible finder pattern in row
	 * @param bool $pureBarcode true if in "pure barcode" mode
	 *
	 * @return bool if a finder pattern candidate was found this time
	 */
	final protected function handlePossibleCenter($stateCount, int $i, int $j, bool $pureBarcode): bool
	{
		$stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2] + $stateCount[3] +
			$stateCount[4];
		$centerJ = self::centerFromEnd($stateCount, $j);
		$centerI = $this->crossCheckVertical($i, (int)($centerJ), $stateCount[2], $stateCountTotal);
		if (!is_nan($centerI)) {
			// Re-cross check
			$centerJ = $this->crossCheckHorizontal((int)($centerJ), (int)($centerI), $stateCount[2], $stateCountTotal);
			if (
				!is_nan($centerJ) &&
				(!$pureBarcode || $this->crossCheckDiagonal((int)($centerI), (int)($centerJ), $stateCount[2], $stateCountTotal))
			) {
				$estimatedModuleSize = (float)$stateCountTotal / 7.0;
				$found = false;
				for ($index = 0; $index < count($this->possibleCenters); $index++) {
					$center = $this->possibleCenters[$index];
					// Look for about the same center and module size:
					if ($center->aboutEquals($estimatedModuleSize, $centerI, $centerJ)) {
						$this->possibleCenters[$index] = $center->combineEstimate($centerI, $centerJ, $estimatedModuleSize);
						$found = true;
						break;
					}
				}
				if (!$found) {
					$point = new FinderPattern($centerJ, $centerI, $estimatedModuleSize);
					$this->possibleCenters[] = $point;
					if ($this->resultPointCallback != null) {
						$this->resultPointCallback->foundPossibleResultPoint($point);
					}
				}

				return true;
			}
		}

		return false;
	}

	/**
	 * Given a count of black/white/black/white/black pixels just seen and an end position,
	 * figures the location of the center of this run.
	 */
	private static function centerFromEnd(array $stateCount, int $end)
	{
		return (float)($end - $stateCount[4] - $stateCount[3]) - $stateCount[2] / 2.0;
	}

	/**
	 * <p>After a horizontal scan finds a potential finder pattern, this method
	 * "cross-checks" by scanning down vertically through the center of the possible
	 * finder pattern to see if the same proportion is detected.</p>
	 *
	 * @param int $startI   ;  row where a finder pattern was detected
	 * @param int $centerJ   ; center of the section that appears to cross a finder pattern
	 * @param int $maxCount ; maximum reasonable number of modules that should be
	 *                  observed in any reading state, based on the results of the horizontal scan
	 *
	 * @return float vertical center of finder pattern, or {@link Float#NaN} if not found
	 */
	private function crossCheckVertical(
		int $startI,
		int $centerJ,
		int $maxCount,
		int|float $originalStateCountTotal
	) {
		$image = $this->image;

		$maxI = $image->getHeight();
		$stateCount = $this->getCrossCheckStateCount();

		// Start counting up from center
		$i = $startI;
		while ($i >= 0 && $image->get($centerJ, $i)) {
			$stateCount[2]++;
			$i--;
		}
		if ($i < 0) {
			return NAN;
		}
		while ($i >= 0 && !$image->get($centerJ, $i) && $stateCount[1] <= $maxCount) {
			$stateCount[1]++;
			$i--;
		}
		// If already too many modules in this state or ran off the edge:
		if ($i < 0 || $stateCount[1] > $maxCount) {
			return NAN;
		}
		while ($i >= 0 && $image->get($centerJ, $i) && $stateCount[0] <= $maxCount) {
			$stateCount[0]++;
			$i--;
		}
		if ($stateCount[0] > $maxCount) {
			return NAN;
		}

		// Now also count down from center
		$i = $startI + 1;
		while ($i < $maxI && $image->get($centerJ, $i)) {
			$stateCount[2]++;
			$i++;
		}
		if ($i == $maxI) {
			return NAN;
		}
		while ($i < $maxI && !$image->get($centerJ, $i) && $stateCount[3] < $maxCount) {
			$stateCount[3]++;
			$i++;
		}
		if ($i == $maxI || $stateCount[3] >= $maxCount) {
			return NAN;
		}
		while ($i < $maxI && $image->get($centerJ, $i) && $stateCount[4] < $maxCount) {
			$stateCount[4]++;
			$i++;
		}
		if ($stateCount[4] >= $maxCount) {
			return NAN;
		}

		// If we found a finder-pattern-like section, but its size is more than 40% different than
		// the original, assume it's a false positive
		$stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2] + $stateCount[3] +
			$stateCount[4];
		if (5 * abs($stateCountTotal - $originalStateCountTotal) >= 2 * $originalStateCountTotal) {
			return NAN;
		}

		return self::foundPatternCross($stateCount) ? self::centerFromEnd($stateCount, $i) : NAN;
	}

	private function getCrossCheckStateCount()
	{
		$this->crossCheckStateCount[0] = 0;
		$this->crossCheckStateCount[1] = 0;
		$this->crossCheckStateCount[2] = 0;
		$this->crossCheckStateCount[3] = 0;
		$this->crossCheckStateCount[4] = 0;

		return $this->crossCheckStateCount;
	}

	/**
	 * <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical,
	 * except it reads horizontally instead of vertically. This is used to cross-cross
	 * check a vertical cross check and locate the real center of the alignment pattern.</p>
	 */
	private function crossCheckHorizontal(
		int $startJ,
		int $centerI,
		int $maxCount,
		int|float $originalStateCountTotal
	) {
		$image = $this->image;

		$maxJ = $this->image->getWidth();
		$stateCount = $this->getCrossCheckStateCount();

		$j = $startJ;
		while ($j >= 0 && $image->get($j, $centerI)) {
			$stateCount[2]++;
			$j--;
		}
		if ($j < 0) {
			return NAN;
		}
		while ($j >= 0 && !$image->get($j, $centerI) && $stateCount[1] <= $maxCount) {
			$stateCount[1]++;
			$j--;
		}
		if ($j < 0 || $stateCount[1] > $maxCount) {
			return NAN;
		}
		while ($j >= 0 && $image->get($j, $centerI) && $stateCount[0] <= $maxCount) {
			$stateCount[0]++;
			$j--;
		}
		if ($stateCount[0] > $maxCount) {
			return NAN;
		}

		$j = $startJ + 1;
		while ($j < $maxJ && $image->get($j, $centerI)) {
			$stateCount[2]++;
			$j++;
		}
		if ($j == $maxJ) {
			return NAN;
		}
		while ($j < $maxJ && !$image->get($j, $centerI) && $stateCount[3] < $maxCount) {
			$stateCount[3]++;
			$j++;
		}
		if ($j == $maxJ || $stateCount[3] >= $maxCount) {
			return NAN;
		}
		while ($j < $maxJ && $this->image->get($j, $centerI) && $stateCount[4] < $maxCount) {
			$stateCount[4]++;
			$j++;
		}
		if ($stateCount[4] >= $maxCount) {
			return NAN;
		}

		// If we found a finder-pattern-like section, but its size is significantly different than
		// the original, assume it's a false positive
		$stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2] + $stateCount[3] +
			$stateCount[4];
		if (5 * abs($stateCountTotal - $originalStateCountTotal) >= $originalStateCountTotal) {
			return NAN;
		}

		return static::foundPatternCross($stateCount) ? self::centerFromEnd($stateCount, $j) : NAN;
	}

	/**
	 * After a vertical and horizontal scan finds a potential finder pattern, this method
	 * "cross-cross-cross-checks" by scanning down diagonally through the center of the possible
	 * finder pattern to see if the same proportion is detected.
	 *
	 * @param $startI                 ;  row where a finder pattern was detected
	 * @param $centerJ                 ; center of the section that appears to cross a finder pattern
	 * @param $maxCount               ; maximum reasonable number of modules that should be
	 *                                observed in any reading state, based on the results of the horizontal scan
	 * @param $originalStateCountTotal ; The original state count total.
	 *
	 * @return bool if proportions are withing expected limits
	 */
	private function crossCheckDiagonal(int $startI, int $centerJ, $maxCount, int|float $originalStateCountTotal): bool
	{
		$stateCount = $this->getCrossCheckStateCount();

		// Start counting up, left from center finding black center mass
		$i = 0;
		while ($startI >= $i && $centerJ >= $i && $this->image->get($centerJ - $i, $startI - $i)) {
			$stateCount[2]++;
			$i++;
		}

		if ($startI < $i || $centerJ < $i) {
			return false;
		}

		// Continue up, left finding white space
		while (
			$startI >= $i && $centerJ >= $i && !$this->image->get($centerJ - $i, $startI - $i) &&
			$stateCount[1] <= $maxCount
		) {
			$stateCount[1]++;
			$i++;
		}

		// If already too many modules in this state or ran off the edge:
		if ($startI < $i || $centerJ < $i || $stateCount[1] > $maxCount) {
			return false;
		}

		// Continue up, left finding black border
		while (
			$startI >= $i && $centerJ >= $i && $this->image->get($centerJ - $i, $startI - $i) &&
			$stateCount[0] <= $maxCount
		) {
			$stateCount[0]++;
			$i++;
		}
		if ($stateCount[0] > $maxCount) {
			return false;
		}

		$maxI = $this->image->getHeight();
		$maxJ = $this->image->getWidth();

		// Now also count down, right from center
		$i = 1;
		while ($startI + $i < $maxI && $centerJ + $i < $maxJ && $this->image->get($centerJ + $i, $startI + $i)) {
			$stateCount[2]++;
			$i++;
		}

		// Ran off the edge?
		if ($startI + $i >= $maxI || $centerJ + $i >= $maxJ) {
			return false;
		}

		while (
			$startI + $i < $maxI && $centerJ + $i < $maxJ && !$this->image->get($centerJ + $i, $startI + $i) &&
			$stateCount[3] < $maxCount
		) {
			$stateCount[3]++;
			$i++;
		}

		if ($startI + $i >= $maxI || $centerJ + $i >= $maxJ || $stateCount[3] >= $maxCount) {
			return false;
		}

		while (
			$startI + $i < $maxI && $centerJ + $i < $maxJ && $this->image->get($centerJ + $i, $startI + $i) &&
			$stateCount[4] < $maxCount
		) {
			$stateCount[4]++;
			$i++;
		}

		if ($stateCount[4] >= $maxCount) {
			return false;
		}

		// If we found a finder-pattern-like section, but its size is more than 100% different than
		// the original, assume it's a false positive
		$stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2] + $stateCount[3] + $stateCount[4];

		return
			abs($stateCountTotal - $originalStateCountTotal) < 2 * $originalStateCountTotal &&
			self::foundPatternCross($stateCount);
	}

	/**
	 * @return bool iff we have found at least 3 finder patterns that have been detected at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the candidates is "pretty similar"
	 */
	private function haveMultiplyConfirmedCenters(?float $allowedDeviation = 0.05): bool
	{
		$confirmedCount = 0;
		$totalModuleSize = 0.0;
		$max = count($this->possibleCenters);
		foreach ($this->possibleCenters as $pattern) {
			if ($pattern->getCount() >= self::$CENTER_QUORUM) {
				$confirmedCount++;
				$totalModuleSize += $pattern->getEstimatedModuleSize();
			}
		}
		if ($confirmedCount < 3) {
			return false;
		}
		// OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"
		// and that we need to keep looking. We detect this by asking if the estimated module sizes
		// vary too much. We arbitrarily say that when the total deviation from average exceeds
		// 5% of the total module size estimates, it's too much.
		$average = $totalModuleSize / (float)$max;
		$totalDeviation = 0.0;
		foreach ($this->possibleCenters as $pattern) {
			$totalDeviation += abs($pattern->getEstimatedModuleSize() - $average);
		}

		return $totalDeviation <= $allowedDeviation * $totalModuleSize;
	}

	/**
	 * @return int number of rows we could safely skip during scanning, based on the first
	 *         two finder patterns that have been located. In some cases their position will
	 *         allow us to infer that the third pattern must lie below a certain point farther
	 *         down in the image.
	 */
	private function findRowSkip()
	{
		$max = count($this->possibleCenters);
		if ($max <= 1) {
			return 0;
		}
		$firstConfirmedCenter = null;
		foreach ($this->possibleCenters as $center) {
			if ($center->getCount() >= self::$CENTER_QUORUM) {
				if ($firstConfirmedCenter == null) {
					$firstConfirmedCenter = $center;
				} else {
					// We have two confirmed centers
					// How far down can we skip before resuming looking for the next
					// pattern? In the worst case, only the difference between the
					// difference in the x / y coordinates of the two centers.
					// This is the case where you find top left last.
					$this->hasSkipped = true;

					return (int)((abs($firstConfirmedCenter->getX() - $center->getX()) -
						abs($firstConfirmedCenter->getY() - $center->getY())) / 2);
				}
			}
		}

		return 0;
	}

	/**
	 * @return array the 3 best {@link FinderPattern}s from our list of candidates. The "best" are
	 *         those that have been detected at least {@link #CENTER_QUORUM} times, and whose module
	 *         size differs from the average among those patterns the least
	 * @throws NotFoundException if 3 such finder patterns do not exist
	 */
	private function selectBestPatterns()
	{
		$startSize = count($this->possibleCenters);
		if ($startSize < 3) {
			// Couldn't find enough finder patterns
			throw new NotFoundException("Could not find 3 finder patterns ($startSize found)");
		}

		// Filter outlier possibilities whose module size is too different
		if ($startSize > 3) {
			// But we can only afford to do so if we have at least 4 possibilities to choose from
			$totalModuleSize = 0.0;
			$square = 0.0;
			foreach ($this->possibleCenters as $center) {
				$size = $center->getEstimatedModuleSize();
				$totalModuleSize += $size;
				$square += $size * $size;
			}
			$this->average = $totalModuleSize / (float)$startSize;
			$stdDev = (float)sqrt($square / $startSize - $this->average * $this->average);

			usort($this->possibleCenters, $this->FurthestFromAverageComparator(...));

			$limit = max(0.2 * $this->average, $stdDev);

			for ($i = 0; $i < count($this->possibleCenters) && count($this->possibleCenters) > 3; $i++) {
				$pattern = $this->possibleCenters[$i];
				if (abs($pattern->getEstimatedModuleSize() - $this->average) > $limit) {
					unset($this->possibleCenters[$i]); //возможно что ключи меняются в java при вызове .remove(i) ???
					$this->possibleCenters = array_values($this->possibleCenters);
					$i--;
				}
			}
		}

		if (count($this->possibleCenters) > 3) {
			// Throw away all but those first size candidate points we found.

			$totalModuleSize = 0.0;
			foreach ($this->possibleCenters as $possibleCenter) {
				$totalModuleSize += $possibleCenter->getEstimatedModuleSize();
			}

			$this->average = $totalModuleSize / (float)count($this->possibleCenters);

			usort($this->possibleCenters, $this->CenterComparator(...));

			array_slice($this->possibleCenters, 3, count($this->possibleCenters) - 3);
		}

		return [$this->possibleCenters[0], $this->possibleCenters[1], $this->possibleCenters[2]];
	}

	/**
	 * <p>Orders by furthest from average</p>
	 *
	 * @psalm-return -1|0|1
	 */
	public function FurthestFromAverageComparator($center1, $center2): int
	{
		$dA = abs($center2->getEstimatedModuleSize() - $this->average);
		$dB = abs($center1->getEstimatedModuleSize() - $this->average);
		if ($dA < $dB) {
			return -1;
		} elseif ($dA == $dB) {
			return 0;
		} else {
			return 1;
		}
	}

	public function CenterComparator($center1, $center2)
	{
		if ($center2->getCount() == $center1->getCount()) {
			$dA = abs($center2->getEstimatedModuleSize() - $this->average);
			$dB = abs($center1->getEstimatedModuleSize() - $this->average);
			if ($dA < $dB) {
				return 1;
			} elseif ($dA == $dB) {
				return 0;
			} else {
				return -1;
			}
		} else {
			return $center2->getCount() - $center1->getCount();
		}
	}

	final protected function getImage(): BitMatrix
	{
		return $this->image;
	}
	/**
	 * <p>Orders by {@link FinderPattern#getCount()}, descending.</p>
	 */
	final protected function getPossibleCenters(): array
	{ //List<FinderPattern> getPossibleCenters()
		return $this->possibleCenters;
	}
}

FinderPatternInfo.phpQR
Script de practica.
Abrir
Ver codigo

<?php
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Zxing\Qrcode\Detector;

/**
 * <p>Encapsulates information about finder patterns in an image, including the location of
 * the three finder patterns, and their estimated module size.</p>
 *
 * @author Sean Owen
 */
final class FinderPatternInfo
{
	private $bottomLeft;
	private $topLeft;
	private $topRight;

	public function __construct($patternCenters)
	{
		$this->bottomLeft = $patternCenters[0];
		$this->topLeft = $patternCenters[1];
		$this->topRight = $patternCenters[2];
	}

	public function getBottomLeft()
	{
		return $this->bottomLeft;
	}

	public function getTopLeft()
	{
		return $this->topLeft;
	}

	public function getTopRight()
	{
		return $this->topRight;
	}
}

proyDATATABLES

Tabla de datos con busqueda y modal (MySQL).
conexion.phpMySQL
Conexion a la base de datos.
Abrir
Ver codigo


<?php

$servidor = "localhost";
$usuario = "root";
$contrasena = "";
$base_datos = "instituto";

$conexion = mysqli_connect(
    $servidor,
    $usuario,
    $contrasena,
    $base_datos
);

if (!$conexion) {
    die("Error de conexión: " . mysqli_connect_error());
}

mysqli_set_charset($conexion, "utf8mb4");
?>

indice.phpMySQL
Listado / indice del ejercicio.
Abrir
Ver codigo


<?php
require_once "conexion.php";

$sql = "SELECT id, carnet, nombres, apellidos,
               carrera, nota_final
        FROM estudiantes";

$resultado = mysqli_query($conexion, $sql);

if (!$resultado) {
    die("Error al consultar estudiantes: "
        . mysqli_error($conexion));
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">

    <title>Gestión de Estudiantes</title>

    <!-- CSS local de DataTables -->
    <link rel="stylesheet" href="datatables/datatables.css">

    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f2f5f9;
            margin: 0;
            padding: 25px;
            color: #263238;
        }

        .contenedor {
            max-width: 1200px;
            margin: auto;
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 3px 12px #00000012;
        }

        h1 {
            color: #17365d;
            margin-top: 0;
        }

        .subtitulo {
            color: #546e7a;
            margin-bottom: 25px;
        }

        .tabla-contenedor {
            overflow-x: auto;
        }

        table {
            width: 100%;
        }

        .aprobado {
            color: #187443;
            font-weight: bold;
        }

        .reprobado {
            color: #bd3030;
            font-weight: bold;
        }
    </style>
</head>
<body>

<div class="contenedor">

    <h1>Gestión de Estudiantes</h1>

    <p class="subtitulo">
        Sistema académico - Consulta de registros
    </p>

    <div class="tabla-contenedor">
        <table id="tablaEstudiantes"
               class="display">

            <thead>
                <tr>
                    <th>ID</th>
                    <th>Carnet</th>
                    <th>Nombres</th>
                    <th>Apellidos</th>
                    <th>Carrera</th>
                    <th>Nota final</th>
                    <th>Estado</th>
                </tr>
            </thead>

            <tbody>
            <?php while ($fila = mysqli_fetch_assoc($resultado)) { ?>

                <tr>
                    <td>
                        <?= (int)$fila["id"] ?>
                    </td>

                    <td>
                        <?= htmlspecialchars(
                            $fila["carnet"],
                            ENT_QUOTES,
                            "UTF-8"
                        ) ?>
                    </td>

                    <td>
                        <?= htmlspecialchars(
                            $fila["nombres"],
                            ENT_QUOTES,
                            "UTF-8"
                        ) ?>
                    </td>

                    <td>
                        <?= htmlspecialchars(
                            $fila["apellidos"],
                            ENT_QUOTES,
                            "UTF-8"
                        ) ?>
                    </td>

                    <td>
                        <?= htmlspecialchars(
                            $fila["carrera"],
                            ENT_QUOTES,
                            "UTF-8"
                        ) ?>
                    </td>

                    <td>
                        <?= htmlspecialchars(
                            (string)$fila["nota_final"],
                            ENT_QUOTES,
                            "UTF-8"
                        ) ?>
                    </td>

                    <td>
                        <?php if ((float)$fila["nota_final"] >= 61) { ?>
                            <span class="aprobado">
                                Aprobado
                            </span>
                        <?php } else { ?>
                            <span class="reprobado">
                                Reprobado
                            </span>
                        <?php } ?>
                    </td>
                </tr>

            <?php } ?>
            </tbody>

        </table>
    </div>

</div>

<!-- JavaScript local de DataTables -->
<script src="datatables/datatables.js"></script>

<script>
    document.addEventListener("DOMContentLoaded", function () {

        new DataTable("#tablaEstudiantes", {

            pageLength: 5,

            lengthMenu: [5, 10, 25, 50],

            order: [[1, "asc"]],

            language: {
                emptyTable: "No hay datos disponibles",
                info: "Mostrando _START_ a _END_ de _TOTAL_ registros",
                infoEmpty: "Mostrando 0 a 0 de 0 registros",
                infoFiltered: "(filtrado de _MAX_ registros totales)",
                lengthMenu: "Mostrar _MENU_ registros",
                loadingRecords: "Cargando...",
                processing: "Procesando...",
                search: "Buscar:",
                zeroRecords: "No se encontraron coincidencias",
                paginate: {
                    first: "Primero",
                    last: "Último",
                    next: "Siguiente",
                    previous: "Anterior"
                },
                aria: {
                    orderable: "Ordenar por esta columna",
                    orderableReverse: "Invertir el orden de esta columna"
                }
            }

        });

    });
</script>

</body>
</html>

<?php
mysqli_free_result($resultado);
mysqli_close($conexion);
?>

indice_modal.phpMySQL
Listado / indice del ejercicio.
Abrir
Ver codigo


<?php
require_once "conexion.php";

$sql = "SELECT * FROM est1";
$resultado = mysqli_query($conexion, $sql);

if (!$resultado) {
    die("Error al consultar estudiantes: "
        . mysqli_error($conexion));
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">

    <title>Gestión de Estudiantes</title>
<!-- Estilos principales -->
    <link rel="stylesheet" href="datatables/datatables.css">
        <!-- Estilos locales de los botones -->
    <link rel="stylesheet" href="datatables/buttons.dataTables.min.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f2f5f9;
            margin: 0;
            padding: 25px;
            color: #263238;
        }

        .contenedor {
            max-width: 1200px;
            margin: auto;
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 3px 12px #00000012;
        }

        h1 {
            color: #17365d;
            margin-top: 0;
        }

        .subtitulo {
            color: #546e7a;
            margin-bottom: 25px;
        }

        .tabla-contenedor {
            overflow-x: auto;
        }

        table {
            width: 100%;
        }

        .aprobado {
            color: #187443;
            font-weight: bold;
        }

        .reprobado {
            color: #bd3030;
            font-weight: bold;
        }

/* Indicar que las filas son seleccionables */
#tablaEstudiantes tbody tr {
    cursor: pointer;
}

/* Efecto visual al pasar el ratón */
#tablaEstudiantes tbody tr:hover {
    background-color: #e8f2ff;
}

/* Fondo oscuro de la ventana modal */
.modal {
    display: none;
    position: fixed;
    z-index: 10000;
    inset: 0;
    background-color: rgba(0, 0, 0, 0.55);

    /* Centrar la ventana */
    justify-content: center;
    align-items: center;

    padding: 20px;
    box-sizing: border-box;
}

/* Contenedor de la ventana */
.modal-contenido {
    background-color: #ffffff;
    width: 100%;
    max-width: 500px;
    max-height: 85vh;
    overflow-y: auto;
    padding: 25px;
    border-radius: 12px;
    box-shadow: 0 5px 25px rgba(0, 0, 0, 0.3);
    box-sizing: border-box;
}

/* Título de la ventana */
.modal-contenido h2 {
    margin-top: 0;
    color: #17365d;
    border-bottom: 2px solid #17365d;
    padding-bottom: 12px;
}

/* Datos del estudiante */
.dato-fila {
    display: flex;
    justify-content: space-between;
    gap: 15px;
    padding: 10px 0;
    border-bottom: 1px solid #eeeeee;
}

.dato-etiqueta {
    font-weight: bold;
    color: #37474f;
}

.dato-valor {
    text-align: right;
    overflow-wrap: anywhere;
}

/* Botón cerrar */
.btn-cerrar {
    display: block;
    width: 100%;
    margin-top: 22px;
    padding: 12px;
    border: none;
    border-radius: 6px;
    background-color: #17365d;
    color: white;
    font-size: 16px;
    cursor: pointer;
}

.btn-cerrar:hover {
    background-color: #24558b;
}

.dt-paging {
    padding-top: 10px !important;
}
.dt-paging .dt-paging-button {
    background-color: lightblue !important;
    border: 1px solid #cfd8dc !important;
    color: #37474f !important;           /* Color del texto ("Siguiente", "Anterior", etc.) */
    border-radius: 6px !important;       /* Bordes redondeados */
    padding: 6px 12px !important;        /* Espaciado interno */
    margin: 0 3px !important;            /* Separación entre botones */
    font-size: 14px !important;
    cursor: pointer;
    transition: all 0.2s ease-in-out;
}


    </style>
</head>
<body>

<div class="contenedor">

    <h1>Gestión de Estudiantes</h1>

    <p class="subtitulo">
        Sistema académico - Consulta de registros
    </p>

    <div class="tabla-contenedor">
        <table id="tablaEstudiantes"
               class="display">

            <thead>
                <tr>
                    <th>ID</th>
                    <th>Apellido Paterno</th>
					<th>Apellido Materno</th>
                    <th>Nombres</th>
                    <th>Género</th>
                    <th>Fecha de nacimiento</th>
                    <th>Email</th>
                </tr>
            </thead>

            <tbody>
            <?php while ($fila = mysqli_fetch_assoc($resultado)) { ?>

                <tr>
                    <td>
                        <?= (int)$fila["id"] ?>
                    </td>

                    <td>
                        <?= htmlspecialchars(
                            $fila["paterno"],
                            ENT_QUOTES,
                            "UTF-8"
                        ) ?>
                    </td>

                    <td>
                        <?= htmlspecialchars(
                            $fila["materno"],
                            ENT_QUOTES,
                            "UTF-8"
                        ) ?>
                    </td>

                    <td>
                        <?= htmlspecialchars(
                            $fila["nombres"],
                            ENT_QUOTES,
                            "UTF-8"
                        ) ?>
                    </td>

                    <td>
                        <?= htmlspecialchars(
                            $fila["genero"],
                            ENT_QUOTES,
                            "UTF-8"
                        ) ?>
                    </td>
                    <td>
                        <?= htmlspecialchars(
                            $fila["fechaNac"],
                            ENT_QUOTES,
                            "UTF-8"
                        ) ?>
                    </td>
                    <td>
                        <?= htmlspecialchars(
                            $fila["email"],
                            ENT_QUOTES,
                            "UTF-8"
                        ) ?>
                    </td>					
<!--
                    <td>
                        <?= htmlspecialchars(
                            (string)$fila["nota_final"],
                            ENT_QUOTES,
                            "UTF-8"
                        ) ?>
                    </td>

                    <td>
                        <?php if ((float)$fila["nota_final"] >= 61) { ?>
                            <span class="aprobado">
                                Aprobado
                            </span>
                        <?php } else { ?>
                            <span class="reprobado">
                                Reprobado
                            </span>
                        <?php } ?>
                    </td>
					-->
                </tr>

            <?php } ?>
            </tbody>

        </table>
    </div>

</div>


<!-- Ventana modal de datos del estudiante -->
<div id="modalEstudiante" class="modal">
    <div class="modal-contenido">
        <h2>Datos del estudiante</h2>
        <div id="detalleEstudiante"></div>
        <button
            type="button"
            id="btnCerrar"
            class="btn-cerrar">
            Cerrar
        </button>
    </div>
</div>

<!-- *************************************** -->
<!-- 1. Script principal de DataTables -->
<script src="datatables/datatables.js"></script>
<!-- 2. Dependencias de exportación locales (JSZip y pdfmake) -->
<script src="datatables/jszip.min.js"></script>
<script src="datatables/pdfmake.min.js"></script>
<script src="datatables/vfs_fonts.js"></script>

<!-- 3. Extensión Buttons y soporte para HTML5 local -->
<script src="datatables/dataTables.buttons.min.js"></script>
<script src="datatables/buttons.html5.min.js"></script>

<script>
document.addEventListener("DOMContentLoaded", function () {

        new DataTable("#tablaEstudiantes", {
            pageLength: 10,
            lengthMenu: [5, 10, 25, 50, 100, 200],
            order: [[1, "asc"]],
            
            // ---  BOTONES ---
layout: {
            topStart: [
                'pageLength', 
                {
                    buttons: [
                        { extend: 'excelHtml5', text: 'Exportar a MS Excel',className: 'btn-excel' },
                        { extend: 'pdfHtml5', text: 'Exportar a PDF',className: 'btn-pdf'  }
                    ]
                }
            ],

			topEnd: {
					search: {
						placeholder: 'Buscar estudiante...',className:'btn-buscar' 
					}
			}
	
        },
            // ----------------------------------------------

            language: {
                emptyTable: "No hay datos disponibles",
                info: "Mostrando _START_ a _END_ de _TOTAL_ registros",
                infoEmpty: "Mostrando 0 a 0 de 0 registros",
                infoFiltered: "(filtrado de _MAX_ registros totales)",
                lengthMenu: "Mostrar _MENU_ registros",
                loadingRecords: "Cargando...",
                processing: "Procesando...",
                search: "Buscar:",
                zeroRecords: "No se encontraron coincidencias",
                paginate: {
                    first: "Primero",
                    last: "Último",
                    next: "Siguiente",
                    previous: "Anterior"
                },
                aria: {
                    orderable: "Ordenar por esta columna",
                    orderableReverse: "Invertir el orden de esta columna"
                }
            }
        });

        // *************************************
const tabla = document.querySelector("#tablaEstudiantes");
const modal = document.querySelector("#modalEstudiante");
const detalle = document.querySelector("#detalleEstudiante");
const btnCerrar = document.querySelector("#btnCerrar");

// Capturar el clic sobre cualquier fila
tabla.querySelector("tbody").addEventListener("click", function (evento) {

    const fila = evento.target.closest("tr");

    if (!fila) {
        return;
    }

    // Obtener las celdas de la fila seleccionada
    const celdas = Array.from(fila.cells);

    const etiquetas = [
        "ID",
        "Apellido Paterno",
        "Apellido Materno",
        "Nombres",
        "Género",
        "Fecha de nacimiento",
        "Email"
    ];

    // Construir el contenido de la ventana
    detalle.replaceChildren();

    celdas.forEach(function (celda, indice) {

        const contenedor = document.createElement("div");
        contenedor.className = "dato-fila";

        const etiqueta = document.createElement("span");
        etiqueta.className = "dato-etiqueta";
        etiqueta.textContent = etiquetas[indice] || "Dato";

        const valor = document.createElement("span");
        valor.className = "dato-valor";
        valor.textContent = celda.innerText.trim();

        contenedor.appendChild(etiqueta);
        contenedor.appendChild(valor);

        detalle.appendChild(contenedor);

    });

    // Mostrar la ventana modal
    modal.style.display = "flex";

});

// Cerrar mediante el botón
btnCerrar.addEventListener("click", function () {
    modal.style.display = "none";
});

// Cerrar al hacer clic fuera de la ventana
modal.addEventListener("click", function (evento) {
    if (evento.target === modal) {
        modal.style.display = "none";
    }
});

// Cerrar con la tecla Escape
document.addEventListener("keydown", function (evento) {
    if (evento.key === "Escape") {
        modal.style.display = "none";
    }
});


    });
</script>

</body>
</html>

<?php
mysqli_free_result($resultado);
mysqli_close($conexion);
?>

KemaMada © 2026 · github.com/KemaMada