Sistema Contenedor Ibiza v2.0 - Despliegue Docker

This commit is contained in:
2026-02-01 00:26:47 -06:00
commit 4d07b4b14c
355 changed files with 110875 additions and 0 deletions

18
.env Normal file
View File

@@ -0,0 +1,18 @@
# Database Configuration
DB_HOST=10.10.4.17:3391
DB_NAME=contenedor_ibiza1
DB_USER=nickpons666
DB_PASS=MiPo6425@@
# Site Configuration
SITE_URL=http://contenedor-test.local:82
# Telegram Bot
TELEGRAM_BOT_TOKEN=8589698394:AAFSphFBEy1DQmOIUDyEKCMAwksTaYlatYE
# Session Configuration
SESSION_NAME=contenedor_session
SESSION_LIFETIME=7200
# Timezone
TIMEZONE=America/Mexico_City

18
.env.example Normal file
View File

@@ -0,0 +1,18 @@
# Database Configuration
DB_HOST=10.10.4.17:3391
DB_NAME=contenedor_ibiza
DB_USER=nickpons666
DB_PASS=MiPo6425@@
# Site Configuration
SITE_URL=http://contenedor-test.local:82
# Telegram Bot
TELEGRAM_BOT_TOKEN=8589698394:AAFSphFBEy1DQmOIUDyEKCMAwksTaYlatYE
# Session Configuration
SESSION_NAME=contenedor_session
SESSION_LIFETIME=7200
# Timezone
TIMEZONE=America/Mexico_City

54
Dockerfile Normal file
View File

@@ -0,0 +1,54 @@
FROM debian:bullseye-slim
# Evitar interacciones durante instalación
ENV DEBIAN_FRONTEND=noninteractive
# Instalar dependencias
RUN apt-get update && apt-get install -y \
apache2 \
php \
php-mysql \
php-mbstring \
php-gd \
php-zip \
php-curl \
composer \
supervisor \
cron \
curl \
unzip \
git \
&& rm -rf /var/lib/apt/lists/*
# Configurar Apache
RUN a2enmod rewrite
COPY apache-config.conf /etc/apache2/sites-available/000-default.conf
# Copiar proyecto
WORKDIR /var/www/html
COPY . .
# Instalar dependencias de Composer
# Ajustar permisos temporalmente para composer
RUN mkdir -p /var/www/html/vendor
RUN composer install --no-dev --optimize-autoloader
# Configurar permisos finales
RUN chown -R www-data:www-data /var/www/html \
&& chmod -R 755 /var/www/html \
&& mkdir -p /var/www/html/logs \
&& chown -R www-data:www-data /var/www/html/logs
# Configurar Supervisor
COPY supervisor.conf /etc/supervisor/conf.d/contenedor.conf
# Exponer puerto
EXPOSE 80
# Configurar Entrypoint
COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
# Iniciar Supervisor
CMD ["/usr/bin/supervisord", "-n", "-c", "/etc/supervisor/conf.d/contenedor.conf"]

75
README.md Normal file
View File

@@ -0,0 +1,75 @@
# Sistema de Gestión de Contenedor Ibiza
Aplicación web integral para la gestión automatizada de rotaciones de turnos, horarios y notificaciones para el contenedor de Ibiza.
## 🚀 Características Principales
* **Gestión de Rotaciones Automatizada**: Generación automática de turnos semanales basada en un "Orden Maestro" personalizable.
* **Roles de Usuario**: Sistema de permisos granular (Administrador, Coordinador, Ayudante).
* **Bot de Telegram Integrado**:
* Consultas interactivas (Itinerario, Horarios, PDF) mediante botones.
* Búsqueda de turnos por nombre natural.
* Gestión de Webhook desde panel administrativo.
* **Generación de PDF**: Reportes descargables con la programación completa.
* **Interfaz Robusta**: Diseño responsive, drag-and-drop para reordenar turnos.
* **Docker Ready**: Preparado para despliegue en CasaOS, ZimaOS o Portainer.
## 📋 Requisitos
* Docker y Docker Compose
* Servidor MySQL/MariaDB externo (o en otro contenedor)
## 🛠️ Instalación y Despliegue
### Opción A: Docker Compose / Portainer
1. Clona el repositorio.
2. Construye la imagen:
```bash
docker build -t contenedor-ibiza .
```
3. Ejecuta con las variables de entorno necesarias (ver `contenedor.yaml` como ejemplo).
### Opción B: CasaOS / ZimaOS
1. Utiliza la función de "Importar" y selecciona el archivo `contenedor.yaml`.
2. Ajusta las variables de entorno en la interfaz antes de finalizar.
## ⚙️ Variables de Entorno
| Variable | Descripción | Ejemplo |
|----------|-------------|---------|
| `DB_HOST` | Host de la base de datos (IP:Puerto) | `10.10.4.17:3306` |
| `DB_NAME` | Nombre de la base de datos | `contenedor_ibiza` |
| `DB_USER` | Usuario de MySQL | `usuario` |
| `DB_PASS` | Contraseña de MySQL | `password` |
| `SITE_URL` | URL pública de la aplicación | `https://tu-dominio.com` |
| `TELEGRAM_BOT_TOKEN` | Token del Bot de Telegram | `123456:ABC-DEF...` |
| `TIMEZONE` | Zona horaria (PHP) | `America/Mexico_City` |
## 📖 Manual de Uso Rápido
### 1. Administrador
* **Gestión de Usuarios**: Crea y edita cuentas. Asigna roles de Coordinador o Ayudante.
* **Telegram**: Configura el Webhook del bot con un solo clic desde el menú "Telegram".
* **Rotaciones**: Puede regenerar todo el calendario si es necesario.
### 2. Coordinador
* **Reorganizar**: Usa la herramienta "Reorganizar Orden" (drag & drop) para cambiar quién sigue a quién en la rotación permanente.
* **Horarios**: Modifica las horas de apertura/cierre de cada día.
### 3. Ayudante / Usuario
* Consulta su turno en el Dashboard.
* Descarga el PDF de rotaciones.
* Interactúa con el Bot de Telegram para consultar info rápida.
## 🤖 Comandos del Bot
El bot cuenta con un menú interactivo, pero también reconoce:
* `/start` o `/menu`: Muestra los botones.
* *(Escribir nombre)*: Busca turnos futuros para esa persona (ej: "Ana").
* `/tabla`: Muestra el listado de próximas semanas.
* `/pdf`: Envía el documento PDF.
---
Desarrollado para Condominio Ibiza.

13
apache-config.conf Normal file
View File

@@ -0,0 +1,13 @@
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/public
<Directory /var/www/html/public>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

18
composer.json Normal file
View File

@@ -0,0 +1,18 @@
{
"name": "contenedor/ibiza",
"description": "Sistema de gestión de rotación de contenedores",
"type": "project",
"require": {
"php": ">=8.0",
"vlucas/phpdotenv": "^5.5",
"tecnickcom/tcpdf": "^6.6"
},
"autoload": {
"psr-4": {
"App\\": "src/"
},
"files": [
"src/Helpers/functions.php"
]
}
}

565
composer.lock generated Normal file
View File

@@ -0,0 +1,565 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "cdd8f12d61317e626c1fa87f94fbf8a4",
"packages": [
{
"name": "graham-campbell/result-type",
"version": "v1.1.4",
"source": {
"type": "git",
"url": "https://github.com/GrahamCampbell/Result-Type.git",
"reference": "e01f4a821471308ba86aa202fed6698b6b695e3b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/e01f4a821471308ba86aa202fed6698b6b695e3b",
"reference": "e01f4a821471308ba86aa202fed6698b6b695e3b",
"shasum": ""
},
"require": {
"php": "^7.2.5 || ^8.0",
"phpoption/phpoption": "^1.9.5"
},
"require-dev": {
"phpunit/phpunit": "^8.5.41 || ^9.6.22 || ^10.5.45 || ^11.5.7"
},
"type": "library",
"autoload": {
"psr-4": {
"GrahamCampbell\\ResultType\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
}
],
"description": "An Implementation Of The Result Type",
"keywords": [
"Graham Campbell",
"GrahamCampbell",
"Result Type",
"Result-Type",
"result"
],
"support": {
"issues": "https://github.com/GrahamCampbell/Result-Type/issues",
"source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.1.4"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/graham-campbell/result-type",
"type": "tidelift"
}
],
"time": "2025-12-27T19:43:20+00:00"
},
{
"name": "phpoption/phpoption",
"version": "1.9.5",
"source": {
"type": "git",
"url": "https://github.com/schmittjoh/php-option.git",
"reference": "75365b91986c2405cf5e1e012c5595cd487a98be"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/schmittjoh/php-option/zipball/75365b91986c2405cf5e1e012c5595cd487a98be",
"reference": "75365b91986c2405cf5e1e012c5595cd487a98be",
"shasum": ""
},
"require": {
"php": "^7.2.5 || ^8.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"phpunit/phpunit": "^8.5.44 || ^9.6.25 || ^10.5.53 || ^11.5.34"
},
"type": "library",
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": false
},
"branch-alias": {
"dev-master": "1.9-dev"
}
},
"autoload": {
"psr-4": {
"PhpOption\\": "src/PhpOption/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"Apache-2.0"
],
"authors": [
{
"name": "Johannes M. Schmitt",
"email": "schmittjoh@gmail.com",
"homepage": "https://github.com/schmittjoh"
},
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
}
],
"description": "Option Type for PHP",
"keywords": [
"language",
"option",
"php",
"type"
],
"support": {
"issues": "https://github.com/schmittjoh/php-option/issues",
"source": "https://github.com/schmittjoh/php-option/tree/1.9.5"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/phpoption/phpoption",
"type": "tidelift"
}
],
"time": "2025-12-27T19:41:33+00:00"
},
{
"name": "symfony/polyfill-ctype",
"version": "v1.33.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-ctype.git",
"reference": "a3cc8b044a6ea513310cbd48ef7333b384945638"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/a3cc8b044a6ea513310cbd48ef7333b384945638",
"reference": "a3cc8b044a6ea513310cbd48ef7333b384945638",
"shasum": ""
},
"require": {
"php": ">=7.2"
},
"provide": {
"ext-ctype": "*"
},
"suggest": {
"ext-ctype": "For best performance"
},
"type": "library",
"extra": {
"thanks": {
"url": "https://github.com/symfony/polyfill",
"name": "symfony/polyfill"
}
},
"autoload": {
"files": [
"bootstrap.php"
],
"psr-4": {
"Symfony\\Polyfill\\Ctype\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Gert de Pagter",
"email": "BackEndTea@gmail.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for ctype functions",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"ctype",
"polyfill",
"portable"
],
"support": {
"source": "https://github.com/symfony/polyfill-ctype/tree/v1.33.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2024-09-09T11:45:10+00:00"
},
{
"name": "symfony/polyfill-mbstring",
"version": "v1.33.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-mbstring.git",
"reference": "6d857f4d76bd4b343eac26d6b539585d2bc56493"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/6d857f4d76bd4b343eac26d6b539585d2bc56493",
"reference": "6d857f4d76bd4b343eac26d6b539585d2bc56493",
"shasum": ""
},
"require": {
"ext-iconv": "*",
"php": ">=7.2"
},
"provide": {
"ext-mbstring": "*"
},
"suggest": {
"ext-mbstring": "For best performance"
},
"type": "library",
"extra": {
"thanks": {
"url": "https://github.com/symfony/polyfill",
"name": "symfony/polyfill"
}
},
"autoload": {
"files": [
"bootstrap.php"
],
"psr-4": {
"Symfony\\Polyfill\\Mbstring\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for the Mbstring extension",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"mbstring",
"polyfill",
"portable",
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-mbstring/tree/v1.33.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2024-12-23T08:48:59+00:00"
},
{
"name": "symfony/polyfill-php80",
"version": "v1.33.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-php80.git",
"reference": "0cc9dd0f17f61d8131e7df6b84bd344899fe2608"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/0cc9dd0f17f61d8131e7df6b84bd344899fe2608",
"reference": "0cc9dd0f17f61d8131e7df6b84bd344899fe2608",
"shasum": ""
},
"require": {
"php": ">=7.2"
},
"type": "library",
"extra": {
"thanks": {
"url": "https://github.com/symfony/polyfill",
"name": "symfony/polyfill"
}
},
"autoload": {
"files": [
"bootstrap.php"
],
"psr-4": {
"Symfony\\Polyfill\\Php80\\": ""
},
"classmap": [
"Resources/stubs"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Ion Bazan",
"email": "ion.bazan@gmail.com"
},
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"polyfill",
"portable",
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-php80/tree/v1.33.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2025-01-02T08:10:11+00:00"
},
{
"name": "tecnickcom/tcpdf",
"version": "6.10.1",
"source": {
"type": "git",
"url": "https://github.com/tecnickcom/TCPDF.git",
"reference": "7a2701251e5d52fc3d508fd71704683eb54f5939"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/tecnickcom/TCPDF/zipball/7a2701251e5d52fc3d508fd71704683eb54f5939",
"reference": "7a2701251e5d52fc3d508fd71704683eb54f5939",
"shasum": ""
},
"require": {
"ext-curl": "*",
"php": ">=7.1.0"
},
"type": "library",
"autoload": {
"classmap": [
"config",
"include",
"tcpdf.php",
"tcpdf_barcodes_1d.php",
"tcpdf_barcodes_2d.php",
"include/tcpdf_colors.php",
"include/tcpdf_filters.php",
"include/tcpdf_font_data.php",
"include/tcpdf_fonts.php",
"include/tcpdf_images.php",
"include/tcpdf_static.php",
"include/barcodes/datamatrix.php",
"include/barcodes/pdf417.php",
"include/barcodes/qrcode.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"LGPL-3.0-or-later"
],
"authors": [
{
"name": "Nicola Asuni",
"email": "info@tecnick.com",
"role": "lead"
}
],
"description": "TCPDF is a PHP class for generating PDF documents and barcodes.",
"homepage": "http://www.tcpdf.org/",
"keywords": [
"PDFD32000-2008",
"TCPDF",
"barcodes",
"datamatrix",
"pdf",
"pdf417",
"qrcode"
],
"support": {
"issues": "https://github.com/tecnickcom/TCPDF/issues",
"source": "https://github.com/tecnickcom/TCPDF/tree/6.10.1"
},
"funding": [
{
"url": "https://www.paypal.com/donate/?hosted_button_id=NZUEC5XS8MFBJ",
"type": "custom"
}
],
"time": "2025-11-21T10:58:21+00:00"
},
{
"name": "vlucas/phpdotenv",
"version": "v5.6.3",
"source": {
"type": "git",
"url": "https://github.com/vlucas/phpdotenv.git",
"reference": "955e7815d677a3eaa7075231212f2110983adecc"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/955e7815d677a3eaa7075231212f2110983adecc",
"reference": "955e7815d677a3eaa7075231212f2110983adecc",
"shasum": ""
},
"require": {
"ext-pcre": "*",
"graham-campbell/result-type": "^1.1.4",
"php": "^7.2.5 || ^8.0",
"phpoption/phpoption": "^1.9.5",
"symfony/polyfill-ctype": "^1.26",
"symfony/polyfill-mbstring": "^1.26",
"symfony/polyfill-php80": "^1.26"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"ext-filter": "*",
"phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2"
},
"suggest": {
"ext-filter": "Required to use the boolean validator."
},
"type": "library",
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": false
},
"branch-alias": {
"dev-master": "5.6-dev"
}
},
"autoload": {
"psr-4": {
"Dotenv\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
},
{
"name": "Vance Lucas",
"email": "vance@vancelucas.com",
"homepage": "https://github.com/vlucas"
}
],
"description": "Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.",
"keywords": [
"dotenv",
"env",
"environment"
],
"support": {
"issues": "https://github.com/vlucas/phpdotenv/issues",
"source": "https://github.com/vlucas/phpdotenv/tree/v5.6.3"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/vlucas/phpdotenv",
"type": "tidelift"
}
],
"time": "2025-12-27T19:49:13+00:00"
}
],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": {
"php": ">=8.0"
},
"platform-dev": [],
"plugin-api-version": "2.6.0"
}

51
contenedor.yaml Normal file
View File

@@ -0,0 +1,51 @@
name: contenedor
services:
contenedor:
cpu_shares: 90
command: []
container_name: contenedor_ibiza
deploy:
resources:
limits:
memory: 16663134208
reservations:
devices: []
dns:
- 8.8.8.8
- 8.8.4.4
environment:
- DB_HOST=10.10.4.17:3390
- DB_NAME=contenedor_ibiza
- DB_PASS=MiPo6425@@
- DB_USER=nickpons666
- SESSION_NAME=contenedor_session
- SITE_URL=https://contenedor-ibiza.ddns.net
- TELEGRAM_BOT_TOKEN=8589698394:AAFSphFBEy1DQmOIUDyEKCMAwksTaYlatYE
- TIMEZONE=America/Mexico_City
- SESSION_LIFETIME=7200
image: 10.10.4.3:5000/contenedor_ibiza:latest
labels:
icon: https://www.punta-diamante.saredesarrollo.com.mx/storage/img/condominios/6/VBgcKjrcQCCQ7gIlGousPfH9EECJ4UluHwAThjJ2.png
ports:
- target: 80
published: "8087"
protocol: tcp
restart: unless-stopped
volumes: []
devices: []
cap_add: []
network_mode: bridge
privileged: false
x-casaos:
author: self
category: self
hostname: ""
icon: https://www.punta-diamante.saredesarrollo.com.mx/storage/img/condominios/6/VBgcKjrcQCCQ7gIlGousPfH9EECJ4UluHwAThjJ2.png
index: /
is_uncontrolled: false
port_map: "8087"
scheme: http
store_app_id: contenedor
title:
custom: ""
en_us: contenedor

81
database.sql Normal file
View File

@@ -0,0 +1,81 @@
-- Sistema de Gestión de Contenedores - Base de Datos
-- Creación de base de datos y tablas
-- NOTA: Se usan DROP TABLE para asegurar una instalación limpia.
USE contenedor_ibiza1;
-- Desactivar checks de llaves foráneas temporalmente para permitir drops
SET FOREIGN_KEY_CHECKS = 0;
-- Eliminar tablas si existen para evitar conflictos de estructura
DROP TABLE IF EXISTS assignments;
DROP TABLE IF EXISTS schedules;
DROP TABLE IF EXISTS users;
SET FOREIGN_KEY_CHECKS = 1;
-- Tabla de usuarios
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
full_name VARCHAR(100) NOT NULL,
role ENUM('admin', 'coordinador', 'ayudante') NOT NULL DEFAULT 'ayudante',
active TINYINT(1) NOT NULL DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_role (role),
INDEX idx_active (active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Tabla de horarios del contenedor
CREATE TABLE schedules (
id INT AUTO_INCREMENT PRIMARY KEY,
day_of_week TINYINT NOT NULL COMMENT '0=Domingo, 1=Lunes, ..., 6=Sábado',
opening_time_1 TIME NULL COMMENT 'Primer horario de apertura',
opening_time_2 TIME NULL COMMENT 'Segundo horario de apertura',
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY unique_day (day_of_week)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Tabla de asignaciones/rotaciones
CREATE TABLE assignments (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
week_number INT NOT NULL COMMENT 'Número de semana del año (1-53)',
year INT NOT NULL,
start_date DATE NOT NULL COMMENT 'Fecha de inicio (siempre domingo)',
end_date DATE NOT NULL COMMENT 'Fecha de fin (siempre sábado)',
order_position INT NOT NULL DEFAULT 0 COMMENT 'Posición en el orden para drag & drop',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
UNIQUE KEY unique_week (year, week_number),
INDEX idx_user (user_id),
INDEX idx_dates (start_date, end_date),
INDEX idx_year_week (year, week_number)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Insertar horarios por defecto
INSERT INTO schedules (day_of_week, opening_time_1, opening_time_2) VALUES
(0, '19:00:00', '22:00:00'), -- Domingo
(1, '06:30:00', '09:00:00'), -- Lunes
(2, '19:00:00', '22:00:00'), -- Martes
(3, '06:30:00', '09:00:00'), -- Miércoles
(4, '19:00:00', '22:00:00'), -- Jueves
(5, '06:30:00', '06:30:00'), -- Viernes
(6, NULL, NULL); -- Sábado (cerrado)
-- Insertar usuario administrador por defecto
-- Password: admin123
INSERT INTO users (username, password, full_name, role, active) VALUES
('admin', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'Administrador', 'admin', 1);
-- Insertar usuarios helpers de ejemplo
INSERT INTO users (username, password, full_name, role, active) VALUES
('ana', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'Ana García', 'ayudante', 1),
('esperanza', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'Esperanza López', 'ayudante', 1),
('mary', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'Mary Martínez', 'ayudante', 1),
('bety', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'Bety Rodríguez', 'ayudante', 1),
('mariela', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'Mariela Sánchez', 'ayudante', 1),
('coord1', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'Coordinador Ejemplo', 'coordinador', 1);

47
docker-entrypoint.sh Normal file
View File

@@ -0,0 +1,47 @@
#!/bin/bash
set -e
# Definir ruta del archivo .env
ENV_FILE="/var/www/html/contenedor/.env"
# Siempre regenerar el archivo .env para asegurar que las variables de entorno (YAML) tengan prioridad
echo "Generating .env file from environment variables..."
# Vaciar/Crear archivo
: > "$ENV_FILE"
# Función helper para escribir variables
write_env() {
local key=$1
local val=$2
if [ ! -z "$val" ]; then
echo "$key=$val" >> "$ENV_FILE"
fi
}
# Escribir variables críticas
# Base de Datos
write_env "DB_HOST" "${DB_HOST:-db}"
write_env "DB_NAME" "${DB_NAME:-contenedor_ibiza}"
write_env "DB_USER" "${DB_USER:-root}"
write_env "DB_PASS" "${DB_PASS:-password}"
# Aplicación
write_env "SITE_URL" "${SITE_URL:-http://localhost}"
write_env "TIMEZONE" "${TIMEZONE:-America/Mexico_City}"
write_env "CAOS_BASE_URL" "${CAOS_BASE_URL}" # Soporte opcional legacy/custom
# Sesión
write_env "SESSION_NAME" "${SESSION_NAME:-ibiza_session}"
write_env "SESSION_LIFETIME" "${SESSION_LIFETIME:-86400}"
# Telegram
write_env "TELEGRAM_BOT_TOKEN" "${TELEGRAM_BOT_TOKEN}"
echo ".env file generated successfully."
# Ajustar permisos por si acaso
chown www-data:www-data "$ENV_FILE"
# Ejecutar el comando original (CMD del Dockerfile)
exec "$@"

7
logs/app.log Normal file
View File

@@ -0,0 +1,7 @@
[31-Jan-2026 23:08:41 America/Mexico_City] Iniciando regeneración desde controlador...
[31-Jan-2026 23:08:41 America/Mexico_City] ERROR CRÍTICO en regeneración: Call to undefined method App\Services\WeekService::getCurrentWeekNumber()
#0 /var/www/html/contenedor/src/Controllers/AssignmentController.php(53): App\Services\RotationService->regenerateFutureFromOrder()
#1 /var/www/html/contenedor/public/rotaciones.php(17): App\Controllers\AssignmentController->generate()
#2 {main}
[31-Jan-2026 23:09:46 America/Mexico_City] Iniciando regeneración desde controlador...
[31-Jan-2026 23:09:47 America/Mexico_City] Regeneración exitosa: 12 semanas

148
public/admin/telegram.php Normal file
View File

@@ -0,0 +1,148 @@
<?php
require_once __DIR__ . '/../../vendor/autoload.php';
use App\Controllers\TelegramController;
use App\Middleware\RoleMiddleware;
use App\Services\AuthService;
RoleMiddleware::admin();
$auth = new AuthService();
$controller = new TelegramController();
// Manejar acciones
if (isPost()) {
$action = post('action');
if ($action === 'setup') {
$controller->setup();
} elseif ($action === 'delete') {
$controller->delete();
}
}
// Obtener datos para la vista
$data = $controller->index();
$info = $data['info'];
$defaultUrl = $data['defaultUrl'];
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Telegram - Contenedor Ibiza</title>
<link rel="stylesheet" href="../assets/css/style.css">
<style>
.status-box {
padding: 1.5rem;
border-radius: 8px;
background-color: #f8fafc;
border: 1px solid #e2e8f0;
margin-bottom: 2rem;
}
.status-item {
margin-bottom: 0.5rem;
}
.status-label {
font-weight: 600;
color: #64748b;
}
.status-badge {
display: inline-block;
padding: 0.25rem 0.5rem;
border-radius: 9999px;
font-size: 0.85rem;
font-weight: 600;
}
.status-active { background-color: #dcfce7; color: #166534; }
.status-inactive { background-color: #fee2e2; color: #991b1b; }
</style>
</head>
<body>
<?php include '../partials/navbar.php'; ?>
<div class="container">
<h1 class="card-title mb-4">🤖 Gestión de Bot Telegram</h1>
<?php if ($msg = flash('success')): ?>
<div class="alert alert-success"><?= e($msg) ?></div>
<?php endif; ?>
<?php if ($msg = flash('error')): ?>
<div class="alert alert-danger"><?= e($msg) ?></div>
<?php endif; ?>
<div class="card">
<h3 class="mb-4">Estado del Webhook</h3>
<div class="status-box">
<?php if ($info && !empty($info['url'])): ?>
<div class="status-item">
<span class="status-label">Estado:</span>
<span class="status-badge status-active">Activo</span>
</div>
<div class="status-item">
<span class="status-label">URL:</span>
<code><?= e($info['url']) ?></code>
</div>
<div class="status-item">
<span class="status-label">Mensajes pendientes:</span>
<?= e($info['pending_update_count'] ?? 0) ?>
</div>
<?php if (!empty($info['last_error_message'])): ?>
<div class="status-item text-danger" style="margin-top: 1rem;">
<span class="status-label">Último error:</span>
<?= e($info['last_error_message']) ?>
(<?= date('d/m/Y H:i', $info['last_error_date'] ?? time()) ?>)
</div>
<?php endif; ?>
<?php else: ?>
<div class="status-item">
<span class="status-label">Estado:</span>
<span class="status-badge status-inactive">Inactivo / No configurado</span>
</div>
<?php endif; ?>
</div>
<h3 class="mb-4">Configuración</h3>
<form method="POST" class="mb-4">
<input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
<input type="hidden" name="action" value="setup">
<div class="form-group">
<label>URL del Webhook (HTTPS requerido)</label>
<input type="url" name="webhook_url" class="form-control"
value="<?= e($defaultUrl) ?>" required>
<small style="display: block; margin-top: 0.5rem; color: #64748b;">
Esta es la URL a la que Telegram enviará los mensajes. Debe ser pública y segura (HTTPS).
Por defecto, se sugiere la URL interna de tu sitio.
</small>
</div>
<button type="submit" class="btn btn-primary">
💾 Guardar Configuración
</button>
</form>
<?php if ($info && !empty($info['url'])): ?>
<hr style="margin: 2rem 0; border: 0; border-top: 1px solid #e2e8f0;">
<h3 class="mb-4 text-danger">Zona de Peligro</h3>
<form method="POST" onsubmit="return confirm('¿Estás seguro de desactivar el bot? Dejará de responder mensajes.');">
<input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
<input type="hidden" name="action" value="delete">
<button type="submit" class="btn btn-danger">
🚫 Borrar Webhook
</button>
<small style="display: block; margin-top: 0.5rem; color: #64748b;">
Esto desconectará el bot de tu servidor.
</small>
</form>
<?php endif; ?>
</div>
</div>
</body>
</html>

206
public/admin/usuarios.php Normal file
View File

@@ -0,0 +1,206 @@
<?php
require_once __DIR__ . '/../../vendor/autoload.php';
use App\Controllers\UserController;
use App\Middleware\RoleMiddleware;
// Middleware maneja la seguridad
$controller = new UserController();
$users = $controller->index(); // Maneja POST internamente y retorna lista para render
?>
<!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 Usuarios - Contenedor Ibiza</title>
<link rel="stylesheet" href="../assets/css/style.css">
<style>
.modal {
display: none;
position: fixed;
top: 0; left: 0;
width: 100%; height: 100%;
background: rgba(0,0,0,0.5);
align-items: center;
justify-content: center;
z-index: 1000;
}
.modal-content {
background: white;
padding: 2rem;
border-radius: 1rem;
width: 100%;
max-width: 500px;
}
</style>
</head>
<body>
<?php include '../partials/navbar.php'; ?>
<div class="container">
<div class="card-header">
<h1 class="card-title">👥 Gestión de Usuarios</h1>
<button onclick="openModal('createModal')" class="btn btn-primary">Nuevo Usuario</button>
</div>
<?php if ($msg = flash('success')): ?>
<div class="alert alert-success"><?= e($msg) ?></div>
<?php endif; ?>
<?php if ($msg = flash('error')): ?>
<div class="alert alert-error"><?= e($msg) ?></div>
<?php endif; ?>
<div class="card">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Usuario</th>
<th>Nombre Completo</th>
<th>Rol</th>
<th>Estado</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $u): ?>
<tr>
<td><?= e($u['username']) ?></td>
<td><?= e($u['full_name']) ?></td>
<td>
<?php
$roles = [
'admin' => 'Administrador',
'coordinador' => 'Coordinador',
'ayudante' => 'Ayudante'
];
echo $roles[$u['role']] ?? $u['role'];
?>
</td>
<td>
<?php if ($u['active']): ?>
<span class="badge badge-success">Activo</span>
<?php else: ?>
<span class="badge badge-danger">Inactivo</span>
<?php endif; ?>
</td>
<td>
<div class="flex">
<button onclick='editUser(<?= json_encode($u) ?>)' class="btn btn-sm btn-secondary">Editar</button>
<form method="POST" style="display:inline;">
<input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
<input type="hidden" name="action" value="toggle">
<input type="hidden" name="id" value="<?= $u['id'] ?>">
<?php if ($u['active']): ?>
<button type="submit" class="btn btn-sm btn-danger">Desactivar</button>
<?php else: ?>
<button type="submit" class="btn btn-sm btn-success">Activar</button>
<?php endif; ?>
</form>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
<!-- Modal Crear -->
<div id="createModal" class="modal">
<div class="modal-content">
<h2 class="mb-4">Nuevo Usuario</h2>
<form method="POST">
<input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
<input type="hidden" name="action" value="create">
<div class="form-group">
<label class="form-label">Nombre de Usuario</label>
<input type="text" name="username" class="form-control" required>
</div>
<div class="form-group">
<label class="form-label">Contraseña</label>
<input type="password" name="password" class="form-control" required>
</div>
<div class="form-group">
<label class="form-label">Nombre Completo</label>
<input type="text" name="full_name" class="form-control" required>
</div>
<div class="form-group">
<label class="form-label">Rol</label>
<select name="role" class="form-control">
<option value="ayudante">Ayudante</option>
<option value="coordinador">Coordinador</option>
<option value="admin">Administrador</option>
</select>
</div>
<div class="flex justify-end mt-4">
<button type="button" onclick="closeModal('createModal')" class="btn btn-secondary">Cancelar</button>
<button type="submit" class="btn btn-primary">Crear</button>
</div>
</form>
</div>
</div>
<!-- Modal Editar -->
<div id="editModal" class="modal">
<div class="modal-content">
<h2 class="mb-4">Editar Usuario</h2>
<form method="POST">
<input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
<input type="hidden" name="action" value="update">
<input type="hidden" name="id" id="edit_id">
<div class="form-group">
<label class="form-label">Nombre de Usuario</label>
<input type="text" name="username" id="edit_username" class="form-control" required>
</div>
<div class="form-group">
<label class="form-label">Nueva Contraseña (Dejar en blanco para no cambiar)</label>
<input type="password" name="password" class="form-control">
</div>
<div class="form-group">
<label class="form-label">Nombre Completo</label>
<input type="text" name="full_name" id="edit_fullname" class="form-control" required>
</div>
<div class="form-group">
<label class="form-label">Rol</label>
<select name="role" id="edit_role" class="form-control">
<option value="ayudante">Ayudante</option>
<option value="coordinador">Coordinador</option>
<option value="admin">Administrador</option>
</select>
</div>
<div class="flex justify-end mt-4">
<button type="button" onclick="closeModal('editModal')" class="btn btn-secondary">Cancelar</button>
<button type="submit" class="btn btn-primary">Guardar</button>
</div>
</form>
</div>
</div>
<script src="../assets/js/main.js"></script>
<script>
function editUser(user) {
document.getElementById('edit_id').value = user.id;
document.getElementById('edit_username').value = user.username;
document.getElementById('edit_fullname').value = user.full_name;
document.getElementById('edit_role').value = user.role;
openModal('editModal');
}
</script>
</body>
</html>

323
public/assets/css/style.css Normal file
View File

@@ -0,0 +1,323 @@
:root {
--primary: #3b82f6;
--primary-dark: #2563eb;
--secondary: #64748b;
--success: #22c55e;
--danger: #ef4444;
--background: #f8fafc;
--surface: #ffffff;
--text: #0f172a;
--text-light: #64748b;
--border: #e2e8f0;
--shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Inter', system-ui, -apple-system, sans-serif;
background-color: var(--background);
color: var(--text);
line-height: 1.5;
}
/* Auth Layout */
.auth-container {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
}
.auth-card {
background: var(--surface);
padding: 2rem;
border-radius: 1rem;
box-shadow: var(--shadow);
width: 100%;
max-width: 400px;
}
.auth-title {
text-align: center;
font-size: 1.5rem;
font-weight: 700;
margin-bottom: 2rem;
color: var(--primary);
}
/* Forms */
.form-group {
margin-bottom: 1.5rem;
}
.form-label {
display: block;
margin-bottom: 0.5rem;
font-weight: 500;
color: var(--text);
}
.form-control {
width: 100%;
padding: 0.75rem;
border: 1px solid var(--border);
border-radius: 0.5rem;
font-size: 1rem;
transition: border-color 0.2s;
}
.form-control:focus {
outline: none;
border-color: var(--primary);
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0.75rem 1.5rem;
border-radius: 0.5rem;
font-weight: 600;
cursor: pointer;
border: none;
transition: all 0.2s;
text-decoration: none;
font-size: 1rem;
}
.btn-primary {
background-color: var(--primary);
color: white;
}
.btn-primary:hover {
background-color: var(--primary-dark);
}
.btn-danger {
background-color: var(--danger);
color: white;
}
.btn-secondary {
background-color: var(--secondary);
color: white;
}
.btn-success {
background-color: var(--success);
color: white;
}
.btn-block {
width: 100%;
}
.btn-sm {
padding: 0.25rem 0.5rem;
font-size: 0.875rem;
}
/* Dashboard Layout */
.navbar {
background: var(--surface);
border-bottom: 1px solid var(--border);
padding: 1rem 2rem;
display: flex;
justify-content: space-between;
align-items: center;
position: sticky;
top: 0;
z-index: 100;
}
.nav-brand {
font-size: 1.25rem;
font-weight: 700;
color: var(--primary);
text-decoration: none;
}
.nav-menu {
display: flex;
gap: 1.5rem;
}
.nav-link {
color: var(--text-light);
text-decoration: none;
font-weight: 500;
transition: color 0.2s;
}
.nav-link:hover,
.nav-link.active {
color: var(--primary);
}
.container {
max-width: 1200px;
margin: 2rem auto;
padding: 0 1rem;
}
/* Cards & Tables */
.card {
background: var(--surface);
border-radius: 1rem;
box-shadow: var(--shadow);
padding: 1.5rem;
margin-bottom: 2rem;
}
.card-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1.5rem;
}
.card-title {
font-size: 1.25rem;
font-weight: 600;
}
.table-responsive {
overflow-x: auto;
}
.table {
width: 100%;
border-collapse: collapse;
}
.table th,
.table td {
padding: 1rem;
text-align: left;
border-bottom: 1px solid var(--border);
}
.table th {
font-weight: 600;
color: var(--text-light);
background-color: #f8fafc;
}
.table tr:last-child td {
border-bottom: none;
}
/* Status Badges */
.badge {
padding: 0.25rem 0.75rem;
border-radius: 9999px;
font-size: 0.75rem;
font-weight: 600;
}
.badge-success {
background: #dcfce7;
color: #166534;
}
.badge-danger {
background: #fee2e2;
color: #991b1b;
}
.badge-warning {
background: #fef3c7;
color: #92400e;
}
/* Drag & Drop */
.drag-list {
list-style: none;
}
.drag-item {
background: var(--surface);
border: 1px solid var(--border);
margin-bottom: 0.5rem;
padding: 1rem;
border-radius: 0.5rem;
display: flex;
justify-content: space-between;
align-items: center;
cursor: move;
/* Fallback */
cursor: grab;
user-select: none;
-webkit-user-select: none;
transition: transform 0.2s, box-shadow 0.2s;
}
.drag-item:active {
cursor: grabbing;
.drag-item:hover {
border-color: var(--primary);
}
.drag-item.dragging {
opacity: 0.5;
background: #f1f5f9;
}
.drag-handle {
margin-right: 1rem;
color: var(--text-light);
}
/* Alerts */
.alert {
padding: 1rem;
border-radius: 0.5rem;
margin-bottom: 1.5rem;
}
.alert-success {
background: #dcfce7;
color: #166534;
border: 1px solid #bbf7d0;
}
.alert-error {
background: #fee2e2;
color: #991b1b;
border: 1px solid #fecaca;
}
/* Utilities */
.text-center {
text-align: center;
}
.mt-2 {
margin-top: 0.5rem;
}
.mt-4 {
margin-top: 1rem;
}
.mb-4 {
margin-bottom: 1rem;
}
.flex {
display: flex;
gap: 0.5rem;
}
.justify-end {
justify-content: flex-end;
}

100
public/assets/js/dragdrop.js vendored Normal file
View File

@@ -0,0 +1,100 @@
/**
* Funcionalidad Drag & Drop para reordenar rotaciones
*/
document.addEventListener('DOMContentLoaded', function() {
const list = document.getElementById('sortable-list');
if (!list) return;
let draggedItem = null;
// Inicializar eventos para items
function setupItems() {
const items = list.querySelectorAll('.drag-item');
items.forEach(item => {
item.setAttribute('draggable', true);
item.addEventListener('dragstart', function(e) {
draggedItem = item;
setTimeout(() => item.classList.add('dragging'), 0);
});
item.addEventListener('dragend', function() {
setTimeout(() => {
item.classList.remove('dragging');
draggedItem = null;
}, 0);
saveOrder(); // Guardar automáticamente al soltar
});
});
}
// Eventos de la lista
list.addEventListener('dragover', function(e) {
e.preventDefault();
const afterElement = getDragAfterElement(list, e.clientY);
const currentItem = document.querySelector('.dragging');
if (afterElement == null) {
list.appendChild(currentItem);
} else {
list.insertBefore(currentItem, afterElement);
}
});
// Helper para determinar posición
function getDragAfterElement(container, y) {
const draggableElements = [...container.querySelectorAll('.drag-item:not(.dragging)')];
return draggableElements.reduce((closest, child) => {
const box = child.getBoundingClientRect();
const offset = y - box.top - box.height / 2;
if (offset < 0 && offset > closest.offset) {
return { offset: offset, element: child };
} else {
return closest;
}
}, { offset: Number.NEGATIVE_INFINITY }).element;
}
// Guardar orden via AJAX
function saveOrder() {
const items = list.querySelectorAll('.drag-item');
const order = Array.from(items).map(item => item.dataset.id);
const feedback = document.getElementById('save-feedback');
if (feedback) feedback.textContent = 'Guardando...';
fetch('reorganizar.php?action=save_order', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
},
body: JSON.stringify({ order: order })
})
.then(response => response.json())
.then(data => {
if (data.success) {
if (feedback) {
feedback.textContent = 'Orden guardado correctamente';
feedback.className = 'text-success';
setTimeout(() => feedback.textContent = '', 2000);
}
} else {
if (feedback) {
feedback.textContent = 'Error al guardar';
feedback.className = 'text-danger';
}
alert('Hubo un error al guardar el orden');
}
})
.catch(error => {
console.error('Error:', error);
if (feedback) feedback.textContent = 'Error de conexión';
});
}
setupItems();
});

28
public/assets/js/main.js Normal file
View File

@@ -0,0 +1,28 @@
/**
* Main JS
*/
function confirmDelete(message = '¿Estás seguro de eliminar este registro?') {
return confirm(message);
}
function openModal(modalId) {
const modal = document.getElementById(modalId);
if (modal) {
modal.style.display = 'flex';
}
}
function closeModal(modalId) {
const modal = document.getElementById(modalId);
if (modal) {
modal.style.display = 'none';
}
}
// Cerrar modales clickeando fuera
window.onclick = function (event) {
if (event.target.classList.contains('modal')) {
event.target.style.display = "none";
}
}

View File

@@ -0,0 +1,84 @@
<?php
require_once __DIR__ . '/../../vendor/autoload.php';
use App\Controllers\AssignmentController;
use App\Middleware\RoleMiddleware;
use App\Services\AuthService;
RoleMiddleware::coordinador(); // Admin o Coord
$controller = new AssignmentController();
// Si es AJAX save_order
if (isset($_GET['action']) && $_GET['action'] == 'save_order') {
$controller->saveOrder();
exit;
}
$assignments = $controller->getHelpersForReorder();
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reorganizar Turnos - Contenedor Ibiza</title>
<link rel="stylesheet" href="../assets/css/style.css">
<style>
.warning-box {
background: #fffbeb;
border: 1px solid #fcd34d;
padding: 1rem;
border-radius: 0.5rem;
margin-bottom: 1.5rem;
color: #92400e;
}
</style>
</head>
<body>
<?php include '../partials/navbar.php'; ?>
<div class="container">
<div class="card-header">
<h1 class="card-title">↔️ Reorganizar Orden de Ayudantes</h1>
<a href="../rotaciones.php" class="btn btn-secondary">Volver</a>
</div>
<div class="warning-box">
<strong>Instrucciones:</strong> Arrastra y suelta para definir el <strong>Orden Maestro de Rotación</strong>.
<br>
Al cambiar este orden, el sistema <strong>regenerará automáticamente</strong> todas las rotaciones futuras para seguir esta nueva secuencia cíclica.
</div>
<div id="save-feedback" style="height: 20px; text-align: right; margin-bottom: 10px; font-weight: bold;"></div>
<div class="card">
<ul id="sortable-list" class="drag-list">
<?php foreach ($assignments as $user): ?>
<li class="drag-item" data-id="<?= $user['id'] ?>" draggable="true">
<div style="display: flex; align-items: center; width: 100%;">
<span class="drag-handle">☰</span>
<div style="flex-grow: 1;">
<strong style="font-size: 1.1rem; color: var(--text);"><?= e($user['full_name']) ?></strong>
<span style="color: #64748b; font-size: 0.9em; margin-left: 10px;">
(@<?= e($user['username']) ?>)
</span>
</div>
<div>
<span class="badge badge-<?= $user['role'] === 'coordinador' ? 'success' : 'secondary' ?>">
<?= ucfirst($user['role']) ?>
</span>
</div>
</div>
</li>
<?php endforeach; ?>
</ul>
</div>
</div>
<script src="../assets/js/dragdrop.js"></script>
<script src="../assets/js/main.js"></script>
</body>
</html>

10
public/export-pdf.php Normal file
View File

@@ -0,0 +1,10 @@
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use App\Controllers\PDFController;
use App\Middleware\RoleMiddleware;
RoleMiddleware::auth(); // Solo usuarios autenticados pueden bajar PDF
$controller = new PDFController();
$controller->download();

119
public/horarios.php Normal file
View File

@@ -0,0 +1,119 @@
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use App\Controllers\ScheduleController;
use App\Middleware\RoleMiddleware;
use App\Services\AuthService;
RoleMiddleware::auth();
$auth = new AuthService();
$controller = new ScheduleController();
if (isPost() && ($auth->isCoordinador() || $auth->isAdmin())) {
$controller->update();
}
// Obtener horarios en formato amigable
// ScheduleController por defecto retorna array flat.
// Para la vista es mejor tenerlo indexado por día.
$model = new \App\Models\Schedule();
$schedules = $model->getScheduleArray();
$days = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
// Función helper local para vista inputs
function getTimeVal($schedules, $day, $key) {
return isset($schedules[$day][$key]) ? substr($schedules[$day][$key], 0, 5) : '';
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Horarios - Contenedor Ibiza</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<?php include 'partials/navbar.php'; ?>
<div class="container">
<h1 class="card-title mb-4">⏰ Horarios de Apertura</h1>
<?php if ($msg = flash('success')): ?>
<div class="alert alert-success"><?= e($msg) ?></div>
<?php endif; ?>
<?php
$canEdit = $auth->isCoordinador() || $auth->isAdmin();
?>
<div class="card">
<?php if ($canEdit): ?>
<form method="POST">
<input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
<?php endif; ?>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Día</th>
<th>Horario Mañana/Tarde</th>
<th>Horario Tarde/Noche</th>
<th>Estado</th>
</tr>
</thead>
<tbody>
<?php foreach ($days as $idx => $dayName): ?>
<tr>
<td style="font-weight: 600;"><?= $dayName ?></td>
<?php if ($canEdit): ?>
<td>
<input type="time" class="form-control" style="width: 140px;"
name="schedule[<?= $idx ?>][time1]"
value="<?= getTimeVal($schedules, $idx, 'opening_time_1') ?>">
</td>
<td>
<input type="time" class="form-control" style="width: 140px;"
name="schedule[<?= $idx ?>][time2]"
value="<?= getTimeVal($schedules, $idx, 'opening_time_2') ?>">
</td>
<?php else: ?>
<td>
<?= getTimeVal($schedules, $idx, 'opening_time_1') ?: '-' ?>
</td>
<td>
<?= getTimeVal($schedules, $idx, 'opening_time_2') ?: '-' ?>
</td>
<?php endif; ?>
<td>
<?php
$t1 = getTimeVal($schedules, $idx, 'opening_time_1');
$t2 = getTimeVal($schedules, $idx, 'opening_time_2');
if (!$t1 && !$t2) {
echo '<span class="badge badge-danger">Cerrado</span>';
} else {
echo '<span class="badge badge-success">Abierto</span>';
}
?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php if ($canEdit): ?>
<div style="margin-top: 1.5rem; text-align: right;">
<button type="submit" class="btn btn-primary">Guardar Cambios</button>
</div>
</form>
<?php endif; ?>
</div>
</div>
</body>
</html>

122
public/index.php Normal file
View File

@@ -0,0 +1,122 @@
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../vendor/autoload.php';
use App\Services\AuthService;
use App\Middleware\RoleMiddleware;
use App\Models\Assignment;
// Verificar Auth
RoleMiddleware::auth();
$auth = new AuthService();
$user = $auth->getCurrentUser();
// Obtener resumen (Semana actual)
$assignmentModel = new Assignment();
$currentAssignment = $assignmentModel->getCurrentWeek();
// Obtener próximas tareas si es ayudante
$myAssignments = [];
if ($auth->isAyudante() || $auth->isCoordinador()) {
$myAssignments = $assignmentModel->getByUser($user['id']);
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard - Contenedor Ibiza</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<?php include 'partials/navbar.php'; ?>
<div class="container">
<h1>Bienvenido, <?= e($user['full_name']) ?></h1>
<p class="mb-4">Panel de Control - Rol: <span class="badge badge-success"><?= strtoupper($user['role']) ?></span></p>
<div class="card">
<div class="card-header">
<h2 class="card-title">📅 Esta Semana en el Contenedor</h2>
</div>
<?php if ($currentAssignment): ?>
<div style="font-size: 1.2rem; text-align: center; padding: 1rem;">
<p><strong>Semana <?= $currentAssignment['week_number'] ?></strong> (<?= formatDate($currentAssignment['start_date']) ?> - <?= formatDate($currentAssignment['end_date']) ?>)</p>
<p class="mt-2">Ayudante a cargo:</p>
<h3 style="font-size: 2rem; color: var(--primary); margin: 1rem 0;">
<?= e($currentAssignment['full_name']) ?>
</h3>
</div>
<?php else: ?>
<p class="text-center">No hay asignación programada para esta semana.</p>
<?php endif; ?>
</div>
<?php if (!empty($myAssignments)): ?>
<div class="card">
<div class="card-header">
<h2 class="card-title">👤 Mis Próximos Turnos</h2>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Semana</th>
<th>Fechas</th>
</tr>
</thead>
<tbody>
<?php
// Filtrar solo futuras
$today = date('Y-m-d');
$count = 0;
foreach ($myAssignments as $asg):
if ($asg['end_date'] < $today) continue;
$count++;
if ($count > 5) break;
?>
<tr>
<td>Semana <?= $asg['week_number'] ?></td>
<td><?= formatDate($asg['start_date']) ?> al <?= formatDate($asg['end_date']) ?></td>
</tr>
<?php endforeach; ?>
<?php if ($count === 0): ?>
<tr><td colspan="2">No tienes turnos pendientes próximamente.</td></tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
<?php endif; ?>
<div class="card">
<div class="card-header">
<h2 class="card-title">🚀 Accesos Rápidos</h2>
</div>
<div style="display: flex; gap: 1rem; flex-wrap: wrap;">
<a href="rotaciones.php" class="btn btn-primary">Ver Rotación Completa</a>
<a href="horarios.php" class="btn btn-secondary">Ver Horarios</a>
<a href="export-pdf.php" target="_blank" class="btn btn-success">Descargar PDF</a>
<?php if ($auth->isCoordinador() || $auth->isAdmin()): ?>
<a href="coordinador/reorganizar.php" class="btn btn-primary">Reorganizar Turnos</a>
<?php endif; ?>
<?php if ($auth->isAdmin()): ?>
<a href="admin/usuarios.php" class="btn btn-primary">Gestionar Usuarios</a>
<?php endif; ?>
</div>
</div>
</div>
<script src="assets/js/main.js"></script>
</body>
</html>

46
public/login.php Normal file
View File

@@ -0,0 +1,46 @@
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use App\Controllers\AuthController;
use App\Helpers\Response;
$auth = new AuthController();
$result = $auth->login();
$error = $result['error'] ?? null;
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login - Contenedor Ibiza</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="auth-container">
<div class="auth-card">
<h1 class="auth-title">Contenedor Ibiza</h1>
<?php if ($error): ?>
<div class="alert alert-error">
<?= e($error) ?>
</div>
<?php endif; ?>
<form method="POST" action="">
<div class="form-group">
<label class="form-label" for="username">Usuario</label>
<input type="text" id="username" name="username" class="form-control" required autofocus>
</div>
<div class="form-group">
<label class="form-label" for="password">Contraseña</label>
<input type="password" id="password" name="password" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary btn-block">Iniciar Sesión</button>
</form>
</div>
</div>
</body>
</html>

5
public/logout.php Normal file
View File

@@ -0,0 +1,5 @@
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use App\Services\AuthService; // Para logout directo si se llama
$auth = new App\Controllers\AuthController();
$auth->logout();

View File

@@ -0,0 +1,30 @@
<?php
use App\Services\AuthService;
if (session_status() === PHP_SESSION_NONE) session_start();
// Helper de URL debe estar disponible
if (!function_exists('siteUrl')) {
require_once __DIR__ . '/../../src/Helpers/functions.php';
}
$auth = new AuthService();
$user = $auth->getCurrentUser();
?>
<nav class="navbar">
<a href="<?= siteUrl('index.php') ?>" class="nav-brand">Contenedor Ibiza</a>
<div class="nav-menu">
<a href="<?= siteUrl('index.php') ?>" class="nav-link">Inicio</a>
<a href="<?= siteUrl('rotaciones.php') ?>" class="nav-link">Rotaciones</a>
<a href="<?= siteUrl('horarios.php') ?>" class="nav-link">Horarios</a>
<?php if ($auth->isAdmin()): ?>
<a href="<?= siteUrl('admin/usuarios.php') ?>" class="nav-link">Usuarios</a>
<a href="<?= siteUrl('admin/telegram.php') ?>" class="nav-link">Telegram</a>
<?php endif; ?>
<div style="border-left: 1px solid #e2e8f0; padding-left: 1rem; margin-left: 0.5rem; display: flex; align-items: center; gap: 1rem;">
<span style="font-size: 0.9rem; font-weight: 600;"><?= e($user['username']) ?></span>
<a href="<?= siteUrl('logout.php') ?>" class="btn btn-sm btn-secondary" style="text-decoration: none;">Salir</a>
</div>
</div>
</nav>

116
public/rotaciones.php Normal file
View File

@@ -0,0 +1,116 @@
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use App\Controllers\AssignmentController;
use App\Middleware\RoleMiddleware;
use App\Services\AuthService;
RoleMiddleware::auth();
$auth = new AuthService();
// Instanciar controlador directamente (Page Controller pattern)
$controller = new AssignmentController();
$assignments = $controller->index();
// Si se envia formulario de generación (Solo Admin)
if (isPost() && $auth->isAdmin()) {
$controller->generate();
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rotaciones - Contenedor Ibiza</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<?php include 'partials/navbar.php'; ?>
<div class="container">
<div class="card-header">
<h1 class="card-title">📅 Tabla de Rotación de Ayudantes</h1>
<a href="export-pdf.php" target="_blank" class="btn btn-success">Descargar PDF</a>
</div>
<?php if ($msg = flash('success')): ?>
<div class="alert alert-success"><?= e($msg) ?></div>
<?php endif; ?>
<?php if ($msg = flash('error')): ?>
<div class="alert alert-error"><?= e($msg) ?></div>
<?php endif; ?>
<!-- Panel de Administración (Solo Admin) -->
<?php if ($auth->isAdmin()): ?>
<div class="card" style="border: 1px solid #cbd5e1; background: #f8fafc;">
<h3 class="card-title" style="font-size: 1rem; margin-bottom: 1rem;">⚙️ Panel de Generación (Solo Administrador)</h3>
<form method="POST" onsubmit="return confirm('¿Estás seguro de generar nuevas rotaciones?')">
<input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
<div style="display: flex; gap: 1rem; align-items: center;">
<select name="type" class="form-control" style="width: auto;">
<option value="extend">Extender (Agregar al final)</option>
<option value="regenerate">Regenerar (Borrar futuras y rehacer)</option>
</select>
<select name="weeks" class="form-control" style="width: auto;">
<option value="4">4 Semanas</option>
<option value="8" selected>8 Semanas</option>
<option value="12">12 Semanas</option>
</select>
<button type="submit" class="btn btn-primary">Generar Rotación</button>
</div>
</form>
</div>
<?php endif; ?>
<?php if ($auth->isCoordinador() || $auth->isAdmin()): ?>
<div class="mb-4 text-center">
<a href="coordinador/reorganizar.php" class="btn btn-secondary btn-block">
↔️ Reorganizar Orden (Drag & Drop)
</a>
</div>
<?php endif; ?>
<div class="card">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Semana</th>
<th>Periodo (Dom - Sáb)</th>
<th>Ayudante Asignado</th>
<th>Rol</th>
</tr>
</thead>
<tbody>
<?php if (empty($assignments)): ?>
<tr>
<td colspan="4" class="text-center">No hay rotaciones generadas.</td>
</tr>
<?php else: ?>
<?php foreach ($assignments as $asg): ?>
<tr>
<td>
<span class="badge badge-warning">Sem <?= $asg['week_number'] ?></span>
</td>
<td>
<?= formatDate($asg['start_date']) ?> - <?= formatDate($asg['end_date']) ?>
</td>
<td style="font-weight: 600;">
<?= e($asg['full_name']) ?>
</td>
<td style="font-size: 0.85rem; color: #64748b;">
<!-- Esto requeriría join con users para rol, ya viene en consulta -->
(<?= e($asg['username']) ?>)
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,17 @@
<?php
require_once __DIR__ . '/../../vendor/autoload.php';
use App\Services\TelegramBot;
// Recibir solicitud webhook
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if ($data) {
$bot = new TelegramBot();
$bot->processWebhook($data);
}
// Retornar 200 OK siempre a Telegram
http_response_code(200);
echo 'OK';

52
scripts/auto-rotation.php Normal file
View File

@@ -0,0 +1,52 @@
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use App\Services\RotationService;
use App\Config\Env;
use App\Config\Database;
// Configuración
Env::load();
date_default_timezone_set(Env::get('TIMEZONE', 'UTC'));
echo "[" . date('Y-m-d H:i:s') . "] Iniciando Worker de Rotación...\n";
// Bucle infinito
while (true) {
try {
$now = new DateTime();
// Ejecutar cada sábado a las 23:00 (o la hora que prefieras)
// Lógica: Si es Sábado (w=6) y hora 23
if ($now->format('w') == 6 && $now->format('H') == 23) {
echo "[" . date('Y-m-d H:i:s') . "] Ejecutando generación semanal...\n";
// Verificar conexión a DB antes de procesar (reconexión si es necesario)
// PDO suele manejar timeouts, pero en workers de larga duración es mejor verificar
// App\Config\Database es Singleton, así que la instancia persiste.
// Una estrategia simple es dejar que el script muera y Supervisor lo reinicie,
// pero lo haremos robusto instanciando servicios frescos en el loop si fuera necesario.
$service = new RotationService();
// Aseguramos que siempre haya al menos 8 semanas futuras.
// Si ya existen, generateNext no duplica, solo agrega si faltan.
$count = $service->generateNext(8);
echo "[" . date('Y-m-d H:i:s') . "] Generadas $count nuevas semanas.\n";
// Dormir 1h para asegurar que pase la hora 23 y no repita
sleep(3600);
} else {
// Dormir 60 segundos antes de volver a verificar
// echo "."; // Keepalive log
}
} catch (Exception $e) {
echo "[" . date('Y-m-d H:i:s') . "] ERROR CRÍTICO: " . $e->getMessage() . "\n";
// Esperar un poco antes de reintentar para no saturar logs
sleep(60);
}
sleep(60);
}

80
src/Config/Database.php Normal file
View File

@@ -0,0 +1,80 @@
<?php
namespace App\Config;
use PDO;
use PDOException;
/**
* Clase singleton para la conexión a la base de datos
*/
class Database
{
private static $instance = null;
private $connection;
/**
* Constructor privado para patrón Singleton
*/
private function __construct()
{
Env::load();
$host = Env::get('DB_HOST');
$dbname = Env::get('DB_NAME');
$user = Env::get('DB_USER');
$pass = Env::get('DB_PASS');
try {
$this->connection = new PDO(
"mysql:host=$host;dbname=$dbname;charset=utf8mb4",
$user,
$pass,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"
]
);
} catch (PDOException $e) {
error_log("Error de conexión a BD: " . $e->getMessage());
die("Error de conexión a la base de datos. Por favor, verifica la configuración.");
}
}
/**
* Obtiene la instancia única de Database
*
* @return Database
*/
public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Obtiene la conexión PDO
*
* @return PDO
*/
public function getConnection()
{
return $this->connection;
}
/**
* Previene la clonación del objeto
*/
private function __clone() {}
/**
* Previene la deserialización del objeto
*/
public function __wakeup()
{
throw new \Exception("No se puede deserializar un singleton");
}
}

50
src/Config/Env.php Normal file
View File

@@ -0,0 +1,50 @@
<?php
namespace App\Config;
use Dotenv\Dotenv;
/**
* Clase para cargar y acceder a variables de entorno
*/
class Env
{
private static $loaded = false;
/**
* Carga las variables de entorno desde el archivo .env
*/
public static function load()
{
if (!self::$loaded) {
$dotenv = Dotenv::createImmutable(__DIR__ . '/../../');
$dotenv->load();
self::$loaded = true;
// Configurar timezone
date_default_timezone_set(self::get('TIMEZONE', 'UTC'));
}
}
/**
* Obtiene el valor de una variable de entorno
*
* @param string $key Nombre de la variable
* @param mixed $default Valor por defecto si no existe
* @return mixed
*/
public static function get($key, $default = null)
{
return $_ENV[$key] ?? $default;
}
/**
* Verifica si una variable de entorno existe
*
* @param string $key Nombre de la variable
* @return bool
*/
public static function has($key)
{
return isset($_ENV[$key]);
}
}

View File

@@ -0,0 +1,129 @@
<?php
namespace App\Controllers;
use App\Models\Assignment;
use App\Models\User;
use App\Services\RotationService;
use App\Middleware\RoleMiddleware;
use App\Helpers\Response;
class AssignmentController
{
private $assignmentModel;
private $rotationService;
public function __construct()
{
$this->assignmentModel = new Assignment();
$this->rotationService = new RotationService();
}
public function index()
{
// Vista pública de rotaciones
// Paginación simple
$page = get('page', 1);
$limit = 10; // Semanas por página
// Nota: Implementar paginación completa en modelo si es necesario (OFFSET)
// Por ahora obtenemos todas las futuras y cortamos en vista o añadimos método paginado en modelo
// Usamos getUpcoming que ya tiene un limit, o implementamos paginacion real.
// Para simplificar: mostramos las próximas 12 semanas siempre.
return $this->assignmentModel->getUpcoming(12);
}
public function generate()
{
// Solo Admin
RoleMiddleware::admin();
if (isPost()) {
if (!verifyCsrfToken(post('csrf_token'))) {
flash('error', 'Token inválido');
redirect(siteUrl('admin/generar-rotacion.php'));
}
$type = post('type'); // 'extend' or 'regenerate'
$weeks = (int)post('weeks', 8);
if ($type === 'regenerate') {
error_log("Iniciando regeneración desde controlador...");
// Usar el nuevo método que respeta el orden maestro
try {
$count = $this->rotationService->regenerateFutureFromOrder();
error_log("Regeneración exitosa: $count semanas");
} catch (\Throwable $e) {
error_log("ERROR CRÍTICO en regeneración: " . $e->getMessage() . "\n" . $e->getTraceAsString());
flash('error', "Error interno: " . $e->getMessage());
redirect(siteUrl('rotaciones.php'));
}
flash('success', "Rotación regenerada basándose en el orden maestro ($count semanas).");
} else {
$count = $this->rotationService->generateNext($weeks);
flash('success', "Se han generado $count nuevas semanas de rotación.");
}
redirect(siteUrl('rotaciones.php'));
}
}
public function getHelpersForReorder()
{
// Endpoint AJAX para drag & drop
RoleMiddleware::coordinador();
// Ahora obtenemos USUARIOS únicos, no asignaciones
$userModel = new User();
$helpers = $userModel->getAllHelpers(); // Ya vienen ordenados por sort_order
// Retornar JSON puro si se llama via AJAX
if (isAjax()) {
Response::success($helpers);
}
return $helpers;
}
public function saveOrder()
{
// Endpoint AJAX para guardar orden
RoleMiddleware::coordinador();
if (!isPost()) {
Response::error('Método no permitido', [], 405);
}
// Leer JSON input
$json = file_get_contents('php://input');
$data = json_decode($json, true);
if (!$data || !isset($data['order'])) {
Response::error('Datos inválidos');
}
// $data['order'] es un array de user_ids en el nuevo orden deseado (0..N)
$userIds = $data['order'];
try {
$db = \App\Config\Database::getInstance()->getConnection();
$db->beginTransaction();
$userModel = new User();
// 1. Actualizar sort_order en la tabla users
foreach ($userIds as $position => $userId) {
$userModel->updateOrder($userId, $position);
}
// 2. Regenerar rotaciones futuras basadas en este nuevo orden
$this->rotationService->regenerateFutureFromOrder();
$db->commit();
Response::success([], 'Orden maestro actualizado y rotaciones regeneradas');
} catch (\Exception $e) {
$db->rollBack();
Response::error('Error al guardar el orden: ' . $e->getMessage());
}
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace App\Controllers;
use App\Services\AuthService;
use App\Helpers\Response;
class AuthController
{
private $authService;
public function __construct()
{
$this->authService = new AuthService();
}
public function login()
{
// Si ya está logueado, redirigir al index
if ($this->authService->isLoggedIn()) {
redirect(siteUrl('index.php'));
}
$error = null;
if (isPost()) {
$username = post('username');
$password = post('password');
if ($this->authService->login($username, $password)) {
redirect(siteUrl('index.php'));
} else {
$error = "Usuario o contraseña incorrectos, o cuenta inactiva.";
}
}
return ['error' => $error];
}
public function logout()
{
$this->authService->logout();
redirect(siteUrl('login.php'));
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Controllers;
use App\Services\PDFService;
class PDFController
{
private $pdfService;
public function __construct()
{
$this->pdfService = new PDFService();
}
public function download()
{
$this->pdfService->generate('D'); // D = Download
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace App\Controllers;
use App\Models\Schedule;
use App\Middleware\RoleMiddleware;
class ScheduleController
{
private $scheduleModel;
public function __construct()
{
// View es pública, pero edición restringida
$this->scheduleModel = new Schedule();
}
public function index()
{
return $this->scheduleModel->getAll();
}
public function update()
{
// Solo admin/coordinador pueden editar
RoleMiddleware::coordinador();
if (isPost()) {
if (!verifyCsrfToken(post('csrf_token'))) {
flash('error', 'Token de seguridad inválido');
return;
}
try {
$days = post('schedule'); // Array de horarios
if (!is_array($days)) {
throw new \Exception("Formato de datos inválido");
}
foreach ($days as $dayOfWeek => $times) {
$time1 = !empty($times['time1']) ? $times['time1'] : null;
$time2 = !empty($times['time2']) ? $times['time2'] : null;
$this->scheduleModel->updateDay($dayOfWeek, $time1, $time2);
}
flash('success', 'Horarios actualizados correctamente');
} catch (\Throwable $e) {
error_log("Error actualizando horarios: " . $e->getMessage());
flash('error', 'Error al guardar: ' . $e->getMessage());
}
redirect(siteUrl('horarios.php'));
}
}
}

View File

@@ -0,0 +1,83 @@
<?php
namespace App\Controllers;
use App\Services\TelegramBot;
use App\Middleware\RoleMiddleware;
use App\Helpers\Response;
class TelegramController
{
private $bot;
public function __construct()
{
$this->bot = new TelegramBot();
}
public function index()
{
RoleMiddleware::admin();
$info = $this->bot->getWebhookInfo();
$params = [
'info' => $info['result'] ?? null,
'defaultUrl' => siteUrl('telegram/webhook.php')
];
// Renderizar vista (simulado devolviendo datos, la vista la incluirá)
return $params;
}
public function setup()
{
RoleMiddleware::admin();
if (isPost()) {
if (!verifyCsrfToken(post('csrf_token'))) {
flash('error', 'Token inválido');
redirect(siteUrl('admin/telegram.php'));
}
$url = post('webhook_url');
if (empty($url) || !filter_var($url, FILTER_VALIDATE_URL)) {
flash('error', 'URL inválida');
redirect(siteUrl('admin/telegram.php'));
}
$response = $this->bot->setWebhook($url);
$res = json_decode($response, true);
if ($res && $res['ok']) {
flash('success', 'Webhook configurado correctamente');
} else {
flash('error', 'Error al configurar: ' . ($res['description'] ?? 'Desconocido'));
}
redirect(siteUrl('admin/telegram.php'));
}
}
public function delete()
{
RoleMiddleware::admin();
if (isPost()) {
if (!verifyCsrfToken(post('csrf_token'))) {
flash('error', 'Token inválido');
redirect(siteUrl('admin/telegram.php'));
}
$response = $this->bot->deleteWebhook();
$res = json_decode($response, true);
if ($res && $res['ok']) {
flash('success', 'Webhook eliminado correctamente');
} else {
flash('error', 'Error al eliminar: ' . ($res['description'] ?? 'Desconocido'));
}
redirect(siteUrl('admin/telegram.php'));
}
}
}

View File

@@ -0,0 +1,141 @@
<?php
namespace App\Controllers;
use App\Models\User;
use App\Services\AuthService;
use App\Middleware\RoleMiddleware;
class UserController
{
private $userModel;
public function __construct()
{
// Solo administradores pueden gestionar usuarios
RoleMiddleware::admin();
$this->userModel = new User();
}
public function index()
{
// Manejar acciones POST (Crear/Editar/Eliminar/Toggle)
if (isPost()) {
$action = post('action');
if ($action === 'create') {
$this->create();
} elseif ($action === 'update') {
$this->update();
} elseif ($action === 'toggle') {
$this->toggleActive();
} elseif ($action === 'delete') {
$this->delete();
}
}
// Retornar lista de usuarios para la vista
return $this->userModel->getAll();
}
private function create()
{
if (!verifyCsrfToken(post('csrf_token'))) {
flash('error', 'Token de seguridad inválido');
return;
}
$username = trim(post('username'));
if ($this->userModel->usernameExists($username)) {
flash('error', 'El nombre de usuario ya existe');
return;
}
$data = [
'username' => $username,
'password' => post('password'),
'full_name' => trim(post('full_name')),
'role' => post('role'),
'active' => 1
];
if ($this->userModel->create($data)) {
flash('success', 'Usuario creado correctamente');
} else {
flash('error', 'Error al crear usuario');
}
redirect(siteUrl('admin/usuarios.php'));
}
private function update()
{
if (!verifyCsrfToken(post('csrf_token'))) {
flash('error', 'Token de seguridad inválido');
return;
}
$id = post('id');
$username = trim(post('username'));
if ($this->userModel->usernameExists($username, $id)) {
flash('error', 'El nombre de usuario ya existe');
return;
}
$data = [
'username' => $username,
'full_name' => trim(post('full_name')),
'role' => post('role')
];
if (post('password')) {
$data['password'] = post('password');
}
if ($this->userModel->update($id, $data)) {
flash('success', 'Usuario actualizado correctamente');
} else {
flash('error', 'Error al actualizar usuario');
}
redirect(siteUrl('admin/usuarios.php'));
}
private function toggleActive()
{
// Validación CSRF simple o via POST directo
$id = post('id');
// Prevenir desactivarse a sí mismo
if ($id == $_SESSION['user_id']) {
flash('error', 'No puedes desactivar tu propia cuenta');
} else {
$this->userModel->toggleActive($id);
flash('success', 'Estado del usuario actualizado');
}
redirect(siteUrl('admin/usuarios.php'));
}
private function delete()
{
if (!verifyCsrfToken(post('csrf_token'))) {
flash('error', 'Token de seguridad inválido');
return;
}
$id = post('id');
if ($id == $_SESSION['user_id']) {
flash('error', 'No puedes eliminar tu propia cuenta');
} else {
// Nota: User::delete no está implementado en el ejemplo anterior si no se usó BaseModel,
// pero BaseModel tiene delete(). Verificar herencia.
$this->userModel->delete($id);
flash('success', 'Usuario eliminado');
}
redirect(siteUrl('admin/usuarios.php'));
}
}

62
src/Helpers/Response.php Normal file
View File

@@ -0,0 +1,62 @@
<?php
namespace App\Helpers;
/**
* Clase para respuestas JSON estandarizadas
*/
class Response
{
/**
* Respuesta exitosa
*/
public static function success($data = [], $message = 'Operación exitosa', $statusCode = 200)
{
http_response_code($statusCode);
header('Content-Type: application/json');
echo json_encode([
'success' => true,
'message' => $message,
'data' => $data
]);
exit;
}
/**
* Respuesta de error
*/
public static function error($message = 'Error en la operación', $errors = [], $statusCode = 400)
{
http_response_code($statusCode);
header('Content-Type: application/json');
echo json_encode([
'success' => false,
'message' => $message,
'errors' => $errors
]);
exit;
}
/**
* Respuesta no autorizada
*/
public static function unauthorized($message = 'No autorizado')
{
self::error($message, [], 401);
}
/**
* Respuesta prohibida
*/
public static function forbidden($message = 'Acceso denegado')
{
self::error($message, [], 403);
}
/**
* Respuesta no encontrada
*/
public static function notFound($message = 'Recurso no encontrado')
{
self::error($message, [], 404);
}
}

225
src/Helpers/functions.php Normal file
View File

@@ -0,0 +1,225 @@
<?php
/**
* Funciones auxiliares globales
*/
// Configuración de errores
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../../logs/app.log');
use App\Config\Env;
/**
* Escapa HTML para prevenir XSS
*/
function e($string)
{
return htmlspecialchars($string ?? '', ENT_QUOTES, 'UTF-8');
}
/**
* Redirige a una URL
*/
function redirect($url)
{
header("Location: $url");
exit;
}
/**
* Obtiene la URL base del sitio
*/
function siteUrl($path = '')
{
$base = Env::get('SITE_URL', 'http://localhost');
return rtrim($base, '/') . '/' . ltrim($path, '/');
}
/**
* Obtiene la URL del asset
*/
function asset($path)
{
return siteUrl('assets/' . ltrim($path, '/'));
}
/**
* Formatea una fecha
*/
function formatDate($date, $format = 'd/m/Y')
{
if (empty($date)) return '';
if (is_string($date)) {
$date = new DateTime($date);
}
return $date->format($format);
}
/**
* Formatea una hora
*/
function formatTime($time)
{
if (empty($time)) return 'Cerrado';
if (is_string($time)) {
$time = new DateTime($time);
}
return $time->format('H:i');
}
/**
* Obtiene el nombre del día de la semana
*/
function getDayName($dayNumber)
{
$days = [
0 => 'Domingo',
1 => 'Lunes',
2 => 'Martes',
3 => 'Miércoles',
4 => 'Jueves',
5 => 'Viernes',
6 => 'Sábado'
];
return $days[$dayNumber] ?? '';
}
/**
* Genera un token CSRF
*/
function csrfToken()
{
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf_token'];
}
/**
* Verifica un token CSRF
*/
function verifyCsrfToken($token)
{
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}
/**
* Muestra un mensaje flash
*/
function flash($key, $message = null)
{
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
if ($message === null) {
// Obtener mensaje
$msg = $_SESSION['flash_' . $key] ?? null;
unset($_SESSION['flash_' . $key]);
return $msg;
} else {
// Guardar mensaje
$_SESSION['flash_' . $key] = $message;
}
}
/**
* Verifica si hay un mensaje flash
*/
function hasFlash($key)
{
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
return isset($_SESSION['flash_' . $key]);
}
/**
* Responde con JSON
*/
function jsonResponse($data, $statusCode = 200)
{
http_response_code($statusCode);
header('Content-Type: application/json');
echo json_encode($data);
exit;
}
/**
* Verifica si la petición es AJAX
*/
function isAjax()
{
return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
}
/**
* Obtiene el método HTTP de la petición
*/
function requestMethod()
{
return $_SERVER['REQUEST_METHOD'];
}
/**
* Verifica si es una petición POST
*/
function isPost()
{
return requestMethod() === 'POST';
}
/**
* Verifica si es una petición GET
*/
function isGet()
{
return requestMethod() === 'GET';
}
/**
* Obtiene un valor de $_POST de forma segura
*/
function post($key, $default = null)
{
return $_POST[$key] ?? $default;
}
/**
* Obtiene un valor de $_GET de forma segura
*/
function get($key, $default = null)
{
return $_GET[$key] ?? $default;
}
/**
* Debug: imprime y termina
*/
function dd(...$vars)
{
echo '<pre>';
foreach ($vars as $var) {
var_dump($var);
}
echo '</pre>';
die();
}

View File

@@ -0,0 +1,62 @@
<?php
namespace App\Middleware;
use App\Services\AuthService;
/**
* Middleware para control de acceso basado en roles
*/
class RoleMiddleware
{
/**
* Verifica que el usuario tenga uno de los roles permitidos
*
* @param string|array $allowedRoles Roles permitidos
* @param bool $redirect Si debe redirigir al login o mostrar error 403
*/
public static function check($allowedRoles, $redirect = false)
{
$auth = new AuthService();
// Verificar si está autenticado
if (!$auth->isLoggedIn()) {
if ($redirect) {
redirect(siteUrl('login.php'));
} else {
http_response_code(401);
die('No autorizado. Por favor, inicia sesión.');
}
}
// Verificar rol
if (!$auth->hasRole($allowedRoles)) {
http_response_code(403);
die('Acceso denegado. No tienes permisos para acceder a esta página.');
}
}
/**
* Middleware solo para administradores
*/
public static function admin()
{
self::check('admin');
}
/**
* Middleware para coordinadores y administradores
*/
public static function coordinador()
{
self::check(['admin', 'coordinador']);
}
/**
* Middleware para cualquier usuario autenticado
*/
public static function auth()
{
$auth = new AuthService();
$auth->requireAuth();
}
}

234
src/Models/Assignment.php Normal file
View File

@@ -0,0 +1,234 @@
<?php
namespace App\Models;
use PDO;
use DateTime;
/**
* Modelo de asignaciones/rotaciones
*/
class Assignment extends BaseModel
{
protected $table = 'assignments';
/**
* Crea una nueva asignación
*/
public function create($data)
{
$sql = "INSERT INTO assignments (user_id, week_number, year, start_date, end_date, order_position)
VALUES (:user_id, :week_number, :year, :start_date, :end_date, :order_position)";
$stmt = $this->db->prepare($sql);
return $stmt->execute([
'user_id' => $data['user_id'],
'week_number' => $data['week_number'],
'year' => $data['year'],
'start_date' => $data['start_date'],
'end_date' => $data['end_date'],
'order_position' => $data['order_position'] ?? 0
]);
}
/**
* Actualiza una asignación
*/
public function update($id, $data)
{
$fields = [];
$params = ['id' => $id];
if (isset($data['user_id'])) {
$fields[] = "user_id = :user_id";
$params['user_id'] = $data['user_id'];
}
if (isset($data['order_position'])) {
$fields[] = "order_position = :order_position";
$params['order_position'] = $data['order_position'];
}
if (empty($fields)) {
return false;
}
$sql = "UPDATE assignments SET " . implode(', ', $fields) . " WHERE id = :id";
$stmt = $this->db->prepare($sql);
return $stmt->execute($params);
}
/**
* Obtiene la asignación de una semana específica
*/
public function getByWeek($year, $weekNumber)
{
$sql = "SELECT a.*, u.full_name, u.username
FROM assignments a
INNER JOIN users u ON a.user_id = u.id
WHERE a.year = ? AND a.week_number = ?";
$stmt = $this->db->prepare($sql);
$stmt->execute([$year, $weekNumber]);
return $stmt->fetch();
}
/**
* Obtiene las próximas N asignaciones
*/
public function getUpcoming($limit = 8)
{
$today = date('Y-m-d');
$sql = "SELECT a.*, u.full_name, u.username
FROM assignments a
INNER JOIN users u ON a.user_id = u.id
WHERE a.start_date >= :today
ORDER BY a.start_date ASC
LIMIT :limit";
$stmt = $this->db->prepare($sql);
$stmt->bindValue(':today', $today);
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll();
}
/**
* Obtiene todas las asignaciones futuras
*/
public function getFuture()
{
$today = date('Y-m-d');
$sql = "SELECT a.*, u.full_name, u.username
FROM assignments a
INNER JOIN users u ON a.user_id = u.id
WHERE a.start_date >= :today
ORDER BY a.start_date ASC";
$stmt = $this->db->prepare($sql);
$stmt->execute(['today' => $today]);
return $stmt->fetchAll();
}
/**
* Obtiene la última asignación
*/
public function getLatest()
{
$sql = "SELECT a.*, u.full_name, u.username
FROM assignments a
INNER JOIN users u ON a.user_id = u.id
ORDER BY a.year DESC, a.week_number DESC
LIMIT 1";
$stmt = $this->db->query($sql);
return $stmt->fetch();
}
/**
* Obtiene asignaciones de un usuario
*/
public function getByUser($userId)
{
$sql = "SELECT a.*, u.full_name, u.username
FROM assignments a
INNER JOIN users u ON a.user_id = u.id
WHERE a.user_id = ?
ORDER BY a.start_date DESC";
$stmt = $this->db->prepare($sql);
$stmt->execute([$userId]);
return $stmt->fetchAll();
}
/**
* Busca asignaciones por nombre de usuario
*/
public function searchByName($name)
{
$sql = "SELECT a.*, u.full_name, u.username
FROM assignments a
INNER JOIN users u ON a.user_id = u.id
WHERE u.full_name LIKE :name OR u.username LIKE :name
ORDER BY a.start_date ASC";
$stmt = $this->db->prepare($sql);
$stmt->execute(['name' => "%$name%"]);
return $stmt->fetchAll();
}
/**
* Reorganiza el orden de las asignaciones (drag & drop)
*/
public function reorder($assignments)
{
$this->db->beginTransaction();
try {
foreach ($assignments as $position => $assignmentId) {
$stmt = $this->db->prepare("UPDATE assignments SET order_position = ? WHERE id = ?");
$stmt->execute([$position, $assignmentId]);
}
$this->db->commit();
return true;
} catch (\Exception $e) {
$this->db->rollBack();
return false;
}
}
/**
* Verifica si ya existe una asignación para una semana
*/
public function existsForWeek($year, $weekNumber)
{
$stmt = $this->db->prepare("SELECT COUNT(*) as count FROM assignments WHERE year = ? AND week_number = ?");
$stmt->execute([$year, $weekNumber]);
$result = $stmt->fetch();
return $result['count'] > 0;
}
/**
* Elimina asignaciones futuras
*/
public function deleteFuture()
{
$today = date('Y-m-d');
$stmt = $this->db->prepare("DELETE FROM assignments WHERE start_date > ?");
return $stmt->execute([$today]);
}
/**
* Obtiene la asignación de la semana actual
*/
public function getCurrentWeek()
{
$today = date('Y-m-d');
$sql = "SELECT a.*, u.full_name, u.username
FROM assignments a
INNER JOIN users u ON a.user_id = u.id
WHERE :today BETWEEN a.start_date AND a.end_date";
$stmt = $this->db->prepare($sql);
$stmt->execute(['today' => $today]);
return $stmt->fetch();
}
/**
* Elimina asignaciones que comienzan después de una fecha dada
*/
public function deleteFutureAssignments($dateLimit)
{
$stmt = $this->db->prepare("DELETE FROM assignments WHERE start_date > ?");
return $stmt->execute([$dateLimit]);
}
}

57
src/Models/BaseModel.php Normal file
View File

@@ -0,0 +1,57 @@
<?php
namespace App\Models;
use App\Config\Database;
use PDO;
/**
* Modelo base con métodos comunes
*/
abstract class BaseModel
{
protected $db;
protected $table;
public function __construct()
{
$this->db = Database::getInstance()->getConnection();
}
/**
* Obtiene todos los registros
*/
public function getAll()
{
$stmt = $this->db->query("SELECT * FROM {$this->table}");
return $stmt->fetchAll();
}
/**
* Busca un registro por ID
*/
public function findById($id)
{
$stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch();
}
/**
* Elimina un registro por ID
*/
public function delete($id)
{
$stmt = $this->db->prepare("DELETE FROM {$this->table} WHERE id = ?");
return $stmt->execute([$id]);
}
/**
* Cuenta todos los registros
*/
public function count()
{
$stmt = $this->db->query("SELECT COUNT(*) as total FROM {$this->table}");
$result = $stmt->fetch();
return $result['total'];
}
}

74
src/Models/Schedule.php Normal file
View File

@@ -0,0 +1,74 @@
<?php
namespace App\Models;
use PDO;
/**
* Modelo de horarios del contenedor
*/
class Schedule extends BaseModel
{
protected $table = 'schedules';
/**
* Obtiene todos los horarios ordenados por día
*/
public function getAll()
{
$stmt = $this->db->query("SELECT * FROM schedules ORDER BY day_of_week");
return $stmt->fetchAll();
}
/**
* Obtiene el horario de un día específico
*/
public function getByDay($dayOfWeek)
{
$stmt = $this->db->prepare("SELECT * FROM schedules WHERE day_of_week = ?");
$stmt->execute([$dayOfWeek]);
return $stmt->fetch();
}
/**
* Actualiza el horario de un día
*/
public function updateDay($dayOfWeek, $openingTime1, $openingTime2)
{
$sql = "INSERT INTO schedules (day_of_week, opening_time_1, opening_time_2)
VALUES (:day, :time1, :time2)
ON DUPLICATE KEY UPDATE
opening_time_1 = :time1_upd,
opening_time_2 = :time2_upd";
$stmt = $this->db->prepare($sql);
$t1 = $openingTime1 ?: null;
$t2 = $openingTime2 ?: null;
return $stmt->execute([
'day' => $dayOfWeek,
'time1' => $t1,
'time2' => $t2,
'time1_upd' => $t1,
'time2_upd' => $t2
]);
}
/**
* Obtiene los horarios en formato array asociativo
*/
public function getScheduleArray()
{
$schedules = $this->getAll();
$result = [];
foreach ($schedules as $schedule) {
$result[$schedule['day_of_week']] = [
'opening_time_1' => $schedule['opening_time_1'],
'opening_time_2' => $schedule['opening_time_2']
];
}
return $result;
}
}

154
src/Models/User.php Normal file
View File

@@ -0,0 +1,154 @@
<?php
namespace App\Models;
use PDO;
/**
* Modelo de usuarios
*/
class User extends BaseModel
{
protected $table = 'users';
/**
* Crea un nuevo usuario
*/
public function create($data)
{
$sql = "INSERT INTO users (username, password, full_name, role, active)
VALUES (:username, :password, :full_name, :role, :active)";
$stmt = $this->db->prepare($sql);
return $stmt->execute([
'username' => $data['username'],
'password' => password_hash($data['password'], PASSWORD_BCRYPT),
'full_name' => $data['full_name'],
'role' => $data['role'] ?? 'ayudante',
'active' => $data['active'] ?? 1
]);
}
/**
* Actualiza un usuario
*/
public function update($id, $data)
{
$fields = [];
$params = ['id' => $id];
if (isset($data['username'])) {
$fields[] = "username = :username";
$params['username'] = $data['username'];
}
if (isset($data['password']) && !empty($data['password'])) {
$fields[] = "password = :password";
$params['password'] = password_hash($data['password'], PASSWORD_BCRYPT);
}
if (isset($data['full_name'])) {
$fields[] = "full_name = :full_name";
$params['full_name'] = $data['full_name'];
}
if (isset($data['role'])) {
$fields[] = "role = :role";
$params['role'] = $data['role'];
}
if (isset($data['active'])) {
$fields[] = "active = :active";
$params['active'] = $data['active'];
}
if (empty($fields)) {
return false;
}
$sql = "UPDATE users SET " . implode(', ', $fields) . " WHERE id = :id";
$stmt = $this->db->prepare($sql);
return $stmt->execute($params);
}
/**
* Busca un usuario por nombre de usuario
*/
public function findByUsername($username)
{
$stmt = $this->db->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
return $stmt->fetch();
}
/**
* Obtiene usuarios por rol
*/
public function getByRole($role)
{
$stmt = $this->db->prepare("SELECT * FROM users WHERE role = ? AND active = 1 ORDER BY full_name");
$stmt->execute([$role]);
return $stmt->fetchAll();
}
/**
* Obtiene todos los ayudantes (incluyendo coordinadores) ordenados por sort_order
*/
public function getAllHelpers()
{
$sql = "SELECT * FROM users
WHERE role IN ('ayudante', 'coordinador')
AND active = 1
ORDER BY sort_order ASC, id ASC";
$stmt = $this->db->query($sql);
return $stmt->fetchAll();
}
/**
* Actualiza el orden de un usuario para la rotación
* @param int $userId
* @param int $position
*/
public function updateOrder($userId, $position)
{
$stmt = $this->db->prepare("UPDATE users SET sort_order = ? WHERE id = ?");
return $stmt->execute([$position, $userId]);
}
/**
* Obtiene usuarios activos
*/
public function getActive()
{
$stmt = $this->db->query("SELECT * FROM users WHERE active = 1 ORDER BY full_name");
return $stmt->fetchAll();
}
/**
* Verifica si un nombre de usuario ya existe
*/
public function usernameExists($username, $excludeId = null)
{
if ($excludeId) {
$stmt = $this->db->prepare("SELECT COUNT(*) as count FROM users WHERE username = ? AND id != ?");
$stmt->execute([$username, $excludeId]);
} else {
$stmt = $this->db->prepare("SELECT COUNT(*) as count FROM users WHERE username = ?");
$stmt->execute([$username]);
}
$result = $stmt->fetch();
return $result['count'] > 0;
}
/**
* Activa o desactiva un usuario
*/
public function toggleActive($id)
{
$stmt = $this->db->prepare("UPDATE users SET active = NOT active WHERE id = ?");
return $stmt->execute([$id]);
}
}

View File

@@ -0,0 +1,193 @@
<?php
namespace App\Services;
use App\Models\User;
use App\Config\Env;
/**
* Servicio de autenticación
*/
class AuthService
{
private $userModel;
public function __construct()
{
$this->userModel = new User();
$this->startSession();
}
/**
* Inicia la sesión si no está iniciada
*/
private function startSession()
{
if (session_status() === PHP_SESSION_NONE) {
Env::load();
session_name(Env::get('SESSION_NAME', 'contenedor_session'));
session_start([
'cookie_lifetime' => Env::get('SESSION_LIFETIME', 7200),
'cookie_httponly' => true,
'cookie_secure' => isset($_SERVER['HTTPS']),
'use_strict_mode' => true
]);
}
}
/**
* Intenta autenticar un usuario
*
* @param string $username
* @param string $password
* @return bool
*/
public function login($username, $password)
{
$user = $this->userModel->findByUsername($username);
if (!$user) {
return false;
}
if (!$user['active']) {
return false;
}
if (!password_verify($password, $user['password'])) {
return false;
}
// Guardar datos del usuario en sesión
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['full_name'] = $user['full_name'];
$_SESSION['role'] = $user['role'];
$_SESSION['logged_in'] = true;
// Regenerar ID de sesión por seguridad
session_regenerate_id(true);
return true;
}
/**
* Cierra la sesión del usuario
*/
public function logout()
{
$_SESSION = [];
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 3600, '/');
}
session_destroy();
}
/**
* Verifica si hay un usuario autenticado
*
* @return bool
*/
public function isLoggedIn()
{
return isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true;
}
/**
* Obtiene los datos del usuario actual
*
* @return array|null
*/
public function getCurrentUser()
{
if (!$this->isLoggedIn()) {
return null;
}
return [
'id' => $_SESSION['user_id'] ?? null,
'username' => $_SESSION['username'] ?? null,
'full_name' => $_SESSION['full_name'] ?? null,
'role' => $_SESSION['role'] ?? null
];
}
/**
* Verifica si el usuario tiene un rol específico
*
* @param string|array $roles
* @return bool
*/
public function hasRole($roles)
{
if (!$this->isLoggedIn()) {
return false;
}
$userRole = $_SESSION['role'] ?? null;
if (is_array($roles)) {
return in_array($userRole, $roles);
}
return $userRole === $roles;
}
/**
* Requiere que el usuario tenga un rol específico
* Redirige si no lo tiene
*
* @param string|array $roles
*/
public function requireRole($roles)
{
if (!$this->hasRole($roles)) {
http_response_code(403);
die('Acceso denegado. No tienes permisos para acceder a esta página.');
}
}
/**
* Requiere que el usuario esté autenticado
* Redirige al login si no lo está
*/
public function requireAuth()
{
if (!$this->isLoggedIn()) {
redirect(siteUrl('login.php'));
}
}
/**
* Verifica si el usuario es administrador
*
* @return bool
*/
public function isAdmin()
{
return $this->hasRole('admin');
}
/**
* Verifica si el usuario es coordinador
*
* @return bool
*/
public function isCoordinador()
{
return $this->hasRole('coordinador');
}
/**
* Verifica si el usuario es ayudante
*
* @return bool
*/
public function isAyudante()
{
return $this->hasRole('ayudante');
}
}

133
src/Services/PDFService.php Normal file
View File

@@ -0,0 +1,133 @@
<?php
namespace App\Services;
use TCPDF;
use App\Models\Assignment;
use App\Models\Schedule;
/**
* Servicio para generación de PDFs
*/
class PDFService
{
private $assignmentModel;
private $scheduleModel;
public function __construct()
{
$this->assignmentModel = new Assignment();
$this->scheduleModel = new Schedule();
}
/**
* Genera el PDF con rotaciones y horarios
*
* @param string $outputMode 'D' para descarga, 'F' para guardar archivo (path), 'I' para browser inline
* @param string $savePath Ruta donde guardar si mode es 'F'
* @return string|void
*/
public function generate($outputMode = 'D', $savePath = '')
{
// Crear instancia TCPDF
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// Configuración del documento
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Sistema Contenedor Ibiza');
$pdf->SetTitle('Rotación de Ayudantes y Horarios');
// Quitar cabeceras y pies de página default
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
// Márgenes
$pdf->SetMargins(15, 15, 15);
// Agregar página
$pdf->AddPage();
// --- TÍTULO ---
$pdf->SetFont('helvetica', 'B', 20);
$pdf->Cell(0, 10, 'Control de Contenedor de Basura', 0, 1, 'C');
$pdf->SetFont('helvetica', '', 12);
$pdf->Cell(0, 10, 'Generado el: ' . date('d/m/Y H:i'), 0, 1, 'C');
$pdf->Ln(5);
// --- TABLA DE HORARIOS ---
$pdf->SetFont('helvetica', 'B', 14);
$pdf->Cell(0, 10, 'Horarios de Apertura', 0, 1, 'L');
$pdf->Ln(2);
$schedules = $this->scheduleModel->getAll();
// Cabecera tabla horarios
$pdf->SetFont('helvetica', 'B', 11);
$pdf->SetFillColor(230, 230, 230);
$colWidth = 180 / 7;
$days = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
// Días
foreach ($days as $day) {
$pdf->Cell($colWidth, 8, $day, 1, 0, 'C', 1);
}
$pdf->Ln();
// Horarios Turno 1
$pdf->SetFont('helvetica', '', 10);
foreach ($schedules as $sch) {
$time = $sch['opening_time_1'] ? substr($sch['opening_time_1'], 0, 5) : '-';
$pdf->Cell($colWidth, 8, $time, 1, 0, 'C');
}
$pdf->Ln();
// Horarios Turno 2
foreach ($schedules as $sch) {
$time = $sch['opening_time_2'] ? substr($sch['opening_time_2'], 0, 5) : '-';
$text = (!$sch['opening_time_1'] && !$sch['opening_time_2']) ? 'Cerrado' : $time;
// Si dice Cerrado, que ocupe el espacio o sea visible
if ($text == 'Cerrado') {
// Ya se pintó arriba un guión, aquí ponemos Cerrado? O mejor estructura
// Recalculando lógica visual...
// Mejor: Fila 1 = Turno Mañana/Tarde 1, Fila 2 = Turno Tarde/Noche 2
}
$pdf->Cell($colWidth, 8, $text, 1, 0, 'C');
}
$pdf->Ln(15);
// --- TABLA DE ROTACIÓN ---
$pdf->SetFont('helvetica', 'B', 14);
$pdf->Cell(0, 10, 'Rotación de Ayudantes (Próximas Semanas)', 0, 1, 'L');
$pdf->Ln(2);
$assignments = $this->assignmentModel->getUpcoming(12); // Mostrar 12 semanas
// Cabecera tabla rotación
$pdf->SetFont('helvetica', 'B', 11);
$pdf->Cell(30, 10, 'Semana y Año', 1, 0, 'C', 1);
$pdf->Cell(90, 10, 'Ayudante Asignado', 1, 0, 'C', 1);
$pdf->Cell(60, 10, 'Periodo', 1, 1, 'C', 1);
$pdf->SetFont('helvetica', '', 11);
foreach ($assignments as $asg) {
$periodo = date('d/m', strtotime($asg['start_date'])) . ' - ' . date('d/m', strtotime($asg['end_date']));
$semTxt = "Sem " . $asg['week_number']; // . " (" . $asg['year'] . ")";
$pdf->Cell(30, 8, $semTxt, 1, 0, 'C');
$pdf->Cell(90, 8, $asg['full_name'], 1, 0, 'L');
$pdf->Cell(60, 8, $periodo, 1, 1, 'C');
}
// Output
if ($outputMode == 'F') {
$pdf->Output($savePath, 'F');
return $savePath;
} else {
$pdf->Output('rotacion-contenedor.pdf', $outputMode);
}
}
}

View File

@@ -0,0 +1,136 @@
<?php
namespace App\Services;
use App\Models\User;
use App\Models\Assignment;
use DateTime;
use DateInterval;
/**
* Servicio para la generación automática de rotaciones
*/
class RotationService
{
private $userModel;
private $assignmentModel;
private $weekService;
public function __construct()
{
$this->userModel = new User();
$this->assignmentModel = new Assignment();
$this->weekService = new WeekService();
}
/**
* Genera las próximas N semanas de rotación
*
* @param int $weeksCount Número de semanas a generar
* @return int Número de asignaciones creadas
*/
public function generateNext($weeksCount = 8)
{
// 1. Obtener todos los ayudantes y coordinadores activos ordenados
// El orden es crucial para la rotación constante
$helpers = $this->userModel->getAllHelpers();
if (empty($helpers)) {
return 0;
}
// 2. Obtener la última asignación registrada para saber dónde continuar
$lastAssignment = $this->assignmentModel->getLatest();
$nextDate = null;
$nextHelperIndex = 0;
if ($lastAssignment) {
// Continuar desde la siguiente semana de la última asignación
$nextDate = $this->weekService->getNextWeekStart($lastAssignment['start_date']);
// Buscar índice del último usuario asignado para continuar con el siguiente
$lastUserId = $lastAssignment['user_id'];
foreach ($helpers as $index => $helper) {
if ($helper['id'] == $lastUserId) {
$nextHelperIndex = ($index + 1) % count($helpers);
break;
}
}
} else {
// Si no hay asignaciones previas, empezar desde la semana actual
$dates = $this->weekService->getCurrentWeekDates();
$nextDate = $dates['start'];
// Empezar con el primer ayudante de la lista (orden alfabético por defecto en User::getAllHelpers)
$nextHelperIndex = 0;
}
$count = 0;
// 3. Generar las asignaciones
for ($i = 0; $i < $weeksCount; $i++) {
// Calcular fecha fin (sábado)
$startDateObj = new DateTime($nextDate);
$endDateObj = clone $startDateObj;
$endDateObj->add(new DateInterval('P6D'));
$weekNumber = (int)$startDateObj->format('W');
$year = (int)$startDateObj->format('Y');
// Verificar si ya existe asignación para esta semana (evitar duplicados)
if (!$this->assignmentModel->existsForWeek($year, $weekNumber)) {
$helper = $helpers[$nextHelperIndex];
$data = [
'user_id' => $helper['id'],
'week_number' => $weekNumber,
'year' => $year,
'start_date' => $startDateObj->format('Y-m-d'),
'end_date' => $endDateObj->format('Y-m-d'),
'order_position' => $count // Opcional, útil si se implementa reordenamiento futuro
];
$this->assignmentModel->create($data);
$count++;
}
// Avanzar al siguiente ayudante
$nextHelperIndex = ($nextHelperIndex + 1) % count($helpers);
// Avanzar a la siguiente semana
$nextDateObj = new DateTime($nextDate);
$nextDateObj->add(new DateInterval('P7D'));
$nextDate = $nextDateObj->format('Y-m-d');
}
return $count;
}
/**
* Regenera las asignaciones futuras basándose en el orden maestro de usuarios
* Mantiene historial pasado, limpia futuro próximo y regenera.
*/
public function regenerateFutureFromOrder()
{
// 1. Definir fecha de corte: HOY
// No borramos asignaciones pasadas ni la actual en curso para no romper historial.
$today = date('Y-m-d');
// Pero debemos tener cuidado: Si estamos a mitad de semana, la asignación actual DEBE mantenerse.
// La función deleteFutureAssignments borrará todo lo que empiece DESPUÉS de una fecha dada.
// Vamos a calcular el fin de la semana actual.
$currentWeek = $this->weekService->getCurrentWeekNumber();
$currentYear = $this->weekService->getCurrentYear();
$dates = $this->weekService->getWeekDateRange($currentYear, $currentWeek);
$cutOffDate = $dates['end']; // Sábado de esta semana
// Eliminar asignaciones que empiezan DESPUÉS de esta semana
$this->assignmentModel->deleteFutureAssignments($cutOffDate);
// 2. Generar nuevas asignaciones
// Esto automáticamente buscará la última asignación válida (la de esta semana)
// y continuará desde la siguiente fecha con el siguiente usuario del ciclo maestro.
return $this->generateNext(12); // Generar 12 semanas
}
}

View File

@@ -0,0 +1,290 @@
<?php
namespace App\Services;
use App\Models\Assignment;
use App\Models\Schedule;
use App\Config\Env;
/**
* Servicio para manejar el Bot de Telegram
*/
class TelegramBot
{
private $token;
private $apiUrl;
private $assignmentModel;
private $scheduleModel;
private $pdfService;
public function __construct()
{
$this->token = Env::get('TELEGRAM_BOT_TOKEN');
$this->apiUrl = "https://api.telegram.org/bot{$this->token}/";
$this->assignmentModel = new Assignment();
$this->scheduleModel = new Schedule();
$this->pdfService = new PDFService();
}
/**
* Procesa la solicitud entrante del Webhook
*/
public function processWebhook($data)
{
if (!isset($data['message'])) {
return;
}
$message = $data['message'];
$chatId = $message['chat']['id'];
$text = trim($message['text'] ?? '');
// Log básico para debug
error_log("Telegram Msg: $text from $chatId");
// Comandos de sistema
if ($text === '/start' || $text === '/menu') {
$this->sendMainMenu($chatId);
return;
}
// Manejo de botones del menú
switch ($text) {
case '📅 Itinerario':
$this->sendRotationTable($chatId);
break;
case '⏰ Horas':
$this->sendContainerHours($chatId);
break;
case '📄 PDF':
$this->sendPdf($chatId);
break;
default:
// Si es un comando antiguo, soportarlo
if (strpos($text, '/') === 0) {
$parts = explode(' ', $text);
$command = strtolower($parts[0]);
if ($command === '/tabla') $this->sendRotationTable($chatId);
elseif ($command === '/pdf') $this->sendPdf($chatId);
elseif ($command === '/horario') {
$args = array_slice($parts, 1);
$this->sendUserSchedule($chatId, implode(' ', $args));
}
} else {
// Si es texto libre, asumir que es búsqueda de nombre
if (!empty($text)) {
$this->sendUserSchedule($chatId, $text);
}
}
break;
}
}
/**
* Envía el menú principal con botones
*/
private function sendMainMenu($chatId)
{
$keyboard = [
'keyboard' => [
[['text' => '📅 Itinerario'], ['text' => '⏰ Horas']],
[['text' => '📄 PDF']]
],
'resize_keyboard' => true,
'persistent' => true
];
$msg = "👋 ¡Hola! Soy el Bot del Contenedor de Ibiza.\n\n" .
"Selecciona una opción del menú o *escribe el nombre* de una persona para ver sus turnos.";
$this->sendMessage($chatId, $msg, $keyboard);
}
/**
* Envía los horarios de apertura
*/
private function sendContainerHours($chatId)
{
$schedules = $this->scheduleModel->getAll();
$daysMap = [0 => 'Domingo', 1 => 'Lunes', 2 => 'Martes', 3 => 'Miércoles', 4 => 'Jueves', 5 => 'Viernes', 6 => 'Sábado'];
$msg = "⏰ *Horarios de Apertura*\n\n";
foreach ($schedules as $sch) {
$dayName = $daysMap[$sch['day_of_week']] ?? 'Día ' . $sch['day_of_week'];
$t1 = $sch['opening_time_1'] ? substr($sch['opening_time_1'], 0, 5) : null;
$t2 = $sch['opening_time_2'] ? substr($sch['opening_time_2'], 0, 5) : null;
$status = "Cerrado";
if ($t1 || $t2) {
$status = "";
if ($t1) $status .= "$t1 ";
if ($t2) $status .= "| $t2";
} else {
$status = "🚫 Cerrado";
}
$msg .= "*$dayName*: $status\n";
}
$this->sendMessage($chatId, $msg);
}
/**
* Envía mensaje de texto (con teclado opcional)
*/
public function sendMessage($chatId, $text, $keyboard = null)
{
$data = [
'chat_id' => $chatId,
'text' => $text,
'parse_mode' => 'Markdown'
];
if ($keyboard) {
$data['reply_markup'] = json_encode($keyboard);
}
$this->request('sendMessage', $data);
}
// ... (El resto de métodos handleCommand antiguos se pueden eliminar o dejar como legacy si se invocan internamente, pero aquí reestructuramos processWebhook)
/**
* Envía la tabla de rotación en texto
*/
private function sendRotationTable($chatId)
{
$assignments = $this->assignmentModel->getUpcoming(10); // Ver más semanas
if (empty($assignments)) {
$this->sendMessage($chatId, "No hay rotaciones programadas próximamente.");
return;
}
$msg = "📅 *Itinerario de Rotación*\n\n";
foreach ($assignments as $asg) {
$dates = date('d/m', strtotime($asg['start_date'])) . "-" . date('d/m', strtotime($asg['end_date']));
$msg .= "`" . str_pad($dates, 11) . "` : *" . $asg['full_name'] . "*\n";
}
$this->sendMessage($chatId, $msg);
}
/**
* Busca y envía el horario de un usuario
*/
private function sendUserSchedule($chatId, $name)
{
// Buscar por nombre similar
$assignments = $this->assignmentModel->searchByName($name);
if (empty($assignments)) {
$this->sendMessage($chatId, "🤷‍♂️ No encontré turnos futuros para \"$name\".\nIntenta escribir solo el nombre, ej: *Ana*");
return;
}
// Agrupar por usuario si la búsqueda trae varios (Ana Maria, Ana Lu)
// Pero searchByName ordena por fecha.
// Asumimos que queremos ver próximos turnos de todos los matches
// Optimización: Si hay muchos resultados distintos usuarios, avisar.
// Por ahora listamos todo simple.
$msg = "👤 *Resultados para \"$name\"*\n\n";
$count = 0;
foreach ($assignments as $asg) {
if ($count >= 10) break; // Limitar
$msg .= "🔹 *" . $asg['full_name'] . "*: Semana " . $asg['week_number'] . "\n";
$msg .= " (" . date('d/m', strtotime($asg['start_date'])) . " - " . date('d/m', strtotime($asg['end_date'])) . ")\n\n";
$count++;
}
$this->sendMessage($chatId, $msg);
}
/**
* Genera y envía el PDF
*/
private function sendPdf($chatId)
{
$this->sendMessage($chatId, "📄 Generando PDF...");
try {
$tmpDir = sys_get_temp_dir();
$filename = "Rotacion_" . date('Y-m-d') . ".pdf";
$path = $tmpDir . '/' . $filename;
$this->pdfService->generate('F', $path);
$this->sendDocument($chatId, $path);
@unlink($path);
} catch (\Exception $e) {
error_log("Error PDF Telegram: " . $e->getMessage());
$this->sendMessage($chatId, " Hubo un error al generar el PDF.");
}
}
/**
* Envía un documento
*/
private function sendDocument($chatId, $filePath)
{
$cFile = new \CURLFile($filePath);
$data = [
'chat_id' => $chatId,
'document' => $cFile
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->apiUrl . "sendDocument");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
/**
* Realiza petición cURL
*/
private function request($method, $data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->apiUrl . $method);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function setWebhook($url)
{
return $this->request('setWebhook', ['url' => $url]);
}
/**
* Obtiene información del Webhook
*/
public function getWebhookInfo()
{
$response = $this->request('getWebhookInfo', []);
return json_decode($response, true);
}
/**
* Elimina el Webhook actual
*/
public function deleteWebhook()
{
return $this->request('deleteWebhook', []);
}
}

View File

@@ -0,0 +1,113 @@
<?php
namespace App\Services;
use DateTime;
use DateInterval;
use DatePeriod;
/**
* Servicio para cálculos de fechas y semanas
* Regla de negocio: Las semanas inician Domingo y terminan Sábado
*/
class WeekService
{
/**
* Obtiene la fecha de inicio (domingo) y fin (sábado) de la semana actual
*/
public function getCurrentWeekDates()
{
$today = new DateTime();
$dayOfWeek = $today->format('w'); // 0 (dom) a 6 (sab)
// Calcular inicio (domingo de esta semana)
$start = clone $today;
$start->sub(new DateInterval("P{$dayOfWeek}D"));
// Calcular fin (sábado de esta semana)
$end = clone $start;
$end->add(new DateInterval('P6D'));
return [
'start' => $start->format('Y-m-d'),
'end' => $end->format('Y-m-d'),
'week_number' => $start->format('W'), // Nota: 'W' usa estándar ISO (Lunes inicio), puede variar
'year' => $start->format('Y')
];
}
/**
* Obtiene el número de semana ajustado para inicio en domingo
*/
public function getWeekNumber($dateStr)
{
$date = new DateTime($dateStr);
// Si es domingo, PHP lo cuenta como final de la semana anterior en ISO-8601
// Para nuestro caso, domingo es inicio, así que usamos el número de semana "natural"
return (int)$date->format('W');
}
/**
* Obtiene las fechas de una semana específica dado año y número
*/
public function getWeekDates($year, $weekNumber)
{
$dto = new DateTime();
// 'W' es ISO-8601, inicia Lunes.
// setISODate($year, $weekNumber, $day) -> 1=Lunes, 7=Domingo
// Aproximación: obtener el lunes de esa semana ISO y restar 1 día para obtener el domingo previo
$dto->setISODate($year, $weekNumber, 1);
$dto->sub(new DateInterval('P1D')); // Retroceder al Domingo
$start = $dto;
$end = clone $start;
$end->add(new DateInterval('P6D')); // Sábado
return [
'start' => $start->format('Y-m-d'),
'end' => $end->format('Y-m-d')
];
}
/**
* Obtiene la fecha del próximo domingo (inicio de siguiente semana) dada una fecha de referencia
*/
public function getNextWeekStart($dateStr)
{
$date = new DateTime($dateStr);
$dayOfWeek = $date->format('w');
// Ir al domingo de la semana actual de esa fecha
$date->sub(new DateInterval("P{$dayOfWeek}D"));
// Sumar 7 días
$date->add(new DateInterval('P7D'));
return $date->format('Y-m-d');
}
/**
* Obtiene el número de semana actual
*/
public function getCurrentWeekNumber()
{
$dates = $this->getCurrentWeekDates();
return $dates['week_number'];
}
/**
* Obtiene el año actual
*/
public function getCurrentYear()
{
$dates = $this->getCurrentWeekDates();
return $dates['year'];
}
/**
* Alias para getWeekDates
*/
public function getWeekDateRange($year, $weekNumber)
{
return $this->getWeekDates($year, $weekNumber);
}
}

16
supervisor.conf Normal file
View File

@@ -0,0 +1,16 @@
[supervisord]
nodaemon=true
[program:apache2]
command=/usr/sbin/apache2ctl -D FOREGROUND
autostart=true
autorestart=true
stderr_logfile=/var/log/apache2/error.log
stdout_logfile=/var/log/apache2/access.log
[program:rotation-worker]
command=/usr/bin/php /var/www/html/scripts/auto-rotation.php
autostart=true
autorestart=true
stderr_logfile=/var/www/html/logs/rotation-error.log
stdout_logfile=/var/www/html/logs/rotation-output.log

25
vendor/autoload.php vendored Normal file
View File

@@ -0,0 +1,25 @@
<?php
// autoload.php @generated by Composer
if (PHP_VERSION_ID < 50600) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, $err);
} elseif (!headers_sent()) {
echo $err;
}
}
trigger_error(
$err,
E_USER_ERROR
);
}
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitcdd8f12d61317e626c1fa87f94fbf8a4::getLoader();

579
vendor/composer/ClassLoader.php vendored Normal file
View File

@@ -0,0 +1,579 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @see https://www.php-fig.org/psr/psr-0/
* @see https://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
/** @var \Closure(string):void */
private static $includeFile;
/** @var string|null */
private $vendorDir;
// PSR-4
/**
* @var array<string, array<string, int>>
*/
private $prefixLengthsPsr4 = array();
/**
* @var array<string, list<string>>
*/
private $prefixDirsPsr4 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr4 = array();
// PSR-0
/**
* List of PSR-0 prefixes
*
* Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2')))
*
* @var array<string, array<string, list<string>>>
*/
private $prefixesPsr0 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr0 = array();
/** @var bool */
private $useIncludePath = false;
/**
* @var array<string, string>
*/
private $classMap = array();
/** @var bool */
private $classMapAuthoritative = false;
/**
* @var array<string, bool>
*/
private $missingClasses = array();
/** @var string|null */
private $apcuPrefix;
/**
* @var array<string, self>
*/
private static $registeredLoaders = array();
/**
* @param string|null $vendorDir
*/
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
self::initializeIncludeClosure();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
/**
* @return list<string>
*/
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
/**
* @return list<string>
*/
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
/**
* @return array<string, string> Array of classname => path
*/
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array<string, string> $classMap Class to filename map
*
* @return void
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*
* @return void
*/
public function add($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
$paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
$paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
$paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
$paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
$paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
$paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 base directories
*
* @return void
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*
* @return void
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*
* @return void
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*
* @return void
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*
* @return void
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
if (null === $this->vendorDir) {
return;
}
if ($prepend) {
self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
} else {
unset(self::$registeredLoaders[$this->vendorDir]);
self::$registeredLoaders[$this->vendorDir] = $this;
}
}
/**
* Unregisters this instance as an autoloader.
*
* @return void
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
if (null !== $this->vendorDir) {
unset(self::$registeredLoaders[$this->vendorDir]);
}
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return true|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
$includeFile = self::$includeFile;
$includeFile($file);
return true;
}
return null;
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
/**
* Returns the currently registered loaders keyed by their corresponding vendor directories.
*
* @return array<string, self>
*/
public static function getRegisteredLoaders()
{
return self::$registeredLoaders;
}
/**
* @param string $class
* @param string $ext
* @return string|false
*/
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
/**
* @return void
*/
private static function initializeIncludeClosure()
{
if (self::$includeFile !== null) {
return;
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*
* @param string $file
* @return void
*/
self::$includeFile = \Closure::bind(static function($file) {
include $file;
}, null, null);
}
}

359
vendor/composer/InstalledVersions.php vendored Normal file
View File

@@ -0,0 +1,359 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Autoload\ClassLoader;
use Composer\Semver\VersionParser;
/**
* This class is copied in every Composer installed project and available to all
*
* See also https://getcomposer.org/doc/07-runtime.md#installed-versions
*
* To require its presence, you can require `composer-runtime-api ^2.0`
*
* @final
*/
class InstalledVersions
{
/**
* @var mixed[]|null
* @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null
*/
private static $installed;
/**
* @var bool|null
*/
private static $canGetVendors;
/**
* @var array[]
* @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static $installedByVendor = array();
/**
* Returns a list of all package names which are present, either by being installed, replaced or provided
*
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackages()
{
$packages = array();
foreach (self::getInstalled() as $installed) {
$packages[] = array_keys($installed['versions']);
}
if (1 === \count($packages)) {
return $packages[0];
}
return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
}
/**
* Returns a list of all package names with a specific type e.g. 'library'
*
* @param string $type
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackagesByType($type)
{
$packagesByType = array();
foreach (self::getInstalled() as $installed) {
foreach ($installed['versions'] as $name => $package) {
if (isset($package['type']) && $package['type'] === $type) {
$packagesByType[] = $name;
}
}
}
return $packagesByType;
}
/**
* Checks whether the given package is installed
*
* This also returns true if the package name is provided or replaced by another package
*
* @param string $packageName
* @param bool $includeDevRequirements
* @return bool
*/
public static function isInstalled($packageName, $includeDevRequirements = true)
{
foreach (self::getInstalled() as $installed) {
if (isset($installed['versions'][$packageName])) {
return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false;
}
}
return false;
}
/**
* Checks whether the given package satisfies a version constraint
*
* e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call:
*
* Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3')
*
* @param VersionParser $parser Install composer/semver to have access to this class and functionality
* @param string $packageName
* @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package
* @return bool
*/
public static function satisfies(VersionParser $parser, $packageName, $constraint)
{
$constraint = $parser->parseConstraints((string) $constraint);
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
return $provided->matches($constraint);
}
/**
* Returns a version constraint representing all the range(s) which are installed for a given package
*
* It is easier to use this via isInstalled() with the $constraint argument if you need to check
* whether a given version of a package is installed, and not just whether it exists
*
* @param string $packageName
* @return string Version constraint usable with composer/semver
*/
public static function getVersionRanges($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
$ranges = array();
if (isset($installed['versions'][$packageName]['pretty_version'])) {
$ranges[] = $installed['versions'][$packageName]['pretty_version'];
}
if (array_key_exists('aliases', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
}
if (array_key_exists('replaced', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
}
if (array_key_exists('provided', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
}
return implode(' || ', $ranges);
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['version'])) {
return null;
}
return $installed['versions'][$packageName]['version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getPrettyVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['pretty_version'])) {
return null;
}
return $installed['versions'][$packageName]['pretty_version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference
*/
public static function getReference($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['reference'])) {
return null;
}
return $installed['versions'][$packageName]['reference'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path.
*/
public static function getInstallPath($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null;
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @return array
* @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}
*/
public static function getRootPackage()
{
$installed = self::getInstalled();
return $installed[0]['root'];
}
/**
* Returns the raw installed.php data for custom implementations
*
* @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect.
* @return array[]
* @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}
*/
public static function getRawData()
{
@trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED);
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
self::$installed = include __DIR__ . '/installed.php';
} else {
self::$installed = array();
}
}
return self::$installed;
}
/**
* Returns the raw data of all installed.php which are currently loaded for custom implementations
*
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
public static function getAllRawData()
{
return self::getInstalled();
}
/**
* Lets you reload the static array from another file
*
* This is only useful for complex integrations in which a project needs to use
* this class but then also needs to execute another project's autoloader in process,
* and wants to ensure both projects have access to their version of installed.php.
*
* A typical case would be PHPUnit, where it would need to make sure it reads all
* the data it needs from this class, then call reload() with
* `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure
* the project in which it runs can then also use this class safely, without
* interference between PHPUnit's dependencies and the project's dependencies.
*
* @param array[] $data A vendor/composer/installed.php data set
* @return void
*
* @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data
*/
public static function reload($data)
{
self::$installed = $data;
self::$installedByVendor = array();
}
/**
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static function getInstalled()
{
if (null === self::$canGetVendors) {
self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
}
$installed = array();
if (self::$canGetVendors) {
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir.'/composer/installed.php')) {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require $vendorDir.'/composer/installed.php';
$installed[] = self::$installedByVendor[$vendorDir] = $required;
if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) {
self::$installed = $installed[count($installed) - 1];
}
}
}
}
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require __DIR__ . '/installed.php';
self::$installed = $required;
} else {
self::$installed = array();
}
}
if (self::$installed !== array()) {
$installed[] = self::$installed;
}
return $installed;
}
}

19
vendor/composer/LICENSE vendored Normal file
View File

@@ -0,0 +1,19 @@
Copyright (c) Nils Adermann, Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

27
vendor/composer/autoload_classmap.php vendored Normal file
View File

@@ -0,0 +1,27 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Attribute' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
'Datamatrix' => $vendorDir . '/tecnickcom/tcpdf/include/barcodes/datamatrix.php',
'PDF417' => $vendorDir . '/tecnickcom/tcpdf/include/barcodes/pdf417.php',
'PhpToken' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php',
'QRcode' => $vendorDir . '/tecnickcom/tcpdf/include/barcodes/qrcode.php',
'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
'TCPDF' => $vendorDir . '/tecnickcom/tcpdf/tcpdf.php',
'TCPDF2DBarcode' => $vendorDir . '/tecnickcom/tcpdf/tcpdf_barcodes_2d.php',
'TCPDFBarcode' => $vendorDir . '/tecnickcom/tcpdf/tcpdf_barcodes_1d.php',
'TCPDF_COLORS' => $vendorDir . '/tecnickcom/tcpdf/include/tcpdf_colors.php',
'TCPDF_FILTERS' => $vendorDir . '/tecnickcom/tcpdf/include/tcpdf_filters.php',
'TCPDF_FONTS' => $vendorDir . '/tecnickcom/tcpdf/include/tcpdf_fonts.php',
'TCPDF_FONT_DATA' => $vendorDir . '/tecnickcom/tcpdf/include/tcpdf_font_data.php',
'TCPDF_IMAGES' => $vendorDir . '/tecnickcom/tcpdf/include/tcpdf_images.php',
'TCPDF_STATIC' => $vendorDir . '/tecnickcom/tcpdf/include/tcpdf_static.php',
'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php',
'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php',
);

13
vendor/composer/autoload_files.php vendored Normal file
View File

@@ -0,0 +1,13 @@
<?php
// autoload_files.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php',
'13df9613870142dcdf3a7050535cba4b' => $baseDir . '/src/Helpers/functions.php',
);

View File

@@ -0,0 +1,9 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
);

16
vendor/composer/autoload_psr4.php vendored Normal file
View File

@@ -0,0 +1,16 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'),
'PhpOption\\' => array($vendorDir . '/phpoption/phpoption/src/PhpOption'),
'GrahamCampbell\\ResultType\\' => array($vendorDir . '/graham-campbell/result-type/src'),
'Dotenv\\' => array($vendorDir . '/vlucas/phpdotenv/src'),
'App\\' => array($baseDir . '/src'),
);

50
vendor/composer/autoload_real.php vendored Normal file
View File

@@ -0,0 +1,50 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInitcdd8f12d61317e626c1fa87f94fbf8a4
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
/**
* @return \Composer\Autoload\ClassLoader
*/
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
require __DIR__ . '/platform_check.php';
spl_autoload_register(array('ComposerAutoloaderInitcdd8f12d61317e626c1fa87f94fbf8a4', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInitcdd8f12d61317e626c1fa87f94fbf8a4', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInitcdd8f12d61317e626c1fa87f94fbf8a4::getInitializer($loader));
$loader->register(true);
$filesToLoad = \Composer\Autoload\ComposerStaticInitcdd8f12d61317e626c1fa87f94fbf8a4::$files;
$requireFile = \Closure::bind(static function ($fileIdentifier, $file) {
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
require $file;
}
}, null, null);
foreach ($filesToLoad as $fileIdentifier => $file) {
$requireFile($fileIdentifier, $file);
}
return $loader;
}
}

102
vendor/composer/autoload_static.php vendored Normal file
View File

@@ -0,0 +1,102 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInitcdd8f12d61317e626c1fa87f94fbf8a4
{
public static $files = array (
'320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php',
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php',
'13df9613870142dcdf3a7050535cba4b' => __DIR__ . '/../..' . '/src/Helpers/functions.php',
);
public static $prefixLengthsPsr4 = array (
'S' =>
array (
'Symfony\\Polyfill\\Php80\\' => 23,
'Symfony\\Polyfill\\Mbstring\\' => 26,
'Symfony\\Polyfill\\Ctype\\' => 23,
),
'P' =>
array (
'PhpOption\\' => 10,
),
'G' =>
array (
'GrahamCampbell\\ResultType\\' => 26,
),
'D' =>
array (
'Dotenv\\' => 7,
),
'A' =>
array (
'App\\' => 4,
),
);
public static $prefixDirsPsr4 = array (
'Symfony\\Polyfill\\Php80\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-php80',
),
'Symfony\\Polyfill\\Mbstring\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring',
),
'Symfony\\Polyfill\\Ctype\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-ctype',
),
'PhpOption\\' =>
array (
0 => __DIR__ . '/..' . '/phpoption/phpoption/src/PhpOption',
),
'GrahamCampbell\\ResultType\\' =>
array (
0 => __DIR__ . '/..' . '/graham-campbell/result-type/src',
),
'Dotenv\\' =>
array (
0 => __DIR__ . '/..' . '/vlucas/phpdotenv/src',
),
'App\\' =>
array (
0 => __DIR__ . '/../..' . '/src',
),
);
public static $classMap = array (
'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
'Datamatrix' => __DIR__ . '/..' . '/tecnickcom/tcpdf/include/barcodes/datamatrix.php',
'PDF417' => __DIR__ . '/..' . '/tecnickcom/tcpdf/include/barcodes/pdf417.php',
'PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php',
'QRcode' => __DIR__ . '/..' . '/tecnickcom/tcpdf/include/barcodes/qrcode.php',
'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
'TCPDF' => __DIR__ . '/..' . '/tecnickcom/tcpdf/tcpdf.php',
'TCPDF2DBarcode' => __DIR__ . '/..' . '/tecnickcom/tcpdf/tcpdf_barcodes_2d.php',
'TCPDFBarcode' => __DIR__ . '/..' . '/tecnickcom/tcpdf/tcpdf_barcodes_1d.php',
'TCPDF_COLORS' => __DIR__ . '/..' . '/tecnickcom/tcpdf/include/tcpdf_colors.php',
'TCPDF_FILTERS' => __DIR__ . '/..' . '/tecnickcom/tcpdf/include/tcpdf_filters.php',
'TCPDF_FONTS' => __DIR__ . '/..' . '/tecnickcom/tcpdf/include/tcpdf_fonts.php',
'TCPDF_FONT_DATA' => __DIR__ . '/..' . '/tecnickcom/tcpdf/include/tcpdf_font_data.php',
'TCPDF_IMAGES' => __DIR__ . '/..' . '/tecnickcom/tcpdf/include/tcpdf_images.php',
'TCPDF_STATIC' => __DIR__ . '/..' . '/tecnickcom/tcpdf/include/tcpdf_static.php',
'UnhandledMatchError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php',
'ValueError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/ValueError.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInitcdd8f12d61317e626c1fa87f94fbf8a4::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitcdd8f12d61317e626c1fa87f94fbf8a4::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInitcdd8f12d61317e626c1fa87f94fbf8a4::$classMap;
}, null, ClassLoader::class);
}
}

571
vendor/composer/installed.json vendored Normal file
View File

@@ -0,0 +1,571 @@
{
"packages": [
{
"name": "graham-campbell/result-type",
"version": "v1.1.4",
"version_normalized": "1.1.4.0",
"source": {
"type": "git",
"url": "https://github.com/GrahamCampbell/Result-Type.git",
"reference": "e01f4a821471308ba86aa202fed6698b6b695e3b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/e01f4a821471308ba86aa202fed6698b6b695e3b",
"reference": "e01f4a821471308ba86aa202fed6698b6b695e3b",
"shasum": ""
},
"require": {
"php": "^7.2.5 || ^8.0",
"phpoption/phpoption": "^1.9.5"
},
"require-dev": {
"phpunit/phpunit": "^8.5.41 || ^9.6.22 || ^10.5.45 || ^11.5.7"
},
"time": "2025-12-27T19:43:20+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"GrahamCampbell\\ResultType\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
}
],
"description": "An Implementation Of The Result Type",
"keywords": [
"Graham Campbell",
"GrahamCampbell",
"Result Type",
"Result-Type",
"result"
],
"support": {
"issues": "https://github.com/GrahamCampbell/Result-Type/issues",
"source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.1.4"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/graham-campbell/result-type",
"type": "tidelift"
}
],
"install-path": "../graham-campbell/result-type"
},
{
"name": "phpoption/phpoption",
"version": "1.9.5",
"version_normalized": "1.9.5.0",
"source": {
"type": "git",
"url": "https://github.com/schmittjoh/php-option.git",
"reference": "75365b91986c2405cf5e1e012c5595cd487a98be"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/schmittjoh/php-option/zipball/75365b91986c2405cf5e1e012c5595cd487a98be",
"reference": "75365b91986c2405cf5e1e012c5595cd487a98be",
"shasum": ""
},
"require": {
"php": "^7.2.5 || ^8.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"phpunit/phpunit": "^8.5.44 || ^9.6.25 || ^10.5.53 || ^11.5.34"
},
"time": "2025-12-27T19:41:33+00:00",
"type": "library",
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": false
},
"branch-alias": {
"dev-master": "1.9-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"PhpOption\\": "src/PhpOption/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"Apache-2.0"
],
"authors": [
{
"name": "Johannes M. Schmitt",
"email": "schmittjoh@gmail.com",
"homepage": "https://github.com/schmittjoh"
},
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
}
],
"description": "Option Type for PHP",
"keywords": [
"language",
"option",
"php",
"type"
],
"support": {
"issues": "https://github.com/schmittjoh/php-option/issues",
"source": "https://github.com/schmittjoh/php-option/tree/1.9.5"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/phpoption/phpoption",
"type": "tidelift"
}
],
"install-path": "../phpoption/phpoption"
},
{
"name": "symfony/polyfill-ctype",
"version": "v1.33.0",
"version_normalized": "1.33.0.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-ctype.git",
"reference": "a3cc8b044a6ea513310cbd48ef7333b384945638"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/a3cc8b044a6ea513310cbd48ef7333b384945638",
"reference": "a3cc8b044a6ea513310cbd48ef7333b384945638",
"shasum": ""
},
"require": {
"php": ">=7.2"
},
"provide": {
"ext-ctype": "*"
},
"suggest": {
"ext-ctype": "For best performance"
},
"time": "2024-09-09T11:45:10+00:00",
"type": "library",
"extra": {
"thanks": {
"url": "https://github.com/symfony/polyfill",
"name": "symfony/polyfill"
}
},
"installation-source": "dist",
"autoload": {
"files": [
"bootstrap.php"
],
"psr-4": {
"Symfony\\Polyfill\\Ctype\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Gert de Pagter",
"email": "BackEndTea@gmail.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for ctype functions",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"ctype",
"polyfill",
"portable"
],
"support": {
"source": "https://github.com/symfony/polyfill-ctype/tree/v1.33.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"install-path": "../symfony/polyfill-ctype"
},
{
"name": "symfony/polyfill-mbstring",
"version": "v1.33.0",
"version_normalized": "1.33.0.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-mbstring.git",
"reference": "6d857f4d76bd4b343eac26d6b539585d2bc56493"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/6d857f4d76bd4b343eac26d6b539585d2bc56493",
"reference": "6d857f4d76bd4b343eac26d6b539585d2bc56493",
"shasum": ""
},
"require": {
"ext-iconv": "*",
"php": ">=7.2"
},
"provide": {
"ext-mbstring": "*"
},
"suggest": {
"ext-mbstring": "For best performance"
},
"time": "2024-12-23T08:48:59+00:00",
"type": "library",
"extra": {
"thanks": {
"url": "https://github.com/symfony/polyfill",
"name": "symfony/polyfill"
}
},
"installation-source": "dist",
"autoload": {
"files": [
"bootstrap.php"
],
"psr-4": {
"Symfony\\Polyfill\\Mbstring\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for the Mbstring extension",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"mbstring",
"polyfill",
"portable",
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-mbstring/tree/v1.33.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"install-path": "../symfony/polyfill-mbstring"
},
{
"name": "symfony/polyfill-php80",
"version": "v1.33.0",
"version_normalized": "1.33.0.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-php80.git",
"reference": "0cc9dd0f17f61d8131e7df6b84bd344899fe2608"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/0cc9dd0f17f61d8131e7df6b84bd344899fe2608",
"reference": "0cc9dd0f17f61d8131e7df6b84bd344899fe2608",
"shasum": ""
},
"require": {
"php": ">=7.2"
},
"time": "2025-01-02T08:10:11+00:00",
"type": "library",
"extra": {
"thanks": {
"url": "https://github.com/symfony/polyfill",
"name": "symfony/polyfill"
}
},
"installation-source": "dist",
"autoload": {
"files": [
"bootstrap.php"
],
"psr-4": {
"Symfony\\Polyfill\\Php80\\": ""
},
"classmap": [
"Resources/stubs"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Ion Bazan",
"email": "ion.bazan@gmail.com"
},
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"polyfill",
"portable",
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-php80/tree/v1.33.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"install-path": "../symfony/polyfill-php80"
},
{
"name": "tecnickcom/tcpdf",
"version": "6.10.1",
"version_normalized": "6.10.1.0",
"source": {
"type": "git",
"url": "https://github.com/tecnickcom/TCPDF.git",
"reference": "7a2701251e5d52fc3d508fd71704683eb54f5939"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/tecnickcom/TCPDF/zipball/7a2701251e5d52fc3d508fd71704683eb54f5939",
"reference": "7a2701251e5d52fc3d508fd71704683eb54f5939",
"shasum": ""
},
"require": {
"ext-curl": "*",
"php": ">=7.1.0"
},
"time": "2025-11-21T10:58:21+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"classmap": [
"config",
"include",
"tcpdf.php",
"tcpdf_barcodes_1d.php",
"tcpdf_barcodes_2d.php",
"include/tcpdf_colors.php",
"include/tcpdf_filters.php",
"include/tcpdf_font_data.php",
"include/tcpdf_fonts.php",
"include/tcpdf_images.php",
"include/tcpdf_static.php",
"include/barcodes/datamatrix.php",
"include/barcodes/pdf417.php",
"include/barcodes/qrcode.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"LGPL-3.0-or-later"
],
"authors": [
{
"name": "Nicola Asuni",
"email": "info@tecnick.com",
"role": "lead"
}
],
"description": "TCPDF is a PHP class for generating PDF documents and barcodes.",
"homepage": "http://www.tcpdf.org/",
"keywords": [
"PDFD32000-2008",
"TCPDF",
"barcodes",
"datamatrix",
"pdf",
"pdf417",
"qrcode"
],
"support": {
"issues": "https://github.com/tecnickcom/TCPDF/issues",
"source": "https://github.com/tecnickcom/TCPDF/tree/6.10.1"
},
"funding": [
{
"url": "https://www.paypal.com/donate/?hosted_button_id=NZUEC5XS8MFBJ",
"type": "custom"
}
],
"install-path": "../tecnickcom/tcpdf"
},
{
"name": "vlucas/phpdotenv",
"version": "v5.6.3",
"version_normalized": "5.6.3.0",
"source": {
"type": "git",
"url": "https://github.com/vlucas/phpdotenv.git",
"reference": "955e7815d677a3eaa7075231212f2110983adecc"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/955e7815d677a3eaa7075231212f2110983adecc",
"reference": "955e7815d677a3eaa7075231212f2110983adecc",
"shasum": ""
},
"require": {
"ext-pcre": "*",
"graham-campbell/result-type": "^1.1.4",
"php": "^7.2.5 || ^8.0",
"phpoption/phpoption": "^1.9.5",
"symfony/polyfill-ctype": "^1.26",
"symfony/polyfill-mbstring": "^1.26",
"symfony/polyfill-php80": "^1.26"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"ext-filter": "*",
"phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2"
},
"suggest": {
"ext-filter": "Required to use the boolean validator."
},
"time": "2025-12-27T19:49:13+00:00",
"type": "library",
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": false
},
"branch-alias": {
"dev-master": "5.6-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Dotenv\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
},
{
"name": "Vance Lucas",
"email": "vance@vancelucas.com",
"homepage": "https://github.com/vlucas"
}
],
"description": "Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.",
"keywords": [
"dotenv",
"env",
"environment"
],
"support": {
"issues": "https://github.com/vlucas/phpdotenv/issues",
"source": "https://github.com/vlucas/phpdotenv/tree/v5.6.3"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/vlucas/phpdotenv",
"type": "tidelift"
}
],
"install-path": "../vlucas/phpdotenv"
}
],
"dev": true,
"dev-package-names": []
}

86
vendor/composer/installed.php vendored Normal file
View File

@@ -0,0 +1,86 @@
<?php return array(
'root' => array(
'name' => 'contenedor/ibiza',
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'reference' => null,
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev' => true,
),
'versions' => array(
'contenedor/ibiza' => array(
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'reference' => null,
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev_requirement' => false,
),
'graham-campbell/result-type' => array(
'pretty_version' => 'v1.1.4',
'version' => '1.1.4.0',
'reference' => 'e01f4a821471308ba86aa202fed6698b6b695e3b',
'type' => 'library',
'install_path' => __DIR__ . '/../graham-campbell/result-type',
'aliases' => array(),
'dev_requirement' => false,
),
'phpoption/phpoption' => array(
'pretty_version' => '1.9.5',
'version' => '1.9.5.0',
'reference' => '75365b91986c2405cf5e1e012c5595cd487a98be',
'type' => 'library',
'install_path' => __DIR__ . '/../phpoption/phpoption',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/polyfill-ctype' => array(
'pretty_version' => 'v1.33.0',
'version' => '1.33.0.0',
'reference' => 'a3cc8b044a6ea513310cbd48ef7333b384945638',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-ctype',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/polyfill-mbstring' => array(
'pretty_version' => 'v1.33.0',
'version' => '1.33.0.0',
'reference' => '6d857f4d76bd4b343eac26d6b539585d2bc56493',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-mbstring',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/polyfill-php80' => array(
'pretty_version' => 'v1.33.0',
'version' => '1.33.0.0',
'reference' => '0cc9dd0f17f61d8131e7df6b84bd344899fe2608',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-php80',
'aliases' => array(),
'dev_requirement' => false,
),
'tecnickcom/tcpdf' => array(
'pretty_version' => '6.10.1',
'version' => '6.10.1.0',
'reference' => '7a2701251e5d52fc3d508fd71704683eb54f5939',
'type' => 'library',
'install_path' => __DIR__ . '/../tecnickcom/tcpdf',
'aliases' => array(),
'dev_requirement' => false,
),
'vlucas/phpdotenv' => array(
'pretty_version' => 'v5.6.3',
'version' => '5.6.3.0',
'reference' => '955e7815d677a3eaa7075231212f2110983adecc',
'type' => 'library',
'install_path' => __DIR__ . '/../vlucas/phpdotenv',
'aliases' => array(),
'dev_requirement' => false,
),
),
);

26
vendor/composer/platform_check.php vendored Normal file
View File

@@ -0,0 +1,26 @@
<?php
// platform_check.php @generated by Composer
$issues = array();
if (!(PHP_VERSION_ID >= 80000)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 8.0.0". You are running ' . PHP_VERSION . '.';
}
if ($issues) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL);
} elseif (!headers_sent()) {
echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL;
}
}
trigger_error(
'Composer detected issues in your platform: ' . implode(' ', $issues),
E_USER_ERROR
);
}

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2020-2024 Graham Campbell <hello@gjcampbell.co.uk>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,33 @@
{
"name": "graham-campbell/result-type",
"description": "An Implementation Of The Result Type",
"keywords": ["result", "result-type", "Result", "Result Type", "Result-Type", "Graham Campbell", "GrahamCampbell"],
"license": "MIT",
"authors": [
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
}
],
"require": {
"php": "^7.2.5 || ^8.0",
"phpoption/phpoption": "^1.9.5"
},
"require-dev": {
"phpunit/phpunit": "^8.5.41 || ^9.6.22 || ^10.5.45 || ^11.5.7"
},
"autoload": {
"psr-4": {
"GrahamCampbell\\ResultType\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"GrahamCampbell\\Tests\\ResultType\\": "tests/"
}
},
"config": {
"preferred-install": "dist"
}
}

View File

@@ -0,0 +1,121 @@
<?php
declare(strict_types=1);
/*
* This file is part of Result Type.
*
* (c) Graham Campbell <hello@gjcampbell.co.uk>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace GrahamCampbell\ResultType;
use PhpOption\None;
use PhpOption\Some;
/**
* @template T
* @template E
*
* @extends \GrahamCampbell\ResultType\Result<T,E>
*/
final class Error extends Result
{
/**
* @var E
*/
private $value;
/**
* Internal constructor for an error value.
*
* @param E $value
*
* @return void
*/
private function __construct($value)
{
$this->value = $value;
}
/**
* Create a new error value.
*
* @template F
*
* @param F $value
*
* @return \GrahamCampbell\ResultType\Result<T,F>
*/
public static function create($value)
{
return new self($value);
}
/**
* Get the success option value.
*
* @return \PhpOption\Option<T>
*/
public function success()
{
return None::create();
}
/**
* Map over the success value.
*
* @template S
*
* @param callable(T):S $f
*
* @return \GrahamCampbell\ResultType\Result<S,E>
*/
public function map(callable $f)
{
return self::create($this->value);
}
/**
* Flat map over the success value.
*
* @template S
* @template F
*
* @param callable(T):\GrahamCampbell\ResultType\Result<S,F> $f
*
* @return \GrahamCampbell\ResultType\Result<S,F>
*/
public function flatMap(callable $f)
{
/** @var \GrahamCampbell\ResultType\Result<S,F> */
return self::create($this->value);
}
/**
* Get the error option value.
*
* @return \PhpOption\Option<E>
*/
public function error()
{
return Some::create($this->value);
}
/**
* Map over the error value.
*
* @template F
*
* @param callable(E):F $f
*
* @return \GrahamCampbell\ResultType\Result<T,F>
*/
public function mapError(callable $f)
{
return self::create($f($this->value));
}
}

View File

@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
/*
* This file is part of Result Type.
*
* (c) Graham Campbell <hello@gjcampbell.co.uk>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace GrahamCampbell\ResultType;
/**
* @template T
* @template E
*/
abstract class Result
{
/**
* Get the success option value.
*
* @return \PhpOption\Option<T>
*/
abstract public function success();
/**
* Map over the success value.
*
* @template S
*
* @param callable(T):S $f
*
* @return \GrahamCampbell\ResultType\Result<S,E>
*/
abstract public function map(callable $f);
/**
* Flat map over the success value.
*
* @template S
* @template F
*
* @param callable(T):\GrahamCampbell\ResultType\Result<S,F> $f
*
* @return \GrahamCampbell\ResultType\Result<S,F>
*/
abstract public function flatMap(callable $f);
/**
* Get the error option value.
*
* @return \PhpOption\Option<E>
*/
abstract public function error();
/**
* Map over the error value.
*
* @template F
*
* @param callable(E):F $f
*
* @return \GrahamCampbell\ResultType\Result<T,F>
*/
abstract public function mapError(callable $f);
}

View File

@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
/*
* This file is part of Result Type.
*
* (c) Graham Campbell <hello@gjcampbell.co.uk>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace GrahamCampbell\ResultType;
use PhpOption\None;
use PhpOption\Some;
/**
* @template T
* @template E
*
* @extends \GrahamCampbell\ResultType\Result<T,E>
*/
final class Success extends Result
{
/**
* @var T
*/
private $value;
/**
* Internal constructor for a success value.
*
* @param T $value
*
* @return void
*/
private function __construct($value)
{
$this->value = $value;
}
/**
* Create a new error value.
*
* @template S
*
* @param S $value
*
* @return \GrahamCampbell\ResultType\Result<S,E>
*/
public static function create($value)
{
return new self($value);
}
/**
* Get the success option value.
*
* @return \PhpOption\Option<T>
*/
public function success()
{
return Some::create($this->value);
}
/**
* Map over the success value.
*
* @template S
*
* @param callable(T):S $f
*
* @return \GrahamCampbell\ResultType\Result<S,E>
*/
public function map(callable $f)
{
return self::create($f($this->value));
}
/**
* Flat map over the success value.
*
* @template S
* @template F
*
* @param callable(T):\GrahamCampbell\ResultType\Result<S,F> $f
*
* @return \GrahamCampbell\ResultType\Result<S,F>
*/
public function flatMap(callable $f)
{
return $f($this->value);
}
/**
* Get the error option value.
*
* @return \PhpOption\Option<E>
*/
public function error()
{
return None::create();
}
/**
* Map over the error value.
*
* @template F
*
* @param callable(E):F $f
*
* @return \GrahamCampbell\ResultType\Result<T,F>
*/
public function mapError(callable $f)
{
return self::create($this->value);
}
}

201
vendor/phpoption/phpoption/LICENSE vendored Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

View File

@@ -0,0 +1,50 @@
{
"name": "phpoption/phpoption",
"description": "Option Type for PHP",
"keywords": ["php", "option", "language", "type"],
"license": "Apache-2.0",
"authors": [
{
"name": "Johannes M. Schmitt",
"email": "schmittjoh@gmail.com",
"homepage": "https://github.com/schmittjoh"
},
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
}
],
"require": {
"php": "^7.2.5 || ^8.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"phpunit/phpunit": "^8.5.44 || ^9.6.25 || ^10.5.53 || ^11.5.34"
},
"autoload": {
"psr-4": {
"PhpOption\\": "src/PhpOption/"
}
},
"autoload-dev": {
"psr-4": {
"PhpOption\\Tests\\": "tests/PhpOption/Tests/"
}
},
"config": {
"allow-plugins": {
"bamarni/composer-bin-plugin": true
},
"preferred-install": "dist"
},
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": false
},
"branch-alias": {
"dev-master": "1.9-dev"
}
}
}

View File

@@ -0,0 +1,175 @@
<?php
/*
* Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com>
*
* 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 PhpOption;
use Traversable;
/**
* @template T
*
* @extends Option<T>
*/
final class LazyOption extends Option
{
/** @var callable(mixed...):(Option<T>) */
private $callback;
/** @var array<int, mixed> */
private $arguments;
/** @var Option<T>|null */
private $option;
/**
* @template S
* @param callable(mixed...):(Option<S>) $callback
* @param array<int, mixed> $arguments
*
* @return LazyOption<S>
*/
public static function create($callback, array $arguments = []): self
{
return new self($callback, $arguments);
}
/**
* @param callable(mixed...):(Option<T>) $callback
* @param array<int, mixed> $arguments
*/
public function __construct($callback, array $arguments = [])
{
if (!is_callable($callback)) {
throw new \InvalidArgumentException('Invalid callback given');
}
$this->callback = $callback;
$this->arguments = $arguments;
}
public function isDefined(): bool
{
return $this->option()->isDefined();
}
public function isEmpty(): bool
{
return $this->option()->isEmpty();
}
public function get()
{
return $this->option()->get();
}
public function getOrElse($default)
{
return $this->option()->getOrElse($default);
}
public function getOrCall($callable)
{
return $this->option()->getOrCall($callable);
}
public function getOrThrow(\Exception $ex)
{
return $this->option()->getOrThrow($ex);
}
public function orElse(Option $else)
{
return $this->option()->orElse($else);
}
public function ifDefined($callable)
{
$this->option()->forAll($callable);
}
public function forAll($callable)
{
return $this->option()->forAll($callable);
}
public function map($callable)
{
return $this->option()->map($callable);
}
public function flatMap($callable)
{
return $this->option()->flatMap($callable);
}
public function filter($callable)
{
return $this->option()->filter($callable);
}
public function filterNot($callable)
{
return $this->option()->filterNot($callable);
}
public function select($value)
{
return $this->option()->select($value);
}
public function reject($value)
{
return $this->option()->reject($value);
}
/**
* @return Traversable<T>
*/
public function getIterator(): Traversable
{
return $this->option()->getIterator();
}
public function foldLeft($initialValue, $callable)
{
return $this->option()->foldLeft($initialValue, $callable);
}
public function foldRight($initialValue, $callable)
{
return $this->option()->foldRight($initialValue, $callable);
}
/**
* @return Option<T>
*/
private function option(): Option
{
if (null === $this->option) {
/** @var mixed */
$option = call_user_func_array($this->callback, $this->arguments);
if ($option instanceof Option) {
$this->option = $option;
} else {
throw new \RuntimeException(sprintf('Expected instance of %s', Option::class));
}
}
return $this->option;
}
}

View File

@@ -0,0 +1,136 @@
<?php
/*
* Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com>
*
* 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 PhpOption;
use EmptyIterator;
/**
* @extends Option<mixed>
*/
final class None extends Option
{
/** @var None|null */
private static $instance;
/**
* @return None
*/
public static function create(): self
{
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function get()
{
throw new \RuntimeException('None has no value.');
}
public function getOrCall($callable)
{
return $callable();
}
public function getOrElse($default)
{
return $default;
}
public function getOrThrow(\Exception $ex)
{
throw $ex;
}
public function isEmpty(): bool
{
return true;
}
public function isDefined(): bool
{
return false;
}
public function orElse(Option $else)
{
return $else;
}
public function ifDefined($callable)
{
// Just do nothing in that case.
}
public function forAll($callable)
{
return $this;
}
public function map($callable)
{
return $this;
}
public function flatMap($callable)
{
return $this;
}
public function filter($callable)
{
return $this;
}
public function filterNot($callable)
{
return $this;
}
public function select($value)
{
return $this;
}
public function reject($value)
{
return $this;
}
public function getIterator(): EmptyIterator
{
return new EmptyIterator();
}
public function foldLeft($initialValue, $callable)
{
return $initialValue;
}
public function foldRight($initialValue, $callable)
{
return $initialValue;
}
private function __construct()
{
}
}

View File

@@ -0,0 +1,434 @@
<?php
/*
* Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com>
*
* 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 PhpOption;
use ArrayAccess;
use IteratorAggregate;
/**
* @template T
*
* @implements IteratorAggregate<T>
*/
abstract class Option implements IteratorAggregate
{
/**
* Creates an option given a return value.
*
* This is intended for consuming existing APIs and allows you to easily
* convert them to an option. By default, we treat ``null`` as the None
* case, and everything else as Some.
*
* @template S
*
* @param S $value The actual return value.
* @param S $noneValue The value which should be considered "None"; null by
* default.
*
* @return Option<S>
*/
public static function fromValue($value, $noneValue = null)
{
if ($value === $noneValue) {
return None::create();
}
return new Some($value);
}
/**
* Creates an option from an array's value.
*
* If the key does not exist in the array, the array is not actually an
* array, or the array's value at the given key is null, None is returned.
* Otherwise, Some is returned wrapping the value at the given key.
*
* @template S
*
* @param array<string|int,S>|ArrayAccess<string|int,S>|null $array A potential array or \ArrayAccess value.
* @param string|int|null $key The key to check.
*
* @return Option<S>
*/
public static function fromArraysValue($array, $key)
{
if ($key === null || !(is_array($array) || $array instanceof ArrayAccess) || !isset($array[$key])) {
return None::create();
}
return new Some($array[$key]);
}
/**
* Creates a lazy-option with the given callback.
*
* This is also a helper constructor for lazy-consuming existing APIs where
* the return value is not yet an option. By default, we treat ``null`` as
* None case, and everything else as Some.
*
* @template S
*
* @param callable $callback The callback to evaluate.
* @param array $arguments The arguments for the callback.
* @param S $noneValue The value which should be considered "None";
* null by default.
*
* @return LazyOption<S>
*/
public static function fromReturn($callback, array $arguments = [], $noneValue = null)
{
return new LazyOption(static function () use ($callback, $arguments, $noneValue) {
/** @var mixed */
$return = call_user_func_array($callback, $arguments);
if ($return === $noneValue) {
return None::create();
}
return new Some($return);
});
}
/**
* Option factory, which creates new option based on passed value.
*
* If value is already an option, it simply returns. If value is callable,
* LazyOption with passed callback created and returned. If Option
* returned from callback, it returns directly. On other case value passed
* to Option::fromValue() method.
*
* @template S
*
* @param Option<S>|callable|S $value
* @param S $noneValue Used when $value is mixed or
* callable, for None-check.
*
* @return Option<S>|LazyOption<S>
*/
public static function ensure($value, $noneValue = null)
{
if ($value instanceof self) {
return $value;
} elseif (is_callable($value)) {
return new LazyOption(static function () use ($value, $noneValue) {
/** @var mixed */
$return = $value();
if ($return instanceof self) {
return $return;
} else {
return self::fromValue($return, $noneValue);
}
});
} else {
return self::fromValue($value, $noneValue);
}
}
/**
* Lift a function so that it accepts Option as parameters.
*
* We return a new closure that wraps the original callback. If any of the
* parameters passed to the lifted function is empty, the function will
* return a value of None. Otherwise, we will pass all parameters to the
* original callback and return the value inside a new Option, unless an
* Option is returned from the function, in which case, we use that.
*
* @template S
*
* @param callable $callback
* @param mixed $noneValue
*
* @return callable
*/
public static function lift($callback, $noneValue = null)
{
return static function () use ($callback, $noneValue) {
/** @var array<int, mixed> */
$args = func_get_args();
$reduced_args = array_reduce(
$args,
/** @param bool $status */
static function ($status, self $o) {
return $o->isEmpty() ? true : $status;
},
false
);
// if at least one parameter is empty, return None
if ($reduced_args) {
return None::create();
}
$args = array_map(
/** @return T */
static function (self $o) {
// it is safe to do so because the fold above checked
// that all arguments are of type Some
/** @var T */
return $o->get();
},
$args
);
return self::ensure(call_user_func_array($callback, $args), $noneValue);
};
}
/**
* Returns the value if available, or throws an exception otherwise.
*
* @throws \RuntimeException If value is not available.
*
* @return T
*/
abstract public function get();
/**
* Returns the value if available, or the default value if not.
*
* @template S
*
* @param S $default
*
* @return T|S
*/
abstract public function getOrElse($default);
/**
* Returns the value if available, or the results of the callable.
*
* This is preferable over ``getOrElse`` if the computation of the default
* value is expensive.
*
* @template S
*
* @param callable():S $callable
*
* @return T|S
*/
abstract public function getOrCall($callable);
/**
* Returns the value if available, or throws the passed exception.
*
* @param \Exception $ex
*
* @return T
*/
abstract public function getOrThrow(\Exception $ex);
/**
* Returns true if no value is available, false otherwise.
*
* @return bool
*/
abstract public function isEmpty();
/**
* Returns true if a value is available, false otherwise.
*
* @return bool
*/
abstract public function isDefined();
/**
* Returns this option if non-empty, or the passed option otherwise.
*
* This can be used to try multiple alternatives, and is especially useful
* with lazy evaluating options:
*
* ```php
* $repo->findSomething()
* ->orElse(new LazyOption(array($repo, 'findSomethingElse')))
* ->orElse(new LazyOption(array($repo, 'createSomething')));
* ```
*
* @param Option<T> $else
*
* @return Option<T>
*/
abstract public function orElse(self $else);
/**
* This is similar to map() below except that the return value has no meaning;
* the passed callable is simply executed if the option is non-empty, and
* ignored if the option is empty.
*
* In all cases, the return value of the callable is discarded.
*
* ```php
* $comment->getMaybeFile()->ifDefined(function($file) {
* // Do something with $file here.
* });
* ```
*
* If you're looking for something like ``ifEmpty``, you can use ``getOrCall``
* and ``getOrElse`` in these cases.
*
* @deprecated Use forAll() instead.
*
* @param callable(T):mixed $callable
*
* @return void
*/
abstract public function ifDefined($callable);
/**
* This is similar to map() except that the return value of the callable has no meaning.
*
* The passed callable is simply executed if the option is non-empty, and ignored if the
* option is empty. This method is preferred for callables with side-effects, while map()
* is intended for callables without side-effects.
*
* @param callable(T):mixed $callable
*
* @return Option<T>
*/
abstract public function forAll($callable);
/**
* Applies the callable to the value of the option if it is non-empty,
* and returns the return value of the callable wrapped in Some().
*
* If the option is empty, then the callable is not applied.
*
* ```php
* (new Some("foo"))->map('strtoupper')->get(); // "FOO"
* ```
*
* @template S
*
* @param callable(T):S $callable
*
* @return Option<S>
*/
abstract public function map($callable);
/**
* Applies the callable to the value of the option if it is non-empty, and
* returns the return value of the callable directly.
*
* In contrast to ``map``, the return value of the callable is expected to
* be an Option itself; it is not automatically wrapped in Some().
*
* @template S
*
* @param callable(T):Option<S> $callable must return an Option
*
* @return Option<S>
*/
abstract public function flatMap($callable);
/**
* If the option is empty, it is returned immediately without applying the callable.
*
* If the option is non-empty, the callable is applied, and if it returns true,
* the option itself is returned; otherwise, None is returned.
*
* @param callable(T):bool $callable
*
* @return Option<T>
*/
abstract public function filter($callable);
/**
* If the option is empty, it is returned immediately without applying the callable.
*
* If the option is non-empty, the callable is applied, and if it returns false,
* the option itself is returned; otherwise, None is returned.
*
* @param callable(T):bool $callable
*
* @return Option<T>
*/
abstract public function filterNot($callable);
/**
* If the option is empty, it is returned immediately.
*
* If the option is non-empty, and its value does not equal the passed value
* (via a shallow comparison ===), then None is returned. Otherwise, the
* Option is returned.
*
* In other words, this will filter all but the passed value.
*
* @param T $value
*
* @return Option<T>
*/
abstract public function select($value);
/**
* If the option is empty, it is returned immediately.
*
* If the option is non-empty, and its value does equal the passed value (via
* a shallow comparison ===), then None is returned; otherwise, the Option is
* returned.
*
* In other words, this will let all values through except the passed value.
*
* @param T $value
*
* @return Option<T>
*/
abstract public function reject($value);
/**
* Binary operator for the initial value and the option's value.
*
* If empty, the initial value is returned. If non-empty, the callable
* receives the initial value and the option's value as arguments.
*
* ```php
*
* $some = new Some(5);
* $none = None::create();
* $result = $some->foldLeft(1, function($a, $b) { return $a + $b; }); // int(6)
* $result = $none->foldLeft(1, function($a, $b) { return $a + $b; }); // int(1)
*
* // This can be used instead of something like the following:
* $option = Option::fromValue($integerOrNull);
* $result = 1;
* if ( ! $option->isEmpty()) {
* $result += $option->get();
* }
* ```
*
* @template S
*
* @param S $initialValue
* @param callable(S, T):S $callable
*
* @return S
*/
abstract public function foldLeft($initialValue, $callable);
/**
* foldLeft() but with reversed arguments for the callable.
*
* @template S
*
* @param S $initialValue
* @param callable(T, S):S $callable
*
* @return S
*/
abstract public function foldRight($initialValue, $callable);
}

View File

@@ -0,0 +1,169 @@
<?php
/*
* Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com>
*
* 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 PhpOption;
use ArrayIterator;
/**
* @template T
*
* @extends Option<T>
*/
final class Some extends Option
{
/** @var T */
private $value;
/**
* @param T $value
*/
public function __construct($value)
{
$this->value = $value;
}
/**
* @template U
*
* @param U $value
*
* @return Some<U>
*/
public static function create($value): self
{
return new self($value);
}
public function isDefined(): bool
{
return true;
}
public function isEmpty(): bool
{
return false;
}
public function get()
{
return $this->value;
}
public function getOrElse($default)
{
return $this->value;
}
public function getOrCall($callable)
{
return $this->value;
}
public function getOrThrow(\Exception $ex)
{
return $this->value;
}
public function orElse(Option $else)
{
return $this;
}
public function ifDefined($callable)
{
$this->forAll($callable);
}
public function forAll($callable)
{
$callable($this->value);
return $this;
}
public function map($callable)
{
return new self($callable($this->value));
}
public function flatMap($callable)
{
/** @var mixed */
$rs = $callable($this->value);
if (!$rs instanceof Option) {
throw new \RuntimeException('Callables passed to flatMap() must return an Option. Maybe you should use map() instead?');
}
return $rs;
}
public function filter($callable)
{
if (true === $callable($this->value)) {
return $this;
}
return None::create();
}
public function filterNot($callable)
{
if (false === $callable($this->value)) {
return $this;
}
return None::create();
}
public function select($value)
{
if ($this->value === $value) {
return $this;
}
return None::create();
}
public function reject($value)
{
if ($this->value === $value) {
return None::create();
}
return $this;
}
/**
* @return ArrayIterator<int, T>
*/
public function getIterator(): ArrayIterator
{
return new ArrayIterator([$this->value]);
}
public function foldLeft($initialValue, $callable)
{
return $callable($initialValue, $this->value);
}
public function foldRight($initialValue, $callable)
{
return $callable($this->value, $initialValue);
}
}

232
vendor/symfony/polyfill-ctype/Ctype.php vendored Normal file
View File

@@ -0,0 +1,232 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Polyfill\Ctype;
/**
* Ctype implementation through regex.
*
* @internal
*
* @author Gert de Pagter <BackEndTea@gmail.com>
*/
final class Ctype
{
/**
* Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.
*
* @see https://php.net/ctype-alnum
*
* @param mixed $text
*
* @return bool
*/
public static function ctype_alnum($text)
{
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z0-9]/', $text);
}
/**
* Returns TRUE if every character in text is a letter, FALSE otherwise.
*
* @see https://php.net/ctype-alpha
*
* @param mixed $text
*
* @return bool
*/
public static function ctype_alpha($text)
{
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z]/', $text);
}
/**
* Returns TRUE if every character in text is a control character from the current locale, FALSE otherwise.
*
* @see https://php.net/ctype-cntrl
*
* @param mixed $text
*
* @return bool
*/
public static function ctype_cntrl($text)
{
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
return \is_string($text) && '' !== $text && !preg_match('/[^\x00-\x1f\x7f]/', $text);
}
/**
* Returns TRUE if every character in the string text is a decimal digit, FALSE otherwise.
*
* @see https://php.net/ctype-digit
*
* @param mixed $text
*
* @return bool
*/
public static function ctype_digit($text)
{
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
return \is_string($text) && '' !== $text && !preg_match('/[^0-9]/', $text);
}
/**
* Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise.
*
* @see https://php.net/ctype-graph
*
* @param mixed $text
*
* @return bool
*/
public static function ctype_graph($text)
{
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
return \is_string($text) && '' !== $text && !preg_match('/[^!-~]/', $text);
}
/**
* Returns TRUE if every character in text is a lowercase letter.
*
* @see https://php.net/ctype-lower
*
* @param mixed $text
*
* @return bool
*/
public static function ctype_lower($text)
{
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
return \is_string($text) && '' !== $text && !preg_match('/[^a-z]/', $text);
}
/**
* Returns TRUE if every character in text will actually create output (including blanks). Returns FALSE if text contains control characters or characters that do not have any output or control function at all.
*
* @see https://php.net/ctype-print
*
* @param mixed $text
*
* @return bool
*/
public static function ctype_print($text)
{
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
return \is_string($text) && '' !== $text && !preg_match('/[^ -~]/', $text);
}
/**
* Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise.
*
* @see https://php.net/ctype-punct
*
* @param mixed $text
*
* @return bool
*/
public static function ctype_punct($text)
{
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
return \is_string($text) && '' !== $text && !preg_match('/[^!-\/\:-@\[-`\{-~]/', $text);
}
/**
* Returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters.
*
* @see https://php.net/ctype-space
*
* @param mixed $text
*
* @return bool
*/
public static function ctype_space($text)
{
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
return \is_string($text) && '' !== $text && !preg_match('/[^\s]/', $text);
}
/**
* Returns TRUE if every character in text is an uppercase letter.
*
* @see https://php.net/ctype-upper
*
* @param mixed $text
*
* @return bool
*/
public static function ctype_upper($text)
{
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
return \is_string($text) && '' !== $text && !preg_match('/[^A-Z]/', $text);
}
/**
* Returns TRUE if every character in text is a hexadecimal 'digit', that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise.
*
* @see https://php.net/ctype-xdigit
*
* @param mixed $text
*
* @return bool
*/
public static function ctype_xdigit($text)
{
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
return \is_string($text) && '' !== $text && !preg_match('/[^A-Fa-f0-9]/', $text);
}
/**
* Converts integers to their char versions according to normal ctype behaviour, if needed.
*
* If an integer between -128 and 255 inclusive is provided,
* it is interpreted as the ASCII value of a single character
* (negative values have 256 added in order to allow characters in the Extended ASCII range).
* Any other integer is interpreted as a string containing the decimal digits of the integer.
*
* @param mixed $int
* @param string $function
*
* @return mixed
*/
private static function convert_int_to_char_for_ctype($int, $function)
{
if (!\is_int($int)) {
return $int;
}
if ($int < -128 || $int > 255) {
return (string) $int;
}
if (\PHP_VERSION_ID >= 80100) {
@trigger_error($function.'(): Argument of type int will be interpreted as string in the future', \E_USER_DEPRECATED);
}
if ($int < 0) {
$int += 256;
}
return \chr($int);
}
}

19
vendor/symfony/polyfill-ctype/LICENSE vendored Normal file
View File

@@ -0,0 +1,19 @@
Copyright (c) 2018-present Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

12
vendor/symfony/polyfill-ctype/README.md vendored Normal file
View File

@@ -0,0 +1,12 @@
Symfony Polyfill / Ctype
========================
This component provides `ctype_*` functions to users who run php versions without the ctype extension.
More information can be found in the
[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md).
License
=======
This library is released under the [MIT license](LICENSE).

View File

@@ -0,0 +1,50 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Symfony\Polyfill\Ctype as p;
if (\PHP_VERSION_ID >= 80000) {
return require __DIR__.'/bootstrap80.php';
}
if (!function_exists('ctype_alnum')) {
function ctype_alnum($text) { return p\Ctype::ctype_alnum($text); }
}
if (!function_exists('ctype_alpha')) {
function ctype_alpha($text) { return p\Ctype::ctype_alpha($text); }
}
if (!function_exists('ctype_cntrl')) {
function ctype_cntrl($text) { return p\Ctype::ctype_cntrl($text); }
}
if (!function_exists('ctype_digit')) {
function ctype_digit($text) { return p\Ctype::ctype_digit($text); }
}
if (!function_exists('ctype_graph')) {
function ctype_graph($text) { return p\Ctype::ctype_graph($text); }
}
if (!function_exists('ctype_lower')) {
function ctype_lower($text) { return p\Ctype::ctype_lower($text); }
}
if (!function_exists('ctype_print')) {
function ctype_print($text) { return p\Ctype::ctype_print($text); }
}
if (!function_exists('ctype_punct')) {
function ctype_punct($text) { return p\Ctype::ctype_punct($text); }
}
if (!function_exists('ctype_space')) {
function ctype_space($text) { return p\Ctype::ctype_space($text); }
}
if (!function_exists('ctype_upper')) {
function ctype_upper($text) { return p\Ctype::ctype_upper($text); }
}
if (!function_exists('ctype_xdigit')) {
function ctype_xdigit($text) { return p\Ctype::ctype_xdigit($text); }
}

View File

@@ -0,0 +1,46 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Symfony\Polyfill\Ctype as p;
if (!function_exists('ctype_alnum')) {
function ctype_alnum(mixed $text): bool { return p\Ctype::ctype_alnum($text); }
}
if (!function_exists('ctype_alpha')) {
function ctype_alpha(mixed $text): bool { return p\Ctype::ctype_alpha($text); }
}
if (!function_exists('ctype_cntrl')) {
function ctype_cntrl(mixed $text): bool { return p\Ctype::ctype_cntrl($text); }
}
if (!function_exists('ctype_digit')) {
function ctype_digit(mixed $text): bool { return p\Ctype::ctype_digit($text); }
}
if (!function_exists('ctype_graph')) {
function ctype_graph(mixed $text): bool { return p\Ctype::ctype_graph($text); }
}
if (!function_exists('ctype_lower')) {
function ctype_lower(mixed $text): bool { return p\Ctype::ctype_lower($text); }
}
if (!function_exists('ctype_print')) {
function ctype_print(mixed $text): bool { return p\Ctype::ctype_print($text); }
}
if (!function_exists('ctype_punct')) {
function ctype_punct(mixed $text): bool { return p\Ctype::ctype_punct($text); }
}
if (!function_exists('ctype_space')) {
function ctype_space(mixed $text): bool { return p\Ctype::ctype_space($text); }
}
if (!function_exists('ctype_upper')) {
function ctype_upper(mixed $text): bool { return p\Ctype::ctype_upper($text); }
}
if (!function_exists('ctype_xdigit')) {
function ctype_xdigit(mixed $text): bool { return p\Ctype::ctype_xdigit($text); }
}

View File

@@ -0,0 +1,38 @@
{
"name": "symfony/polyfill-ctype",
"type": "library",
"description": "Symfony polyfill for ctype functions",
"keywords": ["polyfill", "compatibility", "portable", "ctype"],
"homepage": "https://symfony.com",
"license": "MIT",
"authors": [
{
"name": "Gert de Pagter",
"email": "BackEndTea@gmail.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"require": {
"php": ">=7.2"
},
"provide": {
"ext-ctype": "*"
},
"autoload": {
"psr-4": { "Symfony\\Polyfill\\Ctype\\": "" },
"files": [ "bootstrap.php" ]
},
"suggest": {
"ext-ctype": "For best performance"
},
"minimum-stability": "dev",
"extra": {
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
}
}
}

View File

@@ -0,0 +1,19 @@
Copyright (c) 2015-present Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,13 @@
Symfony Polyfill / Mbstring
===========================
This component provides a partial, native PHP implementation for the
[Mbstring](https://php.net/mbstring) extension.
More information can be found in the
[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md).
License
=======
This library is released under the [MIT license](LICENSE).

View File

@@ -0,0 +1,119 @@
<?php
return [
'İ' => 'i̇',
'µ' => 'μ',
'ſ' => 's',
'ͅ' => 'ι',
'ς' => 'σ',
'ϐ' => 'β',
'ϑ' => 'θ',
'ϕ' => 'φ',
'ϖ' => 'π',
'ϰ' => 'κ',
'ϱ' => 'ρ',
'ϵ' => 'ε',
'ẛ' => 'ṡ',
'' => 'ι',
'ß' => 'ss',
'ʼn' => 'ʼn',
'ǰ' => 'ǰ',
'ΐ' => 'ΐ',
'ΰ' => 'ΰ',
'և' => 'եւ',
'ẖ' => 'ẖ',
'ẗ' => 'ẗ',
'ẘ' => 'ẘ',
'ẙ' => 'ẙ',
'ẚ' => 'aʾ',
'ẞ' => 'ss',
'ὐ' => 'ὐ',
'ὒ' => 'ὒ',
'ὔ' => 'ὔ',
'ὖ' => 'ὖ',
'ᾀ' => 'ἀι',
'ᾁ' => 'ἁι',
'ᾂ' => 'ἂι',
'ᾃ' => 'ἃι',
'ᾄ' => 'ἄι',
'ᾅ' => 'ἅι',
'ᾆ' => 'ἆι',
'ᾇ' => 'ἇι',
'ᾈ' => 'ἀι',
'ᾉ' => 'ἁι',
'ᾊ' => 'ἂι',
'ᾋ' => 'ἃι',
'ᾌ' => 'ἄι',
'ᾍ' => 'ἅι',
'ᾎ' => 'ἆι',
'ᾏ' => 'ἇι',
'ᾐ' => 'ἠι',
'ᾑ' => 'ἡι',
'ᾒ' => 'ἢι',
'ᾓ' => 'ἣι',
'ᾔ' => 'ἤι',
'ᾕ' => 'ἥι',
'ᾖ' => 'ἦι',
'ᾗ' => 'ἧι',
'ᾘ' => 'ἠι',
'ᾙ' => 'ἡι',
'ᾚ' => 'ἢι',
'ᾛ' => 'ἣι',
'ᾜ' => 'ἤι',
'ᾝ' => 'ἥι',
'ᾞ' => 'ἦι',
'ᾟ' => 'ἧι',
'ᾠ' => 'ὠι',
'ᾡ' => 'ὡι',
'ᾢ' => 'ὢι',
'ᾣ' => 'ὣι',
'ᾤ' => 'ὤι',
'ᾥ' => 'ὥι',
'ᾦ' => 'ὦι',
'ᾧ' => 'ὧι',
'ᾨ' => 'ὠι',
'ᾩ' => 'ὡι',
'ᾪ' => 'ὢι',
'ᾫ' => 'ὣι',
'ᾬ' => 'ὤι',
'ᾭ' => 'ὥι',
'ᾮ' => 'ὦι',
'ᾯ' => 'ὧι',
'ᾲ' => 'ὰι',
'ᾳ' => 'αι',
'ᾴ' => 'άι',
'ᾶ' => 'ᾶ',
'ᾷ' => 'ᾶι',
'ᾼ' => 'αι',
'ῂ' => 'ὴι',
'ῃ' => 'ηι',
'ῄ' => 'ήι',
'ῆ' => 'ῆ',
'ῇ' => 'ῆι',
'ῌ' => 'ηι',
'ῒ' => 'ῒ',
'ῖ' => 'ῖ',
'ῗ' => 'ῗ',
'ῢ' => 'ῢ',
'ῤ' => 'ῤ',
'ῦ' => 'ῦ',
'ῧ' => 'ῧ',
'ῲ' => 'ὼι',
'ῳ' => 'ωι',
'ῴ' => 'ώι',
'ῶ' => 'ῶ',
'ῷ' => 'ῶι',
'ῼ' => 'ωι',
'ff' => 'ff',
'fi' => 'fi',
'fl' => 'fl',
'ffi' => 'ffi',
'ffl' => 'ffl',
'ſt' => 'st',
'st' => 'st',
'ﬓ' => 'մն',
'ﬔ' => 'մե',
'ﬕ' => 'մի',
'ﬖ' => 'վն',
'ﬗ' => 'մխ',
];

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,172 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Symfony\Polyfill\Mbstring as p;
if (\PHP_VERSION_ID >= 80000) {
return require __DIR__.'/bootstrap80.php';
}
if (!function_exists('mb_convert_encoding')) {
function mb_convert_encoding($string, $to_encoding, $from_encoding = null) { return p\Mbstring::mb_convert_encoding($string, $to_encoding, $from_encoding); }
}
if (!function_exists('mb_decode_mimeheader')) {
function mb_decode_mimeheader($string) { return p\Mbstring::mb_decode_mimeheader($string); }
}
if (!function_exists('mb_encode_mimeheader')) {
function mb_encode_mimeheader($string, $charset = null, $transfer_encoding = null, $newline = "\r\n", $indent = 0) { return p\Mbstring::mb_encode_mimeheader($string, $charset, $transfer_encoding, $newline, $indent); }
}
if (!function_exists('mb_decode_numericentity')) {
function mb_decode_numericentity($string, $map, $encoding = null) { return p\Mbstring::mb_decode_numericentity($string, $map, $encoding); }
}
if (!function_exists('mb_encode_numericentity')) {
function mb_encode_numericentity($string, $map, $encoding = null, $hex = false) { return p\Mbstring::mb_encode_numericentity($string, $map, $encoding, $hex); }
}
if (!function_exists('mb_convert_case')) {
function mb_convert_case($string, $mode, $encoding = null) { return p\Mbstring::mb_convert_case($string, $mode, $encoding); }
}
if (!function_exists('mb_internal_encoding')) {
function mb_internal_encoding($encoding = null) { return p\Mbstring::mb_internal_encoding($encoding); }
}
if (!function_exists('mb_language')) {
function mb_language($language = null) { return p\Mbstring::mb_language($language); }
}
if (!function_exists('mb_list_encodings')) {
function mb_list_encodings() { return p\Mbstring::mb_list_encodings(); }
}
if (!function_exists('mb_encoding_aliases')) {
function mb_encoding_aliases($encoding) { return p\Mbstring::mb_encoding_aliases($encoding); }
}
if (!function_exists('mb_check_encoding')) {
function mb_check_encoding($value = null, $encoding = null) { return p\Mbstring::mb_check_encoding($value, $encoding); }
}
if (!function_exists('mb_detect_encoding')) {
function mb_detect_encoding($string, $encodings = null, $strict = false) { return p\Mbstring::mb_detect_encoding($string, $encodings, $strict); }
}
if (!function_exists('mb_detect_order')) {
function mb_detect_order($encoding = null) { return p\Mbstring::mb_detect_order($encoding); }
}
if (!function_exists('mb_parse_str')) {
function mb_parse_str($string, &$result = []) { parse_str($string, $result); return (bool) $result; }
}
if (!function_exists('mb_strlen')) {
function mb_strlen($string, $encoding = null) { return p\Mbstring::mb_strlen($string, $encoding); }
}
if (!function_exists('mb_strpos')) {
function mb_strpos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strpos($haystack, $needle, $offset, $encoding); }
}
if (!function_exists('mb_strtolower')) {
function mb_strtolower($string, $encoding = null) { return p\Mbstring::mb_strtolower($string, $encoding); }
}
if (!function_exists('mb_strtoupper')) {
function mb_strtoupper($string, $encoding = null) { return p\Mbstring::mb_strtoupper($string, $encoding); }
}
if (!function_exists('mb_substitute_character')) {
function mb_substitute_character($substitute_character = null) { return p\Mbstring::mb_substitute_character($substitute_character); }
}
if (!function_exists('mb_substr')) {
function mb_substr($string, $start, $length = 2147483647, $encoding = null) { return p\Mbstring::mb_substr($string, $start, $length, $encoding); }
}
if (!function_exists('mb_stripos')) {
function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_stripos($haystack, $needle, $offset, $encoding); }
}
if (!function_exists('mb_stristr')) {
function mb_stristr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_stristr($haystack, $needle, $before_needle, $encoding); }
}
if (!function_exists('mb_strrchr')) {
function mb_strrchr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strrchr($haystack, $needle, $before_needle, $encoding); }
}
if (!function_exists('mb_strrichr')) {
function mb_strrichr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strrichr($haystack, $needle, $before_needle, $encoding); }
}
if (!function_exists('mb_strripos')) {
function mb_strripos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strripos($haystack, $needle, $offset, $encoding); }
}
if (!function_exists('mb_strrpos')) {
function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strrpos($haystack, $needle, $offset, $encoding); }
}
if (!function_exists('mb_strstr')) {
function mb_strstr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strstr($haystack, $needle, $before_needle, $encoding); }
}
if (!function_exists('mb_get_info')) {
function mb_get_info($type = 'all') { return p\Mbstring::mb_get_info($type); }
}
if (!function_exists('mb_http_output')) {
function mb_http_output($encoding = null) { return p\Mbstring::mb_http_output($encoding); }
}
if (!function_exists('mb_strwidth')) {
function mb_strwidth($string, $encoding = null) { return p\Mbstring::mb_strwidth($string, $encoding); }
}
if (!function_exists('mb_substr_count')) {
function mb_substr_count($haystack, $needle, $encoding = null) { return p\Mbstring::mb_substr_count($haystack, $needle, $encoding); }
}
if (!function_exists('mb_output_handler')) {
function mb_output_handler($string, $status) { return p\Mbstring::mb_output_handler($string, $status); }
}
if (!function_exists('mb_http_input')) {
function mb_http_input($type = null) { return p\Mbstring::mb_http_input($type); }
}
if (!function_exists('mb_convert_variables')) {
function mb_convert_variables($to_encoding, $from_encoding, &...$vars) { return p\Mbstring::mb_convert_variables($to_encoding, $from_encoding, ...$vars); }
}
if (!function_exists('mb_ord')) {
function mb_ord($string, $encoding = null) { return p\Mbstring::mb_ord($string, $encoding); }
}
if (!function_exists('mb_chr')) {
function mb_chr($codepoint, $encoding = null) { return p\Mbstring::mb_chr($codepoint, $encoding); }
}
if (!function_exists('mb_scrub')) {
function mb_scrub($string, $encoding = null) { $encoding = null === $encoding ? mb_internal_encoding() : $encoding; return mb_convert_encoding($string, $encoding, $encoding); }
}
if (!function_exists('mb_str_split')) {
function mb_str_split($string, $length = 1, $encoding = null) { return p\Mbstring::mb_str_split($string, $length, $encoding); }
}
if (!function_exists('mb_str_pad')) {
function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = STR_PAD_RIGHT, ?string $encoding = null): string { return p\Mbstring::mb_str_pad($string, $length, $pad_string, $pad_type, $encoding); }
}
if (!function_exists('mb_ucfirst')) {
function mb_ucfirst(string $string, ?string $encoding = null): string { return p\Mbstring::mb_ucfirst($string, $encoding); }
}
if (!function_exists('mb_lcfirst')) {
function mb_lcfirst(string $string, ?string $encoding = null): string { return p\Mbstring::mb_lcfirst($string, $encoding); }
}
if (!function_exists('mb_trim')) {
function mb_trim(string $string, ?string $characters = null, ?string $encoding = null): string { return p\Mbstring::mb_trim($string, $characters, $encoding); }
}
if (!function_exists('mb_ltrim')) {
function mb_ltrim(string $string, ?string $characters = null, ?string $encoding = null): string { return p\Mbstring::mb_ltrim($string, $characters, $encoding); }
}
if (!function_exists('mb_rtrim')) {
function mb_rtrim(string $string, ?string $characters = null, ?string $encoding = null): string { return p\Mbstring::mb_rtrim($string, $characters, $encoding); }
}
if (extension_loaded('mbstring')) {
return;
}
if (!defined('MB_CASE_UPPER')) {
define('MB_CASE_UPPER', 0);
}
if (!defined('MB_CASE_LOWER')) {
define('MB_CASE_LOWER', 1);
}
if (!defined('MB_CASE_TITLE')) {
define('MB_CASE_TITLE', 2);
}

View File

@@ -0,0 +1,167 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Symfony\Polyfill\Mbstring as p;
if (!function_exists('mb_convert_encoding')) {
function mb_convert_encoding(array|string|null $string, ?string $to_encoding, array|string|null $from_encoding = null): array|string|false { return p\Mbstring::mb_convert_encoding($string ?? '', (string) $to_encoding, $from_encoding); }
}
if (!function_exists('mb_decode_mimeheader')) {
function mb_decode_mimeheader(?string $string): string { return p\Mbstring::mb_decode_mimeheader((string) $string); }
}
if (!function_exists('mb_encode_mimeheader')) {
function mb_encode_mimeheader(?string $string, ?string $charset = null, ?string $transfer_encoding = null, ?string $newline = "\r\n", ?int $indent = 0): string { return p\Mbstring::mb_encode_mimeheader((string) $string, $charset, $transfer_encoding, (string) $newline, (int) $indent); }
}
if (!function_exists('mb_decode_numericentity')) {
function mb_decode_numericentity(?string $string, array $map, ?string $encoding = null): string { return p\Mbstring::mb_decode_numericentity((string) $string, $map, $encoding); }
}
if (!function_exists('mb_encode_numericentity')) {
function mb_encode_numericentity(?string $string, array $map, ?string $encoding = null, ?bool $hex = false): string { return p\Mbstring::mb_encode_numericentity((string) $string, $map, $encoding, (bool) $hex); }
}
if (!function_exists('mb_convert_case')) {
function mb_convert_case(?string $string, ?int $mode, ?string $encoding = null): string { return p\Mbstring::mb_convert_case((string) $string, (int) $mode, $encoding); }
}
if (!function_exists('mb_internal_encoding')) {
function mb_internal_encoding(?string $encoding = null): string|bool { return p\Mbstring::mb_internal_encoding($encoding); }
}
if (!function_exists('mb_language')) {
function mb_language(?string $language = null): string|bool { return p\Mbstring::mb_language($language); }
}
if (!function_exists('mb_list_encodings')) {
function mb_list_encodings(): array { return p\Mbstring::mb_list_encodings(); }
}
if (!function_exists('mb_encoding_aliases')) {
function mb_encoding_aliases(?string $encoding): array { return p\Mbstring::mb_encoding_aliases((string) $encoding); }
}
if (!function_exists('mb_check_encoding')) {
function mb_check_encoding(array|string|null $value = null, ?string $encoding = null): bool { return p\Mbstring::mb_check_encoding($value, $encoding); }
}
if (!function_exists('mb_detect_encoding')) {
function mb_detect_encoding(?string $string, array|string|null $encodings = null, ?bool $strict = false): string|false { return p\Mbstring::mb_detect_encoding((string) $string, $encodings, (bool) $strict); }
}
if (!function_exists('mb_detect_order')) {
function mb_detect_order(array|string|null $encoding = null): array|bool { return p\Mbstring::mb_detect_order($encoding); }
}
if (!function_exists('mb_parse_str')) {
function mb_parse_str(?string $string, &$result = []): bool { parse_str((string) $string, $result); return (bool) $result; }
}
if (!function_exists('mb_strlen')) {
function mb_strlen(?string $string, ?string $encoding = null): int { return p\Mbstring::mb_strlen((string) $string, $encoding); }
}
if (!function_exists('mb_strpos')) {
function mb_strpos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strpos((string) $haystack, (string) $needle, (int) $offset, $encoding); }
}
if (!function_exists('mb_strtolower')) {
function mb_strtolower(?string $string, ?string $encoding = null): string { return p\Mbstring::mb_strtolower((string) $string, $encoding); }
}
if (!function_exists('mb_strtoupper')) {
function mb_strtoupper(?string $string, ?string $encoding = null): string { return p\Mbstring::mb_strtoupper((string) $string, $encoding); }
}
if (!function_exists('mb_substitute_character')) {
function mb_substitute_character(string|int|null $substitute_character = null): string|int|bool { return p\Mbstring::mb_substitute_character($substitute_character); }
}
if (!function_exists('mb_substr')) {
function mb_substr(?string $string, ?int $start, ?int $length = null, ?string $encoding = null): string { return p\Mbstring::mb_substr((string) $string, (int) $start, $length, $encoding); }
}
if (!function_exists('mb_stripos')) {
function mb_stripos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_stripos((string) $haystack, (string) $needle, (int) $offset, $encoding); }
}
if (!function_exists('mb_stristr')) {
function mb_stristr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_stristr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); }
}
if (!function_exists('mb_strrchr')) {
function mb_strrchr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strrchr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); }
}
if (!function_exists('mb_strrichr')) {
function mb_strrichr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strrichr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); }
}
if (!function_exists('mb_strripos')) {
function mb_strripos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strripos((string) $haystack, (string) $needle, (int) $offset, $encoding); }
}
if (!function_exists('mb_strrpos')) {
function mb_strrpos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strrpos((string) $haystack, (string) $needle, (int) $offset, $encoding); }
}
if (!function_exists('mb_strstr')) {
function mb_strstr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strstr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); }
}
if (!function_exists('mb_get_info')) {
function mb_get_info(?string $type = 'all'): array|string|int|false|null { return p\Mbstring::mb_get_info((string) $type); }
}
if (!function_exists('mb_http_output')) {
function mb_http_output(?string $encoding = null): string|bool { return p\Mbstring::mb_http_output($encoding); }
}
if (!function_exists('mb_strwidth')) {
function mb_strwidth(?string $string, ?string $encoding = null): int { return p\Mbstring::mb_strwidth((string) $string, $encoding); }
}
if (!function_exists('mb_substr_count')) {
function mb_substr_count(?string $haystack, ?string $needle, ?string $encoding = null): int { return p\Mbstring::mb_substr_count((string) $haystack, (string) $needle, $encoding); }
}
if (!function_exists('mb_output_handler')) {
function mb_output_handler(?string $string, ?int $status): string { return p\Mbstring::mb_output_handler((string) $string, (int) $status); }
}
if (!function_exists('mb_http_input')) {
function mb_http_input(?string $type = null): array|string|false { return p\Mbstring::mb_http_input($type); }
}
if (!function_exists('mb_convert_variables')) {
function mb_convert_variables(?string $to_encoding, array|string|null $from_encoding, mixed &$var, mixed &...$vars): string|false { return p\Mbstring::mb_convert_variables((string) $to_encoding, $from_encoding ?? '', $var, ...$vars); }
}
if (!function_exists('mb_ord')) {
function mb_ord(?string $string, ?string $encoding = null): int|false { return p\Mbstring::mb_ord((string) $string, $encoding); }
}
if (!function_exists('mb_chr')) {
function mb_chr(?int $codepoint, ?string $encoding = null): string|false { return p\Mbstring::mb_chr((int) $codepoint, $encoding); }
}
if (!function_exists('mb_scrub')) {
function mb_scrub(?string $string, ?string $encoding = null): string { $encoding ??= mb_internal_encoding(); return mb_convert_encoding((string) $string, $encoding, $encoding); }
}
if (!function_exists('mb_str_split')) {
function mb_str_split(?string $string, ?int $length = 1, ?string $encoding = null): array { return p\Mbstring::mb_str_split((string) $string, (int) $length, $encoding); }
}
if (!function_exists('mb_str_pad')) {
function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = STR_PAD_RIGHT, ?string $encoding = null): string { return p\Mbstring::mb_str_pad($string, $length, $pad_string, $pad_type, $encoding); }
}
if (!function_exists('mb_ucfirst')) {
function mb_ucfirst(string $string, ?string $encoding = null): string { return p\Mbstring::mb_ucfirst($string, $encoding); }
}
if (!function_exists('mb_lcfirst')) {
function mb_lcfirst(string $string, ?string $encoding = null): string { return p\Mbstring::mb_lcfirst($string, $encoding); }
}
if (!function_exists('mb_trim')) {
function mb_trim(string $string, ?string $characters = null, ?string $encoding = null): string { return p\Mbstring::mb_trim($string, $characters, $encoding); }
}
if (!function_exists('mb_ltrim')) {
function mb_ltrim(string $string, ?string $characters = null, ?string $encoding = null): string { return p\Mbstring::mb_ltrim($string, $characters, $encoding); }
}
if (!function_exists('mb_rtrim')) {
function mb_rtrim(string $string, ?string $characters = null, ?string $encoding = null): string { return p\Mbstring::mb_rtrim($string, $characters, $encoding); }
}
if (extension_loaded('mbstring')) {
return;
}
if (!defined('MB_CASE_UPPER')) {
define('MB_CASE_UPPER', 0);
}
if (!defined('MB_CASE_LOWER')) {
define('MB_CASE_LOWER', 1);
}
if (!defined('MB_CASE_TITLE')) {
define('MB_CASE_TITLE', 2);
}

View File

@@ -0,0 +1,39 @@
{
"name": "symfony/polyfill-mbstring",
"type": "library",
"description": "Symfony polyfill for the Mbstring extension",
"keywords": ["polyfill", "shim", "compatibility", "portable", "mbstring"],
"homepage": "https://symfony.com",
"license": "MIT",
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"require": {
"php": ">=7.2",
"ext-iconv": "*"
},
"provide": {
"ext-mbstring": "*"
},
"autoload": {
"psr-4": { "Symfony\\Polyfill\\Mbstring\\": "" },
"files": [ "bootstrap.php" ]
},
"suggest": {
"ext-mbstring": "For best performance"
},
"minimum-stability": "dev",
"extra": {
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
}
}
}

19
vendor/symfony/polyfill-php80/LICENSE vendored Normal file
View File

@@ -0,0 +1,19 @@
Copyright (c) 2020-present Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

115
vendor/symfony/polyfill-php80/Php80.php vendored Normal file
View File

@@ -0,0 +1,115 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Polyfill\Php80;
/**
* @author Ion Bazan <ion.bazan@gmail.com>
* @author Nico Oelgart <nicoswd@gmail.com>
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
final class Php80
{
public static function fdiv(float $dividend, float $divisor): float
{
return @($dividend / $divisor);
}
public static function get_debug_type($value): string
{
switch (true) {
case null === $value: return 'null';
case \is_bool($value): return 'bool';
case \is_string($value): return 'string';
case \is_array($value): return 'array';
case \is_int($value): return 'int';
case \is_float($value): return 'float';
case \is_object($value): break;
case $value instanceof \__PHP_Incomplete_Class: return '__PHP_Incomplete_Class';
default:
if (null === $type = @get_resource_type($value)) {
return 'unknown';
}
if ('Unknown' === $type) {
$type = 'closed';
}
return "resource ($type)";
}
$class = \get_class($value);
if (false === strpos($class, '@')) {
return $class;
}
return (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous';
}
public static function get_resource_id($res): int
{
if (!\is_resource($res) && null === @get_resource_type($res)) {
throw new \TypeError(sprintf('Argument 1 passed to get_resource_id() must be of the type resource, %s given', get_debug_type($res)));
}
return (int) $res;
}
public static function preg_last_error_msg(): string
{
switch (preg_last_error()) {
case \PREG_INTERNAL_ERROR:
return 'Internal error';
case \PREG_BAD_UTF8_ERROR:
return 'Malformed UTF-8 characters, possibly incorrectly encoded';
case \PREG_BAD_UTF8_OFFSET_ERROR:
return 'The offset did not correspond to the beginning of a valid UTF-8 code point';
case \PREG_BACKTRACK_LIMIT_ERROR:
return 'Backtrack limit exhausted';
case \PREG_RECURSION_LIMIT_ERROR:
return 'Recursion limit exhausted';
case \PREG_JIT_STACKLIMIT_ERROR:
return 'JIT stack limit exhausted';
case \PREG_NO_ERROR:
return 'No error';
default:
return 'Unknown error';
}
}
public static function str_contains(string $haystack, string $needle): bool
{
return '' === $needle || false !== strpos($haystack, $needle);
}
public static function str_starts_with(string $haystack, string $needle): bool
{
return 0 === strncmp($haystack, $needle, \strlen($needle));
}
public static function str_ends_with(string $haystack, string $needle): bool
{
if ('' === $needle || $needle === $haystack) {
return true;
}
if ('' === $haystack) {
return false;
}
$needleLength = \strlen($needle);
return $needleLength <= \strlen($haystack) && 0 === substr_compare($haystack, $needle, -$needleLength);
}
}

View File

@@ -0,0 +1,106 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Polyfill\Php80;
/**
* @author Fedonyuk Anton <info@ensostudio.ru>
*
* @internal
*/
class PhpToken implements \Stringable
{
/**
* @var int
*/
public $id;
/**
* @var string
*/
public $text;
/**
* @var -1|positive-int
*/
public $line;
/**
* @var int
*/
public $pos;
/**
* @param -1|positive-int $line
*/
public function __construct(int $id, string $text, int $line = -1, int $position = -1)
{
$this->id = $id;
$this->text = $text;
$this->line = $line;
$this->pos = $position;
}
public function getTokenName(): ?string
{
if ('UNKNOWN' === $name = token_name($this->id)) {
$name = \strlen($this->text) > 1 || \ord($this->text) < 32 ? null : $this->text;
}
return $name;
}
/**
* @param int|string|array $kind
*/
public function is($kind): bool
{
foreach ((array) $kind as $value) {
if (\in_array($value, [$this->id, $this->text], true)) {
return true;
}
}
return false;
}
public function isIgnorable(): bool
{
return \in_array($this->id, [\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT, \T_OPEN_TAG], true);
}
public function __toString(): string
{
return (string) $this->text;
}
/**
* @return list<static>
*/
public static function tokenize(string $code, int $flags = 0): array
{
$line = 1;
$position = 0;
$tokens = token_get_all($code, $flags);
foreach ($tokens as $index => $token) {
if (\is_string($token)) {
$id = \ord($token);
$text = $token;
} else {
[$id, $text, $line] = $token;
}
$tokens[$index] = new static($id, $text, $line, $position);
$position += \strlen($text);
}
return $tokens;
}
}

25
vendor/symfony/polyfill-php80/README.md vendored Normal file
View File

@@ -0,0 +1,25 @@
Symfony Polyfill / Php80
========================
This component provides features added to PHP 8.0 core:
- [`Stringable`](https://php.net/stringable) interface
- [`fdiv`](https://php.net/fdiv)
- [`ValueError`](https://php.net/valueerror) class
- [`UnhandledMatchError`](https://php.net/unhandledmatcherror) class
- `FILTER_VALIDATE_BOOL` constant
- [`get_debug_type`](https://php.net/get_debug_type)
- [`PhpToken`](https://php.net/phptoken) class
- [`preg_last_error_msg`](https://php.net/preg_last_error_msg)
- [`str_contains`](https://php.net/str_contains)
- [`str_starts_with`](https://php.net/str_starts_with)
- [`str_ends_with`](https://php.net/str_ends_with)
- [`get_resource_id`](https://php.net/get_resource_id)
More information can be found in the
[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md).
License
=======
This library is released under the [MIT license](LICENSE).

View File

@@ -0,0 +1,31 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#[Attribute(Attribute::TARGET_CLASS)]
final class Attribute
{
public const TARGET_CLASS = 1;
public const TARGET_FUNCTION = 2;
public const TARGET_METHOD = 4;
public const TARGET_PROPERTY = 8;
public const TARGET_CLASS_CONSTANT = 16;
public const TARGET_PARAMETER = 32;
public const TARGET_ALL = 63;
public const IS_REPEATABLE = 64;
/** @var int */
public $flags;
public function __construct(int $flags = self::TARGET_ALL)
{
$this->flags = $flags;
}
}

View File

@@ -0,0 +1,16 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
if (\PHP_VERSION_ID < 80000 && extension_loaded('tokenizer')) {
class PhpToken extends Symfony\Polyfill\Php80\PhpToken
{
}
}

View File

@@ -0,0 +1,20 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
if (\PHP_VERSION_ID < 80000) {
interface Stringable
{
/**
* @return string
*/
public function __toString();
}
}

View File

@@ -0,0 +1,16 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
if (\PHP_VERSION_ID < 80000) {
class UnhandledMatchError extends Error
{
}
}

View File

@@ -0,0 +1,16 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
if (\PHP_VERSION_ID < 80000) {
class ValueError extends Error
{
}
}

View File

@@ -0,0 +1,42 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Symfony\Polyfill\Php80 as p;
if (\PHP_VERSION_ID >= 80000) {
return;
}
if (!defined('FILTER_VALIDATE_BOOL') && defined('FILTER_VALIDATE_BOOLEAN')) {
define('FILTER_VALIDATE_BOOL', \FILTER_VALIDATE_BOOLEAN);
}
if (!function_exists('fdiv')) {
function fdiv(float $num1, float $num2): float { return p\Php80::fdiv($num1, $num2); }
}
if (!function_exists('preg_last_error_msg')) {
function preg_last_error_msg(): string { return p\Php80::preg_last_error_msg(); }
}
if (!function_exists('str_contains')) {
function str_contains(?string $haystack, ?string $needle): bool { return p\Php80::str_contains($haystack ?? '', $needle ?? ''); }
}
if (!function_exists('str_starts_with')) {
function str_starts_with(?string $haystack, ?string $needle): bool { return p\Php80::str_starts_with($haystack ?? '', $needle ?? ''); }
}
if (!function_exists('str_ends_with')) {
function str_ends_with(?string $haystack, ?string $needle): bool { return p\Php80::str_ends_with($haystack ?? '', $needle ?? ''); }
}
if (!function_exists('get_debug_type')) {
function get_debug_type($value): string { return p\Php80::get_debug_type($value); }
}
if (!function_exists('get_resource_id')) {
function get_resource_id($resource): int { return p\Php80::get_resource_id($resource); }
}

View File

@@ -0,0 +1,37 @@
{
"name": "symfony/polyfill-php80",
"type": "library",
"description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions",
"keywords": ["polyfill", "shim", "compatibility", "portable"],
"homepage": "https://symfony.com",
"license": "MIT",
"authors": [
{
"name": "Ion Bazan",
"email": "ion.bazan@gmail.com"
},
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"require": {
"php": ">=7.2"
},
"autoload": {
"psr-4": { "Symfony\\Polyfill\\Php80\\": "" },
"files": [ "bootstrap.php" ],
"classmap": [ "Resources/stubs" ]
},
"minimum-stability": "dev",
"extra": {
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
}
}
}

3206
vendor/tecnickcom/tcpdf/CHANGELOG.TXT vendored Normal file

File diff suppressed because it is too large Load Diff

860
vendor/tecnickcom/tcpdf/LICENSE.TXT vendored Normal file
View File

@@ -0,0 +1,860 @@
**********************************************************************
* TCPDF LICENSE
**********************************************************************
TCPDF is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
2002-2025 Nicola Asuni - Tecnick.com LTD
**********************************************************************
**********************************************************************
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
**********************************************************************
**********************************************************************
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
**********************************************************************
**********************************************************************

Some files were not shown because too many files have changed in this diff Show More