diff --git a/api b/api deleted file mode 160000 index f1dc7122..00000000 --- a/api +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f1dc712215ba609c3f9a39f1b4e021e00d0247fb diff --git a/api/.vscode/settings.json b/api/.vscode/settings.json new file mode 100644 index 00000000..96196938 --- /dev/null +++ b/api/.vscode/settings.json @@ -0,0 +1,124 @@ +{ + "window.zoomLevel": 1, // Permet de zoomer, pratique si vous faites une présentation + + // Apparence + // -- Editeur + "workbench.startupEditor": "none", // On ne veut pas une page d'accueil chargée + "editor.minimap.enabled": false, // On veut voir la minimap + "editor.minimap.showSlider": "always", // On veut voir la minimap + "editor.minimap.size": "fill", // On veut voir la minimap + "editor.minimap.scale": 2, + "editor.tokenColorCustomizations": { + "textMateRules": [ + { + "scope": ["storage.type.function", "storage.type.class"], + "settings": { + "fontStyle": "bold", + "foreground": "#4B9CD3" + } + } + ] + }, + "editor.minimap.renderCharacters": true, + "editor.minimap.maxColumn": 120, + "breadcrumbs.enabled": false, + // -- Tabs + "workbench.editor.wrapTabs": true, // On veut voir les tabs + "workbench.editor.tabSizing": "shrink", // On veut voir les tabs + "workbench.editor.pinnedTabSizing": "compact", + "workbench.editor.enablePreview": false, // Un clic sur un fichier l'ouvre + + // -- Sidebar + "workbench.tree.indent": 15, // Indente plus pour plus de clarté dans la sidebar + "workbench.tree.renderIndentGuides": "always", + // -- Code + "editor.occurrencesHighlight": "singleFile", // On veut voir les occurences d'une variable + "editor.renderWhitespace": "trailing", // On ne veut pas laisser d'espace en fin de ligne + "editor.renderControlCharacters": true, // On veut voir les caractères de contrôle + // Thème + "editor.fontFamily": "'JetBrains Mono', 'Fira Code', 'Operator Mono Lig', monospace", + "editor.fontLigatures": false, + "editor.fontSize": 13, + "editor.lineHeight": 22, + "editor.guides.bracketPairs": "active", + + // Ergonomie + "editor.wordWrap": "off", + "editor.rulers": [], + "editor.suggest.insertMode": "replace", // L'autocomplétion remplace le mot en cours + "editor.acceptSuggestionOnCommitCharacter": false, // Evite que l'autocomplétion soit accepté lors d'un . par exemple + "editor.formatOnSave": true, + "editor.formatOnPaste": true, + "editor.linkedEditing": true, // Quand on change un élément HTML, change la balise fermante + "editor.tabSize": 2, + "editor.unicodeHighlight.nonBasicASCII": false, + + "[php]": { + "editor.defaultFormatter": "bmewburn.vscode-intelephense-client", + "editor.formatOnSave": true, + "editor.formatOnPaste": true + }, + "intelephense.format.braces": "k&r", + "intelephense.format.enable": true, + + "[javascript]": { + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.formatOnSave": true, + "editor.formatOnPaste": true + }, + "prettier.printWidth": 360, + "prettier.semi": true, + "prettier.singleQuote": true, + "prettier.tabWidth": 2, + "prettier.trailingComma": "es5", + + "explorer.autoReveal": false, + "explorer.confirmDragAndDrop": false, + "emmet.triggerExpansionOnTab": true, + + // Fichiers + "files.defaultLanguage": "markdown", + "files.autoSaveWorkspaceFilesOnly": true, + "files.exclude": { + "**/.idea": true + }, + // Languages + "javascript.preferences.importModuleSpecifierEnding": "js", + "typescript.preferences.importModuleSpecifierEnding": "js", + + // Extensions + "tailwindCSS.experimental.configFile": "frontend/tailwind.config.js", + "editor.quickSuggestions": { + "strings": true + }, + + "[svelte]": { + "editor.defaultFormatter": "svelte.svelte-vscode", + "editor.formatOnSave": true + }, + "prettier.documentSelectors": ["**/*.svelte"], + "svelte.plugin.svelte.diagnostics.enable": false, + "problems.decorations.enabled": false, + "js/ts.implicitProjectConfig.checkJs": false, + "svelte.enable-ts-plugin": false, + "workbench.colorCustomizations": { + "activityBar.activeBackground": "#ff6433", + "activityBar.background": "#ff6433", + "activityBar.foreground": "#15202b", + "activityBar.inactiveForeground": "#15202b99", + "activityBarBadge.background": "#00ff3d", + "activityBarBadge.foreground": "#15202b", + "commandCenter.border": "#e7e7e799", + "sash.hoverBorder": "#ff6433", + "statusBar.background": "#ff3d00", + "statusBar.foreground": "#e7e7e7", + "statusBarItem.hoverBackground": "#ff6433", + "statusBarItem.remoteBackground": "#ff3d00", + "statusBarItem.remoteForeground": "#e7e7e7", + "titleBar.activeBackground": "#ff3d00", + "titleBar.activeForeground": "#e7e7e7", + "titleBar.inactiveBackground": "#ff3d0099", + "titleBar.inactiveForeground": "#e7e7e799" + }, + "peacock.color": "#ff3d00" +} diff --git a/api/bootstrap.php b/api/bootstrap.php new file mode 100644 index 00000000..d8be4ea1 --- /dev/null +++ b/api/bootstrap.php @@ -0,0 +1,16 @@ +=8.1", + "phpmailer/phpmailer": "^6.8", + "ext-pdo": "*", + "ext-openssl": "*", + "ext-json": "*" + }, + "autoload": { + "psr-4": { + "App\\": "src/" + } + }, + "config": { + "sort-packages": true, + "optimize-autoloader": true + } +} diff --git a/api/composer.lock b/api/composer.lock new file mode 100644 index 00000000..be981f46 --- /dev/null +++ b/api/composer.lock @@ -0,0 +1,105 @@ +{ + "_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": "03e608fa83a14a82b3f9223977e9674e", + "packages": [ + { + "name": "phpmailer/phpmailer", + "version": "v6.9.3", + "source": { + "type": "git", + "url": "https://github.com/PHPMailer/PHPMailer.git", + "reference": "2f5c94fe7493efc213f643c23b1b1c249d40f47e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/2f5c94fe7493efc213f643c23b1b1c249d40f47e", + "reference": "2f5c94fe7493efc213f643c23b1b1c249d40f47e", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "ext-filter": "*", + "ext-hash": "*", + "php": ">=5.5.0" + }, + "require-dev": { + "dealerdirect/phpcodesniffer-composer-installer": "^1.0", + "doctrine/annotations": "^1.2.6 || ^1.13.3", + "php-parallel-lint/php-console-highlighter": "^1.0.0", + "php-parallel-lint/php-parallel-lint": "^1.3.2", + "phpcompatibility/php-compatibility": "^9.3.5", + "roave/security-advisories": "dev-latest", + "squizlabs/php_codesniffer": "^3.7.2", + "yoast/phpunit-polyfills": "^1.0.4" + }, + "suggest": { + "decomplexity/SendOauth2": "Adapter for using XOAUTH2 authentication", + "ext-mbstring": "Needed to send email in multibyte encoding charset or decode encoded addresses", + "ext-openssl": "Needed for secure SMTP sending and DKIM signing", + "greew/oauth2-azure-provider": "Needed for Microsoft Azure XOAUTH2 authentication", + "hayageek/oauth2-yahoo": "Needed for Yahoo XOAUTH2 authentication", + "league/oauth2-google": "Needed for Google XOAUTH2 authentication", + "psr/log": "For optional PSR-3 debug logging", + "symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)", + "thenetworg/oauth2-azure": "Needed for Microsoft XOAUTH2 authentication" + }, + "type": "library", + "autoload": { + "psr-4": { + "PHPMailer\\PHPMailer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-2.1-only" + ], + "authors": [ + { + "name": "Marcus Bointon", + "email": "phpmailer@synchromedia.co.uk" + }, + { + "name": "Jim Jagielski", + "email": "jimjag@gmail.com" + }, + { + "name": "Andy Prevost", + "email": "codeworxtech@users.sourceforge.net" + }, + { + "name": "Brent R. Matzelle" + } + ], + "description": "PHPMailer is a full-featured email creation and transfer class for PHP", + "support": { + "issues": "https://github.com/PHPMailer/PHPMailer/issues", + "source": "https://github.com/PHPMailer/PHPMailer/tree/v6.9.3" + }, + "funding": [ + { + "url": "https://github.com/Synchro", + "type": "github" + } + ], + "time": "2024-11-24T18:04:13+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": {}, + "prefer-stable": false, + "prefer-lowest": false, + "platform": { + "php": ">=8.1", + "ext-pdo": "*", + "ext-openssl": "*", + "ext-json": "*" + }, + "platform-dev": {}, + "plugin-api-version": "2.6.0" +} diff --git a/api/deploy-api.sh b/api/deploy-api.sh new file mode 100755 index 00000000..b70a6761 --- /dev/null +++ b/api/deploy-api.sh @@ -0,0 +1,145 @@ +#!/bin/bash + +# Script de déploiement pour GEOSECTOR API +# Version: 3.0 (10 mai 2025) +# Auteur: Pierre (avec l'aide de Claude) + +set -euo pipefail + +# Configuration des serveurs +JUMP_USER="root" +JUMP_HOST="195.154.80.116" +JUMP_PORT="22" +JUMP_KEY="/Users/pierre/.ssh/id_rsa_mbpi" + +# Paramètres du container Incus +INCUS_PROJECT=default +INCUS_CONTAINER=dva-geo +CONTAINER_USER=root + +# Paramètres de déploiement +FINAL_PATH="/var/www/geosector/api" +FINAL_OWNER="nginx" +FINAL_GROUP="nginx" +FINAL_OWNER_LOGS="nobody" + +# Couleurs pour les messages +GREEN='\033[0;32m' +RED='\033[0;31m' +YELLOW='\033[0;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +run_in_container() { + echo "-> Running: $*" + incus exec "${INCUS_CONTAINER}" -- "$@" || { + echo "❌ Failed to run: $*" + exit 1 + } +} + +# Fonction pour afficher les messages d'étape +echo_step() { + echo -e "${GREEN}==>${NC} $1" +} + +# Fonction pour afficher les informations +echo_info() { + echo -e "${BLUE}Info:${NC} $1" +} + +# Fonction pour afficher les avertissements +echo_warning() { + echo -e "${YELLOW}Warning:${NC} $1" +} + +# Fonction pour afficher les erreurs +echo_error() { + echo -e "${RED}Error:${NC} $1" + exit 1 +} + +# Vérification de l'environnement +echo_step "Verifying environment..." + +# Vérification des fichiers requis +if [ ! -f "src/Config/AppConfig.php" ]; then + echo_error "Configuration file missing" +fi + +if [ ! -f "composer.json" ] || [ ! -f "composer.lock" ]; then + echo_error "Composer files missing" +fi + +# Étape 0: Définir le nom de l'archive +ARCHIVE_NAME="api-deploy-$(date +%s).tar.gz" +echo_info "Archive name will be: $ARCHIVE_NAME" + +# Étape 1: Créer une archive du projet +echo_step "Creating project archive..." +tar --exclude='.git' \ + --exclude='.gitignore' \ + --exclude='.vscode' \ + --exclude='logs' \ + --exclude='*.template' \ + --exclude='*.sh' \ + --exclude='.env' \ + --exclude='*.log' \ + --exclude='.DS_Store' \ + --exclude='README.md' \ + --exclude="*.tar.gz" \ + --no-xattrs \ + -czf "${ARCHIVE_NAME}" . || echo_error "Failed to create archive" + +# Vérifier la taille de l'archive +ARCHIVE_SIZE=$(du -h "${ARCHIVE_NAME}" | cut -f1) + +SSH_JUMP_CMD="ssh -i ${JUMP_KEY} -p ${JUMP_PORT} ${JUMP_USER}@${JUMP_HOST}" + +# Étape 2: Copier l'archive vers le serveur de saut +echo_step "Copying archive to jump server..." +echo_info "Archive size: $ARCHIVE_SIZE" +scp -i "${JUMP_KEY}" -P "${JUMP_PORT}" "${ARCHIVE_NAME}" "${JUMP_USER}@${JUMP_HOST}:/tmp/${ARCHIVE_NAME}" || echo_error "Failed to copy archive to jump server" + +# Étape 3: Exécuter les commandes sur le serveur de saut pour déployer dans le container Incus +echo_step "Deploying to Incus container..." +$SSH_JUMP_CMD " + set -euo pipefail + + echo '✅ Passage au projet Incus...' + incus project switch ${INCUS_PROJECT} || exit 1 + + echo '📦 Poussée de archive dans le conteneur...' + incus file push /tmp/${ARCHIVE_NAME} ${INCUS_CONTAINER}/tmp/${ARCHIVE_NAME} || exit 1 + + echo '📁 Préparation du dossier final...' + incus exec ${INCUS_CONTAINER} -- mkdir -p ${FINAL_PATH} || exit 1 + incus exec ${INCUS_CONTAINER} -- rm -rf ${FINAL_PATH}/* || exit 1 + incus exec ${INCUS_CONTAINER} -- tar -xzf /tmp/${ARCHIVE_NAME} -C ${FINAL_PATH}/ || exit 1 + + echo '🔧 Réglage des permissions...' + incus exec ${INCUS_CONTAINER} -- mkdir -p ${FINAL_PATH}/logs || exit 1 + incus exec ${INCUS_CONTAINER} -- chown -R ${FINAL_OWNER}:${FINAL_GROUP} ${FINAL_PATH} || exit 1 + incus exec ${INCUS_CONTAINER} -- find ${FINAL_PATH} -type d -exec chmod 755 {} \; || exit 1 + incus exec ${INCUS_CONTAINER} -- find ${FINAL_PATH} -type f -exec chmod 644 {} \; || exit 1 + + # Permissions spéciales pour le dossier logs (pour permettre à PHP-FPM de l'utilisateur nobody d'y écrire) + incus exec ${INCUS_CONTAINER} -- chown -R ${FINAL_OWNER}:${FINAL_OWNER_LOGS} ${FINAL_PATH}/logs || exit 1 + incus exec ${INCUS_CONTAINER} -- chmod -R 775 ${FINAL_PATH}/logs || exit 1 + incus exec ${INCUS_CONTAINER} -- find ${FINAL_PATH}/logs -type f -exec chmod 664 {} \; || exit 1 + + echo '🧹 Nettoyage...' + incus exec ${INCUS_CONTAINER} -- rm -f /tmp/${ARCHIVE_NAME} || exit 1 + rm -f /tmp/${ARCHIVE_NAME} || exit 1 +" + +# Nettoyage local +rm -f "${ARCHIVE_NAME}" + +# Résumé final +echo_step "Deployment completed successfully." +echo_info "Your API has been updated on the container." +echo_info "Deployment completed at: $(date)" + +# Journaliser le déploiement +echo "$(date '+%Y-%m-%d %H:%M:%S') - API deployed to ${JUMP_HOST}:${INCUS_CONTAINER}" >> ~/.geo_deploy_history diff --git a/api/docs/CDC.md b/api/docs/CDC.md new file mode 100644 index 00000000..520bc299 --- /dev/null +++ b/api/docs/CDC.md @@ -0,0 +1,11 @@ +# Présentation du projet + +Créer un projet d'une API très simple en PHP 8.3 pur sans framework, qui servira en backend d'interface (PDO) avec une base de données MariaDB 10.11 déjà existante. L'API RESTFUL doit recevoir des requêtes de 3 URL différentes. + +Ce projet doit permettre de créer une structure réplicable pour être utilisée sur d'autres projets avec des frontends différents (Flutter, Svelte, Javascript Vanilla, ...). + +## TODO : + +- sur le serveur de DEV : créer le conf NGINX et l'url api.d6soft.com +- mettre à jour la config et database +- gérer le login et l'inscription sans mot de passe. diff --git a/api/docs/README-D6MON.md b/api/docs/README-D6MON.md new file mode 100644 index 00000000..626df2ec --- /dev/null +++ b/api/docs/README-D6MON.md @@ -0,0 +1,612 @@ +# API D6MON - Documentation + +## Introduction + +L'API D6MON est une interface RESTful permettant d'interagir avec l'application D6MON. Cette API gère l'authentification des utilisateurs, la gestion des profils utilisateurs et la gestion des entités. + +## Configuration + +### Base URL + +``` +https://app.d6mon.com/api/mon +``` + +### En-têtes requis + +Pour toutes les requêtes à l'API, les en-têtes suivants sont requis : + +``` +Content-Type: application/json +X-App-Identifier: app.d6mon.com +X-Client-Type: mobile +``` + +Pour les endpoints protégés (nécessitant une authentification), ajoutez également : + +``` +Authorization: Bearer {token} +``` + +Où `{token}` est le jeton d'authentification obtenu lors de la connexion. + +## Authentification + +### Connexion + +**Endpoint :** `POST /login` + +**Corps de la requête :** + +```json +{ + "email": "utilisateur@exemple.com", + "password": "motdepasse" +} +``` + +**Réponse réussie :** + +```json +{ + "success": true, + "data": { + "token": "session_token_here", + "user": { + "id": 123, + "email": "utilisateur@exemple.com", + "last_name": "Nom", + "first_name": "Prénom", + "display_name": "Nom d'affichage", + "entity_id": 456 + } + } +} +``` + +### Inscription + +**Endpoint :** `POST /register` + +**Corps de la requête :** + +```json +{ + "display_name": "Nom d'affichage", + "email": "utilisateur@exemple.com", + "first_name": "Prénom", + "last_name": "Nom", + "entity_id": 456 +} +``` + +**Réponse réussie :** + +```json +{ + "success": true, + "message": "Inscription réussie. Un email contenant vos identifiants vous a été envoyé.", + "data": { + "user": { + "id": 123, + "email": "utilisateur@exemple.com", + "display_name": "Nom d'affichage" + } + } +} +``` + +### Mot de passe oublié + +**Endpoint :** `POST /lost-password` + +**Corps de la requête :** + +```json +{ + "email": "utilisateur@exemple.com" +} +``` + +**Réponse réussie :** + +```json +{ + "success": true, + "message": "Un nouveau mot de passe a été envoyé à votre adresse email." +} +``` + +### Déconnexion + +**Endpoint :** `POST /logout` + +**Réponse réussie :** + +```json +{ + "success": true, + "message": "Déconnecté avec succès" +} +``` + +## Gestion des utilisateurs + +### Récupérer le profil de l'utilisateur connecté + +**Endpoint :** `GET /user/profile` + +**Réponse réussie :** + +```json +{ + "success": true, + "data": { + "id": 123, + "entity_id": 456, + "display_name": "Nom d'affichage", + "first_name": "Prénom", + "last_name": "Nom", + "avatar": "url_avatar", + "email": "utilisateur@exemple.com", + "phone": "+33612345678", + "address1": "Adresse ligne 1", + "address2": "Adresse ligne 2", + "code_postal": "75000", + "city": "Paris", + "country": "France", + "seat_name": "Siège", + "created_at": "2023-01-01T00:00:00Z", + "updated_at": "2023-01-01T00:00:00Z", + "connected_at": "2023-01-01T00:00:00Z", + "is_active": true, + "entity": { + "id": 456, + "name": "Nom de l'entité", + "email": "entite@exemple.com", + "phone": "+33123456789", + "address1": "Adresse ligne 1", + "address2": "Adresse ligne 2", + "code_postal": "75000", + "city": "Paris", + "country": "France", + "created_at": "2023-01-01T00:00:00Z", + "updated_at": "2023-01-01T00:00:00Z", + "is_active": true + } + } +} +``` + +### Mettre à jour le profil de l'utilisateur connecté + +**Endpoint :** `PUT /user/profile` + +**Corps de la requête :** + +```json +{ + "display_name": "Nouveau nom d'affichage", + "first_name": "Nouveau prénom", + "last_name": "Nouveau nom", + "phone": "+33612345678", + "address1": "Nouvelle adresse ligne 1", + "address2": "Nouvelle adresse ligne 2", + "code_postal": "75001", + "city": "Paris", + "country": "France", + "seat_name": "Nouveau siège" +} +``` + +**Réponse réussie :** +Même format que `GET /user/profile` avec les données mises à jour. + +### Changer le mot de passe + +**Endpoint :** `POST /user/change-password` + +**Corps de la requête :** + +```json +{ + "current_password": "ancien_mot_de_passe", + "new_password": "nouveau_mot_de_passe" +} +``` + +**Réponse réussie :** + +```json +{ + "success": true, + "message": "Mot de passe changé avec succès" +} +``` + +### Récupérer un utilisateur par ID + +**Endpoint :** `GET /user/{id}` + +**Réponse réussie :** + +```json +{ + "success": true, + "data": { + "id": 123, + "entity_id": 456, + "display_name": "Nom d'affichage", + "first_name": "Prénom", + "last_name": "Nom", + "avatar": "url_avatar", + "email": "utilisateur@exemple.com", + "phone": "+33612345678", + "address1": "Adresse ligne 1", + "address2": "Adresse ligne 2", + "code_postal": "75000", + "city": "Paris", + "country": "France", + "seat_name": "Siège", + "created_at": "2023-01-01T00:00:00Z", + "updated_at": "2023-01-01T00:00:00Z", + "connected_at": "2023-01-01T00:00:00Z", + "is_active": true + } +} +``` + +### Récupérer la liste des utilisateurs + +**Endpoint :** `GET /users` + +**Paramètres de requête :** + +- `page` (optionnel) : Numéro de page (défaut : 1) +- `limit` (optionnel) : Nombre d'éléments par page (défaut : 20) +- `entity_id` (optionnel) : Filtrer par ID d'entité + +**Réponse réussie :** + +```json +{ + "success": true, + "data": { + "users": [ + { + "id": 123, + "entity_id": 456, + "display_name": "Nom d'affichage", + "first_name": "Prénom", + "last_name": "Nom", + "avatar": "url_avatar", + "email": "utilisateur@exemple.com", + "address1": "Adresse ligne 1", + "city": "Paris", + "country": "France", + "created_at": "2023-01-01T00:00:00Z", + "updated_at": "2023-01-01T00:00:00Z", + "connected_at": "2023-01-01T00:00:00Z", + "is_active": true + } + ], + "pagination": { + "total": 100, + "page": 1, + "limit": 20, + "pages": 5 + } + } +} +``` + +### Créer un nouvel utilisateur + +**Endpoint :** `POST /user` + +**Corps de la requête :** + +```json +{ + "display_name": "Nom d'affichage", + "email": "utilisateur@exemple.com", + "first_name": "Prénom", + "last_name": "Nom", + "entity_id": 456, + "phone": "+33612345678", + "address1": "Adresse ligne 1", + "address2": "Adresse ligne 2", + "code_postal": "75000", + "city": "Paris", + "country": "France", + "seat_name": "Siège" +} +``` + +**Réponse réussie :** + +```json +{ + "success": true, + "message": "Utilisateur créé avec succès. Un email avec les identifiants a été envoyé.", + "data": { + "id": 123, + "display_name": "Nom d'affichage", + "email": "utilisateur@exemple.com" + } +} +``` + +### Désactiver un utilisateur + +**Endpoint :** `DELETE /user/{id}` + +**Réponse réussie :** + +```json +{ + "success": true, + "message": "Utilisateur désactivé avec succès" +} +``` + +## Gestion des entités + +### Récupérer toutes les entités + +**Endpoint :** `GET /entities` + +**Paramètres de requête :** + +- `page` (optionnel) : Numéro de page (défaut : 1) +- `limit` (optionnel) : Nombre d'éléments par page (défaut : 20) +- `search` (optionnel) : Terme de recherche + +**Réponse réussie :** + +```json +{ + "success": true, + "data": { + "entities": [ + { + "id": 456, + "name": "Nom de l'entité", + "email": "entite@exemple.com", + "phone": "+33123456789", + "address1": "Adresse ligne 1", + "address2": "Adresse ligne 2", + "code_postal": "75000", + "city": "Paris", + "country": "France", + "created_at": "2023-01-01T00:00:00Z", + "updated_at": "2023-01-01T00:00:00Z", + "is_active": true + } + ], + "pagination": { + "total": 50, + "page": 1, + "limit": 20, + "pages": 3 + } + } +} +``` + +### Récupérer une entité par ID + +**Endpoint :** `GET /entity/{id}` + +**Réponse réussie :** + +```json +{ + "success": true, + "data": { + "id": 456, + "name": "Nom de l'entité", + "email": "entite@exemple.com", + "phone": "+33123456789", + "address1": "Adresse ligne 1", + "address2": "Adresse ligne 2", + "code_postal": "75000", + "city": "Paris", + "country": "France", + "created_at": "2023-01-01T00:00:00Z", + "updated_at": "2023-01-01T00:00:00Z", + "is_active": true, + "users": [ + { + "id": 123, + "display_name": "Nom d'affichage", + "first_name": "Prénom", + "last_name": "Nom", + "avatar": "url_avatar", + "email": "utilisateur@exemple.com", + "created_at": "2023-01-01T00:00:00Z", + "is_active": true + } + ] + } +} +``` + +### Créer une nouvelle entité + +**Endpoint :** `POST /entity` + +**Corps de la requête :** + +```json +{ + "name": "Nom de l'entité", + "email": "entite@exemple.com", + "phone": "+33123456789", + "address1": "Adresse ligne 1", + "address2": "Adresse ligne 2", + "code_postal": "75000", + "city": "Paris", + "country": "France" +} +``` + +**Réponse réussie :** + +```json +{ + "success": true, + "message": "Entité créée avec succès", + "data": { + "id": 456, + "name": "Nom de l'entité" + } +} +``` + +### Mettre à jour une entité + +**Endpoint :** `PUT /entity/{id}` + +**Corps de la requête :** + +```json +{ + "name": "Nouveau nom de l'entité", + "email": "nouvelle-entite@exemple.com", + "phone": "+33987654321", + "address1": "Nouvelle adresse ligne 1", + "address2": "Nouvelle adresse ligne 2", + "code_postal": "75001", + "city": "Paris", + "country": "France" +} +``` + +**Réponse réussie :** +Même format que `GET /entity/{id}` avec les données mises à jour. + +### Désactiver une entité + +**Endpoint :** `DELETE /entity/{id}` + +**Réponse réussie :** + +```json +{ + "success": true, + "message": "Entité désactivée avec succès" +} +``` + +### Récupérer les utilisateurs d'une entité + +**Endpoint :** `GET /entity/{id}/users` + +**Paramètres de requête :** + +- `page` (optionnel) : Numéro de page (défaut : 1) +- `limit` (optionnel) : Nombre d'éléments par page (défaut : 20) + +**Réponse réussie :** + +```json +{ + "success": true, + "data": { + "users": [ + { + "id": 123, + "display_name": "Nom d'affichage", + "first_name": "Prénom", + "last_name": "Nom", + "avatar": "url_avatar", + "email": "utilisateur@exemple.com", + "phone": "+33612345678", + "created_at": "2023-01-01T00:00:00Z", + "updated_at": "2023-01-01T00:00:00Z", + "connected_at": "2023-01-01T00:00:00Z", + "is_active": true + } + ], + "pagination": { + "total": 25, + "page": 1, + "limit": 20, + "pages": 2 + } + } +} +``` + +## Structure des données + +### Table `users` + +```sql +CREATE TABLE users ( + id INT AUTO_INCREMENT PRIMARY KEY, + entity_id INT, + display_name VARCHAR(100) NOT NULL, + first_name VARCHAR(100), + encrypted_last_name VARCHAR(512), + avatar VARCHAR(255), + encrypted_email VARCHAR(512), + encrypted_phone VARCHAR(255), + address1 VARCHAR(255), + address2 VARCHAR(255), + code_postal VARCHAR(20), + city VARCHAR(100), + country VARCHAR(100), + seat_name VARCHAR(20), + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + connected_at DATETIME, + is_active BOOLEAN DEFAULT TRUE, + FOREIGN KEY (entity_id) REFERENCES entities(id) +); +``` + +### Table `entities` + +```sql +CREATE TABLE entities ( + id INT AUTO_INCREMENT PRIMARY KEY, + encrypted_name VARCHAR(512) NOT NULL, + encrypted_email VARCHAR(512), + encrypted_phone VARCHAR(255), + address1 VARCHAR(255), + address2 VARCHAR(255), + code_postal VARCHAR(20), + city VARCHAR(100), + country VARCHAR(100), + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + is_active BOOLEAN DEFAULT TRUE +); +``` + +## Sécurité + +L'API utilise plusieurs mécanismes pour assurer la sécurité des données : + +1. **Authentification par jeton** : Un jeton d'authentification est requis pour accéder aux endpoints protégés. +2. **Chiffrement des données sensibles** : Les données sensibles comme les noms, emails et numéros de téléphone sont chiffrées en base de données. +3. **Validation des entrées** : Toutes les entrées utilisateur sont validées avant traitement. +4. **Gestion des erreurs** : Les erreurs sont gérées de manière sécurisée sans divulguer d'informations sensibles. + +## Codes d'erreur + +- `400 Bad Request` : Requête invalide ou données manquantes +- `401 Unauthorized` : Authentification requise ou échouée +- `403 Forbidden` : Accès non autorisé à la ressource +- `404 Not Found` : Ressource non trouvée +- `409 Conflict` : Conflit avec l'état actuel de la ressource +- `500 Internal Server Error` : Erreur serveur + +## Notes d'implémentation + +- Les mots de passe sont hachés avec l'algorithme bcrypt. +- Les données sensibles sont chiffrées avec AES-256-CBC. +- Les emails sont envoyés pour les opérations importantes (inscription, réinitialisation de mot de passe). +- Les sessions sont gérées côté serveur avec un délai d'expiration. diff --git a/api/docs/TECHBOOK.md b/api/docs/TECHBOOK.md new file mode 100644 index 00000000..272e668b --- /dev/null +++ b/api/docs/TECHBOOK.md @@ -0,0 +1,300 @@ +# Documentation Technique API RESTful PHP 8.3 + +## Table des matières + +1. [Structure du projet](#structure-du-projet) +2. [Configuration du serveur](#configuration-du-serveur) +3. [Flux d'une requête](#flux-dune-requête) +4. [Architecture des composants](#architecture-des-composants) +5. [Base de données](#base-de-données) +6. [Sécurité](#sécurité) +7. [Endpoints API](#endpoints-api) + +## Structure du projet + +```plaintext +/api/ +├── docs/ +│ └── TECHBOOK.md +├── src/ +│ ├── Controllers/ +│ │ └── UserController.php +│ ├── Core/ +│ │ ├── Router.php +│ │ ├── Request.php +│ │ ├── Response.php +│ │ ├── Session.php +│ │ └── Database.php +│ └── Config/ +│ └── config.php +├── index.php +└── .htaccess +``` + +## Configuration du serveur + +### Prérequis + +- Debian 12 +- NGINX +- PHP 8.3-FPM +- MariaDB 10.11 + +### Configuration NGINX + +Le serveur NGINX est configuré pour rediriger toutes les requêtes vers le point d'entrée `index.php` de l'API. + +### Configuration PHP-FPM + +PHP-FPM est configuré pour gérer les processus PHP avec des paramètres optimisés pour une API. + +## Flux d'une requête + +Exemple détaillé du parcours d'une requête POST /api/users : + +1. **Entrée de la requête** + + - La requête arrive sur le serveur NGINX + - NGINX redirige vers PHP-FPM via le socket unix + - Le fichier .htaccess redirige vers index.php + +2. **Initialisation (index.php)** + + - Chargement des dépendances + - Initialisation de la configuration + - Démarrage de la session + - Configuration des headers CORS + - Initialisation du routeur + +3. **Routage** + + - Le Router analyse la méthode HTTP (POST) + - Analyse de l'URI (/api/users) + - Correspondance avec les routes enregistrées + - Instanciation du Controller approprié + +4. **Traitement (UserController)** + + - Vérification de l'authentification + - Récupération des données JSON + - Validation des données reçues + - Traitement métier + - Interaction avec la base de données + - Préparation de la réponse + +5. **Réponse** + - Formatage de la réponse en JSON + - Configuration des headers de réponse + - Envoi au client + +## Architecture des composants + +### Core Components + +#### Router + +- Gère le routage des requêtes +- Associe les URLs aux Controllers +- Gère les paramètres d'URL +- Dispatch vers les méthodes appropriées + +#### Request + +- Parse les données entrantes +- Gère les différents types de contenu +- Nettoie et valide les entrées +- Fournit une interface unifiée pour accéder aux données + +#### Response + +- Formate les réponses en JSON +- Gère les codes HTTP +- Configure les headers de réponse +- Assure la cohérence des réponses + +#### Session + +- Gère l'état des sessions +- Stocke les données d'authentification +- Vérifie les permissions +- Sécurise les données de session + +#### Database + +- Gère la connexion à MariaDB +- Fournit une interface PDO +- Gère le pool de connexions +- Assure la sécurité des requêtes + +## Sécurité + +### Mesures implémentées + +- Validation stricte des entrées +- Protection contre les injections SQL (PDO) +- Hachage sécurisé des mots de passe +- Headers de sécurité HTTP +- Gestion des CORS +- Session sécurisée +- Authentification requise + +## Endpoints API + +### Routes Publiques vs Privées + +L'API distingue deux types de routes : + +#### Routes Publiques + +- POST /api/login +- POST /api/register +- GET /api/health + +#### Routes Privées (Nécessitent une session authentifiée) + +- Toutes les autres routes + +### Authentification + +L'authentification utilise le système de session PHP natif. + +#### Login + +```http +POST /api/login +Content-Type: application/json + +{ + "email": "user@example.com", + "password": "SecurePassword123" +} +``` + +**Réponse réussie :** + +```json +{ + "message": "Connecté avec succès", + "user": { + "id": 123, + "email": "user@example.com" + } +} +``` + +**Notes importantes :** + +- Un cookie de session PHP sécurisé est automatiquement créé +- Le cookie est httpOnly, secure et SameSite=Strict +- L'ID de session est régénéré à chaque login réussi + +#### Logout + +```http +POST /api/logout +``` + +**Réponse réussie :** + +```json +{ + "message": "Déconnecté avec succès" +} +``` + +### Sécurité des Sessions + +La configuration des sessions inclut : + +- Sessions PHP natives sécurisées +- Protection contre la fixation de session +- Cookies httpOnly (protection XSS) +- Mode strict pour les cookies +- Validation côté serveur à chaque requête + +- use_strict_mode = 1 +- cookie_httponly = 1 +- cookie_secure = 1 +- cookie_samesite = Strict +- Régénération de l'ID de session après login +- Destruction complète de la session au logout + +### Users + +#### Création d'utilisateur + +```http +POST /api/users +Content-Type: application/json + +{ + "name": "John Doe", + "email": "john@example.com", + "password": "SecurePassword123" +} +``` + +**Réponse réussie :** + +```json +{ + "message": "Utilisateur créé", + "id": "123" +} +``` + +**Codes de statut :** + +- 201: Création réussie +- 400: Données invalides +- 401: Non authentifié +- 500: Erreur serveur + +#### Autres endpoints + +- GET /api/users +- GET /api/users/{id} +- PUT /api/users/{id} +- DELETE /api/users/{id} + +## Intégration Frontend + +### Configuration des Requêtes + +Toutes les requêtes API depuis le frontend doivent inclure : + +```javascript +fetch('/api/endpoint', { + credentials: 'include', // Important pour les cookies de session + // ... autres options +}); +``` + +### Gestion des Sessions + +- Les cookies de session sont automatiquement gérés par le navigateur +- Pas besoin de stocker ou gérer des tokens manuellement +- Redirection vers /login si session expirée (401) + +## Maintenance et Déploiement + +### Logs + +- Logs d'accès NGINX : /var/log/nginx/api-access.log +- Logs d'erreur NGINX : /var/log/nginx/api-error.log +- Logs PHP : /var/log/php/php-error.log + +### Déploiement + +1. Pull du repository +2. Vérification des permissions +3. Configuration de l'environnement +4. Tests des endpoints +5. Redémarrage des services + +### Surveillance + +- Monitoring des processus PHP-FPM +- Surveillance de la base de données +- Monitoring des performances +- Alertes sur erreurs critiques diff --git a/api/docs/api-analysis.md b/api/docs/api-analysis.md new file mode 100644 index 00000000..886d39bf --- /dev/null +++ b/api/docs/api-analysis.md @@ -0,0 +1,165 @@ +# Synthèse du Projet API PHP 8.3 + +## Introduction + +Ce document présente une synthèse du projet API développé en PHP 8.3 sur Debian 12. Cette API modulaire sert de backend à plusieurs applications frontend, avec une architecture qui permet de traiter différemment les requêtes en fonction de l'application cliente. + +## Architecture globale + +### Caractéristiques principales + +- **Langage** : PHP 8.3 +- **Système d'exploitation** : Debian 12 +- **Architecture** : REST API modulaire +- **Multi-applications** : Support de différentes applications frontend via un système de routage conditionnel +- **Sécurité** : Gestion des sessions, protection CORS, chiffrement des données sensibles + +### Structure du projet + +``` +/api/ +├── bootstrap.php # Initialisation de base et autoload +├── composer.json # Dépendances et configuration de l'autoload +├── index.php # Point d'entrée principal +├── routes/ # Définition des routes par application +│ ├── default.php +│ ├── prokov.php +│ └── resalice.php +├── src/ +│ ├── Config/ # Configuration de l'application +│ ├── Controllers/ # Contrôleurs pour chaque ressource +│ ├── Core/ # Composants fondamentaux (routeur, DB, session) +│ └── Services/ # Services partagés +├── logs/ # Journaux d'activité +└── vendor/ # Dépendances externes +``` + +## Fonctionnement + +### Système d'identification des applications + +L'API identifie l'application cliente grâce à l'en-tête HTTP `X-App-Identifier`. Chaque application a son propre identifiant : +- `prokov.unikoffice.com` - Application Prokov +- `app.resalice.com` - Application Resalice + +En fonction de l'identifiant, l'API : +1. Charge les routes spécifiques à l'application +2. Applique la configuration correspondante (base de données, préfixe API) +3. Active uniquement les modules nécessaires + +### Flux de traitement d'une requête + +1. La requête arrive sur `index.php` +2. Le système vérifie l'en-tête `X-App-Identifier` et charge la configuration appropriée +3. Le routeur analyse l'URI en tenant compte du préfixe API spécifique à l'application +4. Pour les routes privées, le système vérifie l'authentification via Session +5. Le contrôleur approprié est instancié et sa méthode appelée +6. Une réponse JSON est générée et renvoyée au client + +## Composants principaux + +### Classe AppConfig + +Cette classe singleton gère la configuration de l'API, avec des paramètres spécifiques à chaque application : +- Connexion à la base de données +- Préfixe des routes API +- Modules activés +- Clés de chiffrement + +### Classe Router + +Le routeur gère : +- L'enregistrement des routes avec leur méthode HTTP (GET, POST, PUT, DELETE) +- La gestion des paramètres dynamiques dans les URLs +- La distinction entre routes publiques et privées +- Le dispatch vers les contrôleurs + +### Classe Database + +Gère la connexion à la base de données en utilisant PDO avec des paramètres optimisés pour la sécurité : +- Paramètres préparés +- Mode d'erreur strict +- Connexion unique (pattern Singleton) + +### Classe Session + +Gère l'authentification des utilisateurs et les sessions : +- Configuration sécurisée des cookies +- Support de l'authentification par Bearer token +- Vérification de l'activité et expiration +- Protection contre la fixation de session + +### Classe ApiService + +Fournit des fonctionnalités partagées : +- Envoi d'emails via PHPMailer +- Chiffrement et déchiffrement des données sensibles +- Support de deux types de chiffrement (recherchable et non-recherchable) + +### Classe LogService + +Gère la journalisation des événements avec des métadonnées structurées : +- Logs au format JSON pour faciliter l'analyse +- Rotation hebdomadaire des fichiers de logs +- Capture d'informations sur le client et l'environnement + +## Sécurité + +Le projet implémente plusieurs niveaux de sécurité : + +1. **Authentification** : Session PHP sécurisée, support des tokens Bearer +2. **Protection des données** : + - Chiffrement des données sensibles (AES-256-CBC) + - Hachage sécurisé des mots de passe +3. **Sécurité HTTP** : + - Validation stricte du CORS + - En-têtes de sécurité (X-Content-Type-Options, X-Frame-Options, X-XSS-Protection) + - Cookies sécurisés (httpOnly, secure, SameSite=Strict) +4. **Sécurité des requêtes** : + - Validation des entrées + - Protection contre les injections SQL avec PDO + - Sanitisation des données + +## Applications supportées + +### Prokov (prokov.unikoffice.com) + +Application avec le préfixe d'API `api/pkv`, supportant les modules : +- users +- logs +- admin + +### Resalice (app.resalice.com) + +Application avec le préfixe d'API `api/res`, supportant les modules : +- users +- logs +- site3 + +Fonctionnalités spécifiques : +- Gestion des profils utilisateurs avec des champs supplémentaires +- Gestion des professionnels + +## Points d'extension + +Le système est conçu pour faciliter l'ajout de nouvelles applications et fonctionnalités : + +1. Ajouter une entrée dans la configuration AppConfig +2. Créer un fichier de routes spécifique dans le dossier routes/ +3. Implémenter les contrôleurs spécifiques +4. Éventuellement ajouter des services spécifiques à l'application + +## Dépendances externes + +- **phpmailer/phpmailer** : Utilisé pour l'envoi d'emails +- **ext-pdo** : Pour la connexion à la base de données +- **ext-openssl** : Pour le chiffrement des données +- **ext-json** : Pour la manipulation JSON + +## Conclusion + +Cette API RESTful en PHP 8.3 présente une architecture modulaire bien structurée permettant de servir différentes applications frontend avec une base de code commune. Le système d'identification des applications et de routage conditionnel offre une grande flexibilité tout en maintenant une séparation claire des fonctionnalités. + +La sécurité a été prise en compte à plusieurs niveaux, notamment par le chiffrement des données sensibles et une gestion sécurisée des sessions. Le système de logs permet également un suivi efficace de l'activité et facilite le débogage. + +L'architecture modulaire facilite l'extension à de nouvelles applications et l'ajout de nouvelles fonctionnalités, ce qui en fait une solution évolutive à long terme. diff --git a/api/docs/db-d6mon.sql b/api/docs/db-d6mon.sql new file mode 100644 index 00000000..e69de29b diff --git a/api/docs/flowIncus.md b/api/docs/flowIncus.md new file mode 100644 index 00000000..8caea192 --- /dev/null +++ b/api/docs/flowIncus.md @@ -0,0 +1,8 @@ +```mermaid +--- +title: Test +--- +flowchart LR + A[ClientDetector] --> B1[(getAppIdentifier())]; + +``` diff --git a/api/docs/geosector-db-diagram.md b/api/docs/geosector-db-diagram.md new file mode 100644 index 00000000..97d1f680 --- /dev/null +++ b/api/docs/geosector-db-diagram.md @@ -0,0 +1,200 @@ +# Diagramme Relationnel de la Base de Données Geosector + +```mermaid +erDiagram + %% Tables de référence (x_*) + x_devises ||--o{ x_pays : "fk_devise" + x_pays ||--o{ x_regions : "fk_pays" + x_regions ||--o{ x_departements : "fk_region" + x_regions ||--o{ entites : "fk_region" + x_entites_types ||--o{ entites : "fk_type" + x_departements ||--o{ x_villes : "fk_departement" + + %% Utilisateurs et entités + entites ||--o{ users : "fk_entite" + entites ||--o{ operations : "fk_entite" + x_users_roles ||--o{ users : "fk_role" + x_users_titres ||--o{ users : "fk_titre" + + %% Opérations et secteurs + operations ||--o{ ope_sectors : "fk_operation" + operations ||--o{ ope_users : "fk_operation" + operations ||--o{ ope_users_sectors : "fk_operation" + operations ||--o{ ope_pass : "fk_operation" + + users ||--o{ ope_users : "fk_user" + users ||--o{ ope_users_sectors : "fk_user" + users ||--o{ ope_pass : "fk_user" + users ||--o{ ope_pass_histo : "fk_user" + + ope_sectors ||--o{ ope_users_sectors : "fk_sector" + ope_sectors ||--o{ sectors_adresses : "fk_sector" + ope_sectors ||--o{ ope_pass : "fk_sector" + + ope_pass ||--o{ ope_pass_histo : "fk_pass" + x_types_reglements ||--o{ ope_pass : "fk_type_reglement" + + %% Système de chat + chat_rooms ||--o{ chat_participants : "id_room" + chat_rooms ||--o{ chat_messages : "fk_room" + chat_rooms ||--o{ chat_listes_diffusion : "fk_room" + chat_rooms ||--o{ chat_notifications : "fk_room" + + users ||--o{ chat_rooms : "fk_user" + users ||--o{ chat_participants : "id_user" + users ||--o{ chat_messages : "fk_user" + users ||--o{ chat_listes_diffusion : "fk_user" + users ||--o{ chat_read_messages : "fk_user" + users ||--o{ chat_notifications : "fk_user" + + chat_messages ||--o{ chat_read_messages : "fk_message" + chat_messages ||--o{ chat_notifications : "fk_message" + + %% Définition des entités avec leurs attributs principaux + x_devises { + int_unsigned id PK + string code + string symbole + string libelle + tinyint_unsigned chk_active + } + + x_pays { + int_unsigned id PK + int_unsigned fk_continent FK + int_unsigned fk_devise FK + string libelle + tinyint_unsigned chk_active + } + + x_regions { + int_unsigned id PK + int_unsigned fk_pays FK + string libelle + tinyint_unsigned chk_active + } + + x_departements { + int_unsigned id PK + string code + int_unsigned fk_region FK + string libelle + tinyint_unsigned chk_active + } + + x_villes { + int_unsigned id PK + int_unsigned fk_departement FK + string libelle + string cp + tinyint_unsigned chk_active + } + + entites { + int_unsigned id PK + string libelle + int_unsigned fk_region FK + int_unsigned fk_type FK + tinyint_unsigned chk_demo + tinyint_unsigned chk_active + } + + users { + int_unsigned id PK + int_unsigned fk_entite FK + int_unsigned fk_role FK + int_unsigned fk_titre FK + string encrypted_name + string encrypt_user_name + string encrypt_password + tinyint_unsigned chk_active + } + + operations { + int_unsigned id PK + int_unsigned fk_entite FK + string libelle + date date_deb + date date_fin + tinyint_unsigned chk_active + } + + ope_sectors { + int_unsigned id PK + int_unsigned fk_operation FK + string libelle + tinyint_unsigned chk_active + } + + ope_users { + int_unsigned id PK + int_unsigned fk_operation FK + int_unsigned fk_user FK + tinyint_unsigned chk_active + } + + ope_users_sectors { + int_unsigned id PK + int_unsigned fk_operation FK + int_unsigned fk_user FK + int_unsigned fk_sector FK + tinyint_unsigned chk_active + } + + sectors_adresses { + int_unsigned id PK + string fk_adresse + int_unsigned osm_id + int_unsigned fk_sector FK + string rue + string cp + string ville + } + + ope_pass { + int_unsigned id PK + int_unsigned fk_operation FK + int_unsigned fk_sector FK + int_unsigned fk_user FK + int_unsigned fk_type_reglement FK + timestamp passed_at + tinyint_unsigned chk_active + } + + ope_pass_histo { + int_unsigned id PK + int_unsigned fk_pass FK + int_unsigned fk_user FK + } + + chat_rooms { + int_unsigned id PK + string name + enum type + int_unsigned fk_user FK + int_unsigned fk_entite FK + } + + chat_messages { + int_unsigned id PK + int_unsigned fk_room FK + int_unsigned fk_user FK + text content + enum statut + } + + chat_read_messages { + bigint_unsigned id PK + int_unsigned fk_message FK + int_unsigned fk_user FK + timestamp date_read + } + + chat_notifications { + bigint_unsigned id PK + int_unsigned fk_user FK + int_unsigned fk_message FK + int_unsigned fk_room FK + string type + } +``` diff --git a/api/docs/geosector_app.sql b/api/docs/geosector_app.sql new file mode 100644 index 00000000..f95fdbb0 --- /dev/null +++ b/api/docs/geosector_app.sql @@ -0,0 +1,619 @@ +-- Création de la base de données geo_app si elle n'existe pas +DROP DATABASE IF EXISTS `geo_app`; +CREATE DATABASE IF NOT EXISTS `geo_app` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- Création de l'utilisateur et attribution des droits +CREATE USER IF NOT EXISTS 'geo_app_user'@'localhost' IDENTIFIED BY 'QO:96df*?k{4W6m'; +GRANT SELECT, INSERT, UPDATE, DELETE ON `geo_app`.* TO 'geo_app_user'@'localhost'; +FLUSH PRIVILEGES; + +USE geo_app; + +-- +-- Table structure for table `email_counter` +-- + +DROP TABLE IF EXISTS `email_counter`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `email_counter` ( + `id` int unsigned NOT NULL DEFAULT '1', + `hour_start` timestamp NULL DEFAULT NULL, + `count` int unsigned DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `x_devises`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_devises` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `code` varchar(3) DEFAULT NULL, + `symbole` varchar(6) DEFAULT NULL, + `libelle` varchar(45) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_entites_types` +-- + +DROP TABLE IF EXISTS `x_entites_types`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_entites_types` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `libelle` varchar(45) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_types_passages` +-- + +DROP TABLE IF EXISTS `x_types_passages`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_types_passages` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `libelle` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `color_button` varchar(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `color_mark` varchar(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `color_table` varchar(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `chk_active` tinyint(1) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_types_reglements` +-- + +DROP TABLE IF EXISTS `x_types_reglements`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_types_reglements` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `libelle` varchar(45) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_users_roles` +-- + +DROP TABLE IF EXISTS `x_users_roles`; + +CREATE TABLE `x_users_roles` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `libelle` varchar(45) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Les différents rôles des utilisateurs'; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `x_users_titres`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_users_titres` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `libelle` varchar(45) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Les différents titres des utilisateurs'; + +DROP TABLE IF EXISTS `x_pays`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_pays` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `code` varchar(3) DEFAULT NULL, + `fk_continent` int unsigned DEFAULT NULL, + `fk_devise` int unsigned DEFAULT '1', + `libelle` varchar(45) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`), + CONSTRAINT `x_pays_ibfk_1` FOREIGN KEY (`fk_devise`) REFERENCES `x_devises` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Table des pays avec leurs codes'; +/*!40101 SET character_set_client = @saved_cs_client */; + + +DROP TABLE IF EXISTS `x_regions`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_regions` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_pays` int unsigned DEFAULT '1', + `libelle` varchar(45) DEFAULT NULL, + `libelle_long` varchar(45) DEFAULT NULL, + `table_osm` varchar(45) DEFAULT NULL, + `departements` varchar(45) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`), + CONSTRAINT `x_regions_ibfk_1` FOREIGN KEY (`fk_pays`) REFERENCES `x_pays` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `x_departements`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_departements` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `code` varchar(3) DEFAULT NULL, + `fk_region` int unsigned DEFAULT '1', + `libelle` varchar(45) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`), + CONSTRAINT `x_departements_ibfk_1` FOREIGN KEY (`fk_region`) REFERENCES `x_regions` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=105 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `entites`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `entites` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `encrypted_name` varchar(255) DEFAULT NULL, + `adresse1` varchar(45) DEFAULT '', + `adresse2` varchar(45) DEFAULT '', + `code_postal` varchar(5) DEFAULT '', + `ville` varchar(45) DEFAULT '', + `fk_region` int unsigned DEFAULT NULL, + `fk_type` int unsigned DEFAULT '1', + `encrypted_phone` varchar(128) DEFAULT '', + `encrypted_mobile` varchar(128) DEFAULT '', + `encrypted_email` varchar(255) DEFAULT '', + `gps_lat` varchar(20) NOT NULL DEFAULT '', + `gps_lng` varchar(20) NOT NULL DEFAULT '', + `encrypted_stripe_id` varchar(255) DEFAULT '', + `encrypted_iban` varchar(255) DEFAULT '', + `encrypted_bic` varchar(128) DEFAULT '', + `chk_demo` tinyint(1) unsigned DEFAULT '1', + `chk_mdp_manuel` tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT 'Gestion des mots de passe manuelle O/N', + `chk_copie_mail_recu` tinyint(1) unsigned NOT NULL DEFAULT '0', + `chk_accept_sms` tinyint(1) unsigned NOT NULL DEFAULT '0', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `fk_user_creat` int unsigned DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + `fk_user_modif` int unsigned DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + CONSTRAINT `entites_ibfk_1` FOREIGN KEY (`fk_region`) REFERENCES `x_regions` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `entites_ibfk_2` FOREIGN KEY (`fk_type`) REFERENCES `x_entites_types` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `x_villes`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_villes` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_departement` int unsigned DEFAULT '1', + `libelle` varchar(65) DEFAULT NULL, + `cp` varchar(5) DEFAULT NULL, + `code_insee` varchar(5) DEFAULT NULL, + `departement` varchar(65) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`), + CONSTRAINT `x_villes_ibfk_1` FOREIGN KEY (`fk_departement`) REFERENCES `x_departements` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `users`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `users` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_entite` int unsigned DEFAULT '1', + `fk_role` int unsigned DEFAULT '1', + `fk_titre` int unsigned DEFAULT '1', + `encrypted_name` varchar(255) DEFAULT NULL, + `first_name` varchar(45) DEFAULT NULL, + `sect_name` varchar(60) DEFAULT '', + `encrypted_user_name` varchar(128) DEFAULT '', + `user_pass_hash` varchar(60) DEFAULT NULL, + `encrypted_phone` varchar(128) DEFAULT NULL, + `encrypted_mobile` varchar(128) DEFAULT NULL, + `encrypted_email` varchar(255) DEFAULT '', + `chk_alert_email` tinyint(1) unsigned DEFAULT '1', + `chk_suivi` tinyint(1) unsigned DEFAULT '0', + `date_naissance` date DEFAULT NULL, + `date_embauche` date DEFAULT NULL, + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `fk_user_creat` int unsigned DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + `fk_user_modif` int unsigned DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + KEY `fk_entite` (`fk_entite`), + KEY `username` (`encrypted_user_name`), + CONSTRAINT `users_ibfk_1` FOREIGN KEY (`fk_entite`) REFERENCES `entites` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `users_ibfk_2` FOREIGN KEY (`fk_role`) REFERENCES `x_users_roles` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `users_ibfk_3` FOREIGN KEY (`fk_titre`) REFERENCES `x_users_titres` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `operations`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `operations` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_entite` int unsigned NOT NULL DEFAULT '1', + `libelle` varchar(75) NOT NULL DEFAULT '', + `date_deb` date NOT NULL DEFAULT '0000-00-00', + `date_fin` date NOT NULL DEFAULT '0000-00-00', + `chk_distinct_sectors` tinyint(1) unsigned NOT NULL DEFAULT '0', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `fk_user_creat` int unsigned NOT NULL DEFAULT '0', + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + `fk_user_modif` int unsigned NOT NULL DEFAULT '0', + `chk_active` tinyint(1) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + KEY `fk_entite` (`fk_entite`), + KEY `date_deb` (`date_deb`), + CONSTRAINT `operations_ibfk_1` FOREIGN KEY (`fk_entite`) REFERENCES `entites` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + + +DROP TABLE IF EXISTS `ope_sectors`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_sectors` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_operation` int unsigned NOT NULL DEFAULT '0', + `fk_old_sector` int unsigned NOT NULL DEFAULT '0', + `libelle` varchar(75) NOT NULL DEFAULT '', + `sector` text NOT NULL DEFAULT '', + `color` varchar(7) NOT NULL DEFAULT '#4B77BE', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `fk_user_creat` int unsigned NOT NULL DEFAULT '0', + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + `fk_user_modif` int unsigned NOT NULL DEFAULT '0', + `chk_active` tinyint(1) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id` (`id`), + KEY `fk_operation` (`fk_operation`), + CONSTRAINT `ope_sectors_ibfk_1` FOREIGN KEY (`fk_operation`) REFERENCES `operations` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + + +DROP TABLE IF EXISTS `ope_users`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_users` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_operation` int unsigned NOT NULL DEFAULT '0', + `fk_user` int unsigned NOT NULL DEFAULT '0', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `fk_user_creat` int unsigned DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + `fk_user_modif` int unsigned DEFAULT NULL, + `chk_active` tinyint(1) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`), + CONSTRAINT `ope_users_ibfk_1` FOREIGN KEY (`fk_operation`) REFERENCES `operations` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `ope_users_ibfk_2` FOREIGN KEY (`fk_user`) REFERENCES `users` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `email_queue`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `email_queue` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_pass` int unsigned NOT NULL DEFAULT '0', + `to_email` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `subject` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `body` text COLLATE utf8mb4_unicode_ci, + `headers` text COLLATE utf8mb4_unicode_ci, + `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `status` enum('pending','sent','failed') COLLATE utf8mb4_unicode_ci DEFAULT 'pending', + `attempts` int unsigned DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `ope_users_sectors`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_users_sectors` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_operation` int unsigned NOT NULL DEFAULT '0', + `fk_user` int unsigned NOT NULL DEFAULT '0', + `fk_sector` int unsigned NOT NULL DEFAULT '0', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `fk_user_creat` int unsigned NOT NULL DEFAULT '0', + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + `fk_user_modif` int unsigned DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id` (`id`), + KEY `fk_operation` (`fk_operation`), + KEY `fk_user` (`fk_user`), + KEY `fk_sector` (`fk_sector`), + CONSTRAINT `ope_users_sectors_ibfk_1` FOREIGN KEY (`fk_operation`) REFERENCES `operations` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `ope_users_sectors_ibfk_2` FOREIGN KEY (`fk_user`) REFERENCES `users` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `ope_users_sectors_ibfk_3` FOREIGN KEY (`fk_sector`) REFERENCES `ope_sectors` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `ope_users_suivis`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_users_suivis` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_operation` int unsigned NOT NULL DEFAULT '0', + `fk_user` int unsigned NOT NULL DEFAULT '0', + `date_suivi` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date du suivi', + `gps_lat` varchar(20) NOT NULL DEFAULT '', + `gps_lng` varchar(20) NOT NULL DEFAULT '', + `vitesse` varchar(20) NOT NULL DEFAULT '', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `fk_user_creat` int unsigned NOT NULL DEFAULT '0', + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + `fk_user_modif` int unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `sectors_adresses`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `sectors_adresses` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_adresse` varchar(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'adresses.cp??.id', + `osm_id` int unsigned NOT NULL DEFAULT '0', + `fk_sector` int unsigned NOT NULL DEFAULT '0', + `osm_name` varchar(50) NOT NULL DEFAULT '', + `numero` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `rue_bis` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `rue` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `cp` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `ville` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `gps_lat` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `gps_lng` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `osm_date_creat` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + PRIMARY KEY (`id`), + KEY `sectors_adresses_fk_sector_index` (`fk_sector`), + KEY `sectors_adresses_numero_index` (`numero`), + KEY `sectors_adresses_rue_index` (`rue`), + KEY `sectors_adresses_ville_index` (`ville`), + CONSTRAINT `sectors_adresses_ibfk_1` FOREIGN KEY (`fk_sector`) REFERENCES `ope_sectors` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +DROP TABLE IF EXISTS `ope_pass`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_pass` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_operation` int unsigned NOT NULL DEFAULT '0', + `fk_sector` int unsigned DEFAULT '0', + `fk_user` int unsigned NOT NULL DEFAULT '0', + `fk_adresse` varchar(25) DEFAULT '' COMMENT 'adresses.cp??.id', + `passed_at` timestamp NULL DEFAULT NULL COMMENT 'Date du passage', + `fk_type` int unsigned DEFAULT '0', + `numero` varchar(10) NOT NULL DEFAULT '', + `rue` varchar(75) NOT NULL DEFAULT '', + `rue_bis` varchar(1) NOT NULL DEFAULT '', + `ville` varchar(75) NOT NULL DEFAULT '', + `fk_habitat` int unsigned DEFAULT '1', + `appt` varchar(5) DEFAULT '', + `niveau` varchar(5) DEFAULT '', + `residence` varchar(75) DEFAULT '', + `gps_lat` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `gps_lng` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `encrypted_name` varchar(255) NOT NULL DEFAULT '', + `montant` decimal(7,2) NOT NULL DEFAULT '0.00', + `fk_type_reglement` int unsigned DEFAULT '1', + `remarque` text DEFAULT '', + `encrypted_email` varchar(255) DEFAULT '', + `nom_recu` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `date_recu` timestamp NULL DEFAULT NULL COMMENT 'Date de réception', + `date_creat_recu` timestamp NULL DEFAULT NULL COMMENT 'Date de création du reçu', + `date_sent_recu` timestamp NULL DEFAULT NULL COMMENT 'Date envoi du reçu', + `email_erreur` varchar(30) DEFAULT '', + `chk_email_sent` tinyint(1) unsigned NOT NULL DEFAULT '0', + `encrypted_phone` varchar(128) NOT NULL DEFAULT '', + `chk_striped` tinyint(1) unsigned DEFAULT '0', + `docremis` tinyint(1) unsigned DEFAULT '0', + `date_repasser` timestamp NULL DEFAULT NULL COMMENT 'Date prévue pour repasser', + `nb_passages` int DEFAULT '1' COMMENT 'Nb passages pour les a repasser', + `chk_gps_maj` tinyint(1) unsigned DEFAULT '0', + `chk_map_create` tinyint(1) unsigned DEFAULT '0', + `chk_mobile` tinyint(1) unsigned DEFAULT '0', + `chk_synchro` tinyint(1) unsigned DEFAULT '1' COMMENT 'chk synchro entre web et appli', + `chk_api_adresse` tinyint(1) unsigned DEFAULT '0', + `chk_maj_adresse` tinyint(1) unsigned DEFAULT '0', + `anomalie` tinyint(1) unsigned DEFAULT '0', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `fk_user_creat` int unsigned DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + `fk_user_modif` int unsigned DEFAULT NULL, + `chk_active` tinyint(1) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + KEY `fk_operation` (`fk_operation`), + KEY `fk_sector` (`fk_sector`), + KEY `fk_user` (`fk_user`), + KEY `fk_type` (`fk_type`), + KEY `fk_type_reglement` (`fk_type_reglement`), + KEY `email` (`email`), + CONSTRAINT `ope_pass_ibfk_1` FOREIGN KEY (`fk_operation`) REFERENCES `operations` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `ope_pass_ibfk_2` FOREIGN KEY (`fk_sector`) REFERENCES `ope_sectors` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `ope_pass_ibfk_3` FOREIGN KEY (`fk_user`) REFERENCES `users` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `ope_pass_ibfk_4` FOREIGN KEY (`fk_type_reglement`) REFERENCES `x_types_reglements` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `ope_pass_histo`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_pass_histo` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_pass` int unsigned NOT NULL DEFAULT '0', + `date_histo` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date historique', + `sujet` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `remarque` varchar(250) NOT NULL DEFAULT '', + PRIMARY KEY (`id`), + KEY `ope_pass_histo_fk_pass_IDX` (`fk_pass`) USING BTREE, + KEY `ope_pass_histo_date_histo_IDX` (`date_histo`) USING BTREE, + CONSTRAINT `ope_pass_histo_ibfk_1` FOREIGN KEY (`fk_pass`) REFERENCES `ope_pass` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `medias`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `medias` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `support` varchar(45) NOT NULL DEFAULT '', + `support_id` int unsigned NOT NULL DEFAULT '0', + `fichier` varchar(250) NOT NULL DEFAULT '', + `description` varchar(100) NOT NULL DEFAULT '', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `fk_user_creat` int unsigned NOT NULL DEFAULT '0', + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, + `fk_user_modif` int unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- Création des tables pour le système de chat +DROP TABLE IF EXISTS `chat_rooms`; +-- Table des salles de discussion +CREATE TABLE chat_rooms ( + id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(100) NOT NULL, + type ENUM('privee', 'groupe', 'liste_diffusion') NOT NULL, + date_creation timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + fk_user INT UNSIGNED NOT NULL, + fk_entite INT UNSIGNED, + statut ENUM('active', 'archive') NOT NULL DEFAULT 'active', + description TEXT, + INDEX idx_user (fk_user), + INDEX idx_entite (fk_entite) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + + +DROP TABLE IF EXISTS `chat_participants`; +-- Table des participants aux salles de discussion +CREATE TABLE chat_participants ( + id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + id_room INT UNSIGNED NOT NULL, + id_user INT UNSIGNED NOT NULL, + role ENUM('administrateur', 'participant', 'en_lecture_seule') NOT NULL DEFAULT 'participant', + date_ajout timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date ajout', + notification_activee BOOLEAN NOT NULL DEFAULT TRUE, + INDEX idx_room (id_room), + INDEX idx_user (id_user), + CONSTRAINT uc_room_user UNIQUE (id_room, id_user), + FOREIGN KEY (id_room) REFERENCES chat_rooms(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +DROP TABLE IF EXISTS `chat_messages`; +-- Table des messages +CREATE TABLE chat_messages ( + id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + fk_room INT UNSIGNED NOT NULL, + fk_user INT UNSIGNED NOT NULL, + content TEXT, + date_sent timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date envoi', + type ENUM('texte', 'media', 'systeme') NOT NULL DEFAULT 'texte', + statut ENUM('envoye', 'livre', 'lu') NOT NULL DEFAULT 'envoye', + INDEX idx_room (fk_room), + INDEX idx_user (fk_user), + INDEX idx_date (date_sent), + FOREIGN KEY (fk_room) REFERENCES chat_rooms(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +DROP TABLE IF EXISTS `chat_listes_diffusion`; +-- Table des listes de diffusion +CREATE TABLE chat_listes_diffusion ( + id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + fk_room INT UNSIGNED NOT NULL, + name VARCHAR(100) NOT NULL, + description TEXT, + fk_user INT UNSIGNED NOT NULL, + date_creation timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + INDEX idx_room (fk_room), + INDEX idx_user (fk_user), + FOREIGN KEY (fk_room) REFERENCES chat_rooms(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +DROP TABLE IF EXISTS `chat_read_messages`; +-- Table pour suivre la lecture des messages +CREATE TABLE chat_read_messages ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + fk_message INT UNSIGNED NOT NULL, + fk_user INT UNSIGNED NOT NULL, + date_read timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de lecture', + INDEX idx_message (fk_message), + INDEX idx_user (fk_user), + CONSTRAINT uc_message_user UNIQUE (fk_message, fk_user), + FOREIGN KEY (fk_message) REFERENCES chat_messages(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +DROP TABLE IF EXISTS `chat_notifications`; +-- Table des notifications +CREATE TABLE chat_notifications ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + fk_user INT UNSIGNED NOT NULL, + fk_message INT UNSIGNED, + fk_room INT UNSIGNED, + type VARCHAR(50) NOT NULL, + contenu TEXT, + date_creation timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + date_lecture timestamp NULL DEFAULT NULL COMMENT 'Date de lecture', + statut ENUM('non_lue', 'lue') NOT NULL DEFAULT 'non_lue', + INDEX idx_user (fk_user), + INDEX idx_message (fk_message), + INDEX idx_room (fk_room), + FOREIGN KEY (fk_message) REFERENCES chat_messages(id) ON DELETE SET NULL, + FOREIGN KEY (fk_room) REFERENCES chat_rooms(id) ON DELETE SET NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +DROP TABLE IF EXISTS `z_params`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `params` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `libelle` varchar(35) NOT NULL DEFAULT '', + `valeur` varchar(255) NOT NULL DEFAULT '', + `aide` varchar(150) NOT NULL DEFAULT '', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + + +DROP TABLE IF EXISTS `z_sessions`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `z_sessions` ( + `sid` text NOT NULL, + `fk_user` int NOT NULL, + `role` varchar(10) DEFAULT NULL, + `date_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `ip` varchar(50) NOT NULL, + `browser` varchar(150) NOT NULL, + `data` mediumtext +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; diff --git a/api/index.php b/api/index.php new file mode 100644 index 00000000..e0a2828e --- /dev/null +++ b/api/index.php @@ -0,0 +1,54 @@ +getFullConfig(); + +// Initialiser la base de données +Database::init($config['database']); + +// Configuration CORS +$origin = $_SERVER['HTTP_ORIGIN'] ?? ''; +$allowedOrigins = $config['api']['allowed_origins']; + +// Vérifier si l'origine est autorisée +if (in_array($origin, $allowedOrigins)) { + header('Access-Control-Allow-Origin: ' . $origin); + header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); + header('Access-Control-Allow-Headers: Content-Type, Authorization, X-App-Identifier'); + header('Access-Control-Allow-Credentials: true'); +} + +// Gestion des requêtes preflight (OPTIONS) +if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { + exit(0); +} + +// Initialiser la session +Session::start(); + +// Créer l'instance de routeur +$router = new Router(); + +// Gérer la requête +$router->handle(); diff --git a/api/livre-api.sh b/api/livre-api.sh new file mode 100755 index 00000000..7a2775ae --- /dev/null +++ b/api/livre-api.sh @@ -0,0 +1,144 @@ +#!/bin/bash + +# Vérification des arguments +if [ $# -ne 2 ]; then + echo "Usage: $0 " + echo "Example: $0 dva-geo rca-geo" + exit 1 +fi + +HOST_IP="195.154.80.116" +HOST_USER=root +HOST_KEY=/Users/pierre/.ssh/id_rsa_mbpi +HOST_PORT=22 + +SOURCE_CONTAINER=$1 +DEST_CONTAINER=$2 +API_PATH="/var/www/geosector/api" +TIMESTAMP=$(date +"%Y%m%d_%H%M%S") +BACKUP_DIR="${API_PATH}_backup_${TIMESTAMP}" +PROJECT="default" + +echo "🔄 Copie de l'API de $SOURCE_CONTAINER vers $DEST_CONTAINER (projet: $PROJECT)" + +# Vérifier si les containers existent +echo "🔍 Vérification des containers..." +ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus info $SOURCE_CONTAINER --project $PROJECT" > /dev/null 2>&1 +if [ $? -ne 0 ]; then + echo "❌ Erreur: Le container source $SOURCE_CONTAINER n'existe pas ou n'est pas accessible dans le projet $PROJECT" + exit 1 +fi + +ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus info $DEST_CONTAINER --project $PROJECT" > /dev/null 2>&1 +if [ $? -ne 0 ]; then + echo "❌ Erreur: Le container destination $DEST_CONTAINER n'existe pas ou n'est pas accessible dans le projet $PROJECT" + exit 1 +fi + +# Créer une sauvegarde du dossier de destination avant de le remplacer +echo "📦 Création d'une sauvegarde sur $DEST_CONTAINER..." +# Vérifier si le dossier API existe +ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- test -d $API_PATH" +if [ $? -eq 0 ]; then + # Le dossier existe, créer une sauvegarde + ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- cp -r $API_PATH $BACKUP_DIR" + echo "✅ Sauvegarde créée dans $BACKUP_DIR" +else + echo "⚠️ Le dossier API n'existe pas sur la destination" +fi + +# Sauvegarder spécifiquement le dossier logs +echo "📋 Sauvegarde du dossier logs..." +# Vérifier si le dossier logs existe +ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- test -d $API_PATH/logs" +if [ $? -eq 0 ]; then + # Le dossier logs existe, le sauvegarder + ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- mkdir -p /tmp/geosector_logs_backup" + ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- cp -r $API_PATH/logs /tmp/geosector_logs_backup/" + echo "✅ Dossier logs sauvegardé temporairement" +else + echo "⚠️ Le dossier logs n'existe pas sur la destination" +fi + +# Copier le dossier API entre les containers +echo "📋 Copie des fichiers en cours..." + +# Approche directe: utiliser incus copy pour copier directement entre containers +echo "📤 Transfert direct entre containers..." +# Nettoyer le dossier de destination +ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- rm -rf $API_PATH" +ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- mkdir -p $API_PATH" + +# Copier directement du container source vers le container destination +ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $SOURCE_CONTAINER --project $PROJECT -- tar -cf - -C $API_PATH . | incus exec $DEST_CONTAINER --project $PROJECT -- tar -xf - -C $API_PATH" +if [ $? -ne 0 ]; then + echo "❌ Erreur lors du transfert direct entre containers" + echo "⚠️ Tentative de restauration de la sauvegarde..." + # Vérifier si la sauvegarde existe + ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- test -d $BACKUP_DIR" + if [ $? -eq 0 ]; then + # La sauvegarde existe, la restaurer + ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- cp -r $BACKUP_DIR $API_PATH" + echo "✅ Restauration réussie" + else + echo "❌ Échec de la restauration" + fi + exit 1 +fi + +# Pas de fichiers temporaires à nettoyer avec cette approche + +# Restaurer le dossier logs +echo "📋 Restauration du dossier logs..." +# Vérifier si la sauvegarde des logs existe +ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- test -d /tmp/geosector_logs_backup/logs" +if [ $? -eq 0 ]; then + # La sauvegarde des logs existe, la restaurer + ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- mkdir -p $API_PATH/logs" + ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- cp -r /tmp/geosector_logs_backup/logs/* $API_PATH/logs/" + ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- rm -rf /tmp/geosector_logs_backup" + echo "✅ Dossier logs restauré" +else + echo "⚠️ Aucune sauvegarde de logs à restaurer" +fi + +# Changer le propriétaire et les permissions des fichiers +echo "👤 Application des droits et permissions pour tous les fichiers..." + +# Définir le propriétaire pour tous les fichiers +ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- chown -R nginx:nginx $API_PATH" + +# Appliquer les permissions de base pour les dossiers (755) +ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- find $API_PATH -type d -exec chmod 755 {} \;" + +# Appliquer les permissions pour les fichiers (644) +ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- find $API_PATH -type f -exec chmod 644 {} \;" + +# Appliquer des permissions spécifiques pour le dossier logs (pour permettre à PHP-FPM de l'utilisateur nobody d'y écrire) +ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- test -d $API_PATH/logs" +if [ $? -eq 0 ]; then + # Changer le groupe du dossier logs à nobody (utilisateur PHP-FPM) + ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- chown -R nginx:nobody $API_PATH/logs" + # Appliquer les permissions 775 pour le dossier + ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- chmod -R 775 $API_PATH/logs" + # Appliquer les permissions 664 pour les fichiers + ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- find $API_PATH/logs -type f -exec chmod 664 {} \;" + echo "✅ Droits spécifiques appliqués au dossier logs (nginx:nobody avec permissions 775/664)" +else + echo "⚠️ Le dossier logs n'existe pas" +fi + +echo "✅ Propriétaire et permissions appliqués avec succès" + +# Vérifier la copie +echo "✅ Vérification de la copie..." +ssh -i $HOST_KEY -p $HOST_PORT $HOST_USER@$HOST_IP "incus exec $DEST_CONTAINER --project $PROJECT -- test -d $API_PATH" +if [ $? -eq 0 ]; then + echo "✅ Copie réussie" +else + echo "❌ Erreur: Le dossier API n'a pas été copié correctement" +fi + +echo "✅ Opération terminée! L'API a été copiée de $SOURCE_CONTAINER vers $DEST_CONTAINER" +echo "📁 Une sauvegarde a été créée dans $BACKUP_DIR sur $DEST_CONTAINER" +echo "👤 Les fichiers appartiennent maintenant à l'utilisateur nginx" diff --git a/api/scripts/README.md b/api/scripts/README.md new file mode 100644 index 00000000..3c3de3bc --- /dev/null +++ b/api/scripts/README.md @@ -0,0 +1,66 @@ +# Scripts Utilitaires + +Ce dossier contient des scripts utilitaires pour la gestion des bases de données et l'automatisation de tâches. + +## Structure + +- `php/` : Scripts PHP pour la manipulation des données et l'intégration avec l'API +- `shell/` : Scripts shell pour l'automatisation et les opérations système +- `python/` : Scripts Python pour le traitement des données et l'analyse +- `cron/` : Scripts et configurations pour les tâches programmées + +## Migration geosector → geosector_app + +Les scripts de migration permettent de transférer des données de la base MySQL geosector (sur un serveur distant) vers la base MariaDB geosector_app (locale). + +### Prérequis + +- Accès SSH au serveur distant hébergeant la base MySQL geosector +- Accès à la base de données MariaDB geosector_app locale +- Droits suffisants pour lire/écrire dans les deux bases +- Clé SSH pour l'authentification au serveur distant + +### Utilisation + +1. Configurer les paramètres de connexion dans le fichier `config.php` : + - Paramètres SSH (serveur, port, utilisateur, clé) + - Paramètres de la base de données source (distante) + - Paramètres de la base de données cible (locale) + +2. Exécuter le script de migration souhaité : + ``` + php php/migrate_users.php + ``` + ou + ``` + ./shell/migrate_table.sh users + ``` + +3. Pour comparer les schémas de tables entre les deux bases : + ``` + python python/compare_schemas.py users + ``` + ./bash/migrate_table.sh users + ``` + +## Tâches programmées (cron) + +Les scripts dans le dossier `cron/` peuvent être configurés pour s'exécuter automatiquement via crontab. + +Exemple de configuration crontab pour exécuter la synchronisation quotidienne : + +``` +# Synchronisation quotidienne à 2h du matin +0 2 * * * php /chemin/vers/api/scripts/cron/sync_databases.php > /dev/null 2>&1 +``` + +## Fonctionnement du tunnel SSH + +Les scripts établissent automatiquement un tunnel SSH pour accéder à la base de données distante : + +1. Vérification de l'existence d'un tunnel déjà établi +2. Création d'un tunnel SSH si nécessaire +3. Exécution des opérations de base de données via le tunnel +4. Fermeture propre du tunnel à la fin du script + +Les tunnels utilisent un port local (par défaut 13306) pour rediriger vers le port MySQL du serveur distant. diff --git a/api/scripts/config.php b/api/scripts/config.php new file mode 100644 index 00000000..c7bb7038 --- /dev/null +++ b/api/scripts/config.php @@ -0,0 +1,168 @@ +/dev/null"; + exec($command); + logOperation("Tunnel SSH fermé", "INFO"); +} + +/** + * Fonction utilitaire pour se connecter à la base de données source via SSH + */ +function getSourceConnection() { + try { + // Établir le tunnel SSH + if (!createSshTunnel()) { + throw new PDOException("Impossible d'établir le tunnel SSH"); + } + + // Options de connexion PDO + $options = [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4' + ]; + + // Ajouter l'option pour MySQL 8 + if (defined('PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT')) { + $options[PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT] = false; + } + + try { + // D'abord vérifier si la base existe + $tempDsn = 'mysql:host=' . SOURCE_DB_HOST . ';port=' . SOURCE_DB_PORT; + $tempPdo = new PDO($tempDsn, SOURCE_DB_USER, SOURCE_DB_PASS, $options); + + $stmt = $tempPdo->query("SHOW DATABASES"); + $databases = $stmt->fetchAll(PDO::FETCH_COLUMN); + + if (!in_array(SOURCE_DB_NAME, $databases)) { + logOperation("Base de données '" . SOURCE_DB_NAME . "' introuvable. Bases disponibles: " . implode(", ", $databases), "ERROR"); + throw new PDOException("Base de données '" . SOURCE_DB_NAME . "' introuvable"); + } + + // Se connecter à la base spécifique + $dsn = 'mysql:host=' . SOURCE_DB_HOST . ';dbname=' . SOURCE_DB_NAME . ';port=' . SOURCE_DB_PORT; + $pdo = new PDO($dsn, SOURCE_DB_USER, SOURCE_DB_PASS, $options); + + logOperation("Connexion établie à la base '" . SOURCE_DB_NAME . "'", "INFO"); + return $pdo; + } catch (PDOException $e) { + logOperation("Erreur de connexion: " . $e->getMessage(), "ERROR"); + throw $e; + } + } catch (PDOException $e) { + closeSshTunnel(); + throw new Exception("Erreur de connexion à la base source: " . $e->getMessage()); + } +} + +/** + * Fonction utilitaire pour se connecter à la base de données cible + */ +function getTargetConnection() { + try { + $dsn = 'mysql:host=' . TARGET_DB_HOST . ';dbname=' . TARGET_DB_NAME . ';port=' . TARGET_DB_PORT; + $pdo = new PDO($dsn, TARGET_DB_USER, TARGET_DB_PASS, [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4' + ]); + return $pdo; + } catch (PDOException $e) { + die('Erreur de connexion à la base cible: ' . $e->getMessage()); + } +} + +/** + * Fonction pour journaliser les opérations + */ +function logOperation($message, $level = 'INFO') { + $logFile = __DIR__ . '/logs/migration_' . date('Y-m-d') . '.log'; + $logDir = dirname($logFile); + + if (!is_dir($logDir)) { + mkdir($logDir, 0755, true); + } + + $timestamp = date('Y-m-d H:i:s'); + $logMessage = "[$timestamp] [$level] $message" . PHP_EOL; + file_put_contents($logFile, $logMessage, FILE_APPEND); + + if (php_sapi_name() === 'cli') { + echo $logMessage; + } +} diff --git a/api/scripts/cron/sync_databases.php b/api/scripts/cron/sync_databases.php new file mode 100644 index 00000000..e9749f54 --- /dev/null +++ b/api/scripts/cron/sync_databases.php @@ -0,0 +1,102 @@ + /dev/null 2>&1 + */ + +// Définir le chemin d'accès au script +define('SCRIPT_PATH', __DIR__); +define('BASE_PATH', dirname(dirname(__DIR__))); + +// Inclure le fichier de configuration +require_once dirname(__DIR__) . '/config.php'; + +// Liste des tables à synchroniser +$tables_to_sync = [ + 'users' => [ + 'sync_method' => 'php', // Utilise le script PHP spécifique pour cette table + 'script' => dirname(__DIR__) . '/php/migrate_users.php' + ], + 'settings' => [ + 'sync_method' => 'shell', // Utilise le script shell générique + 'script' => dirname(__DIR__) . '/shell/migrate_table.sh' + ], + // Ajouter d'autres tables selon les besoins +]; + +// Fonction pour exécuter un script PHP +function executePhpScript($script_path) { + logOperation("Exécution du script PHP: $script_path"); + include $script_path; + return true; +} + +// Fonction pour exécuter un script shell +function executeShellScript($script_path, $table_name) { + logOperation("Exécution du script shell: $script_path $table_name"); + $command = "bash $script_path $table_name"; + $output = []; + $return_var = 0; + exec($command, $output, $return_var); + + foreach ($output as $line) { + logOperation($line); + } + + return $return_var === 0; +} + +// Démarrage de la synchronisation +logOperation("Démarrage de la synchronisation des bases de données"); +logOperation("Date: " . date('Y-m-d H:i:s')); + +$success_count = 0; +$error_count = 0; + +// Synchroniser chaque table +foreach ($tables_to_sync as $table_name => $config) { + logOperation("Synchronisation de la table: $table_name"); + + try { + $success = false; + + switch ($config['sync_method']) { + case 'php': + $success = executePhpScript($config['script']); + break; + + case 'shell': + $success = executeShellScript($config['script'], $table_name); + break; + + default: + logOperation("Méthode de synchronisation non prise en charge: {$config['sync_method']}", "ERROR"); + $error_count++; + continue; + } + + if ($success) { + logOperation("Synchronisation réussie pour la table: $table_name", "SUCCESS"); + $success_count++; + } else { + logOperation("Échec de la synchronisation pour la table: $table_name", "ERROR"); + $error_count++; + } + } catch (Exception $e) { + logOperation("Erreur lors de la synchronisation de la table $table_name: " . $e->getMessage(), "ERROR"); + $error_count++; + } +} + +// Résumé de la synchronisation +logOperation("Synchronisation terminée"); +logOperation("Succès: $success_count, Erreurs: $error_count"); +logOperation("Date de fin: " . date('Y-m-d H:i:s')); + +// Sortie avec code d'erreur si nécessaire +exit($error_count > 0 ? 1 : 0); diff --git a/api/scripts/geosector.sql b/api/scripts/geosector.sql new file mode 100644 index 00000000..35bca929 --- /dev/null +++ b/api/scripts/geosector.sql @@ -0,0 +1,987 @@ + +-- Table structure for table `email_counter` +-- + +DROP TABLE IF EXISTS `email_counter`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `email_counter` ( + `id` int NOT NULL DEFAULT '1', + `hour_start` timestamp NULL DEFAULT NULL, + `count` int DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `email_queue` +-- + +DROP TABLE IF EXISTS `email_queue`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `email_queue` ( + `id` int NOT NULL AUTO_INCREMENT, + `rowid` int NOT NULL DEFAULT '0' COMMENT 'ope_pass.rowid', + `to_email` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL, + `subject` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL, + `body` text COLLATE utf8mb4_general_ci, + `headers` text COLLATE utf8mb4_general_ci, + `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `status` enum('pending','sent','failed') COLLATE utf8mb4_general_ci DEFAULT 'pending', + `attempts` int DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=40956 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `medias` +-- + +DROP TABLE IF EXISTS `medias`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `medias` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `dir0` varchar(75) NOT NULL DEFAULT '', + `dir1` varchar(150) NOT NULL DEFAULT '', + `dir2` varchar(45) NOT NULL DEFAULT '', + `support` varchar(45) NOT NULL DEFAULT '', + `support_rowid` int NOT NULL DEFAULT '0', + `fichier` varchar(250) NOT NULL DEFAULT '', + `type_fichier` varchar(5) NOT NULL DEFAULT 'pdf', + `description` varchar(100) NOT NULL DEFAULT '', + `position` char(1) NOT NULL DEFAULT 'd', + `hauteur` int NOT NULL DEFAULT '0', + `largeur` int NOT NULL DEFAULT '0', + `niveaugris` tinyint(1) NOT NULL DEFAULT '0', + `date_creat` datetime DEFAULT NULL, + `fk_user_creat` int NOT NULL DEFAULT '0', + `date_modif` datetime DEFAULT NULL, + `fk_user_modif` int NOT NULL DEFAULT '0', + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=327 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ope_pass` +-- + +DROP TABLE IF EXISTS `ope_pass`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_pass` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `fk_operation` int NOT NULL DEFAULT '0', + `fk_sector` int DEFAULT '0', + `fk_user` int NOT NULL DEFAULT '0', + `fk_adresse` varchar(25) DEFAULT '' COMMENT 'adresses.cp??.id', + `date_eve` datetime DEFAULT NULL, + `fk_type` int DEFAULT '0', + `numero` varchar(10) NOT NULL DEFAULT '', + `rue` varchar(75) NOT NULL DEFAULT '', + `rue_bis` varchar(1) NOT NULL DEFAULT '', + `ville` varchar(75) NOT NULL DEFAULT '', + `lieudit` varchar(75) DEFAULT '', + `fk_habitat` int DEFAULT '1', + `appt` varchar(5) DEFAULT NULL, + `niveau` varchar(5) DEFAULT NULL, + `chk_habitat_vide` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'habitat vide (refus)', + `gps_lat` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '', + `gps_lng` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '', + `libelle` varchar(45) NOT NULL DEFAULT '', + `montant` decimal(7,2) NOT NULL DEFAULT '0.00', + `fk_type_reglement` int DEFAULT '1', + `remarque` text, + `recu` varchar(50) DEFAULT NULL, + `email` varchar(75) DEFAULT '', + `email_erreur` varchar(30) DEFAULT '', + `chk_email_sent` tinyint(1) NOT NULL DEFAULT '0', + `phone` varchar(15) NOT NULL DEFAULT '', + `docremis` tinyint(1) DEFAULT '0', + `date_repasser` datetime DEFAULT NULL, + `nb_passages` int DEFAULT '1' COMMENT 'Nb passages pour les a repasser', + `lot_nb_passages` int DEFAULT '1' COMMENT 'Saisie par lot de passages dans la partie mobile', + `chk_gps_maj` tinyint(1) DEFAULT '0', + `chk_map_create` tinyint(1) DEFAULT '0', + `chk_mobile` tinyint(1) DEFAULT '0', + `chk_synchro` tinyint(1) DEFAULT '1' COMMENT 'chk synchro entre web et appli', + `chk_api_adresse` tinyint(1) DEFAULT '0', + `chk_maj_adresse` tinyint(1) DEFAULT '0', + `anomalie` tinyint(1) DEFAULT '0', + `date_creat` datetime DEFAULT NULL, + `fk_user_creat` int DEFAULT NULL, + `date_modif` datetime DEFAULT NULL, + `fk_user_modif` int DEFAULT NULL, + `active` tinyint(1) NOT NULL DEFAULT '1', + PRIMARY KEY (`rowid`), + KEY `fk_operation` (`fk_operation`), + KEY `fk_sector` (`fk_sector`), + KEY `fk_user` (`fk_user`), + KEY `fk_type` (`fk_type`), + KEY `fk_type_reglement` (`fk_type_reglement`), + KEY `email` (`email`) +) ENGINE=InnoDB AUTO_INCREMENT=8367890 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ope_pass_histo` +-- + +DROP TABLE IF EXISTS `ope_pass_histo`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_pass_histo` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `fk_pass` int DEFAULT NULL, + `fk_user` int DEFAULT NULL, + `date_histo` datetime DEFAULT NULL, + `sujet` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, + `remarque` varchar(250) DEFAULT NULL, + PRIMARY KEY (`rowid`), + KEY `ope_pass_histo_fk_pass_IDX` (`fk_pass`) USING BTREE, + KEY `ope_pass_histo_date_histo_IDX` (`date_histo`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=44274 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ope_pass_recus` +-- + +DROP TABLE IF EXISTS `ope_pass_recus`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_pass_recus` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `fk_pass` int DEFAULT NULL, + `chemin` varchar(100) COLLATE utf8mb4_general_ci DEFAULT NULL, + `nom_recu` varchar(50) COLLATE utf8mb4_general_ci DEFAULT NULL, + `date_recu` datetime DEFAULT NULL, + `date_creat_recu` datetime DEFAULT NULL, + `date_sent_recu` datetime DEFAULT NULL, + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`), + KEY `ope_pass_recus_fk_pass_IDX` (`fk_pass`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=140644 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ope_users` +-- + +DROP TABLE IF EXISTS `ope_users`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_users` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `fk_operation` int NOT NULL DEFAULT '0', + `fk_user` int NOT NULL DEFAULT '0', + `date_creat` datetime DEFAULT NULL, + `fk_user_creat` int DEFAULT NULL, + `date_modif` datetime DEFAULT NULL, + `fk_user_modif` int DEFAULT NULL, + `active` tinyint(1) NOT NULL DEFAULT '1', + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=199006 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ope_users_sectors` +-- + +DROP TABLE IF EXISTS `ope_users_sectors`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_users_sectors` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `fk_operation` int DEFAULT NULL, + `fk_user` int DEFAULT NULL, + `fk_sector` int DEFAULT NULL, + `active` tinyint(1) DEFAULT '1', + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid` (`rowid`), + KEY `fk_operation` (`fk_operation`), + KEY `fk_user` (`fk_user`), + KEY `fk_sector` (`fk_sector`) +) ENGINE=InnoDB AUTO_INCREMENT=174364 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ope_users_suivis` +-- + +DROP TABLE IF EXISTS `ope_users_suivis`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_users_suivis` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `fk_operation` int DEFAULT NULL, + `fk_user` int DEFAULT NULL, + `date_suivi` datetime DEFAULT NULL, + `latitude` varchar(20) DEFAULT NULL, + `longitude` varchar(20) DEFAULT NULL, + `vitesse` varchar(20) DEFAULT NULL, + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=2820230 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `operations` +-- + +DROP TABLE IF EXISTS `operations`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `operations` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `fk_entite` int DEFAULT '1', + `libelle` varchar(75) NOT NULL DEFAULT '', + `date_deb` date DEFAULT NULL, + `date_fin` date DEFAULT NULL, + `chk_api_adresse` tinyint(1) DEFAULT '0', + `chk_distinct_sectors` tinyint(1) DEFAULT '0', + `date_creat` datetime DEFAULT NULL, + `fk_user_creat` int DEFAULT NULL, + `date_modif` datetime DEFAULT NULL, + `fk_user_modif` int DEFAULT NULL, + `active` tinyint(1) DEFAULT '1', + PRIMARY KEY (`rowid`), + KEY `fk_entite` (`fk_entite`), + KEY `date_deb` (`date_deb`) +) ENGINE=InnoDB AUTO_INCREMENT=3121 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `operations_docs` +-- + +DROP TABLE IF EXISTS `operations_docs`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `operations_docs` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `fk_operation` int NOT NULL DEFAULT '0', + `libelle` varchar(75) NOT NULL DEFAULT '', + `comment` text NOT NULL, + `active` tinyint(1) NOT NULL DEFAULT '1', + PRIMARY KEY (`rowid`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `operations_eve_docs` +-- + +DROP TABLE IF EXISTS `operations_eve_docs`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `operations_eve_docs` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `fk_evenement` int NOT NULL DEFAULT '0', + `fk_document` int NOT NULL DEFAULT '0', + `date_creat` datetime DEFAULT NULL, + `fk_user_creat` int DEFAULT NULL, + `date_modif` datetime DEFAULT NULL, + `fk_user_modif` int DEFAULT NULL, + `active` tinyint(1) DEFAULT '1', + PRIMARY KEY (`rowid`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `params` +-- + +DROP TABLE IF EXISTS `params`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `params` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `libelle` varchar(35) NOT NULL DEFAULT '', + `valeur` varchar(255) NOT NULL DEFAULT '', + `aide` varchar(150) NOT NULL DEFAULT '', + PRIMARY KEY (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `sectors` +-- + +DROP TABLE IF EXISTS `sectors`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `sectors` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `libelle` varchar(75) DEFAULT '', + `sector` text, + `color` varchar(7) DEFAULT '#4B77BE', + `date_creat` datetime DEFAULT NULL, + `fk_user_creat` int DEFAULT NULL, + `date_modif` datetime DEFAULT NULL, + `fk_user_modif` int DEFAULT NULL, + `active` tinyint(1) DEFAULT '1', + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=34349 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `sectors_adresses` +-- + +DROP TABLE IF EXISTS `sectors_adresses`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `sectors_adresses` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `fk_adresse` varchar(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'adresses.cp??.id', + `fk_sector` int DEFAULT NULL, + `numero` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, + `rue_bis` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, + `rue` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, + `cp` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, + `ville` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, + `gps_lat` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, + `gps_lng` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, + PRIMARY KEY (`rowid`), + KEY `sectors_adresses_fk_sector_index` (`fk_sector`), + KEY `sectors_adresses_numero_index` (`numero`), + KEY `sectors_adresses_rue_index` (`rue`), + KEY `sectors_adresses_ville_index` (`ville`) +) ENGINE=InnoDB AUTO_INCREMENT=24697907 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `sectors_streets` +-- + +DROP TABLE IF EXISTS `sectors_streets`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `sectors_streets` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `fk_sector` int DEFAULT NULL, + `fk_adresse` varchar(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' COMMENT 'adresses.cp??.id', + `osm_id` int DEFAULT NULL, + `osm_lat` varchar(10) DEFAULT NULL, + `osm_lng` varchar(10) DEFAULT NULL, + `osm_name` varchar(50) DEFAULT NULL, + `osm_street` varchar(50) DEFAULT NULL, + `osm_number` varchar(10) DEFAULT NULL, + `osm_city` varchar(50) DEFAULT NULL, + `osm_date_creat` timestamp NULL DEFAULT NULL, + `date_creat` datetime DEFAULT NULL, + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`), + KEY `fk_sector` (`fk_sector`), + KEY `osm_lat` (`osm_lat`), + KEY `osm_lng` (`osm_lng`), + KEY `osm_name` (`osm_name`), + KEY `osm_city` (`osm_city`), + KEY `osm_street` (`osm_street`) +) ENGINE=InnoDB AUTO_INCREMENT=42344357 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `users` +-- + +DROP TABLE IF EXISTS `users`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `users` ( + `rowid` int unsigned NOT NULL AUTO_INCREMENT, + `fk_entite` int DEFAULT '1', + `fk_titre` int DEFAULT '1', + `num_adherent` int NOT NULL DEFAULT '0', + `libelle` varchar(91) DEFAULT NULL, + `libelle_naissance` varchar(90) NOT NULL DEFAULT '', + `prenom` varchar(45) DEFAULT NULL, + `nom_tournee` varchar(60) DEFAULT '', + `username` varchar(50) DEFAULT '', + `userpass` varchar(60) DEFAULT NULL, + `userpswd` varchar(60) DEFAULT NULL, + `josh` tinyint(1) NOT NULL DEFAULT '0', + `telephone` varchar(15) DEFAULT NULL, + `mobile` varchar(15) DEFAULT NULL, + `email` varchar(100) DEFAULT '', + `email_secondaire` varchar(100) NOT NULL DEFAULT '', + `fk_role` int DEFAULT '1', + `infos` varchar(200) NOT NULL DEFAULT '', + `ltt` varchar(10) DEFAULT '48.08', + `lng` varchar(10) DEFAULT '-1.68', + `sector` text, + `alert_email` tinyint(1) DEFAULT '1', + `chk_suivi` tinyint(1) DEFAULT '0', + `date_naissance` date DEFAULT NULL, + `dept_naissance` varchar(2) NOT NULL DEFAULT '', + `commune_naissance` varchar(60) NOT NULL DEFAULT '', + `date_embauche` date DEFAULT NULL, + `anciennete` varchar(20) DEFAULT '-', + `fk_categorie` int NOT NULL DEFAULT '0', + `fk_sous_categorie` int NOT NULL DEFAULT '0', + `adresse_1` varchar(50) NOT NULL DEFAULT '', + `adresse_2` varchar(50) NOT NULL DEFAULT '', + `cp` varchar(5) NOT NULL DEFAULT '', + `ville` varchar(60) NOT NULL DEFAULT '', + `matricule` varchar(10) NOT NULL DEFAULT '', + `fk_grade` int NOT NULL DEFAULT '0', + `chk_adherent_ud` tinyint(1) NOT NULL DEFAULT '0', + `chk_adherent_ur` tinyint(1) NOT NULL DEFAULT '0', + `chk_adherent_fns` tinyint(1) NOT NULL DEFAULT '0', + `chk_archive` tinyint(1) NOT NULL DEFAULT '0', + `chk_double_affectation` tinyint(1) NOT NULL DEFAULT '0', + `fk_user_creat` int DEFAULT NULL, + `date_creat` datetime DEFAULT NULL, + `fk_user_modif` int DEFAULT NULL, + `date_modif` datetime DEFAULT NULL, + `active` tinyint(1) DEFAULT '1', + PRIMARY KEY (`rowid`), + KEY `fk_entite` (`fk_entite`), + KEY `libelle` (`libelle`), + KEY `username` (`username`) +) ENGINE=InnoDB AUTO_INCREMENT=10027744 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `users_entites` +-- + +DROP TABLE IF EXISTS `users_entites`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `users_entites` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `appname` varchar(20) NOT NULL DEFAULT 'geo_sector', + `http_host` varchar(255) NOT NULL DEFAULT 'admin.geosector.fr adm.geosector.fr mobile.goesector.fr mob.geosector.fr', + `libelle` varchar(45) DEFAULT '', + `adresse1` varchar(45) DEFAULT '', + `adresse2` varchar(45) DEFAULT '', + `cp` varchar(5) DEFAULT '', + `ville` varchar(45) DEFAULT '', + `fk_region` int DEFAULT NULL, + `fk_type` int DEFAULT '1', + `tva_intra` varchar(15) DEFAULT '', + `rcs` varchar(45) DEFAULT '', + `siret` varchar(17) DEFAULT NULL, + `ape` varchar(5) DEFAULT '', + `tel1` varchar(20) DEFAULT '', + `tel2` varchar(20) DEFAULT '', + `couleur` varchar(10) DEFAULT '', + `prefecture` varchar(45) DEFAULT '', + `fk_titre_gerant` int DEFAULT '1', + `gerant_prenom` varchar(45) DEFAULT '', + `gerant_nom` varchar(45) DEFAULT '', + `email` varchar(45) DEFAULT '', + `gps_lat` varchar(10) NOT NULL DEFAULT '', + `gps_lng` varchar(10) NOT NULL DEFAULT '', + `site_url` varchar(45) DEFAULT '', + `gerant_signature` varchar(45) DEFAULT '', + `tampon_signature` varchar(45) DEFAULT '', + `banque_libelle` varchar(25) DEFAULT '', + `banque_adresse` varchar(45) DEFAULT '', + `banque_cp` varchar(5) DEFAULT '', + `banque_ville` varchar(40) DEFAULT '', + `iban` varchar(30) DEFAULT '', + `bic` varchar(15) DEFAULT '', + `genbase` varchar(45) NOT NULL, + `groupebase` varchar(45) NOT NULL, + `userbase` varchar(45) NOT NULL, + `passbase` varchar(45) NOT NULL, + `demo` tinyint(1) DEFAULT '0', + `lib_vert` varchar(25) DEFAULT 'Effectué', + `lib_verts` varchar(25) DEFAULT 'Effectués', + `lib_orange` varchar(25) DEFAULT 'A repasser', + `lib_oranges` varchar(25) DEFAULT 'A repasser', + `lib_rouge` varchar(25) DEFAULT 'Refusé', + `lib_rouges` varchar(25) DEFAULT 'Refusés', + `lib_bleu` varchar(25) DEFAULT 'Autre (Don)', + `lib_bleus` varchar(25) DEFAULT 'Autres (Dons)', + `icon_siege` varchar(15) DEFAULT 'fire', + `icon_siege_color` varchar(15) DEFAULT 'red', + `btn_width` varchar(3) DEFAULT '100', + `chk_mdp_manuel` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'Gestion des mots de passe manuelle O/N', + `chk_copie_mail_recu` tinyint(1) NOT NULL DEFAULT '0', + `chk_accept_sms` tinyint(1) NOT NULL DEFAULT '0', + `nbmembres` int DEFAULT '0', + `nbconnex` int DEFAULT '0', + `date_modif` datetime DEFAULT NULL, + `fk_user_modif` int DEFAULT NULL, + `active` tinyint(1) DEFAULT '1', + PRIMARY KEY (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=1229 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `users_lastpos` +-- + +DROP TABLE IF EXISTS `users_lastpos`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `users_lastpos` ( + `fk_user` int NOT NULL, + `fk_operation` int DEFAULT NULL, + `gps_lat` varchar(20) DEFAULT NULL, + `gps_lng` varchar(20) DEFAULT NULL, + `date_pos` datetime DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_civilites` +-- + +DROP TABLE IF EXISTS `x_civilites`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_civilites` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `libelle` varchar(45) DEFAULT NULL, + `active` tinyint(1) DEFAULT '1', + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_departements` +-- + +DROP TABLE IF EXISTS `x_departements`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_departements` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `code` varchar(3) DEFAULT NULL, + `fk_region` int DEFAULT '1', + `libelle` varchar(45) DEFAULT NULL, + `active` tinyint(1) DEFAULT '1', + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=105 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_devises` +-- + +DROP TABLE IF EXISTS `x_devises`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_devises` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `code` varchar(3) DEFAULT NULL, + `symbole` varchar(6) DEFAULT NULL, + `libelle` varchar(45) DEFAULT NULL, + `active` tinyint(1) DEFAULT '1', + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_entites_types` +-- + +DROP TABLE IF EXISTS `x_entites_types`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_entites_types` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `libelle` varchar(45) DEFAULT NULL, + `active` tinyint(1) DEFAULT NULL, + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_pays` +-- + +DROP TABLE IF EXISTS `x_pays`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_pays` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `code` varchar(3) DEFAULT NULL, + `fk_continent` int DEFAULT NULL, + `fk_devise` int DEFAULT '1', + `libelle` varchar(45) DEFAULT NULL, + `active` tinyint(1) DEFAULT '1', + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Table des pays avec leurs codes'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_regions` +-- + +DROP TABLE IF EXISTS `x_regions`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_regions` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `fk_pays` int DEFAULT '1', + `libelle` varchar(45) DEFAULT NULL, + `libelle_long` varchar(45) DEFAULT NULL, + `table_osm` varchar(45) DEFAULT NULL, + `departements` varchar(45) DEFAULT NULL, + `active` tinyint(1) DEFAULT '1', + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_types_passages` +-- + +DROP TABLE IF EXISTS `x_types_passages`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_types_passages` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `libelle` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, + `color_button` varchar(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, + `color_mark` varchar(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, + `color_table` varchar(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, + `chk_active` tinyint(1) NOT NULL DEFAULT '1', + PRIMARY KEY (`rowid`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_types_reglements` +-- + +DROP TABLE IF EXISTS `x_types_reglements`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_types_reglements` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `libelle` varchar(45) DEFAULT NULL, + `active` tinyint(1) DEFAULT '1', + PRIMARY KEY (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_users_categories` +-- + +DROP TABLE IF EXISTS `x_users_categories`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_users_categories` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `libelle` varchar(30) NOT NULL, + `active` tinyint(1) NOT NULL DEFAULT '1', + PRIMARY KEY (`rowid`), + KEY `x_users_categories__libelle` (`libelle`) +) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_users_grades` +-- + +DROP TABLE IF EXISTS `x_users_grades`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_users_grades` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `libelle` varchar(90) NOT NULL DEFAULT '', + `active` tinyint(1) NOT NULL DEFAULT '1', + PRIMARY KEY (`rowid`), + KEY `x_users_grades__libelle` (`libelle`) +) ENGINE=InnoDB AUTO_INCREMENT=84 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_users_roles` +-- + +DROP TABLE IF EXISTS `x_users_roles`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_users_roles` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `libelle` varchar(45) DEFAULT NULL, + `active` tinyint(1) DEFAULT '1', + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Les différents rôles des utilisateurs'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_users_sous_categories` +-- + +DROP TABLE IF EXISTS `x_users_sous_categories`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_users_sous_categories` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `fk_user_categorie` int NOT NULL, + `libelle` varchar(40) NOT NULL DEFAULT '', + `active` tinyint(1) NOT NULL DEFAULT '1', + PRIMARY KEY (`rowid`), + KEY `x_users_sous_categories__libelle` (`libelle`), + KEY `x_users_sous_categories_fk_user_categorie_index` (`fk_user_categorie`) +) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_villes` +-- + +DROP TABLE IF EXISTS `x_villes`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_villes` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `fk_departement` int DEFAULT '1', + `libelle` varchar(65) DEFAULT NULL, + `cp` varchar(5) DEFAULT NULL, + `code_insee` varchar(5) DEFAULT NULL, + `departement` varchar(65) DEFAULT NULL, + `active` tinyint(1) DEFAULT '1', + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=38950 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `y_conf` +-- + +DROP TABLE IF EXISTS `y_conf`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `y_conf` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `admin` tinyint(1) NOT NULL DEFAULT '0', + `appenv` varchar(5) NOT NULL DEFAULT 'dev', + `apptitle` varchar(75) NOT NULL DEFAULT '', + `appversion` varchar(20) NOT NULL DEFAULT '0.5 du 15/01/2016', + `appscript` varchar(25) NOT NULL DEFAULT 'login' COMMENT 'Script à appeler si la session ne reconnaît pas l''utilisateur', + `appicon` varchar(25) NOT NULL DEFAULT 'favicon.png', + `pathimg` varchar(45) NOT NULL DEFAULT '/files/img', + `pathupload` varchar(45) NOT NULL DEFAULT '/files/upload', + `brandgroupe` varchar(45) NOT NULL DEFAULT '', + `brandmulti` tinyint(1) DEFAULT '0', + `date_maintenance` datetime DEFAULT NULL, + `date_renouvellement` date DEFAULT NULL, + `piwikid` varchar(45) DEFAULT '0', + `googlid` varchar(45) DEFAULT '0', + `active` tinyint(1) DEFAULT '1', + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `y_menus` +-- + +DROP TABLE IF EXISTS `y_menus`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `y_menus` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `type_menu` varchar(3) NOT NULL DEFAULT 'mnu' COMMENT '"mnu" pour le menu en header, "bar" pour la barre à gauche, "sdb" pour la sidebar à gauche', + `admin` tinyint DEFAULT '0' COMMENT '0 Public, 1 Admin, 2 Mobile', + `only_type_entite` varchar(45) DEFAULT '', + `only_fk_entite` varchar(45) DEFAULT '', + `only_fk_role` varchar(45) DEFAULT '', + `divider_before` tinyint(1) DEFAULT '0', + `ordre` tinyint DEFAULT '0', + `fk_parent` int DEFAULT '0', + `libelle` varchar(45) DEFAULT '', + `icone` varchar(45) DEFAULT '', + `color` varchar(35) DEFAULT '', + `back-color` varchar(35) DEFAULT '', + `title` varchar(75) DEFAULT '', + `script` varchar(45) NOT NULL COMMENT 'Une page php acceuil ou une function javascript js:nomfonction ou l''appel à l''id d''un bouton btn:btnNoteRapide\n', + `script_command` varchar(45) DEFAULT '', + `active` tinyint(1) DEFAULT '1', + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`), + KEY `type_menu` (`type_menu`), + KEY `script` (`script`), + KEY `ordre` (`ordre`), + KEY `fk_parent` (`fk_parent`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `y_modules` +-- + +DROP TABLE IF EXISTS `y_modules`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `y_modules` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `fk_parent` int DEFAULT '0', + `ordre` int DEFAULT '0', + `libelle` varchar(45) NOT NULL, + `tip` varchar(150) DEFAULT '', + `description` text, + `script` varchar(20) DEFAULT '', + `couleur` varchar(7) DEFAULT '#bcbcbc', + `icone` varchar(30) DEFAULT NULL, + `taille_tuile` int DEFAULT '70' COMMENT 'Taille de la tuile dans l''interface admin', + `admin` tinyint(1) DEFAULT '1', + `active` tinyint(1) DEFAULT '0', + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `y_modules_rules` +-- + +DROP TABLE IF EXISTS `y_modules_rules`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `y_modules_rules` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `fk_module` int DEFAULT '0', + `libelle` varchar(30) NOT NULL DEFAULT '', + `tip` varchar(250) NOT NULL DEFAULT '', + `val_default` varchar(20) NOT NULL DEFAULT '' COMMENT 'Valeur par défaut prise si la valeur d''un CE n''est pas renseignée', + `ce_apa` varchar(20) DEFAULT '', + `ce_csfouest` varchar(20) DEFAULT '', + `ce_demo` varchar(20) DEFAULT '', + `ce_natixis` varchar(20) DEFAULT '', + `ce_purina` varchar(20) DEFAULT '', + `ce_tfn44` varchar(20) DEFAULT '', + `ce_webasto` varchar(20) DEFAULT '', + `active` tinyint(1) NOT NULL DEFAULT '1', + PRIMARY KEY (`rowid`), + UNIQUE KEY `y_modules_regles_rowid_uindex` (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `y_pages` +-- + +DROP TABLE IF EXISTS `y_pages`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `y_pages` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `libelle` varchar(45) DEFAULT NULL, + `titre` varchar(75) DEFAULT NULL, + `tooltip` varchar(45) DEFAULT NULL, + `description` varchar(200) DEFAULT NULL, + `keywords` varchar(200) DEFAULT NULL, + `script` varchar(45) DEFAULT NULL, + `enmaintenance` tinyint(1) DEFAULT '0' COMMENT '0 libre d''accès, 1 en maintenance mais accès aux données, 2 en maintenance sans accès aux données', + `admin` tinyint(1) DEFAULT '0', + `mail` tinyint(1) DEFAULT '0', + `admtools` tinyint(1) DEFAULT '0', + `magazine` tinyint(1) DEFAULT '0', + `files` tinyint(1) DEFAULT '1', + `maps` tinyint(1) DEFAULT '0', + `editor` tinyint(1) DEFAULT '0', + `jqui` tinyint(1) DEFAULT '0', + `form` tinyint(1) DEFAULT '0', + `sidebar` tinyint(1) DEFAULT '0', + `chart` tinyint(1) DEFAULT '0', + `agenda` tinyint(1) DEFAULT '0', + `scheduler` tinyint(1) DEFAULT '0', + `osm` tinyint(1) DEFAULT '0', + `zz` tinyint(1) DEFAULT '0', + `maintenance` tinyint(1) DEFAULT '0', + `layout` varchar(45) DEFAULT 'default.php', + `active` tinyint(1) DEFAULT '1', + PRIMARY KEY (`rowid`), + UNIQUE KEY `rowid_UNIQUE` (`rowid`), + KEY `script` (`script`), + KEY `admin` (`admin`) +) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `z_logs` +-- + +DROP TABLE IF EXISTS `z_logs`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `z_logs` ( + `date` datetime NOT NULL, + `ip` varchar(15) NOT NULL, + `host` varchar(50) NOT NULL, + `adrhost` varchar(50) NOT NULL, + `infos` varchar(200) DEFAULT '', + `fk_user` int DEFAULT '0', + `page` varchar(200) NOT NULL, + `commentaire` text NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Table des logs'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `z_sessions` +-- + +DROP TABLE IF EXISTS `z_sessions`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `z_sessions` ( + `sid` text NOT NULL, + `fk_user` int NOT NULL, + `role` varchar(10) DEFAULT NULL, + `date_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `ip` varchar(50) NOT NULL, + `browser` varchar(150) NOT NULL, + `data` mediumtext +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `z_stats` +-- + +DROP TABLE IF EXISTS `z_stats`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `z_stats` ( + `rowid` int NOT NULL AUTO_INCREMENT, + `libelle` varchar(75) DEFAULT NULL, + `fk_user` int DEFAULT NULL, + `date` datetime DEFAULT NULL, + `ip` varchar(15) DEFAULT NULL, + `browser` varchar(75) DEFAULT NULL, + `origine` varchar(45) DEFAULT NULL, + `status` varchar(10) DEFAULT NULL, + `active` tinyint(1) DEFAULT NULL, + PRIMARY KEY (`rowid`) +) ENGINE=InnoDB AUTO_INCREMENT=210793 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping routines for database 'geosector' +-- +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2025-03-28 9:04:32 diff --git a/api/scripts/geosector_app.sql b/api/scripts/geosector_app.sql new file mode 100644 index 00000000..f95fdbb0 --- /dev/null +++ b/api/scripts/geosector_app.sql @@ -0,0 +1,619 @@ +-- Création de la base de données geo_app si elle n'existe pas +DROP DATABASE IF EXISTS `geo_app`; +CREATE DATABASE IF NOT EXISTS `geo_app` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- Création de l'utilisateur et attribution des droits +CREATE USER IF NOT EXISTS 'geo_app_user'@'localhost' IDENTIFIED BY 'QO:96df*?k{4W6m'; +GRANT SELECT, INSERT, UPDATE, DELETE ON `geo_app`.* TO 'geo_app_user'@'localhost'; +FLUSH PRIVILEGES; + +USE geo_app; + +-- +-- Table structure for table `email_counter` +-- + +DROP TABLE IF EXISTS `email_counter`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `email_counter` ( + `id` int unsigned NOT NULL DEFAULT '1', + `hour_start` timestamp NULL DEFAULT NULL, + `count` int unsigned DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `x_devises`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_devises` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `code` varchar(3) DEFAULT NULL, + `symbole` varchar(6) DEFAULT NULL, + `libelle` varchar(45) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_entites_types` +-- + +DROP TABLE IF EXISTS `x_entites_types`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_entites_types` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `libelle` varchar(45) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_types_passages` +-- + +DROP TABLE IF EXISTS `x_types_passages`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_types_passages` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `libelle` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `color_button` varchar(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `color_mark` varchar(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `color_table` varchar(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `chk_active` tinyint(1) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_types_reglements` +-- + +DROP TABLE IF EXISTS `x_types_reglements`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_types_reglements` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `libelle` varchar(45) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `x_users_roles` +-- + +DROP TABLE IF EXISTS `x_users_roles`; + +CREATE TABLE `x_users_roles` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `libelle` varchar(45) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Les différents rôles des utilisateurs'; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `x_users_titres`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_users_titres` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `libelle` varchar(45) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Les différents titres des utilisateurs'; + +DROP TABLE IF EXISTS `x_pays`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_pays` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `code` varchar(3) DEFAULT NULL, + `fk_continent` int unsigned DEFAULT NULL, + `fk_devise` int unsigned DEFAULT '1', + `libelle` varchar(45) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`), + CONSTRAINT `x_pays_ibfk_1` FOREIGN KEY (`fk_devise`) REFERENCES `x_devises` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Table des pays avec leurs codes'; +/*!40101 SET character_set_client = @saved_cs_client */; + + +DROP TABLE IF EXISTS `x_regions`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_regions` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_pays` int unsigned DEFAULT '1', + `libelle` varchar(45) DEFAULT NULL, + `libelle_long` varchar(45) DEFAULT NULL, + `table_osm` varchar(45) DEFAULT NULL, + `departements` varchar(45) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`), + CONSTRAINT `x_regions_ibfk_1` FOREIGN KEY (`fk_pays`) REFERENCES `x_pays` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `x_departements`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_departements` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `code` varchar(3) DEFAULT NULL, + `fk_region` int unsigned DEFAULT '1', + `libelle` varchar(45) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`), + CONSTRAINT `x_departements_ibfk_1` FOREIGN KEY (`fk_region`) REFERENCES `x_regions` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=105 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `entites`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `entites` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `encrypted_name` varchar(255) DEFAULT NULL, + `adresse1` varchar(45) DEFAULT '', + `adresse2` varchar(45) DEFAULT '', + `code_postal` varchar(5) DEFAULT '', + `ville` varchar(45) DEFAULT '', + `fk_region` int unsigned DEFAULT NULL, + `fk_type` int unsigned DEFAULT '1', + `encrypted_phone` varchar(128) DEFAULT '', + `encrypted_mobile` varchar(128) DEFAULT '', + `encrypted_email` varchar(255) DEFAULT '', + `gps_lat` varchar(20) NOT NULL DEFAULT '', + `gps_lng` varchar(20) NOT NULL DEFAULT '', + `encrypted_stripe_id` varchar(255) DEFAULT '', + `encrypted_iban` varchar(255) DEFAULT '', + `encrypted_bic` varchar(128) DEFAULT '', + `chk_demo` tinyint(1) unsigned DEFAULT '1', + `chk_mdp_manuel` tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT 'Gestion des mots de passe manuelle O/N', + `chk_copie_mail_recu` tinyint(1) unsigned NOT NULL DEFAULT '0', + `chk_accept_sms` tinyint(1) unsigned NOT NULL DEFAULT '0', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `fk_user_creat` int unsigned DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + `fk_user_modif` int unsigned DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + CONSTRAINT `entites_ibfk_1` FOREIGN KEY (`fk_region`) REFERENCES `x_regions` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `entites_ibfk_2` FOREIGN KEY (`fk_type`) REFERENCES `x_entites_types` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `x_villes`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `x_villes` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_departement` int unsigned DEFAULT '1', + `libelle` varchar(65) DEFAULT NULL, + `cp` varchar(5) DEFAULT NULL, + `code_insee` varchar(5) DEFAULT NULL, + `departement` varchar(65) DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`), + CONSTRAINT `x_villes_ibfk_1` FOREIGN KEY (`fk_departement`) REFERENCES `x_departements` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `users`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `users` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_entite` int unsigned DEFAULT '1', + `fk_role` int unsigned DEFAULT '1', + `fk_titre` int unsigned DEFAULT '1', + `encrypted_name` varchar(255) DEFAULT NULL, + `first_name` varchar(45) DEFAULT NULL, + `sect_name` varchar(60) DEFAULT '', + `encrypted_user_name` varchar(128) DEFAULT '', + `user_pass_hash` varchar(60) DEFAULT NULL, + `encrypted_phone` varchar(128) DEFAULT NULL, + `encrypted_mobile` varchar(128) DEFAULT NULL, + `encrypted_email` varchar(255) DEFAULT '', + `chk_alert_email` tinyint(1) unsigned DEFAULT '1', + `chk_suivi` tinyint(1) unsigned DEFAULT '0', + `date_naissance` date DEFAULT NULL, + `date_embauche` date DEFAULT NULL, + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `fk_user_creat` int unsigned DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + `fk_user_modif` int unsigned DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + KEY `fk_entite` (`fk_entite`), + KEY `username` (`encrypted_user_name`), + CONSTRAINT `users_ibfk_1` FOREIGN KEY (`fk_entite`) REFERENCES `entites` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `users_ibfk_2` FOREIGN KEY (`fk_role`) REFERENCES `x_users_roles` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `users_ibfk_3` FOREIGN KEY (`fk_titre`) REFERENCES `x_users_titres` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `operations`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `operations` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_entite` int unsigned NOT NULL DEFAULT '1', + `libelle` varchar(75) NOT NULL DEFAULT '', + `date_deb` date NOT NULL DEFAULT '0000-00-00', + `date_fin` date NOT NULL DEFAULT '0000-00-00', + `chk_distinct_sectors` tinyint(1) unsigned NOT NULL DEFAULT '0', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `fk_user_creat` int unsigned NOT NULL DEFAULT '0', + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + `fk_user_modif` int unsigned NOT NULL DEFAULT '0', + `chk_active` tinyint(1) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + KEY `fk_entite` (`fk_entite`), + KEY `date_deb` (`date_deb`), + CONSTRAINT `operations_ibfk_1` FOREIGN KEY (`fk_entite`) REFERENCES `entites` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + + +DROP TABLE IF EXISTS `ope_sectors`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_sectors` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_operation` int unsigned NOT NULL DEFAULT '0', + `fk_old_sector` int unsigned NOT NULL DEFAULT '0', + `libelle` varchar(75) NOT NULL DEFAULT '', + `sector` text NOT NULL DEFAULT '', + `color` varchar(7) NOT NULL DEFAULT '#4B77BE', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `fk_user_creat` int unsigned NOT NULL DEFAULT '0', + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + `fk_user_modif` int unsigned NOT NULL DEFAULT '0', + `chk_active` tinyint(1) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id` (`id`), + KEY `fk_operation` (`fk_operation`), + CONSTRAINT `ope_sectors_ibfk_1` FOREIGN KEY (`fk_operation`) REFERENCES `operations` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + + +DROP TABLE IF EXISTS `ope_users`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_users` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_operation` int unsigned NOT NULL DEFAULT '0', + `fk_user` int unsigned NOT NULL DEFAULT '0', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `fk_user_creat` int unsigned DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + `fk_user_modif` int unsigned DEFAULT NULL, + `chk_active` tinyint(1) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`), + CONSTRAINT `ope_users_ibfk_1` FOREIGN KEY (`fk_operation`) REFERENCES `operations` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `ope_users_ibfk_2` FOREIGN KEY (`fk_user`) REFERENCES `users` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `email_queue`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `email_queue` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_pass` int unsigned NOT NULL DEFAULT '0', + `to_email` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `subject` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `body` text COLLATE utf8mb4_unicode_ci, + `headers` text COLLATE utf8mb4_unicode_ci, + `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `status` enum('pending','sent','failed') COLLATE utf8mb4_unicode_ci DEFAULT 'pending', + `attempts` int unsigned DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `ope_users_sectors`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_users_sectors` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_operation` int unsigned NOT NULL DEFAULT '0', + `fk_user` int unsigned NOT NULL DEFAULT '0', + `fk_sector` int unsigned NOT NULL DEFAULT '0', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `fk_user_creat` int unsigned NOT NULL DEFAULT '0', + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + `fk_user_modif` int unsigned DEFAULT NULL, + `chk_active` tinyint(1) unsigned DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `id` (`id`), + KEY `fk_operation` (`fk_operation`), + KEY `fk_user` (`fk_user`), + KEY `fk_sector` (`fk_sector`), + CONSTRAINT `ope_users_sectors_ibfk_1` FOREIGN KEY (`fk_operation`) REFERENCES `operations` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `ope_users_sectors_ibfk_2` FOREIGN KEY (`fk_user`) REFERENCES `users` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `ope_users_sectors_ibfk_3` FOREIGN KEY (`fk_sector`) REFERENCES `ope_sectors` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `ope_users_suivis`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_users_suivis` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_operation` int unsigned NOT NULL DEFAULT '0', + `fk_user` int unsigned NOT NULL DEFAULT '0', + `date_suivi` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date du suivi', + `gps_lat` varchar(20) NOT NULL DEFAULT '', + `gps_lng` varchar(20) NOT NULL DEFAULT '', + `vitesse` varchar(20) NOT NULL DEFAULT '', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `fk_user_creat` int unsigned NOT NULL DEFAULT '0', + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + `fk_user_modif` int unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `sectors_adresses`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `sectors_adresses` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_adresse` varchar(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'adresses.cp??.id', + `osm_id` int unsigned NOT NULL DEFAULT '0', + `fk_sector` int unsigned NOT NULL DEFAULT '0', + `osm_name` varchar(50) NOT NULL DEFAULT '', + `numero` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `rue_bis` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `rue` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `cp` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `ville` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `gps_lat` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `gps_lng` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `osm_date_creat` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + PRIMARY KEY (`id`), + KEY `sectors_adresses_fk_sector_index` (`fk_sector`), + KEY `sectors_adresses_numero_index` (`numero`), + KEY `sectors_adresses_rue_index` (`rue`), + KEY `sectors_adresses_ville_index` (`ville`), + CONSTRAINT `sectors_adresses_ibfk_1` FOREIGN KEY (`fk_sector`) REFERENCES `ope_sectors` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +DROP TABLE IF EXISTS `ope_pass`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_pass` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_operation` int unsigned NOT NULL DEFAULT '0', + `fk_sector` int unsigned DEFAULT '0', + `fk_user` int unsigned NOT NULL DEFAULT '0', + `fk_adresse` varchar(25) DEFAULT '' COMMENT 'adresses.cp??.id', + `passed_at` timestamp NULL DEFAULT NULL COMMENT 'Date du passage', + `fk_type` int unsigned DEFAULT '0', + `numero` varchar(10) NOT NULL DEFAULT '', + `rue` varchar(75) NOT NULL DEFAULT '', + `rue_bis` varchar(1) NOT NULL DEFAULT '', + `ville` varchar(75) NOT NULL DEFAULT '', + `fk_habitat` int unsigned DEFAULT '1', + `appt` varchar(5) DEFAULT '', + `niveau` varchar(5) DEFAULT '', + `residence` varchar(75) DEFAULT '', + `gps_lat` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `gps_lng` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', + `encrypted_name` varchar(255) NOT NULL DEFAULT '', + `montant` decimal(7,2) NOT NULL DEFAULT '0.00', + `fk_type_reglement` int unsigned DEFAULT '1', + `remarque` text DEFAULT '', + `encrypted_email` varchar(255) DEFAULT '', + `nom_recu` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `date_recu` timestamp NULL DEFAULT NULL COMMENT 'Date de réception', + `date_creat_recu` timestamp NULL DEFAULT NULL COMMENT 'Date de création du reçu', + `date_sent_recu` timestamp NULL DEFAULT NULL COMMENT 'Date envoi du reçu', + `email_erreur` varchar(30) DEFAULT '', + `chk_email_sent` tinyint(1) unsigned NOT NULL DEFAULT '0', + `encrypted_phone` varchar(128) NOT NULL DEFAULT '', + `chk_striped` tinyint(1) unsigned DEFAULT '0', + `docremis` tinyint(1) unsigned DEFAULT '0', + `date_repasser` timestamp NULL DEFAULT NULL COMMENT 'Date prévue pour repasser', + `nb_passages` int DEFAULT '1' COMMENT 'Nb passages pour les a repasser', + `chk_gps_maj` tinyint(1) unsigned DEFAULT '0', + `chk_map_create` tinyint(1) unsigned DEFAULT '0', + `chk_mobile` tinyint(1) unsigned DEFAULT '0', + `chk_synchro` tinyint(1) unsigned DEFAULT '1' COMMENT 'chk synchro entre web et appli', + `chk_api_adresse` tinyint(1) unsigned DEFAULT '0', + `chk_maj_adresse` tinyint(1) unsigned DEFAULT '0', + `anomalie` tinyint(1) unsigned DEFAULT '0', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + `fk_user_creat` int unsigned DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date de modification', + `fk_user_modif` int unsigned DEFAULT NULL, + `chk_active` tinyint(1) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + KEY `fk_operation` (`fk_operation`), + KEY `fk_sector` (`fk_sector`), + KEY `fk_user` (`fk_user`), + KEY `fk_type` (`fk_type`), + KEY `fk_type_reglement` (`fk_type_reglement`), + KEY `email` (`email`), + CONSTRAINT `ope_pass_ibfk_1` FOREIGN KEY (`fk_operation`) REFERENCES `operations` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `ope_pass_ibfk_2` FOREIGN KEY (`fk_sector`) REFERENCES `ope_sectors` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `ope_pass_ibfk_3` FOREIGN KEY (`fk_user`) REFERENCES `users` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT `ope_pass_ibfk_4` FOREIGN KEY (`fk_type_reglement`) REFERENCES `x_types_reglements` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `ope_pass_histo`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ope_pass_histo` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `fk_pass` int unsigned NOT NULL DEFAULT '0', + `date_histo` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date historique', + `sujet` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL, + `remarque` varchar(250) NOT NULL DEFAULT '', + PRIMARY KEY (`id`), + KEY `ope_pass_histo_fk_pass_IDX` (`fk_pass`) USING BTREE, + KEY `ope_pass_histo_date_histo_IDX` (`date_histo`) USING BTREE, + CONSTRAINT `ope_pass_histo_ibfk_1` FOREIGN KEY (`fk_pass`) REFERENCES `ope_pass` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +DROP TABLE IF EXISTS `medias`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `medias` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `support` varchar(45) NOT NULL DEFAULT '', + `support_id` int unsigned NOT NULL DEFAULT '0', + `fichier` varchar(250) NOT NULL DEFAULT '', + `description` varchar(100) NOT NULL DEFAULT '', + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `fk_user_creat` int unsigned NOT NULL DEFAULT '0', + `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, + `fk_user_modif` int unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- Création des tables pour le système de chat +DROP TABLE IF EXISTS `chat_rooms`; +-- Table des salles de discussion +CREATE TABLE chat_rooms ( + id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(100) NOT NULL, + type ENUM('privee', 'groupe', 'liste_diffusion') NOT NULL, + date_creation timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + fk_user INT UNSIGNED NOT NULL, + fk_entite INT UNSIGNED, + statut ENUM('active', 'archive') NOT NULL DEFAULT 'active', + description TEXT, + INDEX idx_user (fk_user), + INDEX idx_entite (fk_entite) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + + +DROP TABLE IF EXISTS `chat_participants`; +-- Table des participants aux salles de discussion +CREATE TABLE chat_participants ( + id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + id_room INT UNSIGNED NOT NULL, + id_user INT UNSIGNED NOT NULL, + role ENUM('administrateur', 'participant', 'en_lecture_seule') NOT NULL DEFAULT 'participant', + date_ajout timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date ajout', + notification_activee BOOLEAN NOT NULL DEFAULT TRUE, + INDEX idx_room (id_room), + INDEX idx_user (id_user), + CONSTRAINT uc_room_user UNIQUE (id_room, id_user), + FOREIGN KEY (id_room) REFERENCES chat_rooms(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +DROP TABLE IF EXISTS `chat_messages`; +-- Table des messages +CREATE TABLE chat_messages ( + id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + fk_room INT UNSIGNED NOT NULL, + fk_user INT UNSIGNED NOT NULL, + content TEXT, + date_sent timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date envoi', + type ENUM('texte', 'media', 'systeme') NOT NULL DEFAULT 'texte', + statut ENUM('envoye', 'livre', 'lu') NOT NULL DEFAULT 'envoye', + INDEX idx_room (fk_room), + INDEX idx_user (fk_user), + INDEX idx_date (date_sent), + FOREIGN KEY (fk_room) REFERENCES chat_rooms(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +DROP TABLE IF EXISTS `chat_listes_diffusion`; +-- Table des listes de diffusion +CREATE TABLE chat_listes_diffusion ( + id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + fk_room INT UNSIGNED NOT NULL, + name VARCHAR(100) NOT NULL, + description TEXT, + fk_user INT UNSIGNED NOT NULL, + date_creation timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + INDEX idx_room (fk_room), + INDEX idx_user (fk_user), + FOREIGN KEY (fk_room) REFERENCES chat_rooms(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +DROP TABLE IF EXISTS `chat_read_messages`; +-- Table pour suivre la lecture des messages +CREATE TABLE chat_read_messages ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + fk_message INT UNSIGNED NOT NULL, + fk_user INT UNSIGNED NOT NULL, + date_read timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de lecture', + INDEX idx_message (fk_message), + INDEX idx_user (fk_user), + CONSTRAINT uc_message_user UNIQUE (fk_message, fk_user), + FOREIGN KEY (fk_message) REFERENCES chat_messages(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +DROP TABLE IF EXISTS `chat_notifications`; +-- Table des notifications +CREATE TABLE chat_notifications ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + fk_user INT UNSIGNED NOT NULL, + fk_message INT UNSIGNED, + fk_room INT UNSIGNED, + type VARCHAR(50) NOT NULL, + contenu TEXT, + date_creation timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Date de création', + date_lecture timestamp NULL DEFAULT NULL COMMENT 'Date de lecture', + statut ENUM('non_lue', 'lue') NOT NULL DEFAULT 'non_lue', + INDEX idx_user (fk_user), + INDEX idx_message (fk_message), + INDEX idx_room (fk_room), + FOREIGN KEY (fk_message) REFERENCES chat_messages(id) ON DELETE SET NULL, + FOREIGN KEY (fk_room) REFERENCES chat_rooms(id) ON DELETE SET NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +DROP TABLE IF EXISTS `z_params`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `params` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `libelle` varchar(35) NOT NULL DEFAULT '', + `valeur` varchar(255) NOT NULL DEFAULT '', + `aide` varchar(150) NOT NULL DEFAULT '', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + + +DROP TABLE IF EXISTS `z_sessions`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `z_sessions` ( + `sid` text NOT NULL, + `fk_user` int NOT NULL, + `role` varchar(10) DEFAULT NULL, + `date_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `ip` varchar(50) NOT NULL, + `browser` varchar(150) NOT NULL, + `data` mediumtext +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; diff --git a/api/scripts/php/MigrationConfig.php b/api/scripts/php/MigrationConfig.php new file mode 100644 index 00000000..8e12be71 --- /dev/null +++ b/api/scripts/php/MigrationConfig.php @@ -0,0 +1,35 @@ + 'Qga2M8Ov6tyx2fIQRWHQ1U6oMK/bAFdTL7A8VRtiDhk=', // Clé de GeoSector + 'app_identifier' => 'geosector', // Identifiant de l'application + ]; + + private function __construct() { + // Constructeur simplifié sans validation d'application + } + + public static function getInstance(): self { + if (self::$instance === null) { + self::$instance = new self(); + } + return self::$instance; + } + + public function getEncryptionKey(): string { + return $this->config['encryption_key']; + } + + public function getAppIdentifier(): string { + return $this->config['app_identifier']; + } +} diff --git a/api/scripts/php/migrate.php b/api/scripts/php/migrate.php new file mode 100644 index 00000000..cec64ffb --- /dev/null +++ b/api/scripts/php/migrate.php @@ -0,0 +1,357 @@ + - Exécute la migration pour une table spécifique + * + * Options: + * --truncate Vide la table cible avant la migration + * --create-table Crée la table cible si elle n'existe pas + * --help Affiche l'aide + */ + +require_once dirname(__DIR__) . '/config.php'; + +// Définition des mappages de colonnes pour chaque table +$tableMappings = [ + 'x_devises' => [ + 'source_to_target' => [ + 'rowid' => 'id', + 'active' => 'chk_active' + ], + 'primary_key' => 'rowid', // Clé primaire dans la table source + 'target_primary_key' => 'id' // Clé primaire dans la table cible + ], + 'users' => [ + 'source_to_target' => [ + 'id' => 'id', + 'user_pass_hash' => 'password_hash', + 'encrypted_user_name' => 'encrypted_last_name', + 'lang' => 'preferred_language', + 'chk_active' => 'is_active' + ], + 'primary_key' => 'id', + 'target_primary_key' => 'id', + 'encrypted_fields' => [ + 'email' => ['field' => 'encrypted_email', 'searchable' => true], + 'user_name' => ['field' => 'encrypted_last_name', 'searchable' => false], + 'phone' => ['field' => 'encrypted_phone', 'searchable' => false], + 'mobile' => ['field' => 'encrypted_mobile', 'searchable' => false] + ] + ], + // Ajoutez d'autres tables selon les besoins +]; + +// Fonction pour afficher l'aide +function showHelp() { + echo "Usage: php migrate.php [--truncate] [--create-table]\n"; + echo "\nOptions disponibles:\n"; + echo " --truncate Vide la table cible avant la migration\n"; + echo " --create-table Crée la table cible si elle n'existe pas\n"; + echo " --help Affiche cette aide\n"; + echo "\nTables disponibles:\n"; + + global $tableMappings; + foreach (array_keys($tableMappings) as $table) { + echo " - $table\n"; + } + + exit(0); +} + +// Définition des scripts de migration disponibles dans l'ordre d'exécution +$migrationScripts = [ + 'x_devises' => __DIR__ . '/migrate_x_devises.php', + 'x_entites_types' => __DIR__ . '/migrate_x_entites_types.php', + 'x_types_passages' => __DIR__ . '/migrate_x_types_passages.php', + 'x_types_reglements' => __DIR__ . '/migrate_x_types_reglements.php', + 'x_users_roles' => __DIR__ . '/migrate_x_users_roles.php', + 'x_pays' => __DIR__ . '/migrate_x_pays.php', + 'x_regions' => __DIR__ . '/migrate_x_regions.php', + 'x_departements' => __DIR__ . '/migrate_x_departements.php', + 'x_villes' => __DIR__ . '/migrate_x_villes.php', + 'entites' => __DIR__ . '/migrate_entites.php', + 'users' => __DIR__ . '/migrate_users.php', + 'operations' => __DIR__ . '/migrate_operations.php', + 'ope_sectors' => __DIR__ . '/migrate_ope_sectors.php', + 'sectors_adresses' => __DIR__ . '/migrate_sectors_adresses.php', + 'ope_users' => __DIR__ . '/migrate_ope_users.php', + 'ope_users_sectors' => __DIR__ . '/migrate_ope_users_sectors.php', + 'ope_pass' => __DIR__ . '/migrate_ope_pass.php', + 'ope_pass_histo' => __DIR__ . '/migrate_ope_pass_histo.php', + 'medias' => __DIR__ . '/migrate_medias.php' + // Ajoutez d'autres scripts de migration au fur et à mesure +]; + +// Fonction pour exécuter un script de migration spécifique +function executeMigrationScript($scriptPath) { + echo "\nExécution du script: " . basename($scriptPath) . "\n"; + echo "------------------------------------------------\n"; + + // Exécuter le script PHP + include $scriptPath; + + echo "\n"; + return true; +} + +// Traitement des arguments de ligne de commande +$tableName = null; +$truncateTable = false; +$createTable = false; +$runAllScripts = true; + +for ($i = 1; $i < $_SERVER['argc']; $i++) { + $arg = $_SERVER['argv'][$i]; + + if ($arg === '--help') { + showHelp(); + } elseif ($arg === '--truncate') { + $truncateTable = true; + } elseif ($arg === '--create-table') { + $createTable = true; + } elseif (substr($arg, 0, 2) !== '--') { + $tableName = $arg; + $runAllScripts = false; + } +} + +// Si aucune table n'est spécifiée, exécuter tous les scripts de migration dans l'ordre +if ($runAllScripts) { + echo "\nDémarrage de la migration complète de la base de données\n"; + echo "=======================================================\n"; + + $startTime = microtime(true); + $successCount = 0; + $failCount = 0; + + foreach ($migrationScripts as $table => $scriptPath) { + if (file_exists($scriptPath)) { + try { + executeMigrationScript($scriptPath); + $successCount++; + } catch (Exception $e) { + echo "\nErreur lors de la migration de la table $table: " . $e->getMessage() . "\n"; + $failCount++; + } + } else { + echo "\nScript de migration introuvable pour la table $table: $scriptPath\n"; + $failCount++; + } + } + + $endTime = microtime(true); + $executionTime = round($endTime - $startTime, 2); + + echo "\n=======================================================\n"; + echo "Migration terminée en $executionTime secondes\n"; + echo "Tables migrées avec succès: $successCount\n"; + echo "Tables en échec: $failCount\n"; + + exit(0); +} + +// Si une table spécifique est demandée, vérifier si un script dédié existe +if (isset($migrationScripts[$tableName])) { + $scriptPath = $migrationScripts[$tableName]; + if (file_exists($scriptPath)) { + executeMigrationScript($scriptPath); + exit(0); + } +} + +// Sinon, utiliser la méthode générique de migration (code existant) +if (!isset($tableMappings[$tableName])) { + echo "Erreur: La table '$tableName' n'est pas configurée pour la migration.\n"; + echo "Tables disponibles: " . implode(', ', array_keys($tableMappings)) . "\n"; + exit(1); +} + +// Création du dossier de logs si nécessaire +if (!is_dir(dirname(__DIR__) . '/logs')) { + mkdir(dirname(__DIR__) . '/logs', 0755, true); +} + +logOperation("Démarrage de la migration de la table $tableName"); + +try { + // Connexion aux bases de données + $sourceDb = getSourceConnection(); + $targetDb = getTargetConnection(); + + // Obtenir le service API pour le chiffrement si nécessaire + $apiService = null; + if (isset($tableMappings[$tableName]['encrypted_fields'])) { + $container = $GLOBALS['container']; + $apiService = $container->get('ApiService'); + } + + // Récupération des données de la source + $stmt = $sourceDb->query("SELECT * FROM $tableName"); + $records = $stmt->fetchAll(); + + logOperation("Nombre d'enregistrements à migrer: " . count($records)); + + // Vérifier si la table existe dans la cible + try { + $targetDb->query("SELECT 1 FROM $tableName LIMIT 1"); + $tableExists = true; + } catch (PDOException $e) { + $tableExists = false; + } + + // Créer la table si elle n'existe pas et si l'option est activée + if (!$tableExists && $createTable) { + logOperation("La table $tableName n'existe pas dans la base cible. Création de la table..."); + + // Récupérer la structure de la table source + $stmt = $sourceDb->query("SHOW CREATE TABLE $tableName"); + $tableStructure = $stmt->fetch(PDO::FETCH_ASSOC); + + if (isset($tableStructure['Create Table'])) { + $createTableSql = $tableStructure['Create Table']; + + // Adapter les noms de colonnes selon le mapping + $mapping = $tableMappings[$tableName]['source_to_target']; + foreach ($mapping as $sourceCol => $targetCol) { + $createTableSql = str_replace("`$sourceCol`", "`$targetCol`", $createTableSql); + } + + // Remplacer le nom de la clé primaire si nécessaire + $sourcePk = $tableMappings[$tableName]['primary_key']; + $targetPk = $tableMappings[$tableName]['target_primary_key']; + if ($sourcePk !== $targetPk) { + $createTableSql = str_replace("PRIMARY KEY (`$sourcePk`)", "PRIMARY KEY (`$targetPk`)", $createTableSql); + } + + // Créer la table + $targetDb->exec($createTableSql); + logOperation("Table $tableName créée avec succès"); + } else { + throw new Exception("Impossible de récupérer la structure de la table source"); + } + } + + // Vider la table cible si l'option est activée + if ($truncateTable && $tableExists) { + logOperation("Vidage de la table cible $tableName..."); + $targetDb->exec("TRUNCATE TABLE $tableName"); + } + + // Construire la requête d'insertion dynamiquement + $mapping = $tableMappings[$tableName]['source_to_target']; + + // Récupérer les colonnes de la table cible + $stmt = $targetDb->query("DESCRIBE $tableName"); + $targetColumns = $stmt->fetchAll(PDO::FETCH_COLUMN); + + // Construire les listes de colonnes pour l'insertion + $insertColumns = []; + $insertPlaceholders = []; + $updateClauses = []; + + foreach ($targetColumns as $column) { + $insertColumns[] = "`$column`"; + $insertPlaceholders[] = ":$column"; + $updateClauses[] = "`$column` = VALUES(`$column`)"; + } + + $insertColumnsSql = implode(", ", $insertColumns); + $insertPlaceholdersSql = implode(", ", $insertPlaceholders); + $updateClausesSql = implode(", ", $updateClauses); + + $insertQuery = "INSERT INTO $tableName ($insertColumnsSql) " + . "VALUES ($insertPlaceholdersSql) " + . "ON DUPLICATE KEY UPDATE $updateClausesSql"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs + $successCount = 0; + $errorCount = 0; + + // Traitement de chaque enregistrement + foreach ($records as $record) { + try { + $data = []; + + // Mappage des colonnes selon la configuration + foreach ($targetColumns as $targetCol) { + // Trouver la colonne source correspondante + $sourceCol = array_search($targetCol, $mapping); + + if ($sourceCol !== false) { + // La colonne existe dans le mapping + $data[$targetCol] = $record[$sourceCol]; + } elseif (isset($record[$targetCol])) { + // La colonne a le même nom dans les deux tables + $data[$targetCol] = $record[$targetCol]; + } else { + // Colonne non trouvée, utiliser NULL ou une valeur par défaut + $data[$targetCol] = null; + } + } + + // Traitement des champs chiffrés si nécessaire + if (isset($tableMappings[$tableName]['encrypted_fields']) && $apiService) { + foreach ($tableMappings[$tableName]['encrypted_fields'] as $sourceField => $config) { + $targetField = $config['field']; + $isSearchable = $config['searchable']; + + if (isset($record[$sourceField]) && !empty($record[$sourceField])) { + // Vérifier si le champ est déjà chiffré + if (isset($record["encrypted_$sourceField"])) { + $data[$targetField] = $record["encrypted_$sourceField"]; + } else { + // Chiffrer la donnée selon qu'elle est recherchable ou non + if ($isSearchable) { + $data[$targetField] = $apiService->encryptSearchableData($record[$sourceField]); + } else { + $data[$targetField] = $apiService->encryptData($record[$sourceField]); + } + } + } + } + } + + // Gestion spécifique pour certaines tables + if ($tableName === 'users') { + // Conversion de chk_active (0,1,2) vers is_active (booléen) + if (isset($record['chk_active'])) { + $data['is_active'] = ($record['chk_active'] > 0) ? 1 : 0; + } + } + + // Insertion dans la base cible + $insertStmt->execute($data); + $successCount++; + + // Identifiant pour le log + $pkField = $tableMappings[$tableName]['primary_key']; + $recordId = $record[$pkField] ?? 'inconnu'; + + logOperation("Enregistrement ID $recordId migré avec succès", "INFO"); + } catch (Exception $e) { + $errorCount++; + $pkField = $tableMappings[$tableName]['primary_key']; + $recordId = $record[$pkField] ?? 'inconnu'; + + logOperation("Erreur lors de la migration de l'enregistrement ID $recordId: " . $e->getMessage(), "ERROR"); + } + } + + logOperation("Migration terminée. Succès: $successCount, Erreurs: $errorCount"); + + // Fermer le tunnel SSH + closeSshTunnel(); + +} catch (Exception $e) { + logOperation("Erreur critique: " . $e->getMessage(), "ERROR"); + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_entites.php b/api/scripts/php/migrate_entites.php new file mode 100644 index 00000000..6bef1226 --- /dev/null +++ b/api/scripts/php/migrate_entites.php @@ -0,0 +1,201 @@ +query("SELECT * FROM users_entites"); + $entites = $stmt->fetchAll(PDO::FETCH_ASSOC); + + echo "Nombre d'entités à migrer: " . count($entites) . PHP_EOL; + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO entites ( + id, + encrypted_name, + adresse1, + adresse2, + code_postal, + ville, + fk_region, + fk_type, + encrypted_phone, + encrypted_mobile, + encrypted_email, + gps_lat, + gps_lng, + encrypted_iban, + encrypted_bic, + chk_demo, + chk_mdp_manuel, + chk_copie_mail_recu, + chk_accept_sms, + fk_user_creat, + fk_user_modif, + chk_active + ) VALUES ( + :id, + :encrypted_name, + :adresse1, + :adresse2, + :code_postal, + :ville, + :fk_region, + :fk_type, + :encrypted_phone, + :encrypted_mobile, + :encrypted_email, + :gps_lat, + :gps_lng, + :encrypted_iban, + :encrypted_bic, + :chk_demo, + :chk_mdp_manuel, + :chk_copie_mail_recu, + :chk_accept_sms, + :fk_user_creat, + :fk_user_modif, + :chk_active + ) ON DUPLICATE KEY UPDATE + encrypted_name = VALUES(encrypted_name), + adresse1 = VALUES(adresse1), + adresse2 = VALUES(adresse2), + code_postal = VALUES(code_postal), + ville = VALUES(ville), + fk_region = VALUES(fk_region), + fk_type = VALUES(fk_type), + encrypted_phone = VALUES(encrypted_phone), + encrypted_mobile = VALUES(encrypted_mobile), + encrypted_email = VALUES(encrypted_email), + gps_lat = VALUES(gps_lat), + gps_lng = VALUES(gps_lng), + encrypted_iban = VALUES(encrypted_iban), + encrypted_bic = VALUES(encrypted_bic), + chk_demo = VALUES(chk_demo), + chk_mdp_manuel = VALUES(chk_mdp_manuel), + chk_copie_mail_recu = VALUES(chk_copie_mail_recu), + chk_accept_sms = VALUES(chk_accept_sms), + fk_user_modif = VALUES(fk_user_modif), + chk_active = VALUES(chk_active)"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs + $successCount = 0; + $errorCount = 0; + + // Traitement de chaque entité + foreach ($entites as $entite) { + try { + // Mappage des champs entre les deux structures + $id = isset($entite['rowid']) ? $entite['rowid'] : $entite['id']; + $chkActive = isset($entite['active']) ? $entite['active'] : (isset($entite['chk_active']) ? $entite['chk_active'] : 1); + + // Chiffrement des données sensibles (uniquement si non vides) + $libelle = $entite['libelle'] ?? ''; + $encryptedName = !empty($libelle) ? ApiService::encryptData($libelle) : ''; + + // Traitement des numéros de téléphone + $tel1 = $entite['tel1'] ?? ''; + $tel2 = $entite['tel2'] ?? ''; + + // Initialisation des variables + $encryptedPhone = ''; + $encryptedMobile = ''; + + // Vérification si tel1 commence par 06 ou 07 (mobile) + if (preg_match('/^0[67]/', $tel1)) { + $encryptedMobile = ApiService::encryptData($tel1); + } elseif (!empty($tel1)) { + $encryptedPhone = ApiService::encryptData($tel1); + } + + // Vérification si tel2 commence par 06 ou 07 (mobile) + if (preg_match('/^0[67]/', $tel2)) { + // Si encryptedMobile est déjà rempli, on garde le premier mobile trouvé + if (empty($encryptedMobile)) { + $encryptedMobile = ApiService::encryptData($tel2); + } elseif (empty($encryptedPhone)) { + // Si on a déjà un mobile mais pas de téléphone fixe, on met le second mobile comme téléphone + $encryptedPhone = ApiService::encryptData($tel2); + } + } elseif (!empty($tel2)) { + // Si encryptedPhone est déjà rempli, on garde le premier fixe trouvé + if (empty($encryptedPhone)) { + $encryptedPhone = ApiService::encryptData($tel2); + } + } + + // Chiffrement des autres données sensibles (uniquement si non vides) + $email = $entite['email'] ?? ''; + $iban = $entite['iban'] ?? ''; + $bic = $entite['bic'] ?? ''; + + $encryptedEmail = !empty($email) ? ApiService::encryptSearchableData($email) : ''; + $encryptedIban = !empty($iban) ? ApiService::encryptData($iban) : ''; + $encryptedBic = !empty($bic) ? ApiService::encryptData($bic) : ''; + + // Préparation des données pour l'insertion + $entiteData = [ + 'id' => $id, + 'encrypted_name' => $encryptedName, + 'adresse1' => $entite['adresse1'] ?? '', + 'adresse2' => $entite['adresse2'] ?? '', + 'code_postal' => $entite['cp'] ?? '', + 'ville' => $entite['ville'] ?? '', + 'fk_region' => $entite['fk_region'] ?? null, + 'fk_type' => $entite['fk_type'] ?? 1, + 'encrypted_phone' => $encryptedPhone, + 'encrypted_mobile' => $encryptedMobile, + 'encrypted_email' => $encryptedEmail, + 'gps_lat' => $entite['gps_lat'] ?? '', + 'gps_lng' => $entite['gps_lng'] ?? '', + 'encrypted_iban' => $encryptedIban, + 'encrypted_bic' => $encryptedBic, + 'chk_demo' => 0, // Valeur par défaut à 0 comme demandé + 'chk_mdp_manuel' => $entite['chk_mdp_manuel'] ?? 1, + 'chk_copie_mail_recu' => $entite['chk_copie_mail_recu'] ?? 0, + 'chk_accept_sms' => $entite['chk_accept_sms'] ?? 0, + 'fk_user_creat' => $entite['fk_user_modif'] ?? null, + 'fk_user_modif' => $entite['fk_user_modif'] ?? null, + 'chk_active' => $chkActive + ]; + + // Insertion dans la base cible + $insertStmt->execute($entiteData); + $successCount++; + } catch (Exception $e) { + $errorCount++; + echo "Erreur lors de la migration de l'entité ID {$id}: " . $e->getMessage() . PHP_EOL; + } + } + + echo "Migration terminée. Succès: $successCount, Erreurs: $errorCount" . PHP_EOL; + + // Fermer le tunnel SSH + closeSshTunnel(); +} catch (Exception $e) { + echo "Erreur critique: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_medias.php b/api/scripts/php/migrate_medias.php new file mode 100644 index 00000000..fc5af44b --- /dev/null +++ b/api/scripts/php/migrate_medias.php @@ -0,0 +1,123 @@ +exec($deleteQuery); + + // Récupération des IDs des utilisateurs qui ont été migrés + $stmt = $targetDb->query("SELECT id FROM users"); + $migratedUsers = $stmt->fetchAll(PDO::FETCH_COLUMN); + + if (empty($migratedUsers)) { + echo "ERREUR: Aucun utilisateur n'a été migré. Veuillez d'abord migrer la table users." . PHP_EOL; + closeSshTunnel(); + exit(1); + } + + // Récupération des médias depuis la source + $query = "SELECT * FROM medias"; + $stmt = $sourceDb->query($query); + $medias = $stmt->fetchAll(PDO::FETCH_ASSOC); + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO medias ( + support, + support_id, + fichier, + description, + created_at, + fk_user_creat, + updated_at, + fk_user_modif + ) VALUES ( + :support, + :support_id, + :fichier, + :description, + :created_at, + :fk_user_creat, + :updated_at, + :fk_user_modif + )"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs pour le suivi + $inserted = 0; + $skipped = 0; + $errors = 0; + + // Traitement de chaque média + foreach ($medias as $media) { + // Vérifier si l'utilisateur de création existe dans la table users de la cible + $fkUserCreat = $media['fk_user_creat'] ?? 0; + if ($fkUserCreat > 0 && !in_array($fkUserCreat, $migratedUsers)) { + // L'utilisateur n'a pas été migré, on utilise 0 (système) + $fkUserCreat = 0; + } + + // Vérifier si l'utilisateur de modification existe dans la table users de la cible + $fkUserModif = $media['fk_user_modif'] ?? 0; + if ($fkUserModif > 0 && !in_array($fkUserModif, $migratedUsers)) { + // L'utilisateur n'a pas été migré, on utilise 0 (système) + $fkUserModif = 0; + } + + // Conversion des dates + $createdAt = !empty($media['date_creat']) ? date('Y-m-d H:i:s', strtotime($media['date_creat'])) : date('Y-m-d H:i:s'); + $updatedAt = !empty($media['date_modif']) ? date('Y-m-d H:i:s', strtotime($media['date_modif'])) : null; + + // Préparation des données pour l'insertion + $mediaData = [ + 'support' => $media['support'] ?? '', + 'support_id' => $media['support_rowid'] ?? 0, // Transformation de support_rowid en support_id + 'fichier' => $media['fichier'] ?? '', + 'description' => $media['description'] ?? '', + 'created_at' => $createdAt, + 'fk_user_creat' => $fkUserCreat, + 'updated_at' => $updatedAt, + 'fk_user_modif' => $fkUserModif + ]; + + try { + // Insertion dans la table cible + $insertStmt->execute($mediaData); + $inserted++; + } catch (PDOException $e) { + echo "ERREUR: Migration du média : " . $e->getMessage() . "\n"; + $errors++; + } + } + + // Afficher uniquement s'il y a des erreurs + if ($errors > 0) { + echo "ERREUR: $errors erreurs lors de la migration de la table medias." . PHP_EOL; + } + + // Fermer le tunnel SSH + closeSshTunnel(); + +} catch (Exception $e) { + echo "ERREUR CRITIQUE: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_ope_pass.php b/api/scripts/php/migrate_ope_pass.php new file mode 100644 index 00000000..5a5a3511 --- /dev/null +++ b/api/scripts/php/migrate_ope_pass.php @@ -0,0 +1,586 @@ +passed_at, libelle=>encrypted_name, email=>encrypted_email, phone=>encrypted_phone) + */ + +require_once dirname(__DIR__) . '/config.php'; +require_once __DIR__ . '/MigrationConfig.php'; +require_once dirname(dirname(__DIR__)) . '/src/Services/ApiService.php'; + +try { + // Vérifier si un processus utilise déjà le port du tunnel SSH + echo "Vérification du port SSH..." . PHP_EOL; + + // Création du tunnel SSH avec une meilleure gestion des erreurs + try { + // Tuer tout processus existant qui utilise le port 13306 + // Sous Linux/Mac + @exec('kill $(lsof -t -i:13306) 2>/dev/null'); + // Attendre un moment pour s'assurer que le port est libéré + sleep(1); + + createSshTunnel(); + echo "Tunnel SSH créé avec succès." . PHP_EOL; + } catch (Exception $e) { + echo "ERREUR lors de la création du tunnel SSH: " . $e->getMessage() . PHP_EOL; + exit(1); + } + + // Connexion aux bases de données avec paramètres pour éviter le timeout + try { + echo "Connexion à la base source..." . PHP_EOL; + $sourceDb = getSourceConnection(); + echo "Connexion à la base source établie." . PHP_EOL; + } catch (Exception $e) { + echo "ERREUR de connexion à la base source: " . $e->getMessage() . PHP_EOL; + closeSshTunnel(); + exit(1); + } + + // Configuration spéciale pour éviter les timeouts sur les grosses opérations + try { + echo "Connexion à la base cible..." . PHP_EOL; + $targetDb = getTargetConnection(); + echo "Connexion à la base cible établie." . PHP_EOL; + + // Configuration des timeouts adaptés à MariaDB 10.11 + $targetDb->setAttribute(PDO::ATTR_TIMEOUT, 600); // 10 minutes pour PDO + + echo " - Configuration des timeouts pour MariaDB 10.11" . PHP_EOL; + + // Configurations spécifiques à MariaDB 10.11 + $timeoutVars = [ + "wait_timeout" => 3600, // 1 heure + "net_read_timeout" => 3600, // 1 heure + "net_write_timeout" => 3600, // 1 heure + "innodb_lock_wait_timeout" => 3600 // 1 heure + ]; + + // Configurer les variables de session + foreach ($timeoutVars as $var => $value) { + try { + $sql = "SET SESSION $var=$value"; + $targetDb->exec($sql); + echo " - Config MariaDB: $var = $value" . PHP_EOL; + } catch (PDOException $e) { + echo " - Impossible de configurer $var: " . $e->getMessage() . PHP_EOL; + } + } + + echo "Paramètres de timeout configurés." . PHP_EOL; + } catch (Exception $e) { + echo "ERREUR de connexion à la base cible: " . $e->getMessage() . PHP_EOL; + closeSshTunnel(); + exit(1); + } + + // Début de la migration + + // Vérifions la version de la base de données cible (MariaDB) + $versionTarget = $targetDb->query('SELECT VERSION() as version')->fetch(); + echo "Version de la base cible (MariaDB): " . $versionTarget['version'] . PHP_EOL; + + // Vérifions la version de la base de données source (MySQL) + $versionSource = $sourceDb->query('SELECT VERSION() as version')->fetch(); + echo "Version de la base source (MySQL): " . $versionSource['version'] . PHP_EOL; + + // Note sur les privilèges de contraintes + echo "NOTE: La suppression et recréation des contraintes nécessitent des privilèges SUPER ou ALTER TABLE." . PHP_EOL; + echo " Ces opérations peuvent être ignorées si l'utilisateur n'a pas les privilèges suffisants." . PHP_EOL; + echo " Il est recommandé d'exécuter ces opérations manuellement avec un utilisateur admin." . PHP_EOL; + + // Suppression des contraintes relationnelles (tentatif) + echo "Tentative de suppression des contraintes relationnelles... " . PHP_EOL; + $dropConstraintsQueries = [ + "ALTER TABLE ope_pass DROP FOREIGN KEY ope_pass_ibfk_1", + "ALTER TABLE ope_pass DROP FOREIGN KEY ope_pass_ibfk_2", + "ALTER TABLE ope_pass DROP FOREIGN KEY ope_pass_ibfk_3", + "ALTER TABLE ope_pass DROP FOREIGN KEY ope_pass_ibfk_4" + ]; + + $constraintDropFailed = false; + foreach ($dropConstraintsQueries as $query) { + try { + $targetDb->exec($query); + echo " - Contrainte supprimée avec succès : " . substr($query, 0, 60) . "..." . PHP_EOL; + } catch (PDOException $e) { + echo " - Erreur lors de la suppression de la contrainte : " . $e->getMessage() . PHP_EOL; + $constraintDropFailed = true; + } + } + + if ($constraintDropFailed) { + echo "ATTENTION: Les contraintes n'ont pas pu être supprimées. La migration continue sans cette étape." . PHP_EOL; + echo " Vous devrez peut-être désactiver les contraintes manuellement si la suppression échoue." . PHP_EOL; + } + + // Suppression de toutes les données existantes dans la table ope_pass par lots pour éviter les timeouts + echo "Suppression des données existantes dans la table ope_pass (par lots)... " . PHP_EOL; + + try { + // Désactiver temporairement les vérifications de clés étrangères + // Cela fonctionne à la fois dans MySQL et MariaDB + try { + $targetDb->exec("SET FOREIGN_KEY_CHECKS=0"); + echo " - Vérification des clés étrangères temporairement désactivée." . PHP_EOL; + } catch (PDOException $e) { + echo " - Erreur lors de la désactivation des clés étrangères: " . $e->getMessage() . PHP_EOL; + } + + // Suppression par lots + $batchSize = 100000; + $totalDeleted = 0; + $continue = true; + + echo " - Suppression par lots de $batchSize enregistrements:" . PHP_EOL; + + while ($continue) { + $deleteQuery = "DELETE FROM ope_pass LIMIT $batchSize"; + $rowCount = $targetDb->exec($deleteQuery); + $totalDeleted += $rowCount; + echo " * Lot supprimé: $rowCount enregistrements (Total: $totalDeleted)" . PHP_EOL; + + // Vérifier si nous avons terminé + if ($rowCount < $batchSize) { + $continue = false; + } + + // Petit délai pour permettre des traitements serveur + if ($continue) { + usleep(100000); // 0.1 seconde + } + } + + echo " - Total: $totalDeleted enregistrements supprimés." . PHP_EOL; + + // Réactiver les vérifications de clés étrangères + try { + $targetDb->exec("SET FOREIGN_KEY_CHECKS=1"); + echo " - Vérification des clés étrangères réactivée." . PHP_EOL; + } catch (PDOException $e) { + echo " - Erreur lors de la réactivation des clés étrangères: " . $e->getMessage() . PHP_EOL; + } + + } catch (PDOException $e) { + echo " - Erreur lors de la suppression des données : " . $e->getMessage() . PHP_EOL; + + // Réactiver les vérifications de clés étrangères en cas d'erreur + try { + $targetDb->exec("SET FOREIGN_KEY_CHECKS=1"); + } catch (Exception $e2) { + echo " - Erreur lors de la réactivation des clés étrangères : " . $e2->getMessage() . PHP_EOL; + } + + closeSshTunnel(); + exit(1); + } + + // Récupération des IDs des opérations qui ont été migrées + $stmt = $targetDb->query("SELECT id FROM operations"); + $migratedOperations = $stmt->fetchAll(PDO::FETCH_COLUMN); + + if (empty($migratedOperations)) { + echo "ERREUR: Aucune opération n'a été migrée. Veuillez d'abord migrer la table operations." . PHP_EOL; + closeSshTunnel(); + exit(1); + } + + // Récupération des IDs des utilisateurs qui ont été migrés + $stmt = $targetDb->query("SELECT id FROM users"); + $migratedUsers = $stmt->fetchAll(PDO::FETCH_COLUMN); + + if (empty($migratedUsers)) { + echo "ERREUR: Aucun utilisateur n'a été migré. Veuillez d'abord migrer la table users." . PHP_EOL; + closeSshTunnel(); + exit(1); + } + + // Récupération de la correspondance entre les anciens secteurs et les nouveaux + $query = "SELECT id, fk_operation, fk_old_sector FROM ope_sectors WHERE fk_old_sector IS NOT NULL"; + $stmt = $targetDb->query($query); + $sectorMapping = $stmt->fetchAll(PDO::FETCH_ASSOC); + + if (empty($sectorMapping)) { + echo "ERREUR: Aucun secteur n'a été migré. Veuillez d'abord migrer la table ope_sectors." . PHP_EOL; + closeSshTunnel(); + exit(1); + } + + // Création d'un tableau associatif pour faciliter la recherche des correspondances + $sectorMap = []; + foreach ($sectorMapping as $mapping) { + $key = $mapping['fk_operation'] . '_' . $mapping['fk_old_sector']; + $sectorMap[$key] = $mapping['id']; + } + + // Pas d'affichage en mode silencieux + + // Création de la liste des IDs d'opérations pour la requête IN + $operationIds = implode(',', $migratedOperations); + + // Compter le nombre total de passages à migrer pour estimer le volume + $countQuery = " + SELECT COUNT(*) as total + FROM ope_pass p + WHERE p.fk_operation IN ($operationIds) + AND p.active = 1 + "; + $countStmt = $sourceDb->query($countQuery); + $totalCount = $countStmt->fetch(PDO::FETCH_ASSOC)['total']; + + echo "Nombre total de passages à migrer: $totalCount" . PHP_EOL; + + // Définir la taille des lots pour éviter les problèmes de mémoire + $batchSize = 5000; + $totalBatches = ceil($totalCount / $batchSize); + + echo "Traitement par lots de $batchSize passages ($totalBatches lots au total)" . PHP_EOL; + + // Pas d'affichage du nombre de passages à migrer en mode silencieux + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO ope_pass ( + fk_operation, + fk_sector, + fk_user, + fk_adresse, + passed_at, + fk_type, + numero, + rue, + rue_bis, + ville, + fk_habitat, + appt, + niveau, + gps_lat, + gps_lng, + encrypted_name, + montant, + fk_type_reglement, + remarque, + encrypted_email, + nom_recu, + email_erreur, + chk_email_sent, + encrypted_phone, + docremis, + date_repasser, + nb_passages, + chk_gps_maj, + chk_map_create, + chk_mobile, + chk_synchro, + chk_api_adresse, + chk_maj_adresse, + anomalie, + created_at, + fk_user_creat, + updated_at, + fk_user_modif, + chk_active + ) VALUES ( + :fk_operation, + :fk_sector, + :fk_user, + :fk_adresse, + :passed_at, + :fk_type, + :numero, + :rue, + :rue_bis, + :ville, + :fk_habitat, + :appt, + :niveau, + :gps_lat, + :gps_lng, + :encrypted_name, + :montant, + :fk_type_reglement, + :remarque, + :encrypted_email, + :nom_recu, + :email_erreur, + :chk_email_sent, + :encrypted_phone, + :docremis, + :date_repasser, + :nb_passages, + :chk_gps_maj, + :chk_map_create, + :chk_mobile, + :chk_synchro, + :chk_api_adresse, + :chk_maj_adresse, + :anomalie, + :created_at, + :fk_user_creat, + :updated_at, + :fk_user_modif, + :chk_active + ) ON DUPLICATE KEY UPDATE + fk_sector = VALUES(fk_sector), + passed_at = VALUES(passed_at), + numero = VALUES(numero), + rue = VALUES(rue), + rue_bis = VALUES(rue_bis), + ville = VALUES(ville), + fk_habitat = VALUES(fk_habitat), + appt = VALUES(appt), + niveau = VALUES(niveau), + gps_lat = VALUES(gps_lat), + gps_lng = VALUES(gps_lng), + encrypted_name = VALUES(encrypted_name), + montant = VALUES(montant), + fk_type_reglement = VALUES(fk_type_reglement), + remarque = VALUES(remarque), + encrypted_email = VALUES(encrypted_email), + nom_recu = VALUES(nom_recu), + email_erreur = VALUES(email_erreur), + chk_email_sent = VALUES(chk_email_sent), + encrypted_phone = VALUES(encrypted_phone), + docremis = VALUES(docremis), + date_repasser = VALUES(date_repasser), + nb_passages = VALUES(nb_passages), + chk_gps_maj = VALUES(chk_gps_maj), + chk_map_create = VALUES(chk_map_create), + chk_mobile = VALUES(chk_mobile), + chk_synchro = VALUES(chk_synchro), + chk_api_adresse = VALUES(chk_api_adresse), + chk_maj_adresse = VALUES(chk_maj_adresse), + anomalie = VALUES(anomalie), + updated_at = VALUES(updated_at), + fk_user_modif = VALUES(fk_user_modif), + chk_active = VALUES(chk_active)"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs + $inserted = 0; + $skipped = 0; + $errors = 0; + + // Traitement par lots pour éviter les problèmes de mémoire + for ($batch = 0; $batch < $totalBatches; $batch++) { + $offset = $batch * $batchSize; + + echo "Traitement du lot " . ($batch + 1) . "/$totalBatches (offset: $offset)" . PHP_EOL; + + // Récupération d'un lot de passages + $query = " + SELECT p.* + FROM ope_pass p + WHERE p.fk_operation IN ($operationIds) + AND p.active = 1 + LIMIT $batchSize OFFSET $offset + "; + + $stmt = $sourceDb->query($query); + $passages = $stmt->fetchAll(PDO::FETCH_ASSOC); + + echo " - " . count($passages) . " passages récupérés dans ce lot" . PHP_EOL; + + // Libérer la mémoire après avoir récupéré les données + $stmt->closeCursor(); + unset($stmt); + + // Traitement des passages de ce lot + $batchInserted = 0; + $batchSkipped = 0; + $batchErrors = 0; + + // Commencer une transaction pour les insertions de ce lot + $targetDb->beginTransaction(); + + foreach ($passages as $passage) { + $fkOperation = $passage['fk_operation']; + $fkOldSector = $passage['fk_sector']; + + // Vérifier si le secteur existe dans la table ope_sectors de la cible + // On utilise la requête pour trouver le secteur correspondant dans la table ope_sectors + $sectorQuery = "SELECT id FROM ope_sectors WHERE fk_operation = :fk_operation AND fk_old_sector = :fk_old_sector"; + $sectorStmt = $targetDb->prepare($sectorQuery); + $sectorStmt->execute([ + ':fk_operation' => $fkOperation, + ':fk_old_sector' => $fkOldSector + ]); + + $newSector = $sectorStmt->fetch(PDO::FETCH_ASSOC); + + // Si le secteur n'a pas été migré, on ignore ce passage silencieusement + if (!$newSector) { + $skipped++; + continue; + } + + $fkNewSector = $newSector['id']; + + // Vérifier si l'utilisateur existe dans la table users de la cible + $fkUser = $passage['fk_user'] ?? 0; + if ($fkUser > 0 && !in_array($fkUser, $migratedUsers)) { + // L'utilisateur n'a pas été migré, on ignore ce passage silencieusement + $skipped++; + continue; + } + + // Conversion des dates + $passedAt = !empty($passage['date_eve']) ? date('Y-m-d H:i:s', strtotime($passage['date_eve'])) : null; + $dateRepasser = !empty($passage['date_repasser']) ? date('Y-m-d H:i:s', strtotime($passage['date_repasser'])) : null; + $createdAt = !empty($passage['date_creat']) ? date('Y-m-d H:i:s', strtotime($passage['date_creat'])) : date('Y-m-d H:i:s'); + $updatedAt = !empty($passage['date_modif']) ? date('Y-m-d H:i:s', strtotime($passage['date_modif'])) : null; + + // Chiffrement des données sensibles + // Validation et chiffrement du nom + $encryptedName = ''; + if (!empty($passage['libelle'])) { + $encryptedName = ApiService::encryptData($passage['libelle']); + } + + // Validation et chiffrement de l'email + $encryptedEmail = ''; + if (!empty($passage['email'])) { + // Vérifier si l'email est valide + if (filter_var($passage['email'], FILTER_VALIDATE_EMAIL)) { + $encryptedEmail = ApiService::encryptSearchableData($passage['email']); + } + } + + $encryptedPhone = !empty($passage['phone']) ? ApiService::encryptData($passage['phone']) : ''; + + // Vérification et correction du type de règlement + $fkTypeReglement = $passage['fk_type_reglement'] ?? 1; + if (!in_array($fkTypeReglement, [1, 2, 3])) { + $fkTypeReglement = 4; // Forcer à 4 si différent de 1, 2 ou 3 + } + + // Préparation des données pour l'insertion + $passageData = [ + 'fk_operation' => $fkOperation, + 'fk_sector' => $fkNewSector, + 'fk_user' => $passage['fk_user'] ?? 0, + 'fk_adresse' => $passage['fk_adresse'] ?? '', + 'passed_at' => $passedAt, // Mapping date_eve => passed_at + 'fk_type' => (isset($passage['fk_type']) && $passage['fk_type'] == '9') ? 6 : + ((isset($passage['fk_type']) && $passage['fk_type'] == '8') ? 5 : + (isset($passage['fk_type']) ? (int)$passage['fk_type'] : 0)), + 'numero' => $passage['numero'] ?? '', + 'rue' => $passage['rue'] ?? '', + 'rue_bis' => $passage['rue_bis'] ?? '', + 'ville' => $passage['ville'] ?? '', + 'fk_habitat' => $passage['fk_habitat'] ?? 1, + 'appt' => $passage['appt'] ?? '', + 'niveau' => $passage['niveau'] ?? '', + 'gps_lat' => $passage['gps_lat'] ?? '', + 'gps_lng' => $passage['gps_lng'] ?? '', + 'encrypted_name' => $encryptedName, // Mapping libelle => encrypted_name avec chiffrement + 'montant' => $passage['montant'] ?? 0, + 'fk_type_reglement' => $fkTypeReglement, // Valeur corrigée + 'remarque' => $passage['remarque'] ?? '', + 'encrypted_email' => $encryptedEmail, // Mapping email => encrypted_email avec chiffrement + 'nom_recu' => $passage['recu'] ?? null, // Mapping recu => nom_recu + 'email_erreur' => $passage['email_erreur'] ?? '', + 'chk_email_sent' => $passage['chk_email_sent'] ?? 0, + 'encrypted_phone' => $encryptedPhone, // Mapping phone => encrypted_phone avec chiffrement + 'docremis' => $passage['docremis'] ?? 0, + 'date_repasser' => $dateRepasser, + 'nb_passages' => $passage['nb_passages'] ?? 1, + 'chk_gps_maj' => $passage['chk_gps_maj'] ?? 0, + 'chk_map_create' => $passage['chk_map_create'] ?? 0, + 'chk_mobile' => $passage['chk_mobile'] ?? 0, + 'chk_synchro' => $passage['chk_synchro'] ?? 1, + 'chk_api_adresse' => $passage['chk_api_adresse'] ?? 0, + 'chk_maj_adresse' => $passage['chk_maj_adresse'] ?? 0, + 'anomalie' => $passage['anomalie'] ?? 0, + 'created_at' => $createdAt, + 'fk_user_creat' => $passage['fk_user_creat'] ?? null, + 'updated_at' => $updatedAt, + 'fk_user_modif' => $passage['fk_user_modif'] ?? null, + 'chk_active' => $passage['active'] ?? 1 + ]; + + try { + // Insertion dans la table cible + $insertStmt->execute($passageData); + $inserted++; + $batchInserted++; + + // Libérer un peu de mémoire entre chaque insertion + if ($batchInserted % 100 == 0) { + unset($passageData); + gc_collect_cycles(); // Forcer le garbage collector + } + } catch (PDOException $e) { + echo "ERREUR: Migration du passage (rowid " . $passage['rowid'] . ", opération $fkOperation) : " . $e->getMessage() . "\n"; + $errors++; + $batchErrors++; + } + + // Libérer la mémoire du passage traité + unset($passage); + } + + // Valider la transaction pour ce lot + try { + $targetDb->commit(); + echo " - Lot $batch commité avec succès: $batchInserted insérés, $batchSkipped ignorés, $batchErrors erreurs" . PHP_EOL; + } catch (PDOException $e) { + $targetDb->rollBack(); + echo "ERREUR lors du commit du lot $batch: " . $e->getMessage() . PHP_EOL; + } + + // Libérer la mémoire après chaque lot + unset($passages); + gc_collect_cycles(); // Forcer le garbage collector + + // Petite pause entre les lots pour éviter de surcharger le serveur + sleep(1); + } + + echo "Migration de la table ope_pass terminée. $inserted passages insérés, $skipped passages ignorés, $errors erreurs." . PHP_EOL; + + // Recréation des contraintes relationnelles + echo "Tentative de recréation des contraintes relationnelles... " . PHP_EOL; + $addConstraintsQueries = [ + "ALTER TABLE ope_pass ADD CONSTRAINT ope_pass_ibfk_1 FOREIGN KEY (fk_operation) REFERENCES operations (id) ON DELETE RESTRICT ON UPDATE CASCADE", + "ALTER TABLE ope_pass ADD CONSTRAINT ope_pass_ibfk_2 FOREIGN KEY (fk_sector) REFERENCES ope_sectors (id) ON DELETE RESTRICT ON UPDATE CASCADE", + "ALTER TABLE ope_pass ADD CONSTRAINT ope_pass_ibfk_3 FOREIGN KEY (fk_user) REFERENCES users (id) ON DELETE RESTRICT ON UPDATE CASCADE", + "ALTER TABLE ope_pass ADD CONSTRAINT ope_pass_ibfk_4 FOREIGN KEY (fk_type_reglement) REFERENCES x_types_reglements (id) ON DELETE RESTRICT ON UPDATE CASCADE" + ]; + + $constraintAddFailed = false; + foreach ($addConstraintsQueries as $query) { + try { + $targetDb->exec($query); + echo " - Contrainte recréée avec succès : " . substr($query, 0, 60) . "..." . PHP_EOL; + } catch (PDOException $e) { + echo " - Erreur lors de la recréation de la contrainte : " . $e->getMessage() . PHP_EOL; + $constraintAddFailed = true; + } + } + + if ($constraintAddFailed) { + echo "ATTENTION: Certaines contraintes n'ont pas pu être recréées." . PHP_EOL; + echo " Script SQL pour recréer manuellement les contraintes:" . PHP_EOL; + echo "--------------------------------------------------------------" . PHP_EOL; + foreach ($addConstraintsQueries as $query) { + echo "$query;" . PHP_EOL; + } + echo "--------------------------------------------------------------" . PHP_EOL; + } + + // Fermer le tunnel SSH + closeSshTunnel(); +} catch (Exception $e) { + echo "ERREUR CRITIQUE: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_ope_pass_histo.php b/api/scripts/php/migrate_ope_pass_histo.php new file mode 100644 index 00000000..959e790f --- /dev/null +++ b/api/scripts/php/migrate_ope_pass_histo.php @@ -0,0 +1,126 @@ +exec($deleteQuery); + + // Récupération des IDs des passages qui ont été migrés + $stmt = $targetDb->query("SELECT id FROM ope_pass"); + $migratedPasses = $stmt->fetchAll(PDO::FETCH_COLUMN); + + if (empty($migratedPasses)) { + echo "ERREUR: Aucun passage n'a été migré. Veuillez d'abord migrer la table ope_pass." . PHP_EOL; + closeSshTunnel(); + exit(1); + } + + // Récupération des IDs des utilisateurs qui ont été migrés + $stmt = $targetDb->query("SELECT id FROM users"); + $migratedUsers = $stmt->fetchAll(PDO::FETCH_COLUMN); + + if (empty($migratedUsers)) { + echo "ERREUR: Aucun utilisateur n'a été migré. Veuillez d'abord migrer la table users." . PHP_EOL; + closeSshTunnel(); + exit(1); + } + + // Récupération directe des IDs des passages dans la table cible + $stmt = $targetDb->query("SELECT id FROM ope_pass"); + $migratedPassIds = $stmt->fetchAll(PDO::FETCH_COLUMN); + + if (empty($migratedPassIds)) { + echo "ERREUR: Aucun passage n'a été migré. Veuillez d'abord migrer la table ope_pass." . PHP_EOL; + closeSshTunnel(); + exit(1); + } + + // Récupération des historiques de passages depuis la source + $query = "SELECT * FROM ope_pass_histo"; + + $stmt = $sourceDb->query($query); + $histos = $stmt->fetchAll(PDO::FETCH_ASSOC); + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO ope_pass_histo ( + fk_pass, + date_histo, + sujet, + remarque + ) VALUES ( + :fk_pass, + :date_histo, + :sujet, + :remarque + )"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs pour le suivi + $inserted = 0; + $skipped = 0; + $errors = 0; + + // Traitement de chaque historique + foreach ($histos as $histo) { + // Vérifier si l'ID du passage existe dans la table cible + $fkPass = $histo['fk_pass']; + if (!in_array($fkPass, $migratedPassIds)) { + // Le passage n'a pas été migré, on ignore cet historique + $skipped++; + continue; + } + + // On ignore le champ fk_user qui n'existe plus dans la table cible + + // Conversion des dates + $dateHisto = !empty($histo['date_histo']) ? date('Y-m-d H:i:s', strtotime($histo['date_histo'])) : null; + + // Préparation des données pour l'insertion + $histoData = [ + 'fk_pass' => $fkPass, + 'date_histo' => $dateHisto, + 'sujet' => $histo['sujet'] ?? '', + 'remarque' => $histo['remarque'] ?? '' + ]; + + try { + // Insertion dans la table cible + $insertStmt->execute($histoData); + $inserted++; + } catch (PDOException $e) { + echo "ERREUR: Migration de l'historique (rowid {$histo['rowid']}, passage {$fkPass}) : " . $e->getMessage() . "\n"; + $errors++; + } + } + + // Afficher uniquement s'il y a des erreurs + if ($errors > 0) { + echo "ERREUR: $errors erreurs lors de la migration de la table ope_pass_histo." . PHP_EOL; + } + + // Fermer le tunnel SSH + closeSshTunnel(); + +} catch (Exception $e) { + echo "ERREUR CRITIQUE: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_ope_sectors.php b/api/scripts/php/migrate_ope_sectors.php new file mode 100644 index 00000000..9e872bc9 --- /dev/null +++ b/api/scripts/php/migrate_ope_sectors.php @@ -0,0 +1,152 @@ +query("SELECT id FROM operations"); + $migratedOperations = $stmt->fetchAll(PDO::FETCH_COLUMN); + + if (empty($migratedOperations)) { + echo "Aucune opération n'a été migrée. Veuillez d'abord migrer la table operations." . PHP_EOL; + closeSshTunnel(); + exit(1); + } + + echo "Nombre d'opérations migrées : " . count($migratedOperations) . PHP_EOL; + + // Création de la liste des IDs d'opérations pour la requête IN + $operationIds = implode(',', $migratedOperations); + + // Récupération des secteurs distincts liés aux opérations migrées + $query = " + SELECT DISTINCT ous.fk_operation, ous.fk_sector, s.libelle, s.sector, s.color + FROM ope_users_sectors ous + JOIN sectors s ON ous.fk_sector = s.rowid + WHERE ous.fk_operation IN ($operationIds) + AND ous.active = 1 + AND s.active = 1 + "; + + $stmt = $sourceDb->query($query); + $sectors = $stmt->fetchAll(PDO::FETCH_ASSOC); + + echo "Nombre de secteurs distincts à migrer : " . count($sectors) . PHP_EOL; + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO ope_sectors ( + fk_operation, + fk_old_sector, + libelle, + sector, + color, + created_at, + fk_user_creat, + updated_at, + fk_user_modif, + chk_active + ) VALUES ( + :fk_operation, + :fk_old_sector, + :libelle, + :sector, + :color, + :created_at, + :fk_user_creat, + :updated_at, + :fk_user_modif, + :chk_active + ) ON DUPLICATE KEY UPDATE + libelle = VALUES(libelle), + sector = VALUES(sector), + color = VALUES(color), + updated_at = VALUES(updated_at), + fk_user_modif = VALUES(fk_user_modif)"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs + $inserted = 0; + $errors = 0; + + // Traitement de chaque secteur + foreach ($sectors as $sector) { + // Récupération des informations du secteur source + $fkOperation = $sector['fk_operation']; + $fkOldSector = $sector['fk_sector']; + $libelle = $sector['libelle'] ?? ''; + $sectorData = $sector['sector'] ?? ''; + $color = $sector['color'] ?? '#4B77BE'; + + // Vérification si le secteur existe déjà pour cette opération + $checkQuery = "SELECT id FROM ope_sectors WHERE fk_operation = :fk_operation AND fk_old_sector = :fk_old_sector"; + $checkStmt = $targetDb->prepare($checkQuery); + $checkStmt->execute([ + 'fk_operation' => $fkOperation, + 'fk_old_sector' => $fkOldSector + ]); + + $exists = $checkStmt->fetch(PDO::FETCH_ASSOC); + + // Si le secteur existe déjà, passer au suivant + if ($exists) { + echo "Le secteur avec fk_operation=$fkOperation et fk_old_sector=$fkOldSector existe déjà. Mise à jour...\n"; + } + + // Préparation des données pour l'insertion + $sectorData = [ + 'fk_operation' => $fkOperation, + 'fk_old_sector' => $fkOldSector, + 'libelle' => $libelle, + 'sector' => $sectorData, + 'color' => $color, + 'created_at' => date('Y-m-d H:i:s'), + 'fk_user_creat' => 1, // Utilisateur par défaut + 'updated_at' => date('Y-m-d H:i:s'), + 'fk_user_modif' => 1, // Utilisateur par défaut + 'chk_active' => 1 + ]; + + try { + // Insertion dans la table cible + $insertStmt->execute($sectorData); + $inserted++; + + // Affichage du progrès + if ($inserted % 10 === 0) { + echo "Progression : $inserted secteurs migrés...\n"; + } + } catch (PDOException $e) { + echo "Erreur lors de la migration du secteur (opération $fkOperation, secteur $fkOldSector) : " . $e->getMessage() . "\n"; + $errors++; + } + } + + echo "Migration terminée. $inserted secteurs migrés avec succès. $errors erreurs rencontrées." . PHP_EOL; + + // Fermer le tunnel SSH + closeSshTunnel(); + +} catch (Exception $e) { + echo "Erreur critique: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_ope_users.php b/api/scripts/php/migrate_ope_users.php new file mode 100644 index 00000000..10958eca --- /dev/null +++ b/api/scripts/php/migrate_ope_users.php @@ -0,0 +1,143 @@ +query("SELECT id FROM operations"); + $migratedOperations = $stmt->fetchAll(PDO::FETCH_COLUMN); + + if (empty($migratedOperations)) { + echo "Aucune opération n'a été migrée. Veuillez d'abord migrer la table operations." . PHP_EOL; + closeSshTunnel(); + exit(1); + } + + echo "Nombre d'opérations migrées : " . count($migratedOperations) . PHP_EOL; + + // Récupération des IDs des utilisateurs qui ont été migrés + $stmt = $targetDb->query("SELECT id FROM users"); + $migratedUsers = $stmt->fetchAll(PDO::FETCH_COLUMN); + + if (empty($migratedUsers)) { + echo "Aucun utilisateur n'a été migré. Veuillez d'abord migrer la table users." . PHP_EOL; + closeSshTunnel(); + exit(1); + } + + echo "Nombre d'utilisateurs migrés : " . count($migratedUsers) . PHP_EOL; + + // Création de la liste des IDs d'opérations pour la requête IN + $operationIds = implode(',', $migratedOperations); + + // Création de la liste des IDs d'utilisateurs pour la requête IN + $userIds = implode(',', $migratedUsers); + + // Récupération des associations utilisateurs-opérations depuis la base source + // Ne récupérer que les associations qui concernent à la fois des opérations et des utilisateurs migrés + $query = "SELECT * FROM ope_users WHERE fk_operation IN ($operationIds) AND fk_user IN ($userIds)"; + $stmt = $sourceDb->query($query); + $opeUsers = $stmt->fetchAll(PDO::FETCH_ASSOC); + + echo "Nombre d'associations utilisateurs-opérations à migrer : " . count($opeUsers) . PHP_EOL; + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO ope_users ( + id, + fk_operation, + fk_user, + created_at, + fk_user_creat, + updated_at, + fk_user_modif, + chk_active + ) VALUES ( + :id, + :fk_operation, + :fk_user, + :created_at, + :fk_user_creat, + :updated_at, + :fk_user_modif, + :chk_active + ) ON DUPLICATE KEY UPDATE + fk_operation = VALUES(fk_operation), + fk_user = VALUES(fk_user), + updated_at = VALUES(updated_at), + fk_user_modif = VALUES(fk_user_modif), + chk_active = VALUES(chk_active)"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs + $inserted = 0; + $errors = 0; + + // Traitement de chaque association utilisateur-opération + foreach ($opeUsers as $opeUser) { + // Mappage des champs + $id = isset($opeUser['rowid']) ? $opeUser['rowid'] : $opeUser['id']; + $chkActive = isset($opeUser['active']) ? $opeUser['active'] : (isset($opeUser['chk_active']) ? $opeUser['chk_active'] : 1); + + // Gestion des dates + $createdAt = isset($opeUser['date_creat']) && !empty($opeUser['date_creat']) ? + date('Y-m-d H:i:s', strtotime($opeUser['date_creat'])) : + date('Y-m-d H:i:s'); + + $updatedAt = isset($opeUser['date_modif']) && !empty($opeUser['date_modif']) ? + date('Y-m-d H:i:s', strtotime($opeUser['date_modif'])) : + null; + + // Préparation des données pour l'insertion + $opeUserData = [ + 'id' => $id, + 'fk_operation' => $opeUser['fk_operation'], + 'fk_user' => $opeUser['fk_user'], + 'created_at' => $createdAt, + 'fk_user_creat' => $opeUser['fk_user_creat'] ?? 0, + 'updated_at' => $updatedAt, + 'fk_user_modif' => $opeUser['fk_user_modif'] ?? 0, + 'chk_active' => $chkActive + ]; + + try { + // Insertion dans la table cible + $insertStmt->execute($opeUserData); + $inserted++; + + // Affichage du progrès + if ($inserted % 100 === 0) { + echo "Progression : $inserted associations utilisateurs-opérations migrées..." . PHP_EOL; + } + } catch (PDOException $e) { + echo "Erreur lors de la migration de l'association utilisateur-opération ID $id : " . $e->getMessage() . PHP_EOL; + $errors++; + } + } + + echo "Migration terminée. $inserted associations utilisateurs-opérations migrées avec succès. $errors erreurs rencontrées." . PHP_EOL; + + // Fermer le tunnel SSH + closeSshTunnel(); + +} catch (Exception $e) { + echo "Erreur critique: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_ope_users_sectors.php b/api/scripts/php/migrate_ope_users_sectors.php new file mode 100644 index 00000000..b294d945 --- /dev/null +++ b/api/scripts/php/migrate_ope_users_sectors.php @@ -0,0 +1,170 @@ +query("SELECT id FROM operations"); + $migratedOperations = $stmt->fetchAll(PDO::FETCH_COLUMN); + + if (empty($migratedOperations)) { + echo "Aucune opération n'a été migrée. Veuillez d'abord migrer la table operations." . PHP_EOL; + closeSshTunnel(); + exit(1); + } + + echo "Nombre d'opérations migrées : " . count($migratedOperations) . PHP_EOL; + + // Récupération des IDs des utilisateurs qui ont été migrés + $stmt = $targetDb->query("SELECT id FROM users"); + $migratedUsers = $stmt->fetchAll(PDO::FETCH_COLUMN); + + if (empty($migratedUsers)) { + echo "Aucun utilisateur n'a été migré. Veuillez d'abord migrer la table users." . PHP_EOL; + closeSshTunnel(); + exit(1); + } + + echo "Nombre d'utilisateurs migrés : " . count($migratedUsers) . PHP_EOL; + + // Récupération de la correspondance entre les anciens secteurs et les nouveaux + $stmt = $targetDb->query("SELECT id, fk_operation, fk_old_sector FROM ope_sectors"); + $sectorMapping = $stmt->fetchAll(PDO::FETCH_ASSOC); + + if (empty($sectorMapping)) { + echo "Aucun secteur n'a été migré. Veuillez d'abord migrer la table ope_sectors." . PHP_EOL; + closeSshTunnel(); + exit(1); + } + + echo "Nombre de secteurs migrés : " . count($sectorMapping) . PHP_EOL; + + // Création d'un tableau associatif pour faciliter la recherche des correspondances + $sectorMap = []; + foreach ($sectorMapping as $mapping) { + $key = $mapping['fk_operation'] . '_' . $mapping['fk_old_sector']; + $sectorMap[$key] = $mapping['id']; + } + + // Création de la liste des IDs d'opérations pour la requête IN + $operationIds = implode(',', $migratedOperations); + + // Création de la liste des IDs d'utilisateurs pour la requête IN + $userIds = implode(',', $migratedUsers); + + // Récupération des associations utilisateurs-secteurs depuis la base source + $query = " + SELECT * FROM ope_users_sectors + WHERE fk_operation IN ($operationIds) + AND fk_user IN ($userIds) + AND active = 1 + "; + + $stmt = $sourceDb->query($query); + $userSectors = $stmt->fetchAll(PDO::FETCH_ASSOC); + + echo "Nombre d'associations utilisateurs-secteurs à migrer : " . count($userSectors) . PHP_EOL; + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO ope_users_sectors ( + fk_operation, + fk_user, + fk_sector, + created_at, + fk_user_creat, + updated_at, + fk_user_modif, + chk_active + ) VALUES ( + :fk_operation, + :fk_user, + :fk_sector, + :created_at, + :fk_user_creat, + :updated_at, + :fk_user_modif, + :chk_active + ) ON DUPLICATE KEY UPDATE + updated_at = VALUES(updated_at), + fk_user_modif = VALUES(fk_user_modif), + chk_active = VALUES(chk_active)"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs + $inserted = 0; + $skipped = 0; + $errors = 0; + + // Traitement de chaque association utilisateur-secteur + foreach ($userSectors as $userSector) { + $fkOperation = $userSector['fk_operation']; + $fkUser = $userSector['fk_user']; + $fkOldSector = $userSector['fk_sector']; + + // Recherche du nouvel ID de secteur + $key = $fkOperation . '_' . $fkOldSector; + if (!isset($sectorMap[$key])) { + echo "Secteur non trouvé pour l'opération $fkOperation et le secteur $fkOldSector. Association ignorée.\n"; + $skipped++; + continue; + } + + $fkNewSector = $sectorMap[$key]; + + // Préparation des données pour l'insertion + $userSectorData = [ + 'fk_operation' => $fkOperation, + 'fk_user' => $fkUser, + 'fk_sector' => $fkNewSector, + 'created_at' => date('Y-m-d H:i:s'), + 'fk_user_creat' => 1, // Utilisateur par défaut + 'updated_at' => date('Y-m-d H:i:s'), + 'fk_user_modif' => 1, // Utilisateur par défaut + 'chk_active' => 1 + ]; + + try { + // Insertion dans la table cible + $insertStmt->execute($userSectorData); + $inserted++; + + // Affichage du progrès + if ($inserted % 100 === 0) { + echo "Progression : $inserted associations utilisateurs-secteurs migrées...\n"; + } + } catch (PDOException $e) { + echo "Erreur lors de la migration de l'association utilisateur-secteur (opération $fkOperation, utilisateur $fkUser, secteur $fkOldSector) : " . $e->getMessage() . "\n"; + $errors++; + } + } + + echo "Migration terminée. $inserted associations utilisateurs-secteurs migrées avec succès, $skipped ignorées. $errors erreurs rencontrées." . PHP_EOL; + + // Fermer le tunnel SSH + closeSshTunnel(); + +} catch (Exception $e) { + echo "Erreur critique: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_operations.php b/api/scripts/php/migrate_operations.php new file mode 100644 index 00000000..4ace23e2 --- /dev/null +++ b/api/scripts/php/migrate_operations.php @@ -0,0 +1,183 @@ +query("SELECT id FROM entites"); + $migratedEntities = $stmt->fetchAll(PDO::FETCH_COLUMN); + + if (empty($migratedEntities)) { + echo "Aucune entité n'a été migrée. Veuillez d'abord migrer la table entites." . PHP_EOL; + closeSshTunnel(); + exit(1); + } + + echo "Nombre d'entités migrées : " . count($migratedEntities) . PHP_EOL; + + // Création de la liste des IDs d'entités pour la requête IN + $entityIds = implode(',', $migratedEntities); + + // Vérification si la table doit être tronquée avant migration + $truncate = false; // Par défaut, ne pas tronquer + + // Vérifier les arguments de ligne de commande + if (isset($argv) && in_array('--truncate', $argv)) { + $truncate = true; + } + + if ($truncate) { + $targetDb->exec("TRUNCATE TABLE operations"); + echo "Table operations tronquée.\n"; + } + + // Récupération des données de la table source + // Ne récupérer que les opérations liées aux entités qui ont été migrées + $query = "SELECT * FROM operations WHERE fk_entite IN ($entityIds) ORDER BY rowid DESC"; + $stmt = $sourceDb->query($query); + $allOperations = $stmt->fetchAll(PDO::FETCH_ASSOC); + + // Filtrer pour ne garder que les 3 dernières opérations par entité + $operationsByEntity = []; + $operations = []; + + foreach ($allOperations as $operation) { + $entityId = $operation['fk_entite'] ?? 1; + + if (!isset($operationsByEntity[$entityId])) { + $operationsByEntity[$entityId] = []; + } + + // Ne garder que les 3 premières opérations par entité (déjà triées par rowid DESC) + if (count($operationsByEntity[$entityId]) < 3) { + $operationsByEntity[$entityId][] = $operation; + $operations[] = $operation; + } + } + + echo "Nombre d'opérations à migrer : " . count($operations) . "\n"; + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO operations ( + id, + fk_entite, + libelle, + date_deb, + date_fin, + chk_distinct_sectors, + created_at, + fk_user_creat, + updated_at, + fk_user_modif, + chk_active + ) VALUES ( + :id, + :fk_entite, + :libelle, + :date_deb, + :date_fin, + :chk_distinct_sectors, + :created_at, + :fk_user_creat, + :updated_at, + :fk_user_modif, + :chk_active + ) ON DUPLICATE KEY UPDATE + fk_entite = VALUES(fk_entite), + libelle = VALUES(libelle), + date_deb = VALUES(date_deb), + date_fin = VALUES(date_fin), + chk_distinct_sectors = VALUES(chk_distinct_sectors), + updated_at = VALUES(updated_at), + fk_user_modif = VALUES(fk_user_modif), + chk_active = VALUES(chk_active)"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs + $inserted = 0; + $errors = 0; + + // Traitement de chaque opération + foreach ($operations as $operation) { + // Mappage des champs + $id = isset($operation['rowid']) ? $operation['rowid'] : $operation['id']; + $chkActive = isset($operation['active']) ? $operation['active'] : (isset($operation['chk_active']) ? $operation['chk_active'] : 1); + + // Gestion des dates + $createdAt = isset($operation['date_creat']) && !empty($operation['date_creat']) ? + date('Y-m-d H:i:s', strtotime($operation['date_creat'])) : + date('Y-m-d H:i:s'); + + $updatedAt = isset($operation['date_modif']) && !empty($operation['date_modif']) ? + date('Y-m-d H:i:s', strtotime($operation['date_modif'])) : + null; + + // Formatage des dates début et fin + $dateDeb = isset($operation['date_deb']) && !empty($operation['date_deb']) ? + date('Y-m-d', strtotime($operation['date_deb'])) : + '0000-00-00'; + + $dateFin = isset($operation['date_fin']) && !empty($operation['date_fin']) ? + date('Y-m-d', strtotime($operation['date_fin'])) : + '0000-00-00'; + + // Préparation des données pour l'insertion + $operationData = [ + 'id' => $id, + 'fk_entite' => $operation['fk_entite'] ?? 1, + 'libelle' => $operation['libelle'] ?? '', + 'date_deb' => $dateDeb, + 'date_fin' => $dateFin, + 'chk_distinct_sectors' => $operation['chk_distinct_sectors'] ?? 0, + 'created_at' => $createdAt, + 'fk_user_creat' => $operation['fk_user_creat'] ?? 0, + 'updated_at' => $updatedAt, + 'fk_user_modif' => $operation['fk_user_modif'] ?? 0, + 'chk_active' => $chkActive + ]; + + try { + // Insertion dans la table cible + $insertStmt->execute($operationData); + $inserted++; + + // Affichage du progrès + if ($inserted % 100 === 0) { + echo "Progression : $inserted opérations migrées...\n"; + } + } catch (PDOException $e) { + echo "Erreur lors de la migration de l'opération ID $id : " . $e->getMessage() . "\n"; + $errors++; + } + } + + echo "Migration terminée. $inserted opérations migrées avec succès. $errors erreurs rencontrées." . PHP_EOL; + + echo "Migration de la table operations terminée avec succès." . PHP_EOL; + + // Fermer le tunnel SSH + closeSshTunnel(); + +} catch (Exception $e) { + echo "Erreur critique: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_sectors_adresses.php b/api/scripts/php/migrate_sectors_adresses.php new file mode 100644 index 00000000..e6799f0d --- /dev/null +++ b/api/scripts/php/migrate_sectors_adresses.php @@ -0,0 +1,163 @@ +query($query); + $sectorMapping = $stmt->fetchAll(PDO::FETCH_ASSOC); + + if (empty($sectorMapping)) { + echo "Aucun secteur n'a été migré. Veuillez d'abord migrer la table ope_sectors." . PHP_EOL; + closeSshTunnel(); + exit(1); + } + + echo "Nombre de secteurs migrés : " . count($sectorMapping) . PHP_EOL; + + // Création d'un tableau associatif pour faciliter la recherche des correspondances + $sectorMap = []; + foreach ($sectorMapping as $mapping) { + $sectorMap[$mapping['fk_old_sector']] = $mapping['id']; + } + + // Création de la liste des IDs de secteurs pour la requête IN + $oldSectorIds = array_keys($sectorMap); + $oldSectorIdsStr = implode(',', $oldSectorIds); + + // Récupération des adresses liées aux secteurs migrés + $query = " + SELECT * FROM sectors_adresses + WHERE fk_sector IN ($oldSectorIdsStr) + "; + + $stmt = $sourceDb->query($query); + $adresses = $stmt->fetchAll(PDO::FETCH_ASSOC); + + echo "Nombre d'adresses à migrer : " . count($adresses) . PHP_EOL; + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO sectors_adresses ( + fk_adresse, + osm_id, + fk_sector, + osm_name, + numero, + rue_bis, + rue, + cp, + ville, + gps_lat, + gps_lng, + osm_date_creat, + created_at, + updated_at + ) VALUES ( + :fk_adresse, + :osm_id, + :fk_sector, + :osm_name, + :numero, + :rue_bis, + :rue, + :cp, + :ville, + :gps_lat, + :gps_lng, + :osm_date_creat, + :created_at, + :updated_at + ) ON DUPLICATE KEY UPDATE + fk_adresse = VALUES(fk_adresse), + numero = VALUES(numero), + rue_bis = VALUES(rue_bis), + rue = VALUES(rue), + cp = VALUES(cp), + ville = VALUES(ville), + gps_lat = VALUES(gps_lat), + gps_lng = VALUES(gps_lng), + updated_at = VALUES(updated_at)"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs + $inserted = 0; + $skipped = 0; + $errors = 0; + + // Traitement de chaque adresse + foreach ($adresses as $adresse) { + $fkOldSector = $adresse['fk_sector']; + + // Recherche du nouvel ID de secteur + if (!isset($sectorMap[$fkOldSector])) { + echo "Secteur non trouvé pour l'ID $fkOldSector. Adresse ignorée.\n"; + $skipped++; + continue; + } + + $fkNewSector = $sectorMap[$fkOldSector]; + + // Préparation des données pour l'insertion + $adresseData = [ + 'fk_adresse' => $adresse['fk_adresse'] ?? '', + 'osm_id' => 0, // Valeur par défaut + 'fk_sector' => $fkNewSector, + 'osm_name' => '', // Valeur par défaut + 'numero' => $adresse['numero'] ?? '', + 'rue_bis' => $adresse['rue_bis'] ?? '', + 'rue' => $adresse['rue'] ?? '', + 'cp' => $adresse['cp'] ?? '', + 'ville' => $adresse['ville'] ?? '', + 'gps_lat' => $adresse['gps_lat'] ?? '', + 'gps_lng' => $adresse['gps_lng'] ?? '', + 'osm_date_creat' => '0000-00-00 00:00:00', // Valeur par défaut + 'created_at' => date('Y-m-d H:i:s'), + 'updated_at' => date('Y-m-d H:i:s') + ]; + + try { + // Insertion dans la table cible + $insertStmt->execute($adresseData); + $inserted++; + + // Affichage du progrès + if ($inserted % 100 === 0) { + echo "Progression : $inserted adresses migrées...\n"; + } + } catch (PDOException $e) { + echo "Erreur lors de la migration de l'adresse (rowid " . $adresse['rowid'] . ", secteur $fkOldSector) : " . $e->getMessage() . "\n"; + $errors++; + } + } + + echo "Migration terminée. $inserted adresses migrées avec succès, $skipped ignorées. $errors erreurs rencontrées." . PHP_EOL; + + // Fermer le tunnel SSH + closeSshTunnel(); + +} catch (Exception $e) { + echo "Erreur critique: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_users.php b/api/scripts/php/migrate_users.php new file mode 100644 index 00000000..d74ce90a --- /dev/null +++ b/api/scripts/php/migrate_users.php @@ -0,0 +1,257 @@ +query("SELECT * FROM users"); + $users = $stmt->fetchAll(PDO::FETCH_ASSOC); + + echo "Nombre d'utilisateurs à migrer: " . count($users) . PHP_EOL; + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO users ( + id, + fk_entite, + fk_role, + fk_titre, + encrypted_name, + first_name, + sect_name, + encrypted_user_name, + user_pass_hash, + encrypted_phone, + encrypted_mobile, + encrypted_email, + chk_alert_email, + chk_suivi, + date_naissance, + date_embauche, + fk_user_creat, + fk_user_modif, + chk_active + ) VALUES ( + :id, + :fk_entite, + :fk_role, + :fk_titre, + :encrypted_name, + :first_name, + :sect_name, + :encrypted_user_name, + :user_pass_hash, + :encrypted_phone, + :encrypted_mobile, + :encrypted_email, + :chk_alert_email, + :chk_suivi, + :date_naissance, + :date_embauche, + :fk_user_creat, + :fk_user_modif, + :chk_active + ) ON DUPLICATE KEY UPDATE + fk_entite = VALUES(fk_entite), + fk_role = VALUES(fk_role), + fk_titre = VALUES(fk_titre), + encrypted_name = VALUES(encrypted_name), + first_name = VALUES(first_name), + sect_name = VALUES(sect_name), + encrypted_user_name = VALUES(encrypted_user_name), + user_pass_hash = VALUES(user_pass_hash), + encrypted_phone = VALUES(encrypted_phone), + encrypted_mobile = VALUES(encrypted_mobile), + encrypted_email = VALUES(encrypted_email), + chk_alert_email = VALUES(chk_alert_email), + chk_suivi = VALUES(chk_suivi), + date_naissance = VALUES(date_naissance), + date_embauche = VALUES(date_embauche), + fk_user_modif = VALUES(fk_user_modif), + chk_active = VALUES(chk_active)"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Préparation de la requête pour vérifier si un utilisateur existe + $checkQuery = "SELECT COUNT(*) FROM users WHERE id = ?"; + $checkStmt = $targetDb->prepare($checkQuery); + + // Préparation de la requête pour la mise à jour + $updateQuery = "UPDATE users SET + fk_entite = :fk_entite, + fk_role = :fk_role, + fk_titre = :fk_titre, + encrypted_name = :encrypted_name, + first_name = :first_name, + sect_name = :sect_name, + encrypted_user_name = :encrypted_user_name, + user_pass_hash = :user_pass_hash, + encrypted_phone = :encrypted_phone, + encrypted_mobile = :encrypted_mobile, + encrypted_email = :encrypted_email, + chk_alert_email = :chk_alert_email, + chk_suivi = :chk_suivi, + date_naissance = :date_naissance, + date_embauche = :date_embauche, + fk_user_modif = :fk_user_modif, + chk_active = :chk_active + WHERE id = :id"; + $updateStmt = $targetDb->prepare($updateQuery); + + // Compteurs + $successCount = 0; + $errorCount = 0; + + // Compteur pour les 100 premiers utilisateurs + $counter = 0; + $maxTestUsers = 100; + + // Traitement de chaque utilisateur + foreach ($users as $user) { + try { + // Mappage des champs + $id = isset($user['rowid']) ? $user['rowid'] : $user['id']; + $chkActive = isset($user['active']) ? $user['active'] : (isset($user['chk_active']) ? $user['chk_active'] : 1); + + // Test de déchiffrement pour les 100 premiers utilisateurs + if ($counter < $maxTestUsers) { + $counter++; + + // Test pour l'email + $email = $user['email'] ?? ''; + $encryptedEmail = !empty($email) ? ApiService::encryptSearchableData($email) : ''; + $decryptedEmail = !empty($encryptedEmail) ? ApiService::decryptSearchableData($encryptedEmail) : ''; + + // Test pour le nom d'utilisateur + $username = $user['username'] ?? ''; + $encryptedUsername = !empty($username) ? ApiService::encryptSearchableData($username) : ''; + $decryptedUsername = !empty($encryptedUsername) ? ApiService::decryptSearchableData($encryptedUsername) : ''; + + // Afficher les résultats pour tous les utilisateurs testés + echo "===== TEST UTILISATEUR ID $id =====\n"; + + // Toujours afficher les informations d'email + echo "Email original: $email\n"; + echo "Email chiffré: $encryptedEmail\n"; + echo "Email déchiffré: $decryptedEmail\n"; + + // Toujours afficher les informations de nom d'utilisateur + echo "Username original: $username\n"; + echo "Username chiffré: $encryptedUsername\n"; + echo "Username déchiffré: $decryptedUsername\n"; + + echo "=================================================\n"; + } + + // Gestion du rôle utilisateur + $fkRole = isset($user['fk_role']) ? $user['fk_role'] : 1; + // Forcer fk_role=1 pour les utilisateurs avec fk_role=0 + if ($fkRole == 0) { + $fkRole = 1; + } + + // Gestion du titre utilisateur + $fkTitre = isset($user['fk_titre']) ? $user['fk_titre'] : 1; + // Forcer fk_titre=1 si différent de 1 ou 2 + if ($fkTitre != 1 && $fkTitre != 2) { + $fkTitre = 1; + } + + // Chiffrement des données sensibles (uniquement si non vides) + $libelle = $user['libelle'] ?? ''; + $encryptedName = !empty($libelle) ? ApiService::encryptData($libelle) : ''; + + // Traitement du prénom + $prenom = $user['prenom'] ?? ''; + + // Traitement du nom de tournée (sect_name) + $sectName = $user['nom_tournee'] ?? ''; + + // Traitement du nom d'utilisateur + $username = $user['username'] ?? ''; + // Utiliser encryptSearchableData car le nom d'utilisateur est utilisé comme clé de recherche + $encryptedUserName = !empty($username) ? ApiService::encryptSearchableData($username) : ''; + + // Traitement du mot de passe + // Utiliser userpswd s'il existe, sinon userpass + $userPassHash = $user['userpswd'] ?? ($user['userpass'] ?? ''); + + // Traitement des numéros de téléphone + $telephone = $user['telephone'] ?? ''; + $mobile = $user['mobile'] ?? ''; + + $encryptedPhone = !empty($telephone) ? ApiService::encryptData($telephone) : ''; + $encryptedMobile = !empty($mobile) ? ApiService::encryptData($mobile) : ''; + + // Chiffrement de l'email + $email = $user['email'] ?? ''; + $encryptedEmail = !empty($email) ? ApiService::encryptSearchableData($email) : ''; + + // Préparation des données pour l'insertion + $userData = [ + 'id' => $id, + 'fk_entite' => $user['fk_entite'] ?? 1, + 'fk_role' => $fkRole, + 'fk_titre' => $fkTitre, + 'encrypted_name' => $encryptedName, + 'first_name' => $prenom, + 'sect_name' => $sectName, + 'encrypted_user_name' => $encryptedUserName, + 'user_pass_hash' => $userPassHash, + 'encrypted_phone' => $encryptedPhone, + 'encrypted_mobile' => $encryptedMobile, + 'encrypted_email' => $encryptedEmail, + 'chk_alert_email' => $user['alert_email'] ?? 1, + 'chk_suivi' => $user['chk_suivi'] ?? 0, + 'date_naissance' => $user['date_naissance'] ?? null, + 'date_embauche' => $user['date_embauche'] ?? null, + 'fk_user_creat' => $user['fk_user_creat'] ?? null, + 'fk_user_modif' => $user['fk_user_modif'] ?? null, + 'chk_active' => $chkActive + ]; + + // Vérifier si l'utilisateur existe déjà + $checkStmt->execute([$id]); + $exists = $checkStmt->fetchColumn() > 0; + + if ($exists) { + + // Mise à jour de l'utilisateur existant - utiliser insertStmt avec ON DUPLICATE KEY UPDATE + $insertStmt->execute($userData); + $successCount++; + } else { + // L'utilisateur n'existe pas, on ne peut pas le mettre à jour + $errorCount++; + } + } catch (Exception $e) { + $errorCount++; + echo "Erreur lors de la migration de l'utilisateur ID {$id}: " . $e->getMessage() . PHP_EOL; + } + } + + echo "Migration terminée. Succès: $successCount, Erreurs: $errorCount" . PHP_EOL; + + // Fermer le tunnel SSH + closeSshTunnel(); +} catch (Exception $e) { + echo "Erreur critique: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_x_departements.php b/api/scripts/php/migrate_x_departements.php new file mode 100644 index 00000000..b7e3cc44 --- /dev/null +++ b/api/scripts/php/migrate_x_departements.php @@ -0,0 +1,87 @@ +query("SELECT * FROM x_departements"); + $departements = $stmt->fetchAll(PDO::FETCH_ASSOC); + + echo "Nombre de départements à migrer: " . count($departements) . PHP_EOL; + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO x_departements ( + id, + code, + fk_region, + libelle, + chk_active + ) VALUES ( + :id, + :code, + :fk_region, + :libelle, + :chk_active + ) ON DUPLICATE KEY UPDATE + code = VALUES(code), + fk_region = VALUES(fk_region), + libelle = VALUES(libelle), + chk_active = VALUES(chk_active)"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs + $successCount = 0; + $errorCount = 0; + + // Traitement de chaque département + foreach ($departements as $departement) { + try { + // Mappage des champs entre les deux structures + $id = isset($departement['rowid']) ? $departement['rowid'] : $departement['id']; + $chkActive = isset($departement['active']) ? $departement['active'] : + (isset($departement['chk_active']) ? $departement['chk_active'] : 1); + + // Préparation des données pour l'insertion + $departementData = [ + 'id' => $id, + 'code' => $departement['code'], + 'fk_region' => $departement['fk_region'], + 'libelle' => $departement['libelle'], + 'chk_active' => $chkActive + ]; + + // Insertion dans la base cible + $insertStmt->execute($departementData); + $successCount++; + + } catch (Exception $e) { + $errorCount++; + echo "Erreur lors de la migration du département ID {$id}: " . $e->getMessage() . PHP_EOL; + } + } + + echo "Migration terminée. Succès: $successCount, Erreurs: $errorCount" . PHP_EOL; + + // Fermer le tunnel SSH + closeSshTunnel(); + +} catch (Exception $e) { + echo "Erreur critique: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_x_devises.php b/api/scripts/php/migrate_x_devises.php new file mode 100644 index 00000000..7387970e --- /dev/null +++ b/api/scripts/php/migrate_x_devises.php @@ -0,0 +1,120 @@ +query("SELECT * FROM x_devises"); + $devises = $stmt->fetchAll(); + + logOperation("Nombre de devises à migrer: " . count($devises)); + + // Vérifier si la table existe dans la cible + try { + $targetDb->query("SELECT 1 FROM x_devises LIMIT 1"); + $tableExists = true; + } catch (PDOException $e) { + $tableExists = false; + } + + // Créer la table si elle n'existe pas + if (!$tableExists) { + logOperation("La table x_devises n'existe pas dans la base cible. Création de la table..."); + + $createTableSql = "CREATE TABLE `x_devises` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `code` varchar(10) NOT NULL, + `libelle` varchar(50) NOT NULL, + `symbole` varchar(10) DEFAULT NULL, + `chk_active` tinyint(1) UNSIGNED NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `code` (`code`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;"; + + $targetDb->exec($createTableSql); + logOperation("Table x_devises créée avec succès"); + } + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO x_devises ( + id, + code, + libelle, + symbole, + chk_active + ) VALUES ( + :id, + :code, + :libelle, + :symbole, + :chk_active + ) ON DUPLICATE KEY UPDATE + code = VALUES(code), + libelle = VALUES(libelle), + symbole = VALUES(symbole), + chk_active = VALUES(chk_active)"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs + $successCount = 0; + $errorCount = 0; + + // Traitement de chaque devise + foreach ($devises as $devise) { + try { + // Mappage des champs entre les deux structures + $id = isset($devise['rowid']) ? $devise['rowid'] : $devise['id']; + $chkActive = isset($devise['active']) ? $devise['active'] : + (isset($devise['chk_active']) ? $devise['chk_active'] : 1); + + // Préparation des données pour l'insertion + $deviseData = [ + 'id' => $id, + 'code' => $devise['code'], + 'libelle' => $devise['libelle'], + 'symbole' => $devise['symbole'] ?? null, + 'chk_active' => $chkActive + ]; + + // Insertion dans la base cible + $insertStmt->execute($deviseData); + $successCount++; + + logOperation("Devise ID {$id} ({$devise['code']}) migrée avec succès", "INFO"); + } catch (Exception $e) { + $errorCount++; + logOperation("Erreur lors de la migration de la devise ID {$id} ({$devise['code']}): " . $e->getMessage(), "ERROR"); + } + } + + logOperation("Migration terminée. Succès: $successCount, Erreurs: $errorCount"); + + // Fermer le tunnel SSH + closeSshTunnel(); + +} catch (Exception $e) { + logOperation("Erreur critique: " . $e->getMessage(), "ERROR"); + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_x_entites_types.php b/api/scripts/php/migrate_x_entites_types.php new file mode 100644 index 00000000..e740cb8d --- /dev/null +++ b/api/scripts/php/migrate_x_entites_types.php @@ -0,0 +1,75 @@ +query("SELECT * FROM x_entites_types"); + $entitesTypes = $stmt->fetchAll(); + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO x_entites_types ( + id, + libelle, + chk_active + ) VALUES ( + :id, + :libelle, + :chk_active + ) ON DUPLICATE KEY UPDATE + libelle = VALUES(libelle), + chk_active = VALUES(chk_active)"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs + $successCount = 0; + $errorCount = 0; + + // Traitement de chaque type d'entité + foreach ($entitesTypes as $entiteType) { + try { + // Mappage des champs entre les deux structures + $id = isset($entiteType['rowid']) ? $entiteType['rowid'] : $entiteType['id']; + $chkActive = isset($entiteType['active']) ? $entiteType['active'] : + (isset($entiteType['chk_active']) ? $entiteType['chk_active'] : 1); + + // Préparation des données pour l'insertion + $entiteTypeData = [ + 'id' => $id, + 'libelle' => $entiteType['libelle'], + 'chk_active' => $chkActive + ]; + + // Insertion dans la base cible + $insertStmt->execute($entiteTypeData); + $successCount++; + + } catch (Exception $e) { + $errorCount++; + echo "Erreur lors de la migration du type d'entité ID {$id}: " . $e->getMessage() . PHP_EOL; + } + } + + echo "Migration terminée. Succès: $successCount, Erreurs: $errorCount" . PHP_EOL; + + // Fermer le tunnel SSH + closeSshTunnel(); + +} catch (Exception $e) { + echo "Erreur critique: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_x_pays.php b/api/scripts/php/migrate_x_pays.php new file mode 100644 index 00000000..ab332354 --- /dev/null +++ b/api/scripts/php/migrate_x_pays.php @@ -0,0 +1,87 @@ +query("SELECT * FROM x_pays"); + $pays = $stmt->fetchAll(); + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO x_pays ( + id, + code, + fk_continent, + fk_devise, + libelle, + chk_active + ) VALUES ( + :id, + :code, + :fk_continent, + :fk_devise, + :libelle, + :chk_active + ) ON DUPLICATE KEY UPDATE + code = VALUES(code), + fk_continent = VALUES(fk_continent), + fk_devise = VALUES(fk_devise), + libelle = VALUES(libelle), + chk_active = VALUES(chk_active)"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs + $successCount = 0; + $errorCount = 0; + + // Traitement de chaque pays + foreach ($pays as $pay) { + try { + // Mappage des champs entre les deux structures + $id = isset($pay['rowid']) ? $pay['rowid'] : $pay['id']; + $chkActive = isset($pay['active']) ? $pay['active'] : + (isset($pay['chk_active']) ? $pay['chk_active'] : 1); + + // Préparation des données pour l'insertion + $paysData = [ + 'id' => $id, + 'code' => $pay['code'], + 'fk_continent' => $pay['fk_continent'], + 'fk_devise' => $pay['fk_devise'], + 'libelle' => $pay['libelle'], + 'chk_active' => $chkActive + ]; + + // Insertion dans la base cible + $insertStmt->execute($paysData); + $successCount++; + + } catch (Exception $e) { + $errorCount++; + echo "Erreur lors de la migration du pays ID {$id}: " . $e->getMessage() . PHP_EOL; + } + } + + echo "Migration terminée. Succès: $successCount, Erreurs: $errorCount" . PHP_EOL; + + // Fermer le tunnel SSH + closeSshTunnel(); + +} catch (Exception $e) { + echo "Erreur critique: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_x_regions.php b/api/scripts/php/migrate_x_regions.php new file mode 100644 index 00000000..b5aa2fe5 --- /dev/null +++ b/api/scripts/php/migrate_x_regions.php @@ -0,0 +1,95 @@ +query("SELECT * FROM x_regions"); + $regions = $stmt->fetchAll(PDO::FETCH_ASSOC); + + echo "Nombre de régions à migrer: " . count($regions) . PHP_EOL; + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO x_regions ( + id, + fk_pays, + libelle, + libelle_long, + table_osm, + departements, + chk_active + ) VALUES ( + :id, + :fk_pays, + :libelle, + :libelle_long, + :table_osm, + :departements, + :chk_active + ) ON DUPLICATE KEY UPDATE + fk_pays = VALUES(fk_pays), + libelle = VALUES(libelle), + libelle_long = VALUES(libelle_long), + table_osm = VALUES(table_osm), + departements = VALUES(departements), + chk_active = VALUES(chk_active)"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs + $successCount = 0; + $errorCount = 0; + + // Traitement de chaque région + foreach ($regions as $region) { + try { + // Mappage des champs entre les deux structures + $id = isset($region['rowid']) ? $region['rowid'] : $region['id']; + $chkActive = isset($region['active']) ? $region['active'] : + (isset($region['chk_active']) ? $region['chk_active'] : 1); + + // Préparation des données pour l'insertion + $regionData = [ + 'id' => $id, + 'fk_pays' => $region['fk_pays'], + 'libelle' => $region['libelle'], + 'libelle_long' => $region['libelle_long'], + 'table_osm' => $region['table_osm'], + 'departements' => $region['departements'], + 'chk_active' => $chkActive + ]; + + // Insertion dans la base cible + $insertStmt->execute($regionData); + $successCount++; + + } catch (Exception $e) { + $errorCount++; + echo "Erreur lors de la migration de la région ID {$id}: " . $e->getMessage() . PHP_EOL; + } + } + + echo "Migration terminée. Succès: $successCount, Erreurs: $errorCount" . PHP_EOL; + + // Fermer le tunnel SSH + closeSshTunnel(); + +} catch (Exception $e) { + echo "Erreur critique: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_x_types_passages.php b/api/scripts/php/migrate_x_types_passages.php new file mode 100644 index 00000000..a8562d5d --- /dev/null +++ b/api/scripts/php/migrate_x_types_passages.php @@ -0,0 +1,87 @@ +query("SELECT * FROM x_types_passages"); + $typesPassages = $stmt->fetchAll(); + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO x_types_passages ( + id, + libelle, + color_button, + color_mark, + color_table, + chk_active + ) VALUES ( + :id, + :libelle, + :color_button, + :color_mark, + :color_table, + :chk_active + ) ON DUPLICATE KEY UPDATE + libelle = VALUES(libelle), + color_button = VALUES(color_button), + color_mark = VALUES(color_mark), + color_table = VALUES(color_table), + chk_active = VALUES(chk_active)"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs + $successCount = 0; + $errorCount = 0; + + // Traitement de chaque type de passage + foreach ($typesPassages as $typePassage) { + try { + // Mappage des champs entre les deux structures + $id = isset($typePassage['rowid']) ? $typePassage['rowid'] : $typePassage['id']; + $chkActive = isset($typePassage['active']) ? $typePassage['active'] : + (isset($typePassage['chk_active']) ? $typePassage['chk_active'] : 1); + + // Préparation des données pour l'insertion + $typePassageData = [ + 'id' => $id, + 'libelle' => $typePassage['libelle'], + 'color_button' => $typePassage['color_button'], + 'color_mark' => $typePassage['color_mark'], + 'color_table' => $typePassage['color_table'], + 'chk_active' => $chkActive + ]; + + // Insertion dans la base cible + $insertStmt->execute($typePassageData); + $successCount++; + + } catch (Exception $e) { + $errorCount++; + echo "Erreur lors de la migration du type de passage ID {$id}: " . $e->getMessage() . PHP_EOL; + } + } + + echo "Migration terminée. Succès: $successCount, Erreurs: $errorCount" . PHP_EOL; + + // Fermer le tunnel SSH + closeSshTunnel(); + +} catch (Exception $e) { + echo "Erreur critique: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_x_types_reglements.php b/api/scripts/php/migrate_x_types_reglements.php new file mode 100644 index 00000000..eeda6652 --- /dev/null +++ b/api/scripts/php/migrate_x_types_reglements.php @@ -0,0 +1,75 @@ +query("SELECT * FROM x_types_reglements"); + $typesReglements = $stmt->fetchAll(); + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO x_types_reglements ( + id, + libelle, + chk_active + ) VALUES ( + :id, + :libelle, + :chk_active + ) ON DUPLICATE KEY UPDATE + libelle = VALUES(libelle), + chk_active = VALUES(chk_active)"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs + $successCount = 0; + $errorCount = 0; + + // Traitement de chaque type de règlement + foreach ($typesReglements as $typeReglement) { + try { + // Mappage des champs entre les deux structures + $id = isset($typeReglement['rowid']) ? $typeReglement['rowid'] : $typeReglement['id']; + $chkActive = isset($typeReglement['active']) ? $typeReglement['active'] : + (isset($typeReglement['chk_active']) ? $typeReglement['chk_active'] : 1); + + // Préparation des données pour l'insertion + $typeReglementData = [ + 'id' => $id, + 'libelle' => $typeReglement['libelle'], + 'chk_active' => $chkActive + ]; + + // Insertion dans la base cible + $insertStmt->execute($typeReglementData); + $successCount++; + + } catch (Exception $e) { + $errorCount++; + echo "Erreur lors de la migration du type de règlement ID {$id}: " . $e->getMessage() . PHP_EOL; + } + } + + echo "Migration terminée. Succès: $successCount, Erreurs: $errorCount" . PHP_EOL; + + // Fermer le tunnel SSH + closeSshTunnel(); + +} catch (Exception $e) { + echo "Erreur critique: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_x_users_roles.php b/api/scripts/php/migrate_x_users_roles.php new file mode 100644 index 00000000..1b32b480 --- /dev/null +++ b/api/scripts/php/migrate_x_users_roles.php @@ -0,0 +1,75 @@ +query("SELECT * FROM x_users_roles"); + $usersRoles = $stmt->fetchAll(); + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO x_users_roles ( + id, + libelle, + chk_active + ) VALUES ( + :id, + :libelle, + :chk_active + ) ON DUPLICATE KEY UPDATE + libelle = VALUES(libelle), + chk_active = VALUES(chk_active)"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs + $successCount = 0; + $errorCount = 0; + + // Traitement de chaque rôle utilisateur + foreach ($usersRoles as $userRole) { + try { + // Mappage des champs entre les deux structures + $id = isset($userRole['rowid']) ? $userRole['rowid'] : $userRole['id']; + $chkActive = isset($userRole['active']) ? $userRole['active'] : + (isset($userRole['chk_active']) ? $userRole['chk_active'] : 1); + + // Préparation des données pour l'insertion + $userRoleData = [ + 'id' => $id, + 'libelle' => $userRole['libelle'], + 'chk_active' => $chkActive + ]; + + // Insertion dans la base cible + $insertStmt->execute($userRoleData); + $successCount++; + + } catch (Exception $e) { + $errorCount++; + echo "Erreur lors de la migration du rôle utilisateur ID {$id}: " . $e->getMessage() . PHP_EOL; + } + } + + echo "Migration terminée. Succès: $successCount, Erreurs: $errorCount" . PHP_EOL; + + // Fermer le tunnel SSH + closeSshTunnel(); + +} catch (Exception $e) { + echo "Erreur critique: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/php/migrate_x_villes.php b/api/scripts/php/migrate_x_villes.php new file mode 100644 index 00000000..dcdfd444 --- /dev/null +++ b/api/scripts/php/migrate_x_villes.php @@ -0,0 +1,94 @@ +query("SELECT * FROM x_villes"); + $villes = $stmt->fetchAll(PDO::FETCH_ASSOC); + + echo "Nombre de villes à migrer: " . count($villes) . PHP_EOL; + + // Préparation de la requête d'insertion + $insertQuery = "INSERT INTO x_villes ( + id, + fk_departement, + libelle, + code_postal, + code_insee, + chk_active + ) VALUES ( + :id, + :fk_departement, + :libelle, + :code_postal, + :code_insee, + :chk_active + ) ON DUPLICATE KEY UPDATE + fk_departement = VALUES(fk_departement), + libelle = VALUES(libelle), + code_postal = VALUES(code_postal), + code_insee = VALUES(code_insee), + chk_active = VALUES(chk_active)"; + + $insertStmt = $targetDb->prepare($insertQuery); + + // Compteurs + $successCount = 0; + $errorCount = 0; + + // Traitement de chaque ville + foreach ($villes as $ville) { + try { + // Mappage des champs + $id = isset($ville['rowid']) ? $ville['rowid'] : $ville['id']; + $chkActive = isset($ville['active']) ? $ville['active'] : (isset($ville['chk_active']) ? $ville['chk_active'] : 1); + + // Formatage du code postal (ajouter un 0 devant s'il ne contient que 4 chiffres) + $codePostal = $ville['cp'] ?? ''; + if (strlen($codePostal) === 4 && is_numeric($codePostal)) { + $codePostal = '0' . $codePostal; + } + + // Préparation des données pour l'insertion + $villeData = [ + 'id' => $id, + 'fk_departement' => $ville['fk_departement'] ?? 1, + 'libelle' => $ville['libelle'] ?? '', + 'code_postal' => $codePostal, + 'code_insee' => $ville['code_insee'] ?? '', + 'chk_active' => $chkActive + ]; + + // Insertion dans la base cible + $insertStmt->execute($villeData); + $successCount++; + } catch (Exception $e) { + $errorCount++; + echo "Erreur lors de la migration de la ville ID {$id}: " . $e->getMessage() . PHP_EOL; + } + } + + echo "Migration terminée. Succès: $successCount, Erreurs: $errorCount" . PHP_EOL; + + // Fermer le tunnel SSH + closeSshTunnel(); +} catch (Exception $e) { + echo "Erreur critique: " . $e->getMessage() . PHP_EOL; + + // Fermer le tunnel SSH en cas d'erreur + closeSshTunnel(); + + exit(1); +} diff --git a/api/scripts/python/compare_schemas.py b/api/scripts/python/compare_schemas.py new file mode 100755 index 00000000..8421e63b --- /dev/null +++ b/api/scripts/python/compare_schemas.py @@ -0,0 +1,371 @@ +#!/usr/bin/env python3 +""" +Script pour comparer les schémas de tables entre deux bases de données +Utile pour vérifier la compatibilité avant migration +""" + +import argparse +import configparser +import os +import sys +import time +import signal +import subprocess +import mysql.connector +from datetime import datetime +from tabulate import tabulate + + +def create_config_if_not_exists(): + """Crée un fichier de configuration s'il n'existe pas déjà""" + config_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'python', 'db_config.ini') + + if not os.path.exists(os.path.dirname(config_path)): + os.makedirs(os.path.dirname(config_path)) + + if not os.path.exists(config_path): + config = configparser.ConfigParser() + + config['SSH'] = { + 'host': 'serveur-distant.exemple.com', + 'port': '22', + 'user': 'utilisateur', + 'key_file': '/chemin/vers/cle_ssh' + } + + config['REMOTE_DB'] = { + 'host': 'localhost', # Hôte de la base sur le serveur distant + 'port': '3306' # Port de la base sur le serveur distant + } + + config['SOURCE_DB'] = { + 'host': 'localhost', # Hôte local pour le tunnel SSH + 'database': 'geosector', + 'user': 'utilisateur_db', + 'password': 'mot_de_passe', + 'port': '13306' # Port local pour le tunnel SSH + } + + config['TARGET_DB'] = { + 'host': 'localhost', + 'database': 'geosector_app', + 'user': 'root', + 'password': '', + 'port': '3306' + } + + with open(config_path, 'w') as configfile: + config.write(configfile) + + print(f"Fichier de configuration créé: {config_path}") + + return config_path + + +def get_db_config(): + """Charge la configuration de la base de données""" + config_path = create_config_if_not_exists() + config = configparser.ConfigParser() + config.read(config_path) + return config + + +# Variable globale pour stocker le processus du tunnel SSH +ssh_tunnel_process = None + +def create_ssh_tunnel(ssh_config, remote_db_config, source_db_config): + """Crée un tunnel SSH vers le serveur distant""" + global ssh_tunnel_process + + # Vérifier si un tunnel SSH est déjà en cours d'exécution + try: + # Commande pour vérifier si le tunnel est déjà en cours d'exécution + check_command = f"ps aux | grep 'ssh -f -N -L {source_db_config['port']}:{remote_db_config['host']}:{remote_db_config['port']}' | grep -v grep" + result = subprocess.run(check_command, shell=True, capture_output=True, text=True) + + if result.stdout.strip(): + print("Un tunnel SSH est déjà en cours d'exécution") + return True + + # Construire la commande SSH pour établir le tunnel + ssh_command = [ + 'ssh', + '-f', '-N', + '-L', f"{source_db_config['port']}:{remote_db_config['host']}:{remote_db_config['port']}", + '-p', ssh_config['port'], + '-i', ssh_config['key_file'], + f"{ssh_config['user']}@{ssh_config['host']}" + ] + + print(f"Création d'un tunnel SSH vers {ssh_config['host']}...") + ssh_tunnel_process = subprocess.Popen(ssh_command) + + # Attendre que le tunnel soit établi + time.sleep(2) + + # Vérifier si le processus est toujours en cours d'exécution + if ssh_tunnel_process.poll() is None: + print(f"Tunnel SSH établi sur le port local {source_db_config['port']}") + return True + else: + print("Erreur lors de la création du tunnel SSH") + return False + + except Exception as e: + print(f"Erreur lors de la création du tunnel SSH: {e}") + return False + +def close_ssh_tunnel(): + """Ferme le tunnel SSH""" + global ssh_tunnel_process + + if ssh_tunnel_process is not None: + try: + # Tuer le processus SSH + ssh_tunnel_process.terminate() + ssh_tunnel_process.wait(timeout=5) + print("Tunnel SSH fermé") + except Exception as e: + print(f"Erreur lors de la fermeture du tunnel SSH: {e}") + # Forcer la fermeture si nécessaire + try: + ssh_tunnel_process.kill() + except: + pass + + # Rechercher et tuer tous les processus SSH correspondants + try: + kill_command = "ps aux | grep 'ssh -f -N -L' | grep -v grep | awk '{print $2}' | xargs kill -9 2>/dev/null" + subprocess.run(kill_command, shell=True) + except: + pass + +def connect_to_db(db_config): + """Se connecte à une base de données MySQL/MariaDB""" + try: + connection = mysql.connector.connect( + host=db_config['host'], + database=db_config['database'], + user=db_config['user'], + password=db_config['password'], + port=int(db_config['port']) + ) + return connection + except mysql.connector.Error as err: + print(f"Erreur de connexion à la base de données: {err}") + sys.exit(1) + + +def get_table_schema(connection, table_name): + """Récupère le schéma d'une table""" + cursor = connection.cursor(dictionary=True) + cursor.execute(f"DESCRIBE {table_name}") + columns = cursor.fetchall() + cursor.close() + return columns + + +def get_all_tables(connection): + """Récupère toutes les tables d'une base de données""" + cursor = connection.cursor() + cursor.execute("SHOW TABLES") + tables = [table[0] for table in cursor.fetchall()] + cursor.close() + return tables + + +def compare_tables(source_schema, target_schema): + """Compare les schémas de deux tables""" + source_columns = {col['Field']: col for col in source_schema} + target_columns = {col['Field']: col for col in target_schema} + + # Colonnes présentes dans les deux tables + common_columns = set(source_columns.keys()) & set(target_columns.keys()) + + # Colonnes uniquement dans la source + source_only = set(source_columns.keys()) - set(target_columns.keys()) + + # Colonnes uniquement dans la cible + target_only = set(target_columns.keys()) - set(source_columns.keys()) + + # Différences dans les colonnes communes + differences = [] + for col_name in common_columns: + source_col = source_columns[col_name] + target_col = target_columns[col_name] + + if source_col['Type'] != target_col['Type'] or \ + source_col['Null'] != target_col['Null'] or \ + source_col['Key'] != target_col['Key'] or \ + source_col['Default'] != target_col['Default']: + differences.append({ + 'Column': col_name, + 'Source_Type': source_col['Type'], + 'Target_Type': target_col['Type'], + 'Source_Null': source_col['Null'], + 'Target_Null': target_col['Null'], + 'Source_Key': source_col['Key'], + 'Target_Key': target_col['Key'], + 'Source_Default': source_col['Default'], + 'Target_Default': target_col['Default'] + }) + + return { + 'common': common_columns, + 'source_only': source_only, + 'target_only': target_only, + 'differences': differences + } + + +def generate_report(table_name, comparison, output_file=None): + """Génère un rapport de comparaison""" + report = [] + report.append(f"Rapport de comparaison pour la table: {table_name}") + report.append(f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") + report.append("") + + # Colonnes communes + report.append(f"Colonnes communes ({len(comparison['common'])}):") + if comparison['common']: + report.append(", ".join(sorted(comparison['common']))) + else: + report.append("Aucune") + report.append("") + + # Colonnes uniquement dans la source + report.append(f"Colonnes uniquement dans la source ({len(comparison['source_only'])}):") + if comparison['source_only']: + report.append(", ".join(sorted(comparison['source_only']))) + else: + report.append("Aucune") + report.append("") + + # Colonnes uniquement dans la cible + report.append(f"Colonnes uniquement dans la cible ({len(comparison['target_only'])}):") + if comparison['target_only']: + report.append(", ".join(sorted(comparison['target_only']))) + else: + report.append("Aucune") + report.append("") + + # Différences dans les colonnes communes + report.append(f"Différences dans les colonnes communes ({len(comparison['differences'])}):") + if comparison['differences']: + headers = ["Colonne", "Type Source", "Type Cible", "Null Source", "Null Cible", "Clé Source", "Clé Cible", "Défaut Source", "Défaut Cible"] + table_data = [] + for diff in comparison['differences']: + table_data.append([ + diff['Column'], + diff['Source_Type'], + diff['Target_Type'], + diff['Source_Null'], + diff['Target_Null'], + diff['Source_Key'], + diff['Target_Key'], + diff['Source_Default'] or 'NULL', + diff['Target_Default'] or 'NULL' + ]) + report.append(tabulate(table_data, headers=headers, tablefmt="grid")) + else: + report.append("Aucune différence") + + report_text = "\n".join(report) + + if output_file: + with open(output_file, 'w') as f: + f.write(report_text) + print(f"Rapport enregistré dans: {output_file}") + + return report_text + + +def main(): + parser = argparse.ArgumentParser(description='Compare les schémas de tables entre deux bases de données') + parser.add_argument('table', help='Nom de la table à comparer') + parser.add_argument('--output', '-o', help='Fichier de sortie pour le rapport') + parser.add_argument('--no-ssh', action='store_true', help='Ne pas utiliser de tunnel SSH') + args = parser.parse_args() + + table_name = args.table + output_file = args.output + use_ssh = not args.no_ssh + + # Créer le dossier de logs si nécessaire + logs_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'logs') + if not os.path.exists(logs_dir): + os.makedirs(logs_dir) + + # Si aucun fichier de sortie n'est spécifié, en créer un dans le dossier logs + if not output_file: + output_file = os.path.join(logs_dir, f"schema_comparison_{table_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt") + + # Charger la configuration + config = get_db_config() + + # Établir un tunnel SSH si nécessaire + if use_ssh and 'SSH' in config and 'REMOTE_DB' in config: + if not create_ssh_tunnel(config['SSH'], config['REMOTE_DB'], config['SOURCE_DB']): + print("Impossible d'établir le tunnel SSH. Abandon.") + sys.exit(1) + + # Se connecter aux bases de données + source_conn = connect_to_db(config['SOURCE_DB']) + target_conn = connect_to_db(config['TARGET_DB']) + + # Vérifier si la table existe dans les deux bases + source_tables = get_all_tables(source_conn) + target_tables = get_all_tables(target_conn) + + if table_name not in source_tables: + print(f"Erreur: La table '{table_name}' n'existe pas dans la base source.") + sys.exit(1) + + if table_name not in target_tables: + print(f"Avertissement: La table '{table_name}' n'existe pas dans la base cible.") + print("Voulez-vous voir uniquement le schéma de la table source? (o/n)") + response = input().lower() + if response != 'o': + sys.exit(0) + + # Afficher uniquement le schéma de la table source + source_schema = get_table_schema(source_conn, table_name) + print(f"\nSchéma de la table '{table_name}' dans la base source:") + headers = ["Champ", "Type", "Null", "Clé", "Défaut", "Extra"] + table_data = [[col['Field'], col['Type'], col['Null'], col['Key'], col['Default'] or 'NULL', col['Extra']] for col in source_schema] + print(tabulate(table_data, headers=headers, tablefmt="grid")) + + # Enregistrer le schéma dans un fichier + with open(output_file, 'w') as f: + f.write(f"Schéma de la table '{table_name}' dans la base source:\n") + f.write(tabulate(table_data, headers=headers, tablefmt="grid")) + + print(f"Schéma enregistré dans: {output_file}") + sys.exit(0) + + # Récupérer les schémas des tables + source_schema = get_table_schema(source_conn, table_name) + target_schema = get_table_schema(target_conn, table_name) + + # Comparer les schémas + comparison = compare_tables(source_schema, target_schema) + + # Générer et afficher le rapport + report = generate_report(table_name, comparison, output_file) + print(report) + + # Fermer les connexions + source_conn.close() + target_conn.close() + + +if __name__ == "__main__": + try: + # Configurer le gestionnaire de signal pour fermer proprement le tunnel SSH + signal.signal(signal.SIGINT, lambda sig, frame: (close_ssh_tunnel(), sys.exit(0))) + signal.signal(signal.SIGTERM, lambda sig, frame: (close_ssh_tunnel(), sys.exit(0))) + + main() + finally: + # Fermer le tunnel SSH à la fin du script + close_ssh_tunnel() diff --git a/api/scripts/shell/migrate_table.sh b/api/scripts/shell/migrate_table.sh new file mode 100755 index 00000000..b003ddc1 --- /dev/null +++ b/api/scripts/shell/migrate_table.sh @@ -0,0 +1,187 @@ +#!/bin/bash +# Script de migration d'une table de geosector vers geosector_app +# Usage: ./migrate_table.sh [options] + +# Chemin du script +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" +BASE_DIR="$(dirname "$SCRIPT_DIR")" +LOG_DIR="$BASE_DIR/logs" +CONFIG_FILE="$BASE_DIR/shell/db_config.sh" + +# Création du répertoire de logs si nécessaire +mkdir -p "$LOG_DIR" + +# Fichier de log +LOG_FILE="$LOG_DIR/migration_$(date +%Y-%m-%d).log" + +# Fonction de logging +log_message() { + local level="$1" + local message="$2" + local timestamp=$(date +"%Y-%m-%d %H:%M:%S") + echo "[$timestamp] [$level] $message" | tee -a "$LOG_FILE" +} + +# Vérification des arguments +if [ -z "$1" ]; then + log_message "ERROR" "Usage: $0 [options]" + exit 1 +fi + +TABLE_NAME="$1" +log_message "INFO" "Démarrage de la migration de la table: $TABLE_NAME" + +# Charger la configuration de la base de données +if [ -f "$CONFIG_FILE" ]; then + source "$CONFIG_FILE" +else + # Configuration SSH par défaut + SSH_HOST="serveur-distant.exemple.com" + SSH_PORT="22" + SSH_USER="utilisateur" + SSH_KEY_FILE="/chemin/vers/cle_ssh" + + # Configuration de la base de données source (distante) + REMOTE_DB_HOST="localhost" + REMOTE_DB_PORT="3306" + SOURCE_DB_HOST="localhost" + SOURCE_DB_NAME="geosector" + SOURCE_DB_USER="utilisateur_db" + SOURCE_DB_PASS="mot_de_passe" + SOURCE_DB_PORT="13306" + + # Configuration de la base de données cible (locale) + TARGET_DB_HOST="localhost" + TARGET_DB_NAME="geosector_app" + TARGET_DB_USER="root" + TARGET_DB_PASS="" + TARGET_DB_PORT="3306" + + # Créer le fichier de configuration + cat > "$CONFIG_FILE" << EOF +#!/bin/bash +# Configuration des bases de données pour les scripts de migration + +# Configuration SSH pour accéder au serveur distant +SSH_HOST="serveur-distant.exemple.com" +SSH_PORT="22" +SSH_USER="utilisateur" +SSH_KEY_FILE="/chemin/vers/cle_ssh" + +# Configuration de la base de données source (distante) +REMOTE_DB_HOST="localhost" +REMOTE_DB_PORT="3306" +SOURCE_DB_HOST="localhost" +SOURCE_DB_NAME="geosector" +SOURCE_DB_USER="utilisateur_db" +SOURCE_DB_PASS="mot_de_passe" +SOURCE_DB_PORT="13306" + +# Configuration de la base de données cible (locale) +TARGET_DB_HOST="localhost" +TARGET_DB_NAME="geosector_app" +TARGET_DB_USER="root" +TARGET_DB_PASS="" +TARGET_DB_PORT="3306" +EOF + chmod +x "$CONFIG_FILE" + log_message "INFO" "Fichier de configuration créé: $CONFIG_FILE" +fi + +# Fonction pour établir un tunnel SSH +establish_ssh_tunnel() { + # Vérifier si un tunnel SSH est déjà en cours d'exécution + TUNNEL_RUNNING=$(ps aux | grep "ssh -f -N -L $SOURCE_DB_PORT:$REMOTE_DB_HOST:$REMOTE_DB_PORT" | grep -v grep) + + if [ -z "$TUNNEL_RUNNING" ]; then + log_message "INFO" "Établissement d'un tunnel SSH vers $SSH_HOST..." + ssh -f -N -L "$SOURCE_DB_PORT:$REMOTE_DB_HOST:$REMOTE_DB_PORT" -p "$SSH_PORT" "$SSH_USER@$SSH_HOST" -i "$SSH_KEY_FILE" + + if [ $? -ne 0 ]; then + log_message "ERROR" "Impossible d'établir le tunnel SSH." + return 1 + fi + + # Attendre que le tunnel soit établi + sleep 2 + log_message "INFO" "Tunnel SSH établi sur le port local $SOURCE_DB_PORT" + else + log_message "INFO" "Un tunnel SSH est déjà en cours d'exécution" + fi + + return 0 +} + +# Fonction pour fermer le tunnel SSH +close_ssh_tunnel() { + log_message "INFO" "Fermeture du tunnel SSH..." + TUNNEL_PID=$(ps aux | grep "ssh -f -N -L $SOURCE_DB_PORT:$REMOTE_DB_HOST:$REMOTE_DB_PORT" | grep -v grep | awk '{print $2}') + + if [ ! -z "$TUNNEL_PID" ]; then + kill -9 "$TUNNEL_PID" 2>/dev/null + log_message "INFO" "Tunnel SSH fermé" + fi +} + +# Établir le tunnel SSH +establish_ssh_tunnel +if [ $? -ne 0 ]; then + log_message "ERROR" "Impossible de continuer sans tunnel SSH." + exit 1 +fi + +# Vérifier si la table existe dans la base source (via le tunnel SSH) +TABLE_EXISTS=$(mysql -h"$SOURCE_DB_HOST" -P"$SOURCE_DB_PORT" -u"$SOURCE_DB_USER" -p"$SOURCE_DB_PASS" -D"$SOURCE_DB_NAME" -se "SHOW TABLES LIKE '$TABLE_NAME'") + +if [ -z "$TABLE_EXISTS" ]; then + log_message "ERROR" "La table '$TABLE_NAME' n'existe pas dans la base source." + close_ssh_tunnel + exit 1 +fi + +# Obtenir la structure de la table source (via le tunnel SSH) +log_message "INFO" "Récupération de la structure de la table source..." +mysql -h"$SOURCE_DB_HOST" -P"$SOURCE_DB_PORT" -u"$SOURCE_DB_USER" -p"$SOURCE_DB_PASS" -D"$SOURCE_DB_NAME" -e "SHOW CREATE TABLE $TABLE_NAME\G" > "$LOG_DIR/structure_source_$TABLE_NAME.sql" + +# Vérifier si la table existe dans la base cible +TARGET_TABLE_EXISTS=$(mysql -h"$TARGET_DB_HOST" -P"$TARGET_DB_PORT" -u"$TARGET_DB_USER" -p"$TARGET_DB_PASS" -D"$TARGET_DB_NAME" -se "SHOW TABLES LIKE '$TABLE_NAME'") + +if [ -z "$TARGET_TABLE_EXISTS" ]; then + log_message "WARNING" "La table '$TABLE_NAME' n'existe pas dans la base cible. Création de la table..." + # Créer la table dans la base cible avec la même structure (source via SSH) + mysql -h"$SOURCE_DB_HOST" -P"$SOURCE_DB_PORT" -u"$SOURCE_DB_USER" -p"$SOURCE_DB_PASS" -D"$SOURCE_DB_NAME" -e "SHOW CREATE TABLE $TABLE_NAME" | awk 'NR==2 {print $0}' | sed 's/CREATE TABLE/CREATE TABLE IF NOT EXISTS/g' > "$LOG_DIR/create_table_$TABLE_NAME.sql" + mysql -h"$TARGET_DB_HOST" -P"$TARGET_DB_PORT" -u"$TARGET_DB_USER" -p"$TARGET_DB_PASS" -D"$TARGET_DB_NAME" < "$LOG_DIR/create_table_$TABLE_NAME.sql" +fi + +# Exporter les données de la table source (via le tunnel SSH) +log_message "INFO" "Exportation des données de la table source..." +mysqldump -h"$SOURCE_DB_HOST" -P"$SOURCE_DB_PORT" -u"$SOURCE_DB_USER" -p"$SOURCE_DB_PASS" --no-create-info --skip-triggers "$SOURCE_DB_NAME" "$TABLE_NAME" > "$LOG_DIR/data_$TABLE_NAME.sql" + +# Vider la table cible (optionnel) +read -p "Voulez-vous vider la table cible avant l'importation? (o/n): " TRUNCATE_TABLE +if [[ "$TRUNCATE_TABLE" =~ ^[Oo]$ ]]; then + log_message "INFO" "Vidage de la table cible..." + mysql -h"$TARGET_DB_HOST" -P"$TARGET_DB_PORT" -u"$TARGET_DB_USER" -p"$TARGET_DB_PASS" -D"$TARGET_DB_NAME" -e "TRUNCATE TABLE $TABLE_NAME" +fi + +# Importer les données dans la table cible +log_message "INFO" "Importation des données dans la table cible..." +mysql -h"$TARGET_DB_HOST" -P"$TARGET_DB_PORT" -u"$TARGET_DB_USER" -p"$TARGET_DB_PASS" "$TARGET_DB_NAME" < "$LOG_DIR/data_$TABLE_NAME.sql" + +# Vérifier le nombre d'enregistrements +SOURCE_COUNT=$(mysql -h"$SOURCE_DB_HOST" -P"$SOURCE_DB_PORT" -u"$SOURCE_DB_USER" -p"$SOURCE_DB_PASS" -D"$SOURCE_DB_NAME" -se "SELECT COUNT(*) FROM $TABLE_NAME") +TARGET_COUNT=$(mysql -h"$TARGET_DB_HOST" -P"$TARGET_DB_PORT" -u"$TARGET_DB_USER" -p"$TARGET_DB_PASS" -D"$TARGET_DB_NAME" -se "SELECT COUNT(*) FROM $TABLE_NAME") + +log_message "INFO" "Nombre d'enregistrements dans la table source: $SOURCE_COUNT" +log_message "INFO" "Nombre d'enregistrements dans la table cible: $TARGET_COUNT" + +if [ "$SOURCE_COUNT" -eq "$TARGET_COUNT" ]; then + log_message "SUCCESS" "Migration réussie! Tous les enregistrements ont été transférés." +else + log_message "WARNING" "Le nombre d'enregistrements diffère entre les tables source et cible." +fi + +log_message "INFO" "Migration terminée pour la table: $TABLE_NAME" + +# Fermer le tunnel SSH à la fin +close_ssh_tunnel diff --git a/api/src/Config/AppConfig.php b/api/src/Config/AppConfig.php new file mode 100644 index 00000000..81f22042 --- /dev/null +++ b/api/src/Config/AppConfig.php @@ -0,0 +1,379 @@ +currentHost = $_SERVER['SERVER_NAME'] ?? $_SERVER['HTTP_HOST'] ?? ''; + + // Récupérer les autres en-têtes pour une utilisation ultérieure si nécessaire + $this->headers = getallheaders(); + + // Déterminer l'adresse IP du client + $this->clientIp = $this->getClientIpAddress(); + + $this->initConfig(); + $this->validateApp(); + } + + public static function getInstance(): self { + if (self::$instance === null) { + self::$instance = new self(); + } + return self::$instance; + } + + private function initConfig(): void { + // Configuration de base commune à tous les environnements + $baseConfig = [ + 'name' => 'geosector', + 'encryption_key' => 'Qga2M8Ov6tyx2fIQRWHQ1U6oMK/bAFdTL7A8VRtiDhk=', + 'smtp' => [ + 'host' => 'barbotte.o2switch.net', + 'auth' => true, + 'user' => 'noreply@geosector.fr', + 'pass' => '@G83^[OMSo^Q', + 'secure' => 'ssl', + 'port' => 465, + ], + 'email' => [ + 'from' => 'noreply@geosector.fr', + 'contact' => 'contact@geosector.fr', + 'hourly_limit' => 1500, // Limite de 1500 emails/heure comme mentionné dans le cahier des charges + ], + 'mapbox' => [ + 'api_key' => '', // À remplir avec la clé API Mapbox + ], + 'stripe' => [ + 'api_key' => '', // À remplir avec la clé API Stripe + 'webhook_secret' => '', // À remplir avec le secret du webhook Stripe + ], + 'sms' => [ + 'provider' => 'ovh', // Comme mentionné dans le cahier des charges + 'api_key' => '', // À remplir avec la clé API SMS OVH + 'api_secret' => '', // À remplir avec le secret API SMS OVH + ], + ]; + + // Configuration PRODUCTION + $this->config['app.geosector.fr'] = array_merge($baseConfig, [ + 'env' => 'production', + 'database' => [ + 'host' => 'localhost', + 'name' => 'geo_app', + 'username' => 'geo_app_user_prod', + 'password' => 'QO:96-SrHJ6k7-df*?k{4W6m', + ], + ]); + + // Configuration RECETTE + $this->config['rapp.geosector.fr'] = array_merge($baseConfig, [ + 'env' => 'recette', + 'database' => [ + 'host' => 'localhost', + 'name' => 'geo_app', + 'username' => 'geo_app_user_rec', + 'password' => 'QO:96df*?k-dS3KiO-{4W6m', + ], + // Vous pouvez remplacer d'autres paramètres spécifiques à l'environnement de recette ici + ]); + + // Configuration DÉVELOPPEMENT + $this->config['dapp.geosector.fr'] = array_merge($baseConfig, [ + 'env' => 'development', + 'database' => [ + 'host' => 'localhost', + 'name' => 'geo_app', + 'username' => 'geo_app_user_dev', + 'password' => '34GOz-X5gJu-oH@Fa3$#Z', + ], + // Vous pouvez activer des fonctionnalités de débogage en développement + 'debug' => true, + // Configurez des endpoints de test pour Stripe, etc. + 'stripe' => [ + 'api_key' => 'pk_test_...', // Clé de test Stripe + 'webhook_secret' => 'whsec_test_...', // Secret de test + ], + ]); + } + + private function validateApp(): void { + // Si l'hôte est vide, utiliser une solution de secours (développement par défaut) + if (empty($this->currentHost)) { + // Journaliser cette situation anormale + error_log("WARNING: No host detected, falling back to development environment"); + $this->currentHost = 'dapp.geosector.fr'; + } + + // Si l'hôte n'existe pas dans la configuration, tenter une correction + if (!isset($this->config[$this->currentHost])) { + // Essayer de faire correspondre avec l'un des hôtes connus + $knownHosts = array_keys($this->config); + foreach ($knownHosts as $host) { + if (strpos($this->currentHost, str_replace(['app.', 'rapp.', 'dapp.'], '', $host)) !== false) { + // Correspondance trouvée, utiliser cette configuration + $this->currentHost = $host; + break; + } + } + + // Si toujours pas de correspondance, utiliser l'environnement de développement par défaut + if (!isset($this->config[$this->currentHost])) { + error_log("WARNING: Unknown host '{$this->currentHost}', falling back to development environment"); + $this->currentHost = 'dapp.geosector.fr'; + } + } + + // Journaliser l'environnement détecté + $environment = $this->config[$this->currentHost]['env'] ?? 'unknown'; + error_log("INFO: Environment detected: {$environment} (Host: {$this->currentHost}, IP: {$this->clientIp})"); + } + + /** + * Retourne le type de client (web, mobile, etc.) + * + * @return string Le type de client ou 'unknown' si non défini + */ + public function getClientType(): string { + return $this->headers['X-Client-Type'] ?? $_SERVER['HTTP_X_CLIENT_TYPE'] ?? 'unknown'; + } + + /** + * Retourne l'identifiant de l'application basé sur l'hôte + * + * @return string L'identifiant de l'application (app.geosector.fr, rapp.geosector.fr, dapp.geosector.fr) + */ + public function getAppIdentifier(): string { + return $this->currentHost; + } + + /** + * Retourne l'environnement actuel (production, recette, development) + * + * @return string L'environnement actuel + */ + public function getEnvironment(): string { + return $this->getCurrentConfig()['env'] ?? 'production'; + } + + /** + * Vérifie si l'application est en mode développement + * + * @return bool True si l'application est en mode développement + */ + public function isDevelopment(): bool { + return $this->getEnvironment() === 'development'; + } + + /** + * Vérifie si l'application est en mode recette + * + * @return bool True si l'application est en mode recette + */ + public function isRecette(): bool { + return $this->getEnvironment() === 'recette'; + } + + /** + * Vérifie si l'application est en mode production + * + * @return bool True si l'application est en mode production + */ + public function isProduction(): bool { + return $this->getEnvironment() === 'production'; + } + + /** + * Retourne la configuration complète de l'environnement actuel + * + * @return array Configuration de l'environnement + */ + public function getCurrentConfig(): array { + return $this->config[$this->currentHost]; + } + + /** + * Retourne le nom de l'application + * + * @return string Nom de l'application (geosector) + */ + public function getName(): string { + return $this->getCurrentConfig()['name']; + } + + /** + * Retourne la configuration de la base de données + * + * @return array Configuration de la base de données + */ + public function getDatabaseConfig(): array { + return $this->getCurrentConfig()['database']; + } + + /** + * Retourne la clé de chiffrement + * + * @return string Clé de chiffrement + */ + public function getEncryptionKey(): string { + return $this->getCurrentConfig()['encryption_key']; + } + + /** + * Retourne la configuration SMTP + * + * @return array Configuration SMTP + */ + public function getSmtpConfig(): array { + return $this->getCurrentConfig()['smtp']; + } + + /** + * Retourne la configuration email + * + * @return array Configuration email + */ + public function getEmailConfig(): array { + return $this->getCurrentConfig()['email']; + } + + /** + * Retourne la configuration Mapbox + * + * @return array Configuration Mapbox + */ + public function getMapboxConfig(): array { + return $this->getCurrentConfig()['mapbox']; + } + + /** + * Retourne la configuration Stripe + * + * @return array Configuration Stripe + */ + public function getStripeConfig(): array { + return $this->getCurrentConfig()['stripe']; + } + + /** + * Retourne la configuration SMS + * + * @return array Configuration SMS + */ + public function getSmsConfig(): array { + return $this->getCurrentConfig()['sms']; + } + + /** + * Retourne si le mode debug est activé + * + * @return bool True si le mode debug est activé + */ + public function isDebugEnabled(): bool { + return $this->getCurrentConfig()['debug'] ?? false; + } + + /** + * Retourne la liste des origines autorisées (domaines) + * + * @return array Liste des origines autorisées + */ + public function getAllowedOrigins(): array { + return array_keys($this->config); + } + + /** + * Vérifie si le client est d'un type spécifique + * + * @param string $type Type de client à vérifier + * @return bool True si le client est du type spécifié + */ + public function isClientType(string $type): bool { + return $this->getClientType() === $type; + } + + /** + * Retourne la configuration complète pour l'utilisation externe + * + * @return array Configuration complète + */ + public function getFullConfig(): array { + return [ + 'environment' => $this->getEnvironment(), + 'database' => $this->getDatabaseConfig(), + 'api' => [ + 'allowed_origins' => $this->getAllowedOrigins(), + 'current_site' => $this->getName(), + ], + 'debug' => $this->isDebugEnabled() + ]; + } + + /** + * Retourne l'adresse IP du client + * + * @return string L'adresse IP du client + */ + public function getClientIp(): string { + return $this->clientIp; + } + + /** + * Détermine l'adresse IP du client en tenant compte des proxys et load balancers + * + * @return string L'adresse IP du client + */ + private function getClientIpAddress(): string { + // Vérifier les en-têtes courants pour l'IP client + $ipSources = [ + 'HTTP_X_REAL_IP', // Nginx proxy + 'HTTP_CLIENT_IP', // Proxy partagé + 'HTTP_X_FORWARDED_FOR', // Proxy ou load balancer courant + 'HTTP_X_FORWARDED', // Proxy générique + 'HTTP_X_CLUSTER_CLIENT_IP', // Reverse proxy + 'HTTP_FORWARDED_FOR', // Proxies précédents + 'HTTP_FORWARDED', // Format standardisé (RFC 7239) + 'REMOTE_ADDR', // Fallback direct + ]; + + foreach ($ipSources as $source) { + if (!empty($_SERVER[$source])) { + // Pour des en-têtes comme X-Forwarded-For qui peuvent contenir plusieurs IPs séparées par des virgules + // (format: "client, proxy1, proxy2") + if ($source === 'HTTP_X_FORWARDED_FOR' || $source === 'HTTP_FORWARDED_FOR') { + $ips = explode(',', $_SERVER[$source]); + $clientIp = trim($ips[0]); // Prendre la première adresse (client original) + } else { + $clientIp = $_SERVER[$source]; + } + + // Valider l'IP pour éviter les injections + $filteredIp = filter_var($clientIp, FILTER_VALIDATE_IP); + if ($filteredIp !== false) { + return $filteredIp; + } + } + } + + // Si aucune adresse IP valide n'est trouvée, retourner une valeur par défaut + return '0.0.0.0'; + } +} diff --git a/api/src/Controllers/EntiteController.php b/api/src/Controllers/EntiteController.php new file mode 100644 index 00000000..881893fc --- /dev/null +++ b/api/src/Controllers/EntiteController.php @@ -0,0 +1,632 @@ +db = Database::getInstance(); + $this->appConfig = AppConfig::getInstance(); + } + + /** + * Crée une nouvelle entité (amicale) si elle n'existe pas déjà avec le code postal spécifié + * + * @param string $name Nom de l'amicale + * @param string $postalCode Code postal + * @param string $cityName Nom de la ville + * @return array|false Tableau contenant l'ID de l'entité créée ou false en cas d'erreur + * @throws Exception Si une entité existe déjà avec ce code postal + */ + public function createEntite(string $name, string $postalCode, string $cityName): array|false { + try { + // Vérification que le code postal n'existe pas déjà + $stmt = $this->db->prepare('SELECT id FROM entites WHERE code_postal = ?'); + $stmt->execute([$postalCode]); + + if ($stmt->fetch()) { + throw new Exception('Une amicale existe déjà sur ce code postal'); + } + + // Chiffrement du nom + $encryptedName = ApiService::encryptData($name); + + // Insertion de la nouvelle entité + $stmt = $this->db->prepare(' + INSERT INTO entites ( + encrypted_name, + code_postal, + ville, + fk_type, + created_at, + chk_active + ) VALUES (?, ?, ?, 1, NOW(), 1) + '); + + $stmt->execute([ + $encryptedName, + $postalCode, + $cityName + ]); + + $entiteId = $this->db->lastInsertId(); + + if (!$entiteId) { + throw new Exception('Erreur lors de la création de l\'entité'); + } + + LogService::log('Création d\'une nouvelle entité GeoSector', [ + 'level' => 'info', + 'entiteId' => $entiteId, + 'name' => $name, + 'postalCode' => $postalCode, + 'cityName' => $cityName + ]); + + return [ + 'id' => $entiteId, + 'name' => $name, + 'postalCode' => $postalCode, + 'cityName' => $cityName + ]; + } catch (Exception $e) { + LogService::log('Erreur lors de la création de l\'entité GeoSector', [ + 'level' => 'error', + 'error' => $e->getMessage(), + 'name' => $name, + 'postalCode' => $postalCode, + 'cityName' => $cityName + ]); + + throw $e; + } + } + + /** + * Récupère une entité par son ID + * + * @param int $id ID de l'entité + * @return array|false Données de l'entité ou false si non trouvée + */ + public function getEntiteById(int $id): array|false { + try { + $stmt = $this->db->prepare(' + SELECT id, encrypted_name, code_postal, ville, fk_type, chk_active + FROM entites + WHERE id = ? AND chk_active = 1 + '); + + $stmt->execute([$id]); + $entite = $stmt->fetch(PDO::FETCH_ASSOC); + + if (!$entite) { + return false; + } + + // Déchiffrement du nom + $entite['name'] = ApiService::decryptData($entite['encrypted_name']); + unset($entite['encrypted_name']); + + return $entite; + } catch (Exception $e) { + LogService::log('Erreur lors de la récupération de l\'entité GeoSector', [ + 'level' => 'error', + 'error' => $e->getMessage(), + 'id' => $id + ]); + + return false; + } + } + + /** + * Récupère une entité par son code postal + * + * @param string $postalCode Code postal + * @return array|false Données de l'entité ou false si non trouvée + */ + public function getEntiteByPostalCode(string $postalCode): array|false { + try { + $stmt = $this->db->prepare(' + SELECT id, encrypted_name, code_postal, ville, fk_type, chk_active + FROM entites + WHERE code_postal = ? AND chk_active = 1 + '); + + $stmt->execute([$postalCode]); + $entite = $stmt->fetch(PDO::FETCH_ASSOC); + + if (!$entite) { + return false; + } + + // Déchiffrement du nom + $entite['name'] = ApiService::decryptData($entite['encrypted_name']); + unset($entite['encrypted_name']); + + return $entite; + } catch (Exception $e) { + LogService::log('Erreur lors de la récupération de l\'entité GeoSector par code postal', [ + 'level' => 'error', + 'error' => $e->getMessage(), + 'postalCode' => $postalCode + ]); + + return false; + } + } + + /** + * Vérifie si une entité existe avec le code postal spécifié, et en crée une nouvelle si nécessaire + * + * @param string $name Nom de l'amicale + * @param string $postalCode Code postal + * @return int ID de l'entité créée ou existante + * @throws Exception Si une entité existe déjà avec ce code postal + */ + public function getOrCreateEntiteByPostalCode(string $name, string $postalCode): int { + try { + // Vérification que le code postal n'existe pas déjà + $stmt = $this->db->prepare('SELECT COUNT(*) as count FROM entites WHERE code_postal = ?'); + $stmt->execute([$postalCode]); + $result = $stmt->fetch(PDO::FETCH_ASSOC); + + if ($result && $result['count'] > 0) { + throw new Exception('Une amicale est déjà inscrite à ce code postal'); + } + + // Chiffrement du nom + $encryptedName = ApiService::encryptData($name); + + // Insertion de la nouvelle entité + $stmt = $this->db->prepare(' + INSERT INTO entites ( + encrypted_name, + code_postal, + ville, + fk_type, + created_at, + chk_active + ) VALUES (?, ?, "", 1, NOW(), 1) + '); + + $stmt->execute([ + $encryptedName, + $postalCode + ]); + + $entiteId = (int)$this->db->lastInsertId(); + + if (!$entiteId) { + throw new Exception('Erreur lors de la création de l\'entité'); + } + + LogService::log('Création d\'une nouvelle entité GeoSector via getOrCreateEntiteByPostalCode', [ + 'level' => 'info', + 'entiteId' => $entiteId, + 'name' => $name, + 'postalCode' => $postalCode + ]); + + return $entiteId; + } catch (Exception $e) { + LogService::log('Erreur lors de la vérification/création de l\'entité GeoSector', [ + 'level' => 'error', + 'error' => $e->getMessage(), + 'name' => $name, + 'postalCode' => $postalCode + ]); + + throw $e; + } + } + + /** + * Récupère toutes les entités actives + * + * @return array Liste des entités + */ + public function getEntites(): void { + try { + $stmt = $this->db->prepare(' + SELECT id, encrypted_name, code_postal, ville, fk_type, chk_active + FROM entites + WHERE chk_active = 1 + ORDER BY code_postal ASC + '); + + $stmt->execute(); + $entites = $stmt->fetchAll(PDO::FETCH_ASSOC); + + $result = []; + foreach ($entites as $entite) { + // Déchiffrement du nom pour chaque entité + $entite['name'] = ApiService::decryptData($entite['encrypted_name']); + unset($entite['encrypted_name']); + $result[] = $entite; + } + + Response::json([ + 'status' => 'success', + 'entites' => $result + ], 200); + } catch (Exception $e) { + LogService::log('Erreur lors de la récupération des entités GeoSector', [ + 'level' => 'error', + 'error' => $e->getMessage() + ]); + + Response::json([ + 'status' => 'error', + 'message' => 'Erreur lors de la récupération des entités' + ], 500); + } + } + + /** + * Recherche les coordonnées GPS d'une caserne de pompiers à partir d'une adresse + * + * @param string $address Adresse complète (adresse + code postal + ville) + * @param string $postalCode Code postal + * @param string $city Ville + * @return array|null Tableau contenant les coordonnées GPS [lat, lng] ou null si non trouvé + */ + private function findFireStationCoordinates(string $address, string $postalCode, string $city): ?array { + try { + // Construire l'adresse complète + $fullAddress = urlencode($address . ' ' . $postalCode . ' ' . $city); + + // Mots-clés pour rechercher une caserne de pompiers + $keywords = ['pompiers', 'sapeurs-pompiers', 'sdis', 'caserne', 'centre de secours']; + + foreach ($keywords as $keyword) { + // Construire l'URL de recherche + $searchUrl = "https://api-adresse.data.gouv.fr/search/?q=" . urlencode($keyword) . "&postcode=$postalCode&limit=1"; + + // Effectuer la requête + $response = file_get_contents($searchUrl); + + if ($response) { + $data = json_decode($response, true); + + // Vérifier si des résultats ont été trouvés + if (isset($data['features']) && count($data['features']) > 0) { + $feature = $data['features'][0]; + + // Vérifier si les coordonnées sont disponibles + if (isset($feature['geometry']['coordinates'])) { + $coordinates = $feature['geometry']['coordinates']; + + // Les coordonnées sont au format [longitude, latitude] + return [ + 'lat' => $coordinates[1], + 'lng' => $coordinates[0] + ]; + } + } + } + } + + // Si aucune caserne n'a été trouvée, essayer avec l'adresse de la mairie + $searchUrl = "https://api-adresse.data.gouv.fr/search/?q=mairie&postcode=$postalCode&limit=1"; + $response = file_get_contents($searchUrl); + + if ($response) { + $data = json_decode($response, true); + + if (isset($data['features']) && count($data['features']) > 0) { + $feature = $data['features'][0]; + + if (isset($feature['geometry']['coordinates'])) { + $coordinates = $feature['geometry']['coordinates']; + + return [ + 'lat' => $coordinates[1], + 'lng' => $coordinates[0] + ]; + } + } + } + + // Si toujours rien, essayer avec l'adresse complète + $searchUrl = "https://api-adresse.data.gouv.fr/search/?q=$fullAddress&limit=1"; + $response = file_get_contents($searchUrl); + + if ($response) { + $data = json_decode($response, true); + + if (isset($data['features']) && count($data['features']) > 0) { + $feature = $data['features'][0]; + + if (isset($feature['geometry']['coordinates'])) { + $coordinates = $feature['geometry']['coordinates']; + + return [ + 'lat' => $coordinates[1], + 'lng' => $coordinates[0] + ]; + } + } + } + + // Aucune coordonnée trouvée + return null; + } catch (Exception $e) { + LogService::log('Erreur lors de la recherche des coordonnées GPS', [ + 'level' => 'error', + 'error' => $e->getMessage(), + 'address' => $address, + 'postalCode' => $postalCode, + 'city' => $city + ]); + + return null; + } + } + + /** + * Met à jour une entité existante avec les données fournies + * Seuls les administrateurs (rôle > 2) peuvent modifier certains champs + * + * @return void + */ + public function updateEntite(): void { + try { + // Vérifier l'authentification et les droits d'accès + $userId = Session::getUserId(); + if (!$userId) { + Response::json([ + 'status' => 'error', + 'message' => 'Vous devez être connecté pour effectuer cette action' + ], 401); + return; + } + + // Récupérer le rôle de l'utilisateur + $stmt = $this->db->prepare('SELECT fk_role FROM users WHERE id = ?'); + $stmt->execute([$userId]); + $user = $stmt->fetch(PDO::FETCH_ASSOC); + + if (!$user) { + Response::json([ + 'status' => 'error', + 'message' => 'Utilisateur non trouvé' + ], 404); + return; + } + + $userRole = (int)$user['fk_role']; + $isAdmin = $userRole > 2; + + // Récupérer les données de la requête + $data = Request::getJson(); + + if (!isset($data['id']) || empty($data['id'])) { + Response::json([ + 'status' => 'error', + 'message' => 'ID de l\'entité requis' + ], 400); + return; + } + + $entiteId = (int)$data['id']; + + // Récupérer les données actuelles de l'entité pour vérifier si l'adresse a changé + $stmt = $this->db->prepare('SELECT adresse1, adresse2, code_postal, ville FROM entites WHERE id = ?'); + $stmt->execute([$entiteId]); + $currentEntite = $stmt->fetch(PDO::FETCH_ASSOC); + + if (!$currentEntite) { + Response::json([ + 'status' => 'error', + 'message' => 'Entité non trouvée' + ], 404); + return; + } + + // Vérifier si l'adresse a changé + $addressChanged = false; + $newAdresse1 = $data['adresse1'] ?? $currentEntite['adresse1']; + $newAdresse2 = $data['adresse2'] ?? $currentEntite['adresse2']; + $newCodePostal = $data['code_postal'] ?? $currentEntite['code_postal']; + $newVille = $data['ville'] ?? $currentEntite['ville']; + + // Vérifier si l'adresse a changé + if ( + $newAdresse1 !== $currentEntite['adresse1'] || + $newAdresse2 !== $currentEntite['adresse2'] || + $newCodePostal !== $currentEntite['code_postal'] || + $newVille !== $currentEntite['ville'] + ) { + $addressChanged = true; + } + + // Si l'adresse a changé, recalculer les coordonnées GPS + if ($addressChanged) { + // Construire l'adresse complète + $fullAddress = $newAdresse1; + if (!empty($newAdresse2)) { + $fullAddress .= ' ' . $newAdresse2; + } + + // Rechercher les coordonnées GPS de la caserne de pompiers + $coordinates = $this->findFireStationCoordinates($fullAddress, $newCodePostal, $newVille); + + // Si des coordonnées ont été trouvées, les ajouter aux champs à mettre à jour + if ($coordinates) { + $data['gps_lat'] = $coordinates['lat']; + $data['gps_lng'] = $coordinates['lng']; + + LogService::log('Coordonnées GPS mises à jour suite à un changement d\'adresse', [ + 'level' => 'info', + 'entiteId' => $entiteId, + 'lat' => $coordinates['lat'], + 'lng' => $coordinates['lng'] + ]); + } + } + + // Préparer les champs à mettre à jour + $updateFields = []; + $params = []; + + // Champs modifiables par tous les utilisateurs + if (isset($data['name']) && !empty($data['name'])) { + $updateFields[] = 'encrypted_name = ?'; + $params[] = ApiService::encryptData($data['name']); + } + + if (isset($data['adresse1'])) { + $updateFields[] = 'adresse1 = ?'; + $params[] = $data['adresse1']; + } + + if (isset($data['adresse2'])) { + $updateFields[] = 'adresse2 = ?'; + $params[] = $data['adresse2']; + } + + if (isset($data['code_postal']) && !empty($data['code_postal'])) { + $updateFields[] = 'code_postal = ?'; + $params[] = $data['code_postal']; + } + + if (isset($data['ville'])) { + $updateFields[] = 'ville = ?'; + $params[] = $data['ville']; + } + + if (isset($data['fk_region'])) { + $updateFields[] = 'fk_region = ?'; + $params[] = $data['fk_region']; + } + + if (isset($data['phone'])) { + $updateFields[] = 'encrypted_phone = ?'; + $params[] = ApiService::encryptData($data['phone']); + } + + if (isset($data['mobile'])) { + $updateFields[] = 'encrypted_mobile = ?'; + $params[] = ApiService::encryptData($data['mobile']); + } + + if (isset($data['email']) && !empty($data['email'])) { + $updateFields[] = 'encrypted_email = ?'; + $params[] = ApiService::encryptSearchableData($data['email']); + } + + if (isset($data['chk_copie_mail_recu'])) { + $updateFields[] = 'chk_copie_mail_recu = ?'; + $params[] = $data['chk_copie_mail_recu'] ? 1 : 0; + } + + if (isset($data['chk_accept_sms'])) { + $updateFields[] = 'chk_accept_sms = ?'; + $params[] = $data['chk_accept_sms'] ? 1 : 0; + } + + // Champs modifiables uniquement par les administrateurs + if ($isAdmin) { + if (isset($data['gps_lat'])) { + $updateFields[] = 'gps_lat = ?'; + $params[] = $data['gps_lat']; + } + + if (isset($data['gps_lng'])) { + $updateFields[] = 'gps_lng = ?'; + $params[] = $data['gps_lng']; + } + + if (isset($data['stripe_id'])) { + $updateFields[] = 'encrypted_stripe_id = ?'; + $params[] = ApiService::encryptData($data['stripe_id']); + } + + if (isset($data['chk_demo'])) { + $updateFields[] = 'chk_demo = ?'; + $params[] = $data['chk_demo'] ? 1 : 0; + } + + if (isset($data['chk_active'])) { + $updateFields[] = 'chk_active = ?'; + $params[] = $data['chk_active'] ? 1 : 0; + } + + if (isset($data['chk_stripe'])) { + $updateFields[] = 'chk_stripe = ?'; + $params[] = $data['chk_stripe'] ? 1 : 0; + } + } + + // Si aucun champ à mettre à jour, retourner une erreur + if (empty($updateFields)) { + Response::json([ + 'status' => 'error', + 'message' => 'Aucune donnée à mettre à jour' + ], 400); + return; + } + + // Ajouter la date de mise à jour + $updateFields[] = 'updated_at = NOW()'; + + // Construire la requête SQL + $sql = 'UPDATE entites SET ' . implode(', ', $updateFields) . ' WHERE id = ?'; + $params[] = $entiteId; + + // Exécuter la requête + $stmt = $this->db->prepare($sql); + $stmt->execute($params); + + // Vérifier si la mise à jour a réussi + if ($stmt->rowCount() === 0) { + Response::json([ + 'status' => 'warning', + 'message' => 'Aucune modification effectuée' + ], 200); + return; + } + + LogService::log('Mise à jour d\'une entité GeoSector', [ + 'level' => 'info', + 'userId' => $userId, + 'entiteId' => $entiteId, + 'isAdmin' => $isAdmin + ]); + + Response::json([ + 'status' => 'success', + 'message' => 'Entité mise à jour avec succès' + ], 200); + } catch (Exception $e) { + LogService::log('Erreur lors de la mise à jour de l\'entité GeoSector', [ + 'level' => 'error', + 'error' => $e->getMessage() + ]); + + Response::json([ + 'status' => 'error', + 'message' => 'Erreur lors de la mise à jour de l\'entité' + ], 500); + } + } +} diff --git a/api/src/Controllers/LogController.php b/api/src/Controllers/LogController.php new file mode 100644 index 00000000..f80911ff --- /dev/null +++ b/api/src/Controllers/LogController.php @@ -0,0 +1,161 @@ + [ + 'side', + 'version', + 'level', + 'timestamp', + 'environment', + 'client' => [ + 'ip', + 'browser' => ['name', 'version'], + 'os' => ['name', 'version'], + 'screenResolution', + 'userAgent' + ] + ], + 'message' + ]; + + public function index(): void { + try { + // Récupérer la configuration de l'application + $appConfig = AppConfig::getInstance(); + $appName = $appConfig->getName(); + $clientType = ClientDetector::getClientType(); + + // Récupérer et décoder le JSON + $data = json_decode(file_get_contents('php://input'), true); + + // Vérifier si le JSON est valide + if (json_last_error() !== JSON_ERROR_NONE) { + throw new \Exception('Invalid JSON format'); + } + + // Valider la structure des données + $this->validateData($data); + + // Ajouter le type de client aux métadonnées + $data['metadata']['client_type'] = $clientType; + + // Si c'est une app mobile, ajouter l'identifiant de l'app + if ($clientType === 'mobile') { + $data['metadata']['app_identifier'] = ClientDetector::getAppIdentifier(); + } + + + // Définir le chemin du dossier logs à la racine du projet + $logDir = __DIR__ . '/../../logs'; + + // Créer le dossier logs s'il n'existe pas + if (!is_dir($logDir)) { + if (!mkdir($logDir, 0777, true)) { + throw new \Exception("Impossible de créer le dossier de logs: {$logDir}"); + } + // S'assurer que les permissions sont correctes + chmod($logDir, 0777); + } + + // Vérifier si le dossier est accessible en écriture + if (!is_writable($logDir)) { + throw new \Exception("Le dossier de logs n'est pas accessible en écriture: {$logDir}"); + } + + // Récupérer l'environnement défini dans la configuration + $environment = $appConfig->getEnvironment(); + + // Créer le nom du fichier basé sur l'environnement et la date + // Format: geosector-production-2025-03-28.log, geosector-recette-2025-03-28.log, geosector-development-2025-03-28.log + $filename = $logDir . '/geosector-' . $environment . '-' . date('Y-m-d') . '.log'; + + // Formater la ligne de log au format plat demandé + // timestamp;browser.name@browser.version;os.name@os.version;client_type;$metadata;$message + $timestamp = date('Y-m-d\TH:i:s'); + $browserInfo = $data['metadata']['client']['browser']['name'] . '@' . $data['metadata']['client']['browser']['version']; + $osInfo = $data['metadata']['client']['os']['name'] . '@' . $data['metadata']['client']['os']['version']; + $clientType = $data['metadata']['client_type']; + + // Extraire le niveau de log + $level = isset($data['metadata']['level']) ? (is_array($data['metadata']['level']) ? 'info' : $data['metadata']['level']) : 'info'; + + // Préparer les métadonnées supplémentaires (exclure celles déjà incluses dans le format et les informations client) + $additionalMetadata = []; + foreach ($data['metadata'] as $key => $value) { + // Exclure les informations client, type client, side, version, level et environment + if (!in_array($key, ['client', 'client_type', 'side', 'version', 'level', 'environment'])) { + if (is_array($value)) { + $additionalMetadata[$key] = json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + } else { + $additionalMetadata[$key] = $value; + } + } + } + + // Joindre les métadonnées supplémentaires avec des virgules + $metadataStr = !empty($additionalMetadata) ? implode(',', array_map(function($k, $v) { + return $k . '=' . $v; + }, array_keys($additionalMetadata), $additionalMetadata)) : '-'; + + // Construire la ligne de log au format demandé + $logLine = implode(';', [ + $timestamp, + $browserInfo, + $osInfo, + $clientType, + $level, + $metadataStr, + $data['message'] + ]) . "\n"; + + // Écrire dans le fichier avec vérification complète + if (file_put_contents($filename, $logLine, FILE_APPEND) === false) { + throw new \Exception("Impossible d'écrire dans le fichier de logs: {$filename}"); + } + + // Retourner 204 No Content en cas de succès + http_response_code(204); + } catch (\Exception $e) { + Response::json([ + 'success' => false, + 'message' => $e->getMessage() + ], 400); + } + } + + private function validateData($data): void { + if (!isset($data['metadata']) || !isset($data['message'])) { + throw new \Exception('Missing required root fields'); + } + + // Valider la structure metadata + foreach (self::REQUIRED_FIELDS['metadata'] as $key => $value) { + if (is_array($value)) { + if (!isset($data['metadata'][$key])) { + throw new \Exception("Missing metadata field: {$key}"); + } + foreach ($value as $subKey => $subValue) { + if (is_array($subValue)) { + foreach ($subValue as $field) { + if (!isset($data['metadata'][$key][$subKey][$field])) { + throw new \Exception("Missing metadata field: {$key}.{$subKey}.{$field}"); + } + } + } else { + if (!isset($data['metadata'][$key][$subValue])) { + throw new \Exception("Missing metadata field: {$key}.{$subValue}"); + } + } + } + } else { + if (!isset($data['metadata'][$value])) { + throw new \Exception("Missing metadata field: {$value}"); + } + } + } + } +} diff --git a/api/src/Controllers/LoginController.php b/api/src/Controllers/LoginController.php new file mode 100644 index 00000000..ddc4c73e --- /dev/null +++ b/api/src/Controllers/LoginController.php @@ -0,0 +1,1276 @@ +db = Database::getInstance(); + $this->appConfig = AppConfig::getInstance(); + } + + public function login(): void { + try { + $data = Request::getJson(); + + if (!isset($data['username'], $data['password'], $data['type'])) { + LogService::log('Tentative de connexion GeoSector échouée : données manquantes', [ + 'level' => 'warning', + 'username' => $data['username'] ?? 'non fourni' + ]); + Response::json(['error' => 'Nom d\'utilisateur et mot de passe requis'], 400); + return; + } + + $interface = trim($data['type']); + $username = trim($data['username']); + $encryptedUsername = ApiService::encryptSearchableData($username); + + // Récupérer le type d'utilisateur + // admin accessible uniquement aux fk_role>1 + // sinon tout user peut se connecter à l'interface utilisateur + $roleCondition = ($interface === 'user') ? '' : 'AND fk_role>1'; + + // Log pour le debug + LogService::log('Tentative de connexion GeoSector', [ + 'level' => 'info', + 'username' => $username, + 'type' => $interface, + 'role_condition' => $roleCondition + ]); + + // Requête optimisée: on récupère l'utilisateur et son entité en une seule fois avec LEFT JOIN + $stmt = $this->db->prepare( + 'SELECT + u.id, u.encrypted_email, u.encrypted_user_name, u.encrypted_name, u.user_pass_hash, + u.first_name, u.fk_role, u.fk_entite, u.chk_active, u.sect_name, + e.id AS entite_id, e.encrypted_name AS entite_encrypted_name, + e.adresse1, e.code_postal, e.ville, e.gps_lat, e.gps_lng, e.chk_active AS entite_chk_active + FROM users u + LEFT JOIN entites e ON u.fk_entite = e.id + WHERE u.encrypted_user_name = ? AND u.chk_active != 0 ' . $roleCondition + ); + $stmt->execute([$encryptedUsername]); + $user = $stmt->fetch(PDO::FETCH_ASSOC); + + if (!$user) { + LogService::log('Tentative de connexion GeoSector échouée : utilisateur non trouvé', [ + 'level' => 'warning', + 'username' => $username + ]); + Response::json(['error' => 'Identifiants invalides'], 401); + return; + } + + // Vérification du mot de passe + $passwordValid = password_verify($data['password'], $user['user_pass_hash']); + + if (!$passwordValid) { + LogService::log('Tentative de connexion GeoSector échouée : mot de passe incorrect', [ + 'level' => 'warning', + 'username' => $username + ]); + Response::json(['error' => 'Identifiants invalides'], 401); + return; + } + + // Vérifier si l'utilisateur a une entité et si elle est active + if (!empty($user['fk_entite']) && (!isset($user['entite_chk_active']) || $user['entite_chk_active'] != 1)) { + LogService::log('Tentative de connexion GeoSector échouée : entité non active', [ + 'level' => 'warning', + 'username' => $username, + 'entite_id' => $user['fk_entite'] + ]); + Response::json([ + 'status' => 'error', + 'message' => 'Votre amicale n\'est pas activée. Veuillez contacter votre administrateur.' + ], 403); + return; + } + + // Mise à jour de last_login et activation du compte si nécessaire + $updateQuery = 'UPDATE users SET + updated_at = NOW()' . + ($user['chk_active'] == -1 ? ', chk_active = 1' : '') . + ($user['chk_active'] == 2 ? ', chk_active = 1' : '') . + ' WHERE id = ?'; + + $updateStmt = $this->db->prepare($updateQuery); + $updateStmt->execute([$user['id']]); + + // Déchiffrement du nom + $decryptedName = ApiService::decryptData($user['encrypted_name']); + + // Déchiffrement de l'email si disponible + $email = ''; + if (!empty($user['encrypted_email'])) { + $email = ApiService::decryptSearchableData($user['encrypted_email']); + + // Si le déchiffrement échoue, renvoyer une erreur + if (empty($email)) { + LogService::log('Déchiffrement email échoué', [ + 'level' => 'error', + 'message' => 'Déchiffrement de l\'email échoué', + 'encrypted_email' => $user['encrypted_email'], + 'user_id' => $user['id'] + ]); + + Response::json([ + 'status' => 'error', + 'message' => 'Erreur de déchiffrement de l\'email. Exécutez le script de migration pour résoudre ce problème.', + 'debug_info' => [ + 'encrypted_email' => $user['encrypted_email'], + 'user_id' => $user['id'] + ] + ], 500); + return; + } + } + + // Création de la session + $sessionData = [ + 'id' => $user['id'], + 'username' => $username, + 'email' => $email, + 'name' => $decryptedName, + 'first_name' => $user['first_name'] ?? '', + 'fk_role' => $user['fk_role'] ?? '0' + // 'interface' supprimée pour se baser uniquement sur le rôle + ]; + Session::login($sessionData); + + // Préparation des données utilisateur pour la réponse (uniquement les champs du user) + $userData = [ + 'id' => $user['id'], + 'fk_entite' => $user['fk_entite'] ?? null, + 'fk_role' => $user['fk_role'] ?? '0', + 'fk_titre' => $user['fk_titre'] ?? null, + 'first_name' => $user['first_name'] ?? '', + 'sect_name' => $user['sect_name'] ?? '', + 'date_naissance' => $user['date_naissance'] ?? null, + 'date_embauche' => $user['date_embauche'] ?? null, + 'username' => $username, + 'name' => $decryptedName + ]; + + // Déchiffrement du téléphone + if (!empty($user['encrypted_phone'])) { + $userData['phone'] = ApiService::decryptData($user['encrypted_phone']); + } else { + $userData['phone'] = ''; + } + + // Déchiffrement du mobile + if (!empty($user['encrypted_mobile'])) { + $userData['mobile'] = ApiService::decryptData($user['encrypted_mobile']); + } else { + $userData['mobile'] = ''; + } + + // L'email est déjà déchiffré plus haut dans le code + $userData['email'] = $email; + + // Suivant l'interface et le role de l'utilisateur, on lui charge toutes ses données utiles + + // operations : + // Si $interface='user' : on ne récupère que la dernière opération active + // Si $interface='admin' et si $user['fk_role']=2 : on récupère les 3 dernières opérations dont celle active + // Dans tous les autres cas, operations: [] + + // secteurs : + // On récupère les secteurs de l'opération active trouvée, sinon secteurs: [] + + // passages : + // On récupère les passages du ou des secteurs trouvés, sinon passages: [] + + // users_sectors : + // On récupère les users affectés aux secteurs partagés de l'utilisateur, si pas de secteurs, users_passages: [] + + // clients : + // Si $interface="admin" et si $user['fk_role']=9 + // On récupère les entités au complet sauf la entite.id=1 dans un group clients contenant id, name, adresse1, adresse2, code_postal, ville, fk_region, lib_region, fk_type, phone, mobile, email, gps_lat, gps_lng, chk_active + + // Suivant l'interface et le role de l'utilisateur, on lui charge toutes ses données utiles + $operationsData = []; + $sectorsData = []; + $passagesData = []; + $usersSectorsData = []; + + // 1. Récupération des opérations selon les critères + $operationLimit = 0; + $activeOperationOnly = false; + + if ($interface === 'user') { + // Interface utilisateur : seulement la dernière opération active + $operationLimit = 1; + $activeOperationOnly = true; + } elseif ($interface === 'admin' && $user['fk_role'] == 2) { + // Interface admin avec rôle 2 : les 3 dernières opérations dont l'active + $operationLimit = 3; + } else { + // Autres cas : pas d'opérations + $operationLimit = 0; + } + + if ($operationLimit > 0 && !empty($user['fk_entite'])) { + $operationQuery = "SELECT id, libelle, date_deb, date_fin + FROM operations + WHERE fk_entite = ?"; + + if ($activeOperationOnly) { + $operationQuery .= " AND chk_active = 1"; + } + + $operationQuery .= " ORDER BY id DESC LIMIT " . $operationLimit; + + $operationStmt = $this->db->prepare($operationQuery); + $operationStmt->execute([$user['fk_entite']]); + $operations = $operationStmt->fetchAll(PDO::FETCH_ASSOC); + + if (!empty($operations)) { + // Formater les données des opérations + foreach ($operations as $operation) { + $operationsData[] = [ + 'id' => $operation['id'], + 'name' => $operation['libelle'], + 'date_deb' => $operation['date_deb'], + 'date_fin' => $operation['date_fin'] + ]; + } + + // Récupérer l'ID de l'opération active (première opération retournée) + $activeOperationId = $operations[0]['id']; + + // 2. Récupérer les secteurs selon l'interface et le rôle + if ($interface === 'user') { + // Interface utilisateur : seulement les secteurs affectés à l'utilisateur + $sectorsStmt = $this->db->prepare( + 'SELECT s.id, s.libelle, s.color, s.sector + FROM ope_sectors s + JOIN ope_users_sectors us ON s.id = us.fk_sector + WHERE us.fk_operation = ? AND us.fk_user = ? AND us.chk_active = 1 AND s.chk_active = 1' + ); + $sectorsStmt->execute([$activeOperationId, $user['id']]); + } elseif ($interface === 'admin' && $user['fk_role'] == 2) { + // Interface admin avec rôle 2 : tous les secteurs distincts de l'opération + $sectorsStmt = $this->db->prepare( + 'SELECT DISTINCT s.id, s.libelle, s.color, s.sector + FROM ope_sectors s + WHERE s.fk_operation = ? AND s.chk_active = 1' + ); + $sectorsStmt->execute([$activeOperationId]); + } else { + // Autres cas : pas de secteurs + $sectors = []; + $sectorsData = []; + } + + // Récupération des secteurs si une requête a été préparée + if (isset($sectorsStmt)) { + $sectors = $sectorsStmt->fetchAll(PDO::FETCH_ASSOC); + } else { + $sectors = []; + } + + if (!empty($sectors)) { + $sectorsData = $sectors; + + // 3. Récupérer les passages selon l'interface et le rôle + if ($interface === 'user' && !empty($sectors)) { + // Interface utilisateur : passages liés aux secteurs de l'utilisateur + $sectorIds = array_column($sectors, 'id'); + $sectorIdsString = implode(',', $sectorIds); + + if (!empty($sectorIdsString)) { + $passagesStmt = $this->db->prepare( + "SELECT id, fk_operation, fk_sector, fk_user, fk_type, fk_adresse, passed_at, numero, rue, rue_bis, ville, residence, fk_habitat, appt, niveau, + gps_lat, gps_lng, nom_recu, encrypted_name, remarque, encrypted_email, encrypted_phone, montant, fk_type_reglement, email_erreur, nb_passages + FROM ope_pass + WHERE fk_operation = ? AND fk_sector IN ($sectorIdsString) AND chk_active = 1" + ); + $passagesStmt->execute([$activeOperationId]); + } + } elseif ($interface === 'admin' && $user['fk_role'] == 2) { + // Interface admin avec rôle 2 : tous les passages de l'opération + $passagesStmt = $this->db->prepare( + "SELECT id, fk_operation, fk_sector, fk_user, fk_type, fk_adresse, passed_at, numero, rue, rue_bis, ville, residence, fk_habitat, appt, niveau, + gps_lat, gps_lng, nom_recu, encrypted_name, remarque, encrypted_email, encrypted_phone, montant, fk_type_reglement, email_erreur, nb_passages + FROM ope_pass + WHERE fk_operation = ? AND chk_active = 1" + ); + $passagesStmt->execute([$activeOperationId]); + } else { + // Autres cas : pas de passages + $passages = []; + $passagesData = []; + } + + // Récupération des passages si une requête a été préparée + if (isset($passagesStmt)) { + $passages = $passagesStmt->fetchAll(PDO::FETCH_ASSOC); + } else { + $passages = []; + } + + if (!empty($passages)) { + // Déchiffrer les données sensibles + foreach ($passages as &$passage) { + // Déchiffrement du nom + $passage['name'] = ''; + if (!empty($passage['encrypted_name'])) { + $passage['name'] = ApiService::decryptData($passage['encrypted_name']); + } + unset($passage['encrypted_name']); + + // Déchiffrement de l'email + $passage['email'] = ''; + if (!empty($passage['encrypted_email'])) { + $decryptedEmail = ApiService::decryptSearchableData($passage['encrypted_email']); + if ($decryptedEmail) { + $passage['email'] = $decryptedEmail; + } + } + unset($passage['encrypted_email']); + + // Déchiffrement du téléphone + $passage['phone'] = ''; + if (!empty($passage['encrypted_phone'])) { + $passage['phone'] = ApiService::decryptData($passage['encrypted_phone']); + } + unset($passage['encrypted_phone']); + } + $passagesData = $passages; + } + + // 4. Récupérer les utilisateurs des secteurs partagés + if (($interface === 'user' || ($interface === 'admin' && $user['fk_role'] == 2)) && !empty($sectors)) { + $sectorIds = array_column($sectors, 'id'); + $sectorIdsString = implode(',', $sectorIds); + + if (!empty($sectorIdsString)) { + $usersSectorsStmt = $this->db->prepare( + "SELECT DISTINCT u.id, u.first_name, u.encrypted_name, u.sect_name, us.fk_sector + FROM users u + JOIN ope_users_sectors us ON u.id = us.fk_user + WHERE us.fk_sector IN ($sectorIdsString) + AND us.fk_operation = ? + AND us.chk_active = 1 + AND u.chk_active = 1 + AND u.id != ?" // Exclure l'utilisateur connecté + ); + $usersSectorsStmt->execute([$activeOperationId, $user['id']]); + $usersSectors = $usersSectorsStmt->fetchAll(PDO::FETCH_ASSOC); + + if (!empty($usersSectors)) { + // Déchiffrer les noms des utilisateurs + foreach ($usersSectors as &$userSector) { + if (!empty($userSector['encrypted_name'])) { + $userSector['name'] = ApiService::decryptData($userSector['encrypted_name']); + unset($userSector['encrypted_name']); + } + } + $usersSectorsData = $usersSectors; + } + } + } else { + // Autres cas : pas d'utilisateurs de secteurs + $usersSectorsData = []; + } + } + } + } + + // Section "clients" supprimée car redondante avec le nouveau groupe "amicales" + + // 6. Récupérer les membres (users de l'entité du user) si nécessaire + if ($interface === 'admin' && $user['fk_role'] == 2 && !empty($user['fk_entite'])) { + $membresStmt = $this->db->prepare( + 'SELECT id, fk_role, fk_titre, encrypted_name, first_name, sect_name, + encrypted_user_name, encrypted_phone, encrypted_mobile, encrypted_email, + date_naissance, date_embauche, chk_active + FROM users + WHERE fk_entite = ?' + ); + $membresStmt->execute([$user['fk_entite']]); + $membres = $membresStmt->fetchAll(PDO::FETCH_ASSOC); + + if (!empty($membres)) { + $membresData = []; + + foreach ($membres as $membre) { + $membreItem = [ + 'id' => $membre['id'], + 'fk_role' => $membre['fk_role'], + 'fk_titre' => $membre['fk_titre'], + 'first_name' => $membre['first_name'] ?? '', + 'sect_name' => $membre['sect_name'] ?? '', + 'date_naissance' => $membre['date_naissance'] ?? null, + 'date_embauche' => $membre['date_embauche'] ?? null, + 'chk_active' => $membre['chk_active'] + ]; + + // Déchiffrement du nom + if (!empty($membre['encrypted_name'])) { + $membreItem['name'] = ApiService::decryptData($membre['encrypted_name']); + } + + // Déchiffrement du nom d'utilisateur + if (!empty($membre['encrypted_user_name'])) { + $membreItem['username'] = ApiService::decryptSearchableData($membre['encrypted_user_name']); + } + + // Déchiffrement du téléphone + if (!empty($membre['encrypted_phone'])) { + $membreItem['phone'] = ApiService::decryptData($membre['encrypted_phone']); + } + + // Déchiffrement du mobile + if (!empty($membre['encrypted_mobile'])) { + $membreItem['mobile'] = ApiService::decryptData($membre['encrypted_mobile']); + } + + // Déchiffrement de l'email + if (!empty($membre['encrypted_email'])) { + $decryptedEmail = ApiService::decryptSearchableData($membre['encrypted_email']); + if ($decryptedEmail) { + $membreItem['email'] = $decryptedEmail; + } + } + + $membresData[] = $membreItem; + } + + // Les membres seront ajoutés à la racine de la réponse plus tard + // (après la préparation de la réponse) + } + } + + // 7. Récupérer les amicales selon le rôle de l'utilisateur + $amicalesData = []; + + if (!empty($user['fk_entite'])) { + if ($user['fk_role'] <= 2) { + // User normal ou admin avec fk_role=2: uniquement son amicale + $amicaleStmt = $this->db->prepare( + 'SELECT e.id, e.encrypted_name as name, e.adresse1, e.adresse2, e.code_postal, e.ville, + e.fk_region, r.libelle AS lib_region, e.fk_type, e.encrypted_phone as phone, e.encrypted_mobile as mobile, + e.encrypted_email as email, e.gps_lat, e.gps_lng, + e.encrypted_stripe_id as stripe_id, e.chk_demo, e.chk_copie_mail_recu, e.chk_accept_sms, e.chk_active, e.chk_stripe + FROM entites e + LEFT JOIN x_regions r ON e.fk_region = r.id + WHERE e.id = ? AND e.chk_active = 1' + ); + $amicaleStmt->execute([$user['fk_entite']]); + $amicales = $amicaleStmt->fetchAll(PDO::FETCH_ASSOC); + } else { + // Admin avec fk_role>2: toutes les amicales sauf id=1 + $amicaleStmt = $this->db->prepare( + 'SELECT e.id, e.encrypted_name as name, e.adresse1, e.adresse2, e.code_postal, e.ville, + e.fk_region, r.libelle AS lib_region, e.fk_type, e.encrypted_phone as phone, e.encrypted_mobile as mobile, + e.encrypted_email as email, e.gps_lat, e.gps_lng, + e.encrypted_stripe_id as stripe_id, e.chk_demo, e.chk_copie_mail_recu, e.chk_accept_sms, e.chk_active, e.chk_stripe + FROM entites e + LEFT JOIN x_regions r ON e.fk_region = r.id + WHERE e.id != 1 AND e.chk_active = 1' + ); + $amicaleStmt->execute(); + $amicales = $amicaleStmt->fetchAll(PDO::FETCH_ASSOC); + } + + if (!empty($amicales)) { + foreach ($amicales as &$amicale) { + // Déchiffrement du nom + if (!empty($amicale['name'])) { + $amicale['name'] = ApiService::decryptData($amicale['name']); + } + + // Déchiffrement de l'email si disponible + if (!empty($amicale['email'])) { + $decryptedEmail = ApiService::decryptSearchableData($amicale['email']); + if ($decryptedEmail) { + $amicale['email'] = $decryptedEmail; + } + } + + // Déchiffrement du téléphone + if (!empty($amicale['phone'])) { + $amicale['phone'] = ApiService::decryptData($amicale['phone']); + } + + // Déchiffrement du mobile + if (!empty($amicale['mobile'])) { + $amicale['mobile'] = ApiService::decryptData($amicale['mobile']); + } + + // Déchiffrement du stripe_id + if (!empty($amicale['stripe_id'])) { + $amicale['stripe_id'] = ApiService::decryptData($amicale['stripe_id']); + } + } + $amicalesData = $amicales; + } + } + + // 8. Récupérer les entités de type 1 pour les utilisateurs avec fk_role > 2 + $entitesData = []; + + if ($user['fk_role'] > 2) { + // Admin avec fk_role > 2: toutes les entités de type 1 + $entitesStmt = $this->db->prepare( + 'SELECT e.id, e.encrypted_name as name, e.adresse1, e.adresse2, e.code_postal, e.ville, + e.fk_region, r.libelle AS lib_region, e.fk_type, e.encrypted_phone as phone, e.encrypted_mobile as mobile, + e.encrypted_email as email, e.gps_lat, e.gps_lng, + e.encrypted_stripe_id as stripe_id, e.chk_demo, e.chk_copie_mail_recu, e.chk_accept_sms, e.chk_active, e.chk_stripe + FROM entites e + LEFT JOIN x_regions r ON e.fk_region = r.id + WHERE e.fk_type = 1 AND e.chk_active = 1' + ); + $entitesStmt->execute(); + $entites = $entitesStmt->fetchAll(PDO::FETCH_ASSOC); + + if (!empty($entites)) { + foreach ($entites as &$entite) { + // Déchiffrement du nom + if (!empty($entite['name'])) { + $entite['name'] = ApiService::decryptData($entite['name']); + } + + // Déchiffrement de l'email si disponible + if (!empty($entite['email'])) { + $decryptedEmail = ApiService::decryptSearchableData($entite['email']); + if ($decryptedEmail) { + $entite['email'] = $decryptedEmail; + } + } + + // Déchiffrement du téléphone + if (!empty($entite['phone'])) { + $entite['phone'] = ApiService::decryptData($entite['phone']); + } + + // Déchiffrement du mobile + if (!empty($entite['mobile'])) { + $entite['mobile'] = ApiService::decryptData($entite['mobile']); + } + + // Déchiffrement du stripe_id + if (!empty($entite['stripe_id'])) { + $entite['stripe_id'] = ApiService::decryptData($entite['stripe_id']); + } + } + $entitesData = $entites; + } + } + + // Préparation de la réponse + $response = [ + 'status' => 'success', + 'message' => 'Connexion réussie', + 'session_id' => session_id(), + 'session_expiry' => date('c', strtotime('+24 hours')), // Ajoute une expiration de 24h + 'user' => $userData + ]; + + // Ajout des amicales à la racine de la réponse si disponibles + if (!empty($amicalesData)) { + // Si c'est un tableau avec un seul élément, on envoie directement l'objet + // pour que le client reçoive un objet et non un tableau avec un seul objet + if (count($amicalesData) === 1) { + $response['amicale'] = $amicalesData[0]; + } else { + $response['amicale'] = $amicalesData; + } + } + + // Ajout des entités à la racine de la réponse sous le nom "clients" (vide pour fk_role <= 2) + $response['clients'] = $entitesData; + + // Ajout des membres à la racine de la réponse si disponibles + if (!empty($membresData)) { + $response['membres'] = $membresData; + } + + // Ajout des opérations à la racine de la réponse si disponibles + if (!empty($operationsData)) { + $response['operations'] = $operationsData; + } + + // Ajout des secteurs à la racine de la réponse si disponibles + if (!empty($sectorsData)) { + $response['sectors'] = $sectorsData; + } + + // Ajout des passages à la racine de la réponse si disponibles + if (!empty($passagesData)) { + $response['passages'] = $passagesData; + } + + // Ajout des utilisateurs des secteurs à la racine de la réponse si disponibles + if (!empty($usersSectorsData)) { + $response['users_sectors'] = $usersSectorsData; + } + + // Section "clients" supprimée car redondante avec le nouveau groupe "amicales" + + // 9. Récupérer les régions selon le rôle de l'utilisateur + $regionsData = []; + + if ($user['fk_role'] <= 2 && !empty($user['fk_entite'])) { + // User normal ou admin avec fk_role=2: uniquement sa région basée sur le code postal de son amicale + $amicaleStmt = $this->db->prepare('SELECT code_postal FROM entites WHERE id = ?'); + $amicaleStmt->execute([$user['fk_entite']]); + $amicale = $amicaleStmt->fetch(PDO::FETCH_ASSOC); + + if (!empty($amicale) && !empty($amicale['code_postal'])) { + $departement = substr($amicale['code_postal'], 0, 2); + + $regionStmt = $this->db->prepare( + 'SELECT id, fk_pays, libelle, libelle_long, table_osm, departements, chk_active + FROM x_regions + WHERE FIND_IN_SET(?, departements) > 0 AND chk_active = 1' + ); + $regionStmt->execute([$departement]); + $regions = $regionStmt->fetchAll(PDO::FETCH_ASSOC); + + if (!empty($regions)) { + $regionsData = $regions; + } + } + } else { + // Admin avec fk_role>2: toutes les régions + $regionStmt = $this->db->prepare( + 'SELECT id, fk_pays, libelle, libelle_long, table_osm, departements, chk_active + FROM x_regions + WHERE chk_active = 1' + ); + $regionStmt->execute(); + $regions = $regionStmt->fetchAll(PDO::FETCH_ASSOC); + + if (!empty($regions)) { + $regionsData = $regions; + } + } + + // Ajout des régions à la racine de la réponse si disponibles + if (!empty($regionsData)) { + $response['regions'] = $regionsData; + } + + // Envoi de la réponse + Response::json($response); + } catch (PDOException $e) { + LogService::log('Erreur base de données lors de la connexion GeoSector', [ + 'level' => 'error', + 'error' => $e->getMessage(), + 'code' => $e->getCode() + ]); + Response::json([ + 'status' => 'error', + 'message' => 'Erreur serveur' + ], 500); + } catch (Exception $e) { + LogService::log('Erreur inattendue lors de la connexion GeoSector', [ + 'level' => 'error', + 'error' => $e->getMessage() + ]); + Response::json([ + 'status' => 'error', + 'message' => 'Une erreur inattendue est survenue' + ], 500); + } + } + + public function lostPassword(): void { + try { + $data = Request::getJson(); + + if (!isset($data['email']) || empty($data['email'])) { + Response::json([ + 'status' => 'error', + 'message' => 'Email requis' + ], 400); + return; + } + + $email = trim($data['email']); + + // Validation de l'email + if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { + Response::json([ + 'status' => 'error', + 'message' => 'Format d\'email invalide' + ], 400); + return; + } + + // Chiffrement de l'email pour la recherche + $encryptedEmail = ApiService::encryptSearchableData($email); + + // Recherche de l'utilisateur + $stmt = $this->db->prepare(' + SELECT id, encrypted_name, encrypted_user_name, chk_active + FROM users + WHERE encrypted_email = ? + '); + $stmt->execute([$encryptedEmail]); + $user = $stmt->fetch(PDO::FETCH_ASSOC); + + if (!$user) { + Response::json([ + 'status' => 'error', + 'message' => 'Aucun compte trouvé avec cet email' + ], 404); + return; + } + + if ($user['chk_active'] == 0) { + Response::json([ + 'status' => 'error', + 'message' => 'Ce compte est désactivé. Contactez l\'administrateur.' + ], 403); + return; + } + + // Déchiffrement du nom et du username + $name = ApiService::decryptData($user['encrypted_name']); + $username = ApiService::decryptSearchableData($user['encrypted_user_name']); + + // Génération d'un nouveau mot de passe + $newPassword = ApiService::generateSecurePassword(); + $passwordHash = password_hash($newPassword, PASSWORD_DEFAULT); + + // Mise à jour du mot de passe + $updateStmt = $this->db->prepare(' + UPDATE users + SET user_pass_hash = ?, updated_at = NOW() + WHERE id = ? + '); + $updateStmt->execute([$passwordHash, $user['id']]); + + // Envoi de l'email avec le nouveau mot de passe + $emailSent = ApiService::sendEmail( + $email, + $name, + 'lostpwd', + ['username' => $username, 'password' => $newPassword] + ); + + if ($emailSent) { + LogService::log('Réinitialisation mot de passe GeoSector réussie', [ + 'level' => 'info', + 'userId' => $user['id'], + 'email' => $email + ]); + + Response::json([ + 'status' => 'success', + 'message' => 'Un nouveau mot de passe a été envoyé à votre adresse email' + ]); + } else { + LogService::log('Échec envoi email réinitialisation mot de passe GeoSector', [ + 'level' => 'error', + 'userId' => $user['id'], + 'email' => $email + ]); + + Response::json([ + 'status' => 'error', + 'message' => 'Impossible d\'envoyer l\'email. Veuillez contacter l\'administrateur.' + ], 500); + } + } catch (Exception $e) { + LogService::log('Erreur lors de la réinitialisation du mot de passe GeoSector', [ + 'level' => 'error', + 'error' => $e->getMessage() + ]); + + Response::json([ + 'status' => 'error', + 'message' => 'Une erreur est survenue. Veuillez réessayer.' + ], 500); + } + } + + public function register(): void { + try { + $data = Request::getJson(); + + // 1. Validation des données de base + if ( + !isset($data['email'], $data['name'], $data['amicale_name'], $data['postal_code'], $data['city_name']) || + empty($data['email']) || empty($data['name']) || empty($data['amicale_name']) || empty($data['postal_code']) + ) { + Response::json([ + 'status' => 'error', + 'message' => 'Tous les champs sont requis' + ], 400); + return; + } + + // 2. Validation du token et du captcha + if (!isset($data['token']) || empty($data['token'])) { + Response::json([ + 'status' => 'error', + 'message' => 'Token de sécurité manquant' + ], 400); + return; + } + + // Vérification que le token est un timestamp valide et récent + // Le frontend envoie un timestamp en millisecondes, donc on le convertit en secondes + $tokenTimestamp = intval($data['token']) / 1000; // Conversion millisecondes -> secondes + $currentTime = time(); + $twoHoursAgo = $currentTime - 7200; // 2 heures = 7200 secondes (plus permissif) + + // Tolérance de 5 minutes pour les décalages d'horloge + $futureTime = $currentTime + 300; // 5 minutes = 300 secondes + + // Log pour le débogage + LogService::log('Vérification du token', [ + 'level' => 'info', + 'token_ms' => $data['token'], + 'token_sec' => $tokenTimestamp, + 'current_time' => $currentTime, + 'two_hours_ago' => $twoHoursAgo, + 'future_time' => $futureTime + ]); + + // Vérification plus permissive + if ($tokenTimestamp < $twoHoursAgo || $tokenTimestamp > $futureTime) { + LogService::log('Tentative d\'inscription avec un token invalide', [ + 'level' => 'warning', + 'token' => $data['token'], + 'token_sec' => $tokenTimestamp, + 'current_time' => $currentTime, + 'email' => $data['email'] ?? 'non fourni' + ]); + + Response::json([ + 'status' => 'error', + 'message' => 'Session expirée, veuillez rafraîchir la page et réessayer' + ], 400); + return; + } + + if ( + !isset($data['captcha_answer'], $data['captcha_expected']) || + $data['captcha_answer'] != $data['captcha_expected'] + ) { + LogService::log('Tentative d\'inscription avec un captcha invalide', [ + 'level' => 'warning', + 'captcha_answer' => $data['captcha_answer'] ?? 'non fourni', + 'captcha_expected' => $data['captcha_expected'] ?? 'non fourni', + 'email' => $data['email'] ?? 'non fourni' + ]); + + Response::json([ + 'status' => 'error', + 'message' => 'Vérification anti-robot échouée' + ], 400); + return; + } + + $email = trim($data['email']); + $name = trim($data['name']); + $amicaleName = trim($data['amicale_name']); + $postalCode = trim($data['postal_code']); + $cityName = trim($data['city_name'] ?? ''); + + // 3. Validation de l'email + if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { + Response::json([ + 'status' => 'error', + 'message' => 'Format d\'email invalide' + ], 400); + return; + } + + // 4. Vérification de l'existence de l'email + $encryptedEmail = ApiService::encryptSearchableData($email); + $checkStmt = $this->db->prepare('SELECT id FROM users WHERE encrypted_email = ?'); + $checkStmt->execute([$encryptedEmail]); + if ($checkStmt->fetch()) { + Response::json([ + 'status' => 'error', + 'message' => 'Cet email est déjà utilisé' + ], 409); + return; + } + + // 5. Vérification de l'existence du code postal dans la table entites + $checkPostalStmt = $this->db->prepare('SELECT id FROM entites WHERE code_postal = ?'); + $checkPostalStmt->execute([$postalCode]); + if ($checkPostalStmt->fetch()) { + Response::json([ + 'status' => 'error', + 'message' => 'Une amicale est déjà inscrite à ce code postal' + ], 409); + return; + } + + // 6. Recherche de la région correspondant au code postal + $departement = substr($postalCode, 0, 2); + $regionStmt = $this->db->prepare(' + SELECT id FROM x_regions + WHERE FIND_IN_SET(?, departements) > 0 AND chk_active = 1 + LIMIT 1 + '); + $regionStmt->execute([$departement]); + $region = $regionStmt->fetch(PDO::FETCH_ASSOC); + $regionId = $region ? $region['id'] : null; + + // 7. Chiffrement des données sensibles + $encryptedName = ApiService::encryptData($name); + $encryptedAmicaleName = ApiService::encryptData($amicaleName); + $encryptedEmail = ApiService::encryptSearchableData($email); + + // 8. Création de l'entité (amicale) + $this->db->beginTransaction(); + try { + // Insertion de la nouvelle entité + $entiteStmt = $this->db->prepare(' + INSERT INTO entites ( + encrypted_name, + code_postal, + ville, + fk_type, + fk_region, + encrypted_email, + chk_demo, + chk_active, + created_at + ) VALUES (?, ?, ?, 1, ?, ?, 1, 1, NOW()) + '); + $entiteStmt->execute([ + $encryptedAmicaleName, + $postalCode, + $cityName, + $regionId, + $encryptedEmail + ]); + $entiteId = $this->db->lastInsertId(); + + if (!$entiteId) { + throw new Exception('Erreur lors de la création de l\'entité'); + } + + // Recherche des coordonnées GPS de la caserne de pompiers + try { + $gpsCoordinates = $this->findFireStationCoordinates($postalCode, $cityName); + + if ($gpsCoordinates) { + // Mise à jour des coordonnées GPS de l'entité + $updateGpsStmt = $this->db->prepare(' + UPDATE entites + SET gps_lat = ?, gps_lng = ? + WHERE id = ? + '); + $updateGpsStmt->execute([ + $gpsCoordinates['lat'], + $gpsCoordinates['lng'], + $entiteId + ]); + + LogService::log('Coordonnées GPS de la caserne de pompiers ajoutées', [ + 'level' => 'info', + 'entiteId' => $entiteId, + 'postalCode' => $postalCode, + 'cityName' => $cityName, + 'lat' => $gpsCoordinates['lat'], + 'lng' => $gpsCoordinates['lng'] + ]); + } else { + LogService::log('Aucune caserne de pompiers trouvée', [ + 'level' => 'warning', + 'entiteId' => $entiteId, + 'postalCode' => $postalCode, + 'cityName' => $cityName + ]); + } + } catch (Exception $e) { + // On ne bloque pas l'inscription si la recherche de coordonnées échoue + LogService::log('Erreur lors de la recherche des coordonnées GPS', [ + 'level' => 'error', + 'entiteId' => $entiteId, + 'postalCode' => $postalCode, + 'cityName' => $cityName, + 'error' => $e->getMessage() + ]); + } + + // 9. Génération du nom d'utilisateur et du mot de passe + $username = ApiService::generateUserName($this->db, $name, $postalCode, $cityName); + $encryptedUsername = ApiService::encryptSearchableData($username); + $password = ApiService::generateSecurePassword(); + $passwordHash = password_hash($password, PASSWORD_DEFAULT); + + // 10. Création de l'utilisateur administrateur + $userStmt = $this->db->prepare(' + INSERT INTO users ( + encrypted_user_name, + encrypted_email, + user_pass_hash, + encrypted_name, + fk_role, + created_at, + chk_active, + fk_entite + ) VALUES (?, ?, ?, ?, 2, NOW(), 1, ?) + '); + $userStmt->execute([ + $encryptedUsername, + $encryptedEmail, + $passwordHash, + $encryptedName, + $entiteId + ]); + $userId = $this->db->lastInsertId(); + + $this->db->commit(); + + // Log du succès de l'inscription + LogService::log('Inscription GeoSector réussie', [ + 'level' => 'info', + 'userId' => $userId, + 'username' => $username, + 'email' => $email, + 'role' => 2, + 'entiteId' => $entiteId, + 'amicaleName' => $amicaleName, + 'postalCode' => $postalCode, + 'cityName' => $cityName + ]); + + // 11. Envoi des emails + // Premier email : bienvenue avec UNIQUEMENT le nom d'utilisateur (sans mot de passe) + // Création d'un mot de passe temporaire pour le template (ne sera pas affiché) + $tempPassword = "********"; + $welcomeResult = ApiService::sendEmail( + $email, + $name, + 'welcome', + ['username' => $username, 'password' => $tempPassword] + ); + + // Email de notification aux administrateurs (sans le nom d'utilisateur ni le mot de passe) + $notificationMessage = "Nouvelle inscription GeoSector:\n\n" . + "Nom: $name\n" . + "Email: $email\n" . + "Amicale: $amicaleName\n" . + "Code postal: $postalCode\n" . + "Ville: $cityName\n"; + + ApiService::sendEmail( + "contactgeosector@gmail.com", + "Admin GeoSector", + 'alert', + ['subject' => 'Nouvelle inscription GeoSector', 'message' => $notificationMessage] + ); + + ApiService::sendEmail( + "contact@geosector.fr", + "Admin GeoSector", + 'alert', + ['subject' => 'Nouvelle inscription GeoSector', 'message' => $notificationMessage] + ); + + // Attendre un court délai avant d'envoyer le second email (pour éviter les filtres anti-spam) + sleep(2); + + // Second email : UNIQUEMENT le mot de passe + $passwordResult = ApiService::sendEmail( + $email, + $name, + 'lostpwd', + ['username' => $username, 'password' => $password] + ); + + // Réponse selon le résultat de l'envoi d'email + if ($welcomeResult === 0 || $passwordResult === 0) { + Response::json([ + 'status' => 'warning', + 'message' => 'Compte créé avec succès mais impossible de vous envoyer tous les emails. ' . + 'Rendez-vous sur la page de login et choisissez mot de passe perdu pour recevoir votre mot de passe.' + ], 201); + } else { + Response::json([ + 'status' => 'success', + 'message' => 'Votre compte a bien été créé et vous recevrez par email votre identifiant et mot de passe' + ], 201); + } + } catch (Exception $e) { + $this->db->rollBack(); + LogService::log('Erreur lors de la création du compte GeoSector', [ + 'level' => 'error', + 'error' => $e->getMessage(), + 'email' => $email, + 'amicaleName' => $amicaleName, + 'postalCode' => $postalCode + ]); + + Response::json([ + 'status' => 'error', + 'message' => $e->getMessage() + ], 500); + return; + } + } catch (PDOException $e) { + LogService::log('Erreur serveur lors de l\'inscription GeoSector', [ + 'level' => 'error', + 'error' => $e->getMessage(), + 'code' => $e->getCode(), + 'trace' => $e->getTraceAsString() + ]); + Response::json([ + 'status' => 'error', + 'message' => 'Erreur lors de la création du compte. Veuillez réessayer.' + ], 500); + } catch (Exception $e) { + LogService::log('Erreur inattendue lors de l\'inscription GeoSector', [ + 'level' => 'error', + 'error' => $e->getMessage() + ]); + Response::json([ + 'status' => 'error', + 'message' => 'Une erreur inattendue est survenue. Veuillez réessayer.' + ], 500); + } + } + + // Méthodes auxiliaires + + public function logout(): void { + $userId = Session::getUserId() ?? null; + $userEmail = Session::getUserEmail() ?? 'anonyme'; + + Session::logout(); + + LogService::log('Déconnexion GeoSector réussie', [ + 'level' => 'info', + 'userId' => $userId, + 'email' => $userEmail + ]); + + // Retourner une réponse standardisée + Response::json([ + 'status' => 'success', + 'message' => 'Déconnexion réussie' + ]); + } + + /** + * Recherche les coordonnées GPS d'une caserne de pompiers dans une ville donnée + * + * @param string $postalCode Le code postal de la ville + * @param string $cityName Le nom de la ville + * @return array|null Tableau associatif contenant les coordonnées GPS (lat, lng) ou null si aucune caserne trouvée + * @throws Exception En cas d'erreur lors de la requête API + */ + private function findFireStationCoordinates(string $postalCode, string $cityName): ?array { + // Mots-clés pour rechercher une caserne de pompiers + $keywords = ['pompiers', 'sdis', 'sapeurs-pompiers', 'caserne', 'centre de secours']; + + // Formater la ville et le code postal pour la recherche + $citySearch = urlencode($cityName . ' ' . $postalCode); + + foreach ($keywords as $keyword) { + // Construire l'URL de recherche pour l'API adresse.gouv.fr + $searchUrl = "https://api-adresse.data.gouv.fr/search/?q=" . urlencode($keyword) . "+$citySearch&limit=5"; + + // Effectuer la requête HTTP + $response = @file_get_contents($searchUrl); + + if ($response === false) { + LogService::log('Erreur lors de la requête à l\'API adresse.gouv.fr', [ + 'level' => 'error', + 'url' => $searchUrl + ]); + continue; // Essayer avec le mot-clé suivant + } + + // Décoder la réponse JSON + $data = json_decode($response, true); + + if (!$data || !isset($data['features']) || empty($data['features'])) { + continue; // Aucun résultat, essayer avec le mot-clé suivant + } + + // Parcourir les résultats pour trouver une caserne de pompiers + foreach ($data['features'] as $feature) { + $properties = $feature['properties'] ?? []; + $name = strtolower($properties['name'] ?? ''); + $label = strtolower($properties['label'] ?? ''); + + // Vérifier si le résultat correspond à une caserne de pompiers + if ( + strpos($name, 'pompier') !== false || + strpos($name, 'sdis') !== false || + strpos($label, 'pompier') !== false || + strpos($label, 'sdis') !== false || + strpos($name, 'caserne') !== false || + strpos($label, 'caserne') !== false || + strpos($name, 'centre de secours') !== false || + strpos($label, 'centre de secours') !== false + ) { + // Extraire les coordonnées GPS + $coordinates = $feature['geometry']['coordinates'] ?? null; + + if ($coordinates && count($coordinates) >= 2) { + // L'API retourne les coordonnées au format [longitude, latitude] + return [ + 'lng' => $coordinates[0], + 'lat' => $coordinates[1] + ]; + } + } + } + } + + // Si aucune caserne n'a été trouvée avec les mots-clés, utiliser les coordonnées du centre de la ville + $cityUrl = "https://api-adresse.data.gouv.fr/search/?q=$citySearch&limit=1"; + $cityResponse = @file_get_contents($cityUrl); + + if ($cityResponse !== false) { + $cityData = json_decode($cityResponse, true); + + if ($cityData && isset($cityData['features'][0]['geometry']['coordinates'])) { + $coordinates = $cityData['features'][0]['geometry']['coordinates']; + + LogService::log('Utilisation des coordonnées du centre de la ville', [ + 'level' => 'info', + 'city' => $cityName, + 'postalCode' => $postalCode + ]); + + return [ + 'lng' => $coordinates[0], + 'lat' => $coordinates[1] + ]; + } + } + + // Aucune coordonnée trouvée + return null; + } +} diff --git a/api/src/Controllers/UserController.php b/api/src/Controllers/UserController.php new file mode 100644 index 00000000..6c3474c0 --- /dev/null +++ b/api/src/Controllers/UserController.php @@ -0,0 +1,605 @@ +db = Database::getInstance(); + $this->appConfig = AppConfig::getInstance(); + } + + + + + + public function getUsers(): void { + Session::requireAuth(); + + // Vérification des droits d'accès (rôle administrateur) + // Récupérer le rôle de l'utilisateur depuis la base de données + $userId = Session::getUserId(); + $stmt = $this->db->prepare('SELECT fk_role FROM users WHERE id = ?'); + $stmt->execute([$userId]); + $result = $stmt->fetch(PDO::FETCH_ASSOC); + $userRole = $result ? $result['fk_role'] : null; + + if ($userRole != '1' && $userRole != '2') { // Supposons que 1 et 2 sont des rôles admin + Response::json([ + 'status' => 'error', + 'message' => 'Accès non autorisé' + ], 403); + return; + } + + try { + $stmt = $this->db->prepare(' + SELECT + u.id, + u.encrypt_email, + u.encrypted_name, + u.first_name, + u.fk_role as role, + u.fk_entite, + u.chk_active, + u.created_at, + u.updated_at, + e.encrypted_name as entite_name + FROM users u + LEFT JOIN entites e ON u.fk_entite = e.id + ORDER BY u.created_at DESC + '); + $stmt->execute(); + $users = $stmt->fetchAll(PDO::FETCH_ASSOC); + + // Déchiffrement des données sensibles pour chaque utilisateur + foreach ($users as &$user) { + $user['email'] = ApiService::decryptSearchableData($user['encrypt_email']); + $user['name'] = ApiService::decryptData($user['encrypted_name']); + + if (!empty($user['entite_name'])) { + $user['entite_name'] = ApiService::decryptData($user['entite_name']); + } + + // Suppression des champs chiffrés + unset($user['encrypt_email']); + unset($user['encrypted_name']); + } + + Response::json([ + 'status' => 'success', + 'users' => $users + ]); + } catch (PDOException $e) { + LogService::log('Erreur lors de la récupération des utilisateurs GeoSector', [ + 'level' => 'error', + 'error' => $e->getMessage() + ]); + Response::json([ + 'status' => 'error', + 'message' => 'Erreur serveur' + ], 500); + } + } + + public function getUserById(string $id): void { + Session::requireAuth(); + + // Vérification des droits d'accès (rôle administrateur ou utilisateur lui-même) + $currentUserId = Session::getUserId(); + + // Récupérer le rôle de l'utilisateur depuis la base de données + $stmt = $this->db->prepare('SELECT fk_role FROM users WHERE id = ?'); + $stmt->execute([$currentUserId]); + $result = $stmt->fetch(PDO::FETCH_ASSOC); + $userRole = $result ? $result['fk_role'] : null; + + if ($userRole != '1' && $userRole != '2' && $currentUserId != $id) { + Response::json([ + 'status' => 'error', + 'message' => 'Accès non autorisé' + ], 403); + return; + } + + try { + $stmt = $this->db->prepare(' + SELECT + u.id, + u.encrypt_email, + u.encrypted_name, + u.first_name, + u.sect_name, + u.encrypt_phone, + u.encrypt_mobile, + u.fk_role as role, + u.fk_entite, + u.infos, + u.chk_alert_email, + u.chk_suivi, + u.date_naissance, + u.date_embauche, + u.matricule, + u.chk_active, + u.created_at, + u.updated_at, + e.encrypted_name as entite_name, + e.adresse1, + e.adresse2, + e.cp, + e.ville, + e.fk_region + FROM users u + LEFT JOIN entites e ON u.fk_entite = e.id + WHERE u.id = ? + '); + $stmt->execute([$id]); + $user = $stmt->fetch(PDO::FETCH_ASSOC); + + if (!$user) { + Response::json([ + 'status' => 'error', + 'message' => 'Utilisateur non trouvé' + ], 404); + return; + } + + // Déchiffrement des données sensibles + $user['email'] = ApiService::decryptSearchableData($user['encrypt_email']); + $user['name'] = ApiService::decryptData($user['encrypted_name']); + $user['phone'] = ApiService::decryptData($user['encrypt_phone'] ?? ''); + $user['mobile'] = ApiService::decryptData($user['encrypt_mobile'] ?? ''); + + if (!empty($user['entite_name'])) { + $user['entite_name'] = ApiService::decryptData($user['entite_name']); + } + + // Suppression des champs chiffrés + unset($user['encrypt_email']); + unset($user['encrypted_name']); + unset($user['encrypt_phone']); + unset($user['encrypt_mobile']); + + Response::json([ + 'status' => 'success', + 'user' => $user + ]); + } catch (PDOException $e) { + LogService::log('Erreur lors de la récupération de l\'utilisateur GeoSector', [ + 'level' => 'error', + 'error' => $e->getMessage(), + 'userId' => $id + ]); + Response::json([ + 'status' => 'error', + 'message' => 'Erreur serveur' + ], 500); + } + } + + public function createUser(): void { + Session::requireAuth(); + + // Vérification des droits d'accès (rôle administrateur) + $currentUserId = Session::getUserId(); + + // Récupérer le rôle de l'utilisateur depuis la base de données + $stmt = $this->db->prepare('SELECT fk_role FROM users WHERE id = ?'); + $stmt->execute([$currentUserId]); + $result = $stmt->fetch(PDO::FETCH_ASSOC); + $userRole = $result ? $result['fk_role'] : null; + + if ($userRole != '1' && $userRole != '2') { + Response::json([ + 'status' => 'error', + 'message' => 'Accès non autorisé' + ], 403); + return; + } + + try { + $data = Request::getJson(); + $currentUserId = Session::getUserId(); + + // Validation des données requises + if (!isset($data['email'], $data['name'])) { + Response::json([ + 'status' => 'error', + 'message' => 'Email et nom requis' + ], 400); + return; + } + + $email = trim(strtolower($data['email'])); + $name = trim($data['name']); + $firstName = isset($data['first_name']) ? trim($data['first_name']) : ''; + $role = isset($data['role']) ? trim($data['role']) : '1'; + $entiteId = isset($data['fk_entite']) ? (int)$data['fk_entite'] : 1; + + // Vérification des longueurs d'entrée + if (strlen($email) > 255 || strlen($name) > 255) { + Response::json([ + 'status' => 'error', + 'message' => 'Email ou nom trop long' + ], 400); + return; + } + + // Validation de l'email + if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { + Response::json([ + 'status' => 'error', + 'message' => 'Format d\'email invalide' + ], 400); + return; + } + + // Chiffrement des données sensibles + $encryptedEmail = ApiService::encryptSearchableData($email); + $encryptedName = ApiService::encryptData($name); + + // Vérification de l'existence de l'email + $checkStmt = $this->db->prepare('SELECT id FROM users WHERE encrypt_email = ?'); + $checkStmt->execute([$encryptedEmail]); + if ($checkStmt->fetch()) { + Response::json([ + 'status' => 'error', + 'message' => 'Cet email est déjà utilisé' + ], 409); + return; + } + + // Génération du mot de passe + $password = ApiService::generateSecurePassword(); + $passwordHash = password_hash($password, PASSWORD_DEFAULT); + + // Préparation des champs optionnels + $phone = isset($data['phone']) ? ApiService::encryptData(trim($data['phone'])) : null; + $mobile = isset($data['mobile']) ? ApiService::encryptData(trim($data['mobile'])) : null; + $sectName = isset($data['sect_name']) ? trim($data['sect_name']) : ''; + $infos = isset($data['infos']) ? trim($data['infos']) : ''; + $alertEmail = isset($data['chk_alert_email']) ? (int)$data['chk_alert_email'] : 1; + $suivi = isset($data['chk_suivi']) ? (int)$data['chk_suivi'] : 0; + $dateNaissance = isset($data['date_naissance']) ? $data['date_naissance'] : null; + $dateEmbauche = isset($data['date_embauche']) ? $data['date_embauche'] : null; + $matricule = isset($data['matricule']) ? trim($data['matricule']) : ''; + + // Insertion en base de données + $stmt = $this->db->prepare(' + INSERT INTO users ( + encrypt_email, user_pswd, encrypted_name, first_name, + sect_name, encrypt_phone, encrypt_mobile, fk_role, + fk_entite, infos, chk_alert_email, chk_suivi, + date_naissance, date_embauche, matricule, + created_at, fk_user_creat, chk_active + ) VALUES ( + ?, ?, ?, ?, + ?, ?, ?, ?, + ?, ?, ?, ?, + ?, ?, ?, + NOW(), ?, 1 + ) + '); + $stmt->execute([ + $encryptedEmail, + $passwordHash, + $encryptedName, + $firstName, + $sectName, + $phone, + $mobile, + $role, + $entiteId, + $infos, + $alertEmail, + $suivi, + $dateNaissance, + $dateEmbauche, + $matricule, + $currentUserId + ]); + $userId = $this->db->lastInsertId(); + + // Envoi de l'email avec les identifiants + ApiService::sendEmail($email, $name, 'welcome', ['password' => $password]); + + LogService::log('Utilisateur GeoSector créé', [ + 'level' => 'info', + 'createdBy' => $currentUserId, + 'newUserId' => $userId, + 'email' => $email + ]); + + Response::json([ + 'status' => 'success', + 'message' => 'Utilisateur créé avec succès', + 'id' => $userId + ], 201); + } catch (PDOException $e) { + LogService::log('Erreur lors de la création d\'un utilisateur GeoSector', [ + 'level' => 'error', + 'error' => $e->getMessage(), + 'code' => $e->getCode() + ]); + Response::json([ + 'status' => 'error', + 'message' => 'Erreur serveur' + ], 500); + } + } + + public function updateUser(string $id): void { + Session::requireAuth(); + + // Vérification des droits d'accès (rôle administrateur ou utilisateur lui-même) + $currentUserId = Session::getUserId(); + + // Récupérer le rôle de l'utilisateur depuis la base de données + $stmt = $this->db->prepare('SELECT fk_role FROM users WHERE id = ?'); + $stmt->execute([$currentUserId]); + $result = $stmt->fetch(PDO::FETCH_ASSOC); + $userRole = $result ? $result['fk_role'] : null; + + if ($userRole != '1' && $userRole != '2' && $currentUserId != $id) { + Response::json([ + 'status' => 'error', + 'message' => 'Accès non autorisé' + ], 403); + return; + } + + try { + $data = Request::getJson(); + + // Vérification qu'il y a des données à mettre à jour + if (empty($data)) { + Response::json([ + 'status' => 'error', + 'message' => 'Aucune donnée à mettre à jour' + ], 400); + return; + } + + // Construction de la requête UPDATE dynamique + $updateFields = []; + $params = ['id' => $id]; + + // Traitement des champs à chiffrer + if (isset($data['email'])) { + // Vérification que l'email n'est pas déjà utilisé par un autre utilisateur + $email = trim(strtolower($data['email'])); + $encryptedEmail = ApiService::encryptSearchableData($email); + + $checkStmt = $this->db->prepare('SELECT id FROM users WHERE encrypt_email = ? AND id != ?'); + $checkStmt->execute([$encryptedEmail, $id]); + if ($checkStmt->fetch()) { + Response::json([ + 'status' => 'error', + 'message' => 'Cet email est déjà utilisé par un autre utilisateur' + ], 409); + return; + } + + $updateFields[] = "encrypt_email = :encrypt_email"; + $params['encrypt_email'] = $encryptedEmail; + } + + if (isset($data['name'])) { + $updateFields[] = "encrypted_name = :encrypted_name"; + $params['encrypted_name'] = ApiService::encryptData(trim($data['name'])); + } + + if (isset($data['phone'])) { + $updateFields[] = "encrypt_phone = :encrypt_phone"; + $params['encrypt_phone'] = ApiService::encryptData(trim($data['phone'])); + } + + if (isset($data['mobile'])) { + $updateFields[] = "encrypt_mobile = :encrypt_mobile"; + $params['encrypt_mobile'] = ApiService::encryptData(trim($data['mobile'])); + } + + // Traitement des champs non chiffrés + $nonEncryptedFields = [ + 'first_name', + 'sect_name', + 'fk_role', + 'fk_entite', + 'infos', + 'chk_alert_email', + 'chk_suivi', + 'date_naissance', + 'date_embauche', + 'matricule', + 'chk_active' + ]; + + foreach ($nonEncryptedFields as $field) { + if (isset($data[$field])) { + $updateFields[] = "$field = :$field"; + $params[$field] = is_string($data[$field]) ? trim($data[$field]) : $data[$field]; + } + } + + // Mise à jour du mot de passe si fourni + if (isset($data['password']) && !empty($data['password'])) { + if (strlen($data['password']) < 8) { + Response::json([ + 'status' => 'error', + 'message' => 'Le mot de passe doit contenir au moins 8 caractères' + ], 400); + return; + } + $updateFields[] = "user_pswd = :password"; + $params['password'] = password_hash($data['password'], PASSWORD_DEFAULT); + } + + // Ajout des champs de mise à jour + $updateFields[] = "updated_at = NOW()"; + $updateFields[] = "fk_user_modif = :modifier_id"; + $params['modifier_id'] = $currentUserId; + + if (!empty($updateFields)) { + $sql = 'UPDATE users SET ' . implode(', ', $updateFields) . ' WHERE id = :id'; + $stmt = $this->db->prepare($sql); + $stmt->execute($params); + + if ($stmt->rowCount() === 0) { + Response::json([ + 'status' => 'warning', + 'message' => 'Aucune modification effectuée' + ]); + return; + } + + LogService::log('Utilisateur GeoSector mis à jour', [ + 'level' => 'info', + 'modifiedBy' => $currentUserId, + 'userId' => $id, + 'fields' => array_keys($data) + ]); + + Response::json([ + 'status' => 'success', + 'message' => 'Utilisateur mis à jour avec succès' + ]); + } else { + Response::json([ + 'status' => 'warning', + 'message' => 'Aucune donnée valide à mettre à jour' + ]); + } + } catch (PDOException $e) { + LogService::log('Erreur lors de la mise à jour d\'un utilisateur GeoSector', [ + 'level' => 'error', + 'error' => $e->getMessage(), + 'userId' => $id + ]); + Response::json([ + 'status' => 'error', + 'message' => 'Erreur serveur' + ], 500); + } + } + + public function deleteUser(string $id): void { + Session::requireAuth(); + + // Vérification des droits d'accès (rôle administrateur) + $currentUserId = Session::getUserId(); + + // Récupérer le rôle de l'utilisateur depuis la base de données + $stmt = $this->db->prepare('SELECT fk_role FROM users WHERE id = ?'); + $stmt->execute([$currentUserId]); + $result = $stmt->fetch(PDO::FETCH_ASSOC); + $userRole = $result ? $result['fk_role'] : null; + + if ($userRole != '1' && $userRole != '2') { + Response::json([ + 'status' => 'error', + 'message' => 'Accès non autorisé' + ], 403); + return; + } + + $currentUserId = Session::getUserId(); + + // Empêcher la suppression de son propre compte + if ($currentUserId == $id) { + Response::json([ + 'status' => 'error', + 'message' => 'Vous ne pouvez pas supprimer votre propre compte' + ], 400); + return; + } + + try { + // Désactivation de l'utilisateur plutôt que suppression + $stmt = $this->db->prepare(' + UPDATE users + SET chk_active = 0, + updated_at = NOW(), + fk_user_modif = ? + WHERE id = ? + '); + $stmt->execute([$currentUserId, $id]); + + if ($stmt->rowCount() === 0) { + Response::json([ + 'status' => 'error', + 'message' => 'Utilisateur non trouvé' + ], 404); + return; + } + + LogService::log('Utilisateur GeoSector désactivé', [ + 'level' => 'info', + 'deactivatedBy' => $currentUserId, + 'userId' => $id + ]); + + Response::json([ + 'status' => 'success', + 'message' => 'Utilisateur désactivé avec succès' + ]); + } catch (PDOException $e) { + LogService::log('Erreur lors de la désactivation d\'un utilisateur GeoSector', [ + 'level' => 'error', + 'error' => $e->getMessage(), + 'userId' => $id + ]); + Response::json([ + 'status' => 'error', + 'message' => 'Erreur serveur' + ], 500); + } + } + + // Méthodes auxiliaires + private function validateUpdateData(array $data): ?string { + // Validation de l'email + if (isset($data['email'])) { + if (!filter_var(trim($data['email']), FILTER_VALIDATE_EMAIL)) { + return 'Format d\'email invalide'; + } + } + + // Validation du nom + if (isset($data['name']) && strlen(trim($data['name'])) < 2) { + return 'Le nom doit contenir au moins 2 caractères'; + } + + // Validation du téléphone + if (isset($data['phone']) && !empty($data['phone'])) { + if (!preg_match('/^[0-9+\s()-]{6,20}$/', trim($data['phone']))) { + return 'Format de téléphone invalide'; + } + } + + // Validation du mobile + if (isset($data['mobile']) && !empty($data['mobile'])) { + if (!preg_match('/^[0-9+\s()-]{6,20}$/', trim($data['mobile']))) { + return 'Format de mobile invalide'; + } + } + + return null; + } +} diff --git a/api/src/Controllers/VilleController.php b/api/src/Controllers/VilleController.php new file mode 100644 index 00000000..107f8e6e --- /dev/null +++ b/api/src/Controllers/VilleController.php @@ -0,0 +1,99 @@ +db = Database::getInstance(); + $this->appConfig = AppConfig::getInstance(); + } + + /** + * Recherche les villes dont le code postal commence par les chiffres saisis + * + * @return void + */ + public function searchVillesByPostalCode(): void { + try { + // Récupérer le paramètre code_postal de la requête + $postalCode = Request::getValue('code_postal'); + + if (empty($postalCode) || strlen($postalCode) < 3) { + Response::json([ + 'status' => 'error', + 'message' => 'Le code postal doit contenir au moins 3 chiffres' + ], 400); + return; + } + + // Valider que le code postal ne contient que des chiffres + if (!ctype_digit($postalCode)) { + Response::json([ + 'status' => 'error', + 'message' => 'Le code postal doit contenir uniquement des chiffres' + ], 400); + return; + } + + // Rechercher les villes dont le code postal commence par les chiffres saisis + $stmt = $this->db->prepare(' + SELECT id, fk_departement, libelle, code_postal + FROM x_villes + WHERE code_postal LIKE ? + ORDER BY libelle ASC + LIMIT 20 + '); + + $stmt->execute([$postalCode . '%']); + $villes = $stmt->fetchAll(PDO::FETCH_ASSOC); + + // Renommer les champs pour une meilleure lisibilité côté client + $result = []; + foreach ($villes as $ville) { + $result[] = [ + 'id' => $ville['id'], + 'departement_id' => $ville['fk_departement'], + 'nom' => $ville['libelle'], + 'code_postal' => $ville['code_postal'] + ]; + } + + Response::json([ + 'status' => 'success', + 'success' => true, + 'data' => $result + ], 200); + } catch (Exception $e) { + LogService::log('Erreur lors de la recherche de villes par code postal', [ + 'level' => 'error', + 'error' => $e->getMessage(), + 'postalCode' => $postalCode ?? 'non défini' + ]); + + Response::json([ + 'status' => 'error', + 'success' => false, + 'message' => 'Erreur lors de la recherche de villes' + ], 500); + } + } +} diff --git a/api/src/Core/Database.php b/api/src/Core/Database.php new file mode 100644 index 00000000..20148bf5 --- /dev/null +++ b/api/src/Core/Database.php @@ -0,0 +1,39 @@ + PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + PDO::ATTR_EMULATE_PREPARES => false, + ]; + + self::$instance = new PDO( + $dsn, + self::$config['username'], + self::$config['password'], + $options + ); + } catch (PDOException $e) { + throw new RuntimeException("Database connection failed: " . $e->getMessage()); + } + } + + return self::$instance; + } +} \ No newline at end of file diff --git a/api/src/Core/Request.php b/api/src/Core/Request.php new file mode 100644 index 00000000..fd4f7c65 --- /dev/null +++ b/api/src/Core/Request.php @@ -0,0 +1,22 @@ + + */ + public static function getJson(): array { + $json = file_get_contents('php://input'); + $data = json_decode($json, true) ?? []; + + if (json_last_error() !== JSON_ERROR_NONE) { + throw new RuntimeException('Invalid JSON payload'); + } + + return $data; + } + + public static function getValue(string $key, mixed $default = null): mixed { + return $_REQUEST[$key] ?? $default; + } +} \ No newline at end of file diff --git a/api/src/Core/Response.php b/api/src/Core/Response.php new file mode 100644 index 00000000..5acb86fd --- /dev/null +++ b/api/src/Core/Response.php @@ -0,0 +1,97 @@ + 0) { + ob_end_clean(); + } + + // Headers CORS pour permettre les requêtes cross-origin (applications mobiles) + $origin = $_SERVER['HTTP_ORIGIN'] ?? '*'; + + // Configurer les headers CORS + header("Access-Control-Allow-Origin: $origin"); + header('Access-Control-Allow-Credentials: true'); + header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); + header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With, X-App-Identifier, X-Client-Type'); + header('Access-Control-Expose-Headers: Content-Length, X-Kuma-Revision'); + + // Définir les headers de réponse + header('Content-Type: application/json; charset=utf-8'); + header('X-Content-Type-Options: nosniff'); + + // Définir le code de statut + http_response_code($status); + + // Ajouter status et message à la réponse si non présents + if (!isset($data['status'])) { + if ($status >= 200 && $status < 300) { + $data['status'] = 'success'; + } else { + $data['status'] = 'error'; + } + } + + if (!isset($data['message']) && isset($data['error'])) { + $data['message'] = $data['error']; + } + + // Sanitize data to ensure valid UTF-8 before encoding + $sanitizedData = self::sanitizeForJson($data); + + // Encoder et envoyer la réponse + $jsonResponse = json_encode($sanitizedData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + // Vérifier si l'encodage a échoué + if ($jsonResponse === false) { + error_log('Erreur d\'encodage JSON: ' . json_last_error_msg()); + $jsonResponse = json_encode([ + 'status' => 'error', + 'message' => 'Erreur d\'encodage de la réponse', + 'debug_info' => json_last_error_msg() + ]); + } + + // Log de débogage + error_log('Envoi de la réponse JSON: ' . $jsonResponse); + + // Envoyer la réponse + echo $jsonResponse; + + // S'assurer que tout est envoyé + flush(); + } + + /** + * Sanitize data recursively to ensure valid UTF-8 encoding for JSON + * + * @param mixed $data The data to sanitize + * @return mixed The sanitized data + */ + private static function sanitizeForJson($data) { + if (is_string($data)) { + // Replace invalid UTF-8 characters + if (!mb_check_encoding($data, 'UTF-8')) { + // Try to convert from other encodings + $encodings = ['ISO-8859-1', 'Windows-1252']; + foreach ($encodings as $encoding) { + $converted = mb_convert_encoding($data, 'UTF-8', $encoding); + if (mb_check_encoding($converted, 'UTF-8')) { + return $converted; + } + } + // If conversion fails, strip invalid characters + return mb_convert_encoding($data, 'UTF-8', 'UTF-8'); + } + return $data; + } else if (is_array($data)) { + // Recursively sanitize array elements + foreach ($data as $key => $value) { + $data[$key] = self::sanitizeForJson($value); + } + } + return $data; + } +} \ No newline at end of file diff --git a/api/src/Core/Router.php b/api/src/Core/Router.php new file mode 100644 index 00000000..e6c760b7 --- /dev/null +++ b/api/src/Core/Router.php @@ -0,0 +1,208 @@ +configureRoutes(); + } + + /** + * Configure toutes les routes de l'application + */ + private function configureRoutes(): void { + // Routes publiques + $this->post('login', ['LoginController', 'login']); + $this->post('register', ['LoginController', 'register']); + $this->post('lostpassword', ['LoginController', 'lostPassword']); + + // Route pour les logs + $this->post('log', ['LogController', 'index']); + + // Routes privées utilisateurs + $this->get('users', ['UserController', 'getUsers']); + $this->get('users/:id', ['UserController', 'getUserById']); + $this->post('users', ['UserController', 'createUser']); + $this->put('users/:id', ['UserController', 'updateUser']); + $this->delete('users/:id', ['UserController', 'deleteUser']); + $this->post('logout', ['LoginController', 'logout']); + + // Routes entités + $this->get('entites', ['EntiteController', 'getEntites']); + $this->get('entites/:id', ['EntiteController', 'getEntiteById']); + $this->get('entites/postal/:code', ['EntiteController', 'getEntiteByPostalCode']); + + // Routes villes + $this->get('villes', ['VilleController', 'searchVillesByPostalCode']); + } + + public function handle(): void { + $method = $_SERVER['REQUEST_METHOD']; + $uri = $this->normalizeUri($_SERVER['REQUEST_URI']); + + error_log("Initial URI: $uri"); + + // Handle CORS preflight + if ($method === 'OPTIONS') { + header('HTTP/1.1 200 OK'); + exit(); + } + + // Prendre le préfixe API à partir de la constante + $apiPrefix = self::API_PREFIX; + + // Vérifier si l'URI commence bien par le préfixe API + $prefixMatch = strpos($uri, $apiPrefix) === 0; + + if (!$prefixMatch) { + Response::json([ + 'error' => 'Invalid API prefix', + 'path' => $uri, + 'expected_prefix' => $apiPrefix + ], 404); + return; + } + + // Extraire l'endpoint en retirant le préfixe API + $endpoint = substr($uri, strlen($apiPrefix) + 1); // +1 pour le slash + $endpoint = trim($endpoint, '/'); + + // Check if endpoint is public + if ($this->isPublicEndpoint($endpoint)) { + error_log("Public endpoint found: $endpoint"); + $route = $this->findRoute($method, $endpoint); + if ($route) { + $this->executeRoute($route); + return; + } + } else { + error_log("Private endpoint: $endpoint"); + // Private route - check auth first + Session::requireAuth(); + + $route = $this->findRoute($method, $endpoint); + if ($route) { + $this->executeRoute($route); + return; + } + } + + // No route found + Response::json([ + 'error' => 'Route not found', + 'endpoint' => $endpoint, + 'uri' => $uri + ], 404); + } + + private function normalizeUri(string $uri): string { + return trim(preg_replace('#/+#', '/', parse_url($uri, PHP_URL_PATH)), '/'); + } + + private function isPublicEndpoint(string $endpoint): bool { + return in_array($endpoint, $this->publicEndpoints); + } + + private function executeRoute(array $route): void { + [$controllerName, $method] = $route['handler']; + + // Essayer de trouver le contrôleur en tenant compte des namespaces possibles + $classNames = [ + $controllerName, // Sans namespace + "\\App\\Controllers\\$controllerName", // Avec namespace complet + "\\$controllerName" // Avec namespace racine + ]; + + $controllerClass = null; + foreach ($classNames as $className) { + if (class_exists($className)) { + $controllerClass = $className; + break; + } + } + + if ($controllerClass === null) { + // Classe non trouvée, gérer l'erreur + Response::json([ + 'error' => 'Controller not found', + 'controller' => $controllerName, + 'status' => 'error', + 'message' => 'Controller not found', + 'tried_namespaces' => implode(', ', $classNames) + ], 404); + return; + } + + $controller = new $controllerClass(); + + if (!empty($route['params'])) { + $controller->$method(...$route['params']); + } else { + $controller->$method(); + } + } + + public function get(string $path, array $handler): void { + $this->addRoute('GET', $path, $handler); + } + + public function post(string $path, array $handler): void { + $this->addRoute('POST', $path, $handler); + } + + public function put(string $path, array $handler): void { + $this->addRoute('PUT', $path, $handler); + } + + public function delete(string $path, array $handler): void { + $this->addRoute('DELETE', $path, $handler); + } + + private function addRoute(string $method, string $path, array $handler): void { + // Normalize the path + $path = trim($path, '/'); + $this->routes[$method][$path] = $handler; + } + + private function findRoute(string $method, string $uri): ?array { + if (!isset($this->routes[$method])) { + error_log("Méthode $method non trouvée dans les routes"); + return null; + } + + $uri = trim($uri, '/'); + error_log("Recherche de route pour: méthode=$method, uri=$uri"); + error_log("Routes disponibles pour $method: " . implode(', ', array_keys($this->routes[$method]))); + + foreach ($this->routes[$method] as $route => $handler) { + $pattern = preg_replace('/{[^}]+}/', '([^/]+)', $route); + $pattern = "@^" . $pattern . "$@D"; + error_log("Test pattern: $pattern contre uri: $uri"); + + if (preg_match($pattern, $uri, $matches)) { + error_log("Route trouvée! Pattern: $pattern, Handler: {$handler[0]}::{$handler[1]}"); + array_shift($matches); + return [ + 'handler' => $handler, + 'params' => $matches + ]; + } + } + + error_log("Aucune route trouvée pour $method $uri"); + + return null; + } +} diff --git a/api/src/Core/Session.php b/api/src/Core/Session.php new file mode 100644 index 00000000..ac4f5f72 --- /dev/null +++ b/api/src/Core/Session.php @@ -0,0 +1,135 @@ + 'Non authentifié - Veuillez vous connecter'], 401); + exit; + } + } + + // Vérification optionnelle de l'activité + public static function checkActivity(): void { + $inactiveTime = 3600; // 1 heure + if ( + isset($_SESSION['last_activity']) && + (time() - $_SESSION['last_activity'] > $inactiveTime) + ) { + self::logout(); + Response::json(['error' => 'Session expirée'], 440); + exit; + } + $_SESSION['last_activity'] = time(); + } + + // Récupère le session_id du Bearer token et le définit comme session_id courant + private static function getSessionFromBearer(): void { + // Vérifier si le header Authorization est présent + $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? ''; + + // Mettre toutes les erreurs dans un fichier de log dédié + $logFile = __DIR__ . '/../../logs/session_' . date('Y-m-d') . '.log'; + file_put_contents($logFile, date('Y-m-d H:i:s') . " - Auth Header: " . $authHeader . "\n", FILE_APPEND); + + // Nettoyage du header d'autorisation + $authHeader = trim($authHeader); + + // Support de plusieurs formats possibles + if (strpos($authHeader, 'Bearer ') === 0) { + // Format standard "Bearer token" + $sessionId = substr($authHeader, 7); + } elseif (strpos(strtolower($authHeader), 'bearer ') === 0) { + // Cas insensible à la casse + $sessionId = substr($authHeader, 7); + } elseif (preg_match('/^bearer\s+(.*)$/i', $authHeader, $matches)) { + // Utilisation de l'expression régulière + $sessionId = $matches[1]; + } else { + file_put_contents($logFile, date('Y-m-d H:i:s') . " - No Bearer token found in Authorization header\n", FILE_APPEND); + return; + } + + // Nettoyage du token + $sessionId = trim($sessionId); + file_put_contents($logFile, date('Y-m-d H:i:s') . " - Session ID extracted: " . $sessionId . "\n", FILE_APPEND); + + // Vérifier que le session_id a un format valide (alphanumerique avec quelques caractères spéciaux) + // Attention: les sessions en PHP peuvent contenir des caractères non-alphanumériques + // Assouplir les règles de validation si nécessaire + if (!empty($sessionId) && strlen($sessionId) <= 128) { + // Définir l'ID de session avant de démarrer la session + session_id($sessionId); + file_put_contents($logFile, date('Y-m-d H:i:s') . " - Session ID set: " . $sessionId . "\n", FILE_APPEND); + } else { + file_put_contents($logFile, date('Y-m-d H:i:s') . " - Invalid session ID format in Bearer token\n", FILE_APPEND); + } + } +} diff --git a/api/src/Services/ApiService.php b/api/src/Services/ApiService.php new file mode 100644 index 00000000..b50c3447 --- /dev/null +++ b/api/src/Services/ApiService.php @@ -0,0 +1,300 @@ +getSmtpConfig(); + $emailConfig = $appConfig->getEmailConfig(); + + // Configuration du serveur + $mail->isSMTP(); + $mail->Host = $smtpConfig['host']; + $mail->SMTPAuth = $smtpConfig['auth']; + $mail->Username = $smtpConfig['user']; + $mail->Password = $smtpConfig['pass']; + $mail->SMTPSecure = $smtpConfig['secure']; + $mail->Port = $smtpConfig['port']; + + // Configuration de base + $mail->setFrom($emailConfig['from'], 'GEOSECTOR'); + $mail->addAddress($email, $name); + $mail->isHTML(true); + $mail->CharSet = 'UTF-8'; + + // Configuration selon le type d'email + switch ($type) { + case 'welcome': + $mail->Subject = 'Bienvenue sur GEOSECTOR'; + $mail->Body = EmailTemplates::getWelcomeTemplate($name, $data['username'] ?? '', $data['password']); + break; + + case 'lostpwd': + $mail->Subject = 'Réinitialisation de votre mot de passe GEOSECTOR'; + $mail->Body = EmailTemplates::getLostPasswordTemplate($name, $data['username'] ?? '', $data['password']); + break; + + case 'alert': + $mail->Subject = $data['subject'] ?? 'Alerte GEOSECTOR'; + $mail->Body = EmailTemplates::getAlertTemplate($data['subject'] ?? 'Alerte', $data['message'] ?? ''); + break; + + case 'receipt': + $mail->Subject = 'Reçu de passage GEOSECTOR'; + $mail->Body = EmailTemplates::getReceiptTemplate( + $name, + $data['date'] ?? date('d/m/Y'), + $data['address'] ?? '', + $data['amount'] ?? '0', + $data['paymentMethod'] ?? 'Espèces' + ); + break; + + default: + throw new Exception("Type d'email non reconnu"); + } + + $mail->send(); + LogService::log("Email '$type' envoyé avec succès", [ + 'level' => 'info', + 'email' => $email, + 'type' => $type + ]); + + return 1; + } catch (Exception $e) { + LogService::log("Échec d'envoi d'email", [ + 'level' => 'error', + 'error' => $e->getMessage(), + 'email' => $email, + 'type' => $type + ]); + + return 0; + } + } + + // Pour les données qui servent de clé de recherche (comme l'email) + public static function encryptSearchableData(string $data): string { + if (empty($data)) { + return ''; + } + + // Forcer un padding cohérent en ajoutant un caractère spécial de contrôle + $data = $data . "\x01"; // Garantit que même un bloc parfait reçoit du padding + + $keyBase64 = AppConfig::getInstance()->getEncryptionKey(); + $key = base64_decode($keyBase64); // Décoder la clé base64 en binaire + $iv = str_repeat("\0", 16); // IV fixe + + // Expliciter les options de padding + $options = 0; // PKCS7 padding par défaut + $encrypted = openssl_encrypt($data, 'AES-256-CBC', $key, $options, $iv); + + return base64_encode($encrypted); + } + + // Pour les données qui ne servent pas de clé de recherche (comme le nom) + public static function encryptData(string $data): string { + if (empty($data)) { + return ''; + } + + $keyBase64 = AppConfig::getInstance()->getEncryptionKey(); + $key = base64_decode($keyBase64); // Décoder la clé base64 en binaire + $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('AES-256-CBC')); + $encrypted = openssl_encrypt($data, 'AES-256-CBC', $key, 0, $iv); + return base64_encode($iv . $encrypted); + } + + public static function decryptSearchableData(string $encryptedData): string { + if (empty($encryptedData)) { + return ''; + } + + // Décoder la chaîne base64 + $encrypted = base64_decode($encryptedData); + + // Vérifier que le décodage base64 a fonctionné + if ($encrypted === false) { + return ''; // Échec du décodage, retourner une chaîne vide + } + + // Méthode simple et robuste utilisant le même IV fixe que pour le chiffrement + $keyBase64 = AppConfig::getInstance()->getEncryptionKey(); + $key = base64_decode($keyBase64); // Décoder la clé base64 en binaire + $iv = str_repeat("\0", 16); // IV fixe identique à celui utilisé pour le chiffrement + + // Déchiffrer avec la méthode standard + $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $key, 0, $iv); + + // Si le déchiffrement a échoué, retourner une chaîne vide + if ($decrypted === false) { + return ''; + } + + // Supprimer uniquement le caractère de contrôle ajouté + if (substr($decrypted, -1) === "\x01") { + return substr($decrypted, 0, -1); + } + + return $decrypted; // Pour la rétrocompatibilité avec les anciennes données + } + + public static function decryptData(string $encryptedData): string { + if (empty($encryptedData)) { + return ''; + } + + $keyBase64 = AppConfig::getInstance()->getEncryptionKey(); + $key = base64_decode($keyBase64); // Décoder la clé base64 en binaire + + $data = base64_decode($encryptedData); + + // Vérifier que le décodage base64 a fonctionné + if ($data === false) { + return $encryptedData; // Retourner la chaîne d'origine en cas d'échec + } + + $ivLength = openssl_cipher_iv_length('AES-256-CBC'); + + // Vérifier que les données sont assez longues pour contenir l'IV + if (strlen($data) <= $ivLength) { + return $encryptedData; // Retourner la chaîne d'origine en cas d'échec + } + + $iv = substr($data, 0, $ivLength); + $encrypted = substr($data, $ivLength); + + $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $key, 0, $iv); + + // Si le déchiffrement échoue, retourner la chaîne d'origine + return $decrypted !== false ? $decrypted : $encryptedData; + } + + /** + * Génère un nom d'utilisateur unique à partir du nom, du code postal et de la ville + * + * @param PDO $db Instance de la base de données + * @param string $name Nom de l'utilisateur + * @param string $postalCode Code postal + * @param string $cityName Nom de la ville + * @param int $minLength Longueur minimale du nom d'utilisateur (par défaut 10) + * @return string Nom d'utilisateur généré + */ + public static function generateUserName(PDO $db, string $name, string $postalCode, string $cityName, int $minLength = 10): string { + // Nettoyer et préparer les chaînes + $name = preg_replace('/[^a-zA-Z0-9]/', '', strtolower($name)); + $postalCode = preg_replace('/[^0-9]/', '', $postalCode); + $cityName = preg_replace('/[^a-zA-Z0-9]/', '', strtolower($cityName)); + + // Extraire les premières lettres du nom (2 à 5 caractères) + $nameLength = min(5, max(2, rand(2, strlen($name)))); + $namePart = substr($name, 0, $nameLength); + + // Extraire une partie du code postal (2 à 3 chiffres) + $postalLength = min(3, max(2, rand(2, strlen($postalCode)))); + $postalPart = substr($postalCode, 0, $postalLength); + + // Extraire une partie du nom de la ville (2 à 4 caractères) + $cityLength = min(4, max(2, rand(2, strlen($cityName)))); + $cityPart = substr($cityName, 0, $cityLength); + + // Combiner les parties avec un séparateur aléatoire + $separators = ['', '.', '_', '-']; + $separator1 = $separators[array_rand($separators)]; + $separator2 = $separators[array_rand($separators)]; + + // Ajouter un nombre aléatoire pour garantir l'unicité + $randomNum = rand(10, 999); + + // Construire le nom d'utilisateur + $username = $namePart . $separator1 . $postalPart . $separator2 . $cityPart . $randomNum; + + // S'assurer que la longueur minimale est respectée + while (strlen($username) < $minLength) { + $username .= rand(0, 9); + } + + // Vérifier l'unicité du nom d'utilisateur dans la base de données + $isUnique = false; + $attempts = 0; + $originalUsername = $username; + + while (!$isUnique && $attempts < 10) { + // Chiffrer le nom d'utilisateur pour la recherche + $encryptedUsername = self::encryptSearchableData($username); + + // Vérifier si le nom d'utilisateur existe déjà + $stmt = $db->prepare('SELECT COUNT(*) as count FROM users WHERE encrypted_user_name = ?'); + $stmt->execute([$encryptedUsername]); + $result = $stmt->fetch(PDO::FETCH_ASSOC); + + if ($result && $result['count'] == 0) { + $isUnique = true; + } else { + // Ajouter un nombre aléatoire supplémentaire + $username = $originalUsername . rand(100, 999); + $attempts++; + } + } + + return $username; + } + + /** + * Génère un mot de passe sécurisé aléatoire + * + * @param int $minLength Longueur minimale du mot de passe (par défaut 12) + * @param int $maxLength Longueur maximale du mot de passe (par défaut 16) + * @return string Mot de passe généré + */ + public static function generateSecurePassword(int $minLength = 12, int $maxLength = 16): string { + $lowercase = 'abcdefghijklmnopqrstuvwxyz'; + $uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + $numbers = '0123456789'; + $special = '!@#$%^&*()_+-=[]{}|;:,.<>?'; + + $length = rand($minLength, $maxLength); + $password = ''; + + // Au moins un de chaque type + $password .= $lowercase[rand(0, strlen($lowercase) - 1)]; + $password .= $uppercase[rand(0, strlen($uppercase) - 1)]; + $password .= $numbers[rand(0, strlen($numbers) - 1)]; + $password .= $special[rand(0, strlen($special) - 1)]; + + // Compléter avec des caractères aléatoires + $all = $lowercase . $uppercase . $numbers . $special; + for ($i = strlen($password); $i < $length; $i++) { + $password .= $all[rand(0, strlen($all) - 1)]; + } + + // Mélanger le mot de passe + return str_shuffle($password); + } +} diff --git a/api/src/Services/EmailTemplates.php b/api/src/Services/EmailTemplates.php new file mode 100644 index 00000000..13b1c4e4 --- /dev/null +++ b/api/src/Services/EmailTemplates.php @@ -0,0 +1,76 @@ +
+ Votre compte a été créé avec succès sur GeoSector.

+ Identifiant : $username
+ Mot de passe : $password

+ Vous pouvez vous connecter dès maintenant sur app.geosector.fr

+ À très bientôt,
+ L'équipe GeoSector"; + } + + /** + * Template d'email pour mot de passe perdu + */ + public static function getLostPasswordTemplate(string $name, string $username, string $password): string { + return " + Bonjour $name,

+ Vous avez demandé la réinitialisation de votre mot de passe sur GeoSector.

+ Nouveau mot de passe : $password

+ Vous pouvez vous connecter avec ce nouveau mot de passe sur app.geosector.fr

+ À très bientôt,
+ L'équipe GeoSector"; + } + + /** + * Template d'email pour alerte + */ + public static function getAlertTemplate(string $subject, string $message): string { + return " +

$subject

+

$message

+
+

L'équipe GeoSector

"; + } + + /** + * Template de reçu de passage + */ + public static function getReceiptTemplate(string $name, string $date, string $address, string $amount, string $paymentMethod): string { + return " +

Reçu de passage GeoSector

+

Bonjour $name,

+

Nous vous remercions pour votre contribution lors de notre passage.

+
+ + + + + + + + + + + + + + + + + +
Date :$date
Adresse :$address
Montant :$amount €
Mode de paiement :$paymentMethod
+
+

Votre soutien est précieux pour notre amicale. Nous vous en remercions chaleureusement.

+

À bientôt,

+

L'équipe GeoSector

"; + } +} diff --git a/api/src/Services/LogService.php b/api/src/Services/LogService.php new file mode 100644 index 00000000..21547220 --- /dev/null +++ b/api/src/Services/LogService.php @@ -0,0 +1,117 @@ + 'info', + 'client' => [ + 'ip' => $clientInfo['ip'], + 'browser' => $clientInfo['browser'], + 'os' => $clientInfo['os'], + 'screenResolution' => 'N/A', + 'userAgent' => $clientInfo['userAgent'] + ], + 'client_type' => $clientType + ]; + + // Si c'est une app mobile, ajouter l'identifiant de l'app + if ($clientType === 'mobile' && isset($clientInfo['appIdentifier'])) { + $defaultMetadata['app_identifier'] = $clientInfo['appIdentifier']; + } + + $metadata = array_merge_recursive($defaultMetadata, $metadata); + + $logData = [ + 'metadata' => $metadata, + 'message' => $message + ]; + + try { + // Récupérer la configuration de l'application + $appConfig = AppConfig::getInstance(); + $appName = $appConfig->getName(); + + // Récupérer l'environnement défini dans la configuration + $environment = $appConfig->getEnvironment(); + + // Définir le chemin du dossier logs à la racine du projet + $logDir = __DIR__ . '/../../logs'; + + // Créer le nom du fichier basé sur l'application et l'environnement + // Format: geosector-production-2025-03-28.log, geosector-recette-2025-03-28.log, geosector-development-2025-03-28.log + $filename = $logDir . '/' . $appName . '-' . $environment . '-' . date('Y-m-d') . '.log'; + + // Créer le dossier logs s'il n'existe pas + if (!is_dir($logDir)) { + if (!mkdir($logDir, 0777, true)) { + error_log("Impossible de créer le dossier de logs: {$logDir}"); + return; // Sortir de la fonction si on ne peut pas créer le dossier + } + // S'assurer que les permissions sont correctes + chmod($logDir, 0777); + } + + // Vérifier si le dossier est accessible en écriture + if (!is_writable($logDir)) { + error_log("Le dossier de logs n'est pas accessible en écriture: {$logDir}"); + return; // Sortir de la fonction si on ne peut pas écrire dans le dossier + } + } catch (\Exception $e) { + error_log("Erreur lors de la configuration des logs: " . $e->getMessage()); + return; // Sortir de la fonction en cas d'erreur + } + + try { + // Formater la ligne de log au format plat demandé + // timestamp;browser.name@browser.version;os.name@os.version;client_type;$metadata;$message + $timestamp = date('Y-m-d\TH:i:s'); + $browserInfo = $clientInfo['browser']['name'] . '@' . $clientInfo['browser']['version']; + $osInfo = $clientInfo['os']['name'] . '@' . $clientInfo['os']['version']; + + // Extraire le niveau de log + $level = isset($metadata['level']) ? (is_array($metadata['level']) ? 'info' : $metadata['level']) : 'info'; + + // Préparer les métadonnées supplémentaires (exclure celles déjà incluses dans le format) + $additionalMetadata = []; + foreach ($metadata as $key => $value) { + if (!in_array($key, ['browser', 'os', 'client_type', 'side', 'version', 'level', 'environment', 'client'])) { + if (is_array($value)) { + $additionalMetadata[$key] = json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + } else { + $additionalMetadata[$key] = $value; + } + } + } + + // Joindre les métadonnées supplémentaires avec des virgules + $metadataStr = !empty($additionalMetadata) ? implode(',', array_map(function($k, $v) { + return $k . '=' . $v; + }, array_keys($additionalMetadata), $additionalMetadata)) : '-'; + + // Construire la ligne de log au format demandé + $logLine = implode(';', [ + $timestamp, + $browserInfo, + $osInfo, + $clientType, + $level, + $metadataStr, + $message + ]) . "\n"; + + // Écrire dans le fichier avec gestion d'erreur + if (file_put_contents($filename, $logLine, FILE_APPEND) === false) { + error_log("Impossible d'écrire dans le fichier de logs: {$filename}"); + } + } catch (\Exception $e) { + error_log("Erreur lors de l'écriture des logs: " . $e->getMessage()); + } + } +} diff --git a/api/src/Utils/ClientDetector.php b/api/src/Utils/ClientDetector.php new file mode 100644 index 00000000..d19aabd6 --- /dev/null +++ b/api/src/Utils/ClientDetector.php @@ -0,0 +1,97 @@ + self::getClientType(), + 'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown', + 'userAgent' => $userAgent, + 'browser' => [ + 'name' => 'unknown', + 'version' => 'unknown' + ], + 'os' => [ + 'name' => 'unknown', + 'version' => 'unknown' + ] + ]; + + // Détection du navigateur + if (preg_match('/(Chrome|Safari|Firefox|Edge|MSIE|Trident)[\s\/]([0-9\.]+)/i', $userAgent, $matches)) { + $clientInfo['browser']['name'] = $matches[1]; + $clientInfo['browser']['version'] = $matches[2]; + } + + // Détection du système d'exploitation + if (preg_match('/(Android|iOS|iPhone OS|iPad|iPod|Windows NT|Mac OS X|Linux)[\s\/]([0-9\._]+)/i', $userAgent, $matches)) { + $clientInfo['os']['name'] = $matches[1]; + $clientInfo['os']['version'] = $matches[2]; + } + + // Si c'est une application mobile, ajouter l'identifiant + if ($clientInfo['type'] === 'mobile') { + $clientInfo['appIdentifier'] = self::getAppIdentifier(); + } + + return $clientInfo; + } +} diff --git a/api/vendor/autoload.php b/api/vendor/autoload.php new file mode 100644 index 00000000..8ddac8fe --- /dev/null +++ b/api/vendor/autoload.php @@ -0,0 +1,25 @@ + + * Jordi Boggiano + * + * 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 + * @author Jordi Boggiano + * @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> + */ + private $prefixLengthsPsr4 = array(); + /** + * @var array> + */ + private $prefixDirsPsr4 = array(); + /** + * @var list + */ + 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>> + */ + private $prefixesPsr0 = array(); + /** + * @var list + */ + private $fallbackDirsPsr0 = array(); + + /** @var bool */ + private $useIncludePath = false; + + /** + * @var array + */ + private $classMap = array(); + + /** @var bool */ + private $classMapAuthoritative = false; + + /** + * @var array + */ + private $missingClasses = array(); + + /** @var string|null */ + private $apcuPrefix; + + /** + * @var array + */ + private static $registeredLoaders = array(); + + /** + * @param string|null $vendorDir + */ + public function __construct($vendorDir = null) + { + $this->vendorDir = $vendorDir; + self::initializeIncludeClosure(); + } + + /** + * @return array> + */ + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); + } + + return array(); + } + + /** + * @return array> + */ + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + /** + * @return list + */ + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + /** + * @return list + */ + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + /** + * @return array Array of classname => path + */ + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param array $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 $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 $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 $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 $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 + */ + 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); + } +} diff --git a/api/vendor/composer/InstalledVersions.php b/api/vendor/composer/InstalledVersions.php new file mode 100644 index 00000000..6d29bff6 --- /dev/null +++ b/api/vendor/composer/InstalledVersions.php @@ -0,0 +1,378 @@ + + * Jordi Boggiano + * + * 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}|array{}|null + */ + private static $installed; + + /** + * @var bool + */ + private static $installedIsLocalDir; + + /** + * @var bool|null + */ + private static $canGetVendors; + + /** + * @var array[] + * @psalm-var array}> + */ + 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 + */ + 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 + */ + 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} + */ + 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}> + */ + 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} $data + */ + public static function reload($data) + { + self::$installed = $data; + self::$installedByVendor = array(); + + // when using reload, we disable the duplicate protection to ensure that self::$installed data is + // always returned, but we cannot know whether it comes from the installed.php in __DIR__ or not, + // so we have to assume it does not, and that may result in duplicate data being returned when listing + // all installed packages for example + self::$installedIsLocalDir = false; + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + $copiedLocalDir = false; + + if (self::$canGetVendors) { + $selfDir = strtr(__DIR__, '\\', '/'); + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + $vendorDir = strtr($vendorDir, '\\', '/'); + 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} $required */ + $required = require $vendorDir.'/composer/installed.php'; + self::$installedByVendor[$vendorDir] = $required; + $installed[] = $required; + if (self::$installed === null && $vendorDir.'/composer' === $selfDir) { + self::$installed = $required; + self::$installedIsLocalDir = true; + } + } + if (self::$installedIsLocalDir && $vendorDir.'/composer' === $selfDir) { + $copiedLocalDir = true; + } + } + } + + 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} $required */ + $required = require __DIR__ . '/installed.php'; + self::$installed = $required; + } else { + self::$installed = array(); + } + } + + if (self::$installed !== array() && !$copiedLocalDir) { + $installed[] = self::$installed; + } + + return $installed; + } +} diff --git a/api/vendor/composer/LICENSE b/api/vendor/composer/LICENSE new file mode 100644 index 00000000..f27399a0 --- /dev/null +++ b/api/vendor/composer/LICENSE @@ -0,0 +1,21 @@ + +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. + diff --git a/api/vendor/composer/autoload_classmap.php b/api/vendor/composer/autoload_classmap.php new file mode 100644 index 00000000..c20440c1 --- /dev/null +++ b/api/vendor/composer/autoload_classmap.php @@ -0,0 +1,17 @@ + $vendorDir . '/composer/InstalledVersions.php', + 'PHPMailer\\PHPMailer\\DSNConfigurator' => $vendorDir . '/phpmailer/phpmailer/src/DSNConfigurator.php', + 'PHPMailer\\PHPMailer\\Exception' => $vendorDir . '/phpmailer/phpmailer/src/Exception.php', + 'PHPMailer\\PHPMailer\\OAuth' => $vendorDir . '/phpmailer/phpmailer/src/OAuth.php', + 'PHPMailer\\PHPMailer\\OAuthTokenProvider' => $vendorDir . '/phpmailer/phpmailer/src/OAuthTokenProvider.php', + 'PHPMailer\\PHPMailer\\PHPMailer' => $vendorDir . '/phpmailer/phpmailer/src/PHPMailer.php', + 'PHPMailer\\PHPMailer\\POP3' => $vendorDir . '/phpmailer/phpmailer/src/POP3.php', + 'PHPMailer\\PHPMailer\\SMTP' => $vendorDir . '/phpmailer/phpmailer/src/SMTP.php', +); diff --git a/api/vendor/composer/autoload_namespaces.php b/api/vendor/composer/autoload_namespaces.php new file mode 100644 index 00000000..15a2ff3a --- /dev/null +++ b/api/vendor/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ + array($vendorDir . '/phpmailer/phpmailer/src'), + 'App\\' => array($baseDir . '/src'), +); diff --git a/api/vendor/composer/autoload_real.php b/api/vendor/composer/autoload_real.php new file mode 100644 index 00000000..d2aba9b2 --- /dev/null +++ b/api/vendor/composer/autoload_real.php @@ -0,0 +1,38 @@ +register(true); + + return $loader; + } +} diff --git a/api/vendor/composer/autoload_static.php b/api/vendor/composer/autoload_static.php new file mode 100644 index 00000000..620bbd1f --- /dev/null +++ b/api/vendor/composer/autoload_static.php @@ -0,0 +1,51 @@ + + array ( + 'PHPMailer\\PHPMailer\\' => 20, + ), + 'A' => + array ( + 'App\\' => 4, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'PHPMailer\\PHPMailer\\' => + array ( + 0 => __DIR__ . '/..' . '/phpmailer/phpmailer/src', + ), + 'App\\' => + array ( + 0 => __DIR__ . '/../..' . '/src', + ), + ); + + public static $classMap = array ( + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + 'PHPMailer\\PHPMailer\\DSNConfigurator' => __DIR__ . '/..' . '/phpmailer/phpmailer/src/DSNConfigurator.php', + 'PHPMailer\\PHPMailer\\Exception' => __DIR__ . '/..' . '/phpmailer/phpmailer/src/Exception.php', + 'PHPMailer\\PHPMailer\\OAuth' => __DIR__ . '/..' . '/phpmailer/phpmailer/src/OAuth.php', + 'PHPMailer\\PHPMailer\\OAuthTokenProvider' => __DIR__ . '/..' . '/phpmailer/phpmailer/src/OAuthTokenProvider.php', + 'PHPMailer\\PHPMailer\\PHPMailer' => __DIR__ . '/..' . '/phpmailer/phpmailer/src/PHPMailer.php', + 'PHPMailer\\PHPMailer\\POP3' => __DIR__ . '/..' . '/phpmailer/phpmailer/src/POP3.php', + 'PHPMailer\\PHPMailer\\SMTP' => __DIR__ . '/..' . '/phpmailer/phpmailer/src/SMTP.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInit03e608fa83a14a82b3f9223977e9674e::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInit03e608fa83a14a82b3f9223977e9674e::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInit03e608fa83a14a82b3f9223977e9674e::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/api/vendor/composer/installed.json b/api/vendor/composer/installed.json new file mode 100644 index 00000000..6a697b3c --- /dev/null +++ b/api/vendor/composer/installed.json @@ -0,0 +1,90 @@ +{ + "packages": [ + { + "name": "phpmailer/phpmailer", + "version": "v6.9.3", + "version_normalized": "6.9.3.0", + "source": { + "type": "git", + "url": "https://github.com/PHPMailer/PHPMailer.git", + "reference": "2f5c94fe7493efc213f643c23b1b1c249d40f47e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/2f5c94fe7493efc213f643c23b1b1c249d40f47e", + "reference": "2f5c94fe7493efc213f643c23b1b1c249d40f47e", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "ext-filter": "*", + "ext-hash": "*", + "php": ">=5.5.0" + }, + "require-dev": { + "dealerdirect/phpcodesniffer-composer-installer": "^1.0", + "doctrine/annotations": "^1.2.6 || ^1.13.3", + "php-parallel-lint/php-console-highlighter": "^1.0.0", + "php-parallel-lint/php-parallel-lint": "^1.3.2", + "phpcompatibility/php-compatibility": "^9.3.5", + "roave/security-advisories": "dev-latest", + "squizlabs/php_codesniffer": "^3.7.2", + "yoast/phpunit-polyfills": "^1.0.4" + }, + "suggest": { + "decomplexity/SendOauth2": "Adapter for using XOAUTH2 authentication", + "ext-mbstring": "Needed to send email in multibyte encoding charset or decode encoded addresses", + "ext-openssl": "Needed for secure SMTP sending and DKIM signing", + "greew/oauth2-azure-provider": "Needed for Microsoft Azure XOAUTH2 authentication", + "hayageek/oauth2-yahoo": "Needed for Yahoo XOAUTH2 authentication", + "league/oauth2-google": "Needed for Google XOAUTH2 authentication", + "psr/log": "For optional PSR-3 debug logging", + "symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)", + "thenetworg/oauth2-azure": "Needed for Microsoft XOAUTH2 authentication" + }, + "time": "2024-11-24T18:04:13+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "PHPMailer\\PHPMailer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-2.1-only" + ], + "authors": [ + { + "name": "Marcus Bointon", + "email": "phpmailer@synchromedia.co.uk" + }, + { + "name": "Jim Jagielski", + "email": "jimjag@gmail.com" + }, + { + "name": "Andy Prevost", + "email": "codeworxtech@users.sourceforge.net" + }, + { + "name": "Brent R. Matzelle" + } + ], + "description": "PHPMailer is a full-featured email creation and transfer class for PHP", + "support": { + "issues": "https://github.com/PHPMailer/PHPMailer/issues", + "source": "https://github.com/PHPMailer/PHPMailer/tree/v6.9.3" + }, + "funding": [ + { + "url": "https://github.com/Synchro", + "type": "github" + } + ], + "install-path": "../phpmailer/phpmailer" + } + ], + "dev": true, + "dev-package-names": [] +} diff --git a/api/vendor/composer/installed.php b/api/vendor/composer/installed.php new file mode 100644 index 00000000..21e851b4 --- /dev/null +++ b/api/vendor/composer/installed.php @@ -0,0 +1,32 @@ + array( + 'name' => 'your-vendor/api', + 'pretty_version' => 'dev-main', + 'version' => 'dev-main', + 'reference' => '254f026824de5b6ef6183b0885c1512d32a5d78c', + 'type' => 'project', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev' => true, + ), + 'versions' => array( + 'phpmailer/phpmailer' => array( + 'pretty_version' => 'v6.9.3', + 'version' => '6.9.3.0', + 'reference' => '2f5c94fe7493efc213f643c23b1b1c249d40f47e', + 'type' => 'library', + 'install_path' => __DIR__ . '/../phpmailer/phpmailer', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'your-vendor/api' => array( + 'pretty_version' => 'dev-main', + 'version' => 'dev-main', + 'reference' => '254f026824de5b6ef6183b0885c1512d32a5d78c', + 'type' => 'project', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev_requirement' => false, + ), + ), +); diff --git a/api/vendor/composer/platform_check.php b/api/vendor/composer/platform_check.php new file mode 100644 index 00000000..4c3a5d68 --- /dev/null +++ b/api/vendor/composer/platform_check.php @@ -0,0 +1,26 @@ += 80100)) { + $issues[] = 'Your Composer dependencies require a PHP version ">= 8.1.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 + ); +} diff --git a/api/vendor/phpmailer/phpmailer/.editorconfig b/api/vendor/phpmailer/phpmailer/.editorconfig new file mode 100644 index 00000000..a7c44ddb --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false + +[*.{yml,yaml}] +indent_size = 2 diff --git a/api/vendor/phpmailer/phpmailer/COMMITMENT b/api/vendor/phpmailer/phpmailer/COMMITMENT new file mode 100644 index 00000000..a687e0dd --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/COMMITMENT @@ -0,0 +1,46 @@ +GPL Cooperation Commitment +Version 1.0 + +Before filing or continuing to prosecute any legal proceeding or claim +(other than a Defensive Action) arising from termination of a Covered +License, we commit to extend to the person or entity ('you') accused +of violating the Covered License the following provisions regarding +cure and reinstatement, taken from GPL version 3. As used here, the +term 'this License' refers to the specific Covered License being +enforced. + + 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. + +We intend this Commitment to be irrevocable, and binding and +enforceable against us and assignees of or successors to our +copyrights. + +Definitions + +'Covered License' means the GNU General Public License, version 2 +(GPLv2), the GNU Lesser General Public License, version 2.1 +(LGPLv2.1), or the GNU Library General Public License, version 2 +(LGPLv2), all as published by the Free Software Foundation. + +'Defensive Action' means a legal proceeding or claim that We bring +against you in response to a prior proceeding or claim initiated by +you or your affiliate. + +'We' means each contributor to this repository as of the date of +inclusion of this file, including subsidiaries of a corporate +contributor. + +This work is available under a Creative Commons Attribution-ShareAlike +4.0 International license (https://creativecommons.org/licenses/by-sa/4.0/). diff --git a/api/vendor/phpmailer/phpmailer/LICENSE b/api/vendor/phpmailer/phpmailer/LICENSE new file mode 100644 index 00000000..f166cc57 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/LICENSE @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +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 this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. 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 not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the 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 +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "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 +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY 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 +LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library 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 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! \ No newline at end of file diff --git a/api/vendor/phpmailer/phpmailer/README.md b/api/vendor/phpmailer/phpmailer/README.md new file mode 100644 index 00000000..07fe8c8a --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/README.md @@ -0,0 +1,231 @@ +[![SWUbanner](https://raw.githubusercontent.com/vshymanskyy/StandWithUkraine/main/banner2-direct.svg)](https://supportukrainenow.org/) + +![PHPMailer](https://raw.github.com/PHPMailer/PHPMailer/master/examples/images/phpmailer.png) + +# PHPMailer – A full-featured email creation and transfer class for PHP + +[![Test status](https://github.com/PHPMailer/PHPMailer/workflows/Tests/badge.svg)](https://github.com/PHPMailer/PHPMailer/actions) +[![codecov.io](https://codecov.io/gh/PHPMailer/PHPMailer/branch/master/graph/badge.svg?token=iORZpwmYmM)](https://codecov.io/gh/PHPMailer/PHPMailer) +[![Latest Stable Version](https://poser.pugx.org/phpmailer/phpmailer/v/stable.svg)](https://packagist.org/packages/phpmailer/phpmailer) +[![Total Downloads](https://poser.pugx.org/phpmailer/phpmailer/downloads)](https://packagist.org/packages/phpmailer/phpmailer) +[![License](https://poser.pugx.org/phpmailer/phpmailer/license.svg)](https://packagist.org/packages/phpmailer/phpmailer) +[![API Docs](https://github.com/phpmailer/phpmailer/workflows/Docs/badge.svg)](https://phpmailer.github.io/PHPMailer/) +[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/PHPMailer/PHPMailer/badge)](https://api.securityscorecards.dev/projects/github.com/PHPMailer/PHPMailer) + +## Features +- Probably the world's most popular code for sending email from PHP! +- Used by many open-source projects: WordPress, Drupal, 1CRM, SugarCRM, Yii, Joomla! and many more +- Integrated SMTP support – send without a local mail server +- Send emails with multiple To, CC, BCC, and Reply-to addresses +- Multipart/alternative emails for mail clients that do not read HTML email +- Add attachments, including inline +- Support for UTF-8 content and 8bit, base64, binary, and quoted-printable encodings +- SMTP authentication with LOGIN, PLAIN, CRAM-MD5, and XOAUTH2 mechanisms over SMTPS and SMTP+STARTTLS transports +- Validates email addresses automatically +- Protects against header injection attacks +- Error messages in over 50 languages! +- DKIM and S/MIME signing support +- Compatible with PHP 5.5 and later, including PHP 8.2 +- Namespaced to prevent name clashes +- Much more! + +## Why you might need it +Many PHP developers need to send email from their code. The only PHP function that supports this directly is [`mail()`](https://www.php.net/manual/en/function.mail.php). However, it does not provide any assistance for making use of popular features such as encryption, authentication, HTML messages, and attachments. + +Formatting email correctly is surprisingly difficult. There are myriad overlapping (and conflicting) standards, requiring tight adherence to horribly complicated formatting and encoding rules – the vast majority of code that you'll find online that uses the `mail()` function directly is just plain wrong, if not unsafe! + +The PHP `mail()` function usually sends via a local mail server, typically fronted by a `sendmail` binary on Linux, BSD, and macOS platforms, however, Windows usually doesn't include a local mail server; PHPMailer's integrated SMTP client allows email sending on all platforms without needing a local mail server. Be aware though, that the `mail()` function should be avoided when possible; it's both faster and [safer](https://exploitbox.io/paper/Pwning-PHP-Mail-Function-For-Fun-And-RCE.html) to use SMTP to localhost. + +*Please* don't be tempted to do it yourself – if you don't use PHPMailer, there are many other excellent libraries that +you should look at before rolling your own. Try [SwiftMailer](https://swiftmailer.symfony.com/) +, [Laminas/Mail](https://docs.laminas.dev/laminas-mail/), [ZetaComponents](https://github.com/zetacomponents/Mail), etc. + +## License +This software is distributed under the [LGPL 2.1](https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html) license, along with the [GPL Cooperation Commitment](https://gplcc.github.io/gplcc/). Please read [LICENSE](https://github.com/PHPMailer/PHPMailer/blob/master/LICENSE) for information on the software availability and distribution. + +## Installation & loading +PHPMailer is available on [Packagist](https://packagist.org/packages/phpmailer/phpmailer) (using semantic versioning), and installation via [Composer](https://getcomposer.org) is the recommended way to install PHPMailer. Just add this line to your `composer.json` file: + +```json +"phpmailer/phpmailer": "^6.9.2" +``` + +or run + +```sh +composer require phpmailer/phpmailer +``` + +Note that the `vendor` folder and the `vendor/autoload.php` script are generated by Composer; they are not part of PHPMailer. + +If you want to use XOAUTH2 authentication, you will also need to add a dependency on the `league/oauth2-client` and appropriate service adapters package in your `composer.json`, or take a look at +by @decomplexity's [SendOauth2 wrapper](https://github.com/decomplexity/SendOauth2), especially if you're using Microsoft services. + +Alternatively, if you're not using Composer, you +can [download PHPMailer as a zip file](https://github.com/PHPMailer/PHPMailer/archive/master.zip), (note that docs and examples are not included in the zip file), then copy the contents of the PHPMailer folder into one of the `include_path` directories specified in your PHP configuration and load each class file manually: + +```php +SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output + $mail->isSMTP(); //Send using SMTP + $mail->Host = 'smtp.example.com'; //Set the SMTP server to send through + $mail->SMTPAuth = true; //Enable SMTP authentication + $mail->Username = 'user@example.com'; //SMTP username + $mail->Password = 'secret'; //SMTP password + $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption + $mail->Port = 465; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS` + + //Recipients + $mail->setFrom('from@example.com', 'Mailer'); + $mail->addAddress('joe@example.net', 'Joe User'); //Add a recipient + $mail->addAddress('ellen@example.com'); //Name is optional + $mail->addReplyTo('info@example.com', 'Information'); + $mail->addCC('cc@example.com'); + $mail->addBCC('bcc@example.com'); + + //Attachments + $mail->addAttachment('/var/tmp/file.tar.gz'); //Add attachments + $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //Optional name + + //Content + $mail->isHTML(true); //Set email format to HTML + $mail->Subject = 'Here is the subject'; + $mail->Body = 'This is the HTML message body in bold!'; + $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; + + $mail->send(); + echo 'Message has been sent'; +} catch (Exception $e) { + echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; +} +``` + +You'll find plenty to play with in the [examples](https://github.com/PHPMailer/PHPMailer/tree/master/examples) folder, which covers many common scenarios including sending through Gmail, building contact forms, sending to mailing lists, and more. + +If you are re-using the instance (e.g. when sending to a mailing list), you may need to clear the recipient list to avoid sending duplicate messages. See [the mailing list example](https://github.com/PHPMailer/PHPMailer/blob/master/examples/mailing_list.phps) for further guidance. + +That's it. You should now be ready to use PHPMailer! + +## Localization +PHPMailer defaults to English, but in the [language](https://github.com/PHPMailer/PHPMailer/tree/master/language/) folder, you'll find many translations for PHPMailer error messages that you may encounter. Their filenames contain [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1) language code for the translations, for example `fr` for French. To specify a language, you need to tell PHPMailer which one to use, like this: + +```php +//To load the French version +$mail->setLanguage('fr', '/optional/path/to/language/directory/'); +``` + +We welcome corrections and new languages – if you're looking for corrections, run the [Language/TranslationCompletenessTest.php](https://github.com/PHPMailer/PHPMailer/blob/master/test/Language/TranslationCompletenessTest.php) script in the tests folder and it will show any missing translations. + +## Documentation +Start reading at the [GitHub wiki](https://github.com/PHPMailer/PHPMailer/wiki). If you're having trouble, head for [the troubleshooting guide](https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting) as it's frequently updated. + +Examples of how to use PHPMailer for common scenarios can be found in the [examples](https://github.com/PHPMailer/PHPMailer/tree/master/examples) folder. If you're looking for a good starting point, we recommend you start with [the Gmail example](https://github.com/PHPMailer/PHPMailer/tree/master/examples/gmail.phps). + +To reduce PHPMailer's deployed code footprint, examples are not included if you load PHPMailer via Composer or via [GitHub's zip file download](https://github.com/PHPMailer/PHPMailer/archive/master.zip), so you'll need to either clone the git repository or use the above links to get to the examples directly. + +Complete generated API documentation is [available online](https://phpmailer.github.io/PHPMailer/). + +You can generate complete API-level documentation by running `phpdoc` in the top-level folder, and documentation will appear in the `docs` folder, though you'll need to have [PHPDocumentor](https://www.phpdoc.org) installed. You may find [the unit tests](https://github.com/PHPMailer/PHPMailer/blob/master/test/PHPMailer/PHPMailerTest.php) a good reference for how to do various operations such as encryption. + +If the documentation doesn't cover what you need, search the [many questions on Stack Overflow](https://stackoverflow.com/questions/tagged/phpmailer), and before you ask a question about "SMTP Error: Could not connect to SMTP host.", [read the troubleshooting guide](https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting). + +## Tests +[PHPMailer tests](https://github.com/PHPMailer/PHPMailer/tree/master/test/) use PHPUnit 9, with [a polyfill](https://github.com/Yoast/PHPUnit-Polyfills) to let 9-style tests run on older PHPUnit and PHP versions. + +[![Test status](https://github.com/PHPMailer/PHPMailer/workflows/Tests/badge.svg)](https://github.com/PHPMailer/PHPMailer/actions) + +If this isn't passing, is there something you can do to help? + +## Security +Please disclose any vulnerabilities found responsibly – report security issues to the maintainers privately. + +See [SECURITY](https://github.com/PHPMailer/PHPMailer/tree/master/SECURITY.md) and [PHPMailer's security advisories on GitHub](https://github.com/PHPMailer/PHPMailer/security). + +## Contributing +Please submit bug reports, suggestions, and pull requests to the [GitHub issue tracker](https://github.com/PHPMailer/PHPMailer/issues). + +We're particularly interested in fixing edge cases, expanding test coverage, and updating translations. + +If you found a mistake in the docs, or want to add something, go ahead and amend the wiki – anyone can edit it. + +If you have git clones from prior to the move to the PHPMailer GitHub organisation, you'll need to update any remote URLs referencing the old GitHub location with a command like this from within your clone: + +```sh +git remote set-url upstream https://github.com/PHPMailer/PHPMailer.git +``` + +Please *don't* use the SourceForge or Google Code projects any more; they are obsolete and no longer maintained. + +## Sponsorship +Development time and resources for PHPMailer are provided by [Smartmessages.net](https://info.smartmessages.net/), the world's only privacy-first email marketing system. + +Smartmessages.net privacy-first email marketing logo + +Donations are very welcome, whether in beer 🍺, T-shirts 👕, or cold, hard cash 💰. Sponsorship through GitHub is a simple and convenient way to say "thank you" to PHPMailer's maintainers and contributors – just click the "Sponsor" button [on the project page](https://github.com/PHPMailer/PHPMailer). If your company uses PHPMailer, consider taking part in Tidelift's enterprise support programme. + +## PHPMailer For Enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of PHPMailer and thousands of other packages are working with Tidelift to deliver commercial +support and maintenance for the open-source packages you use to build your applications. Save time, reduce risk, and +improve code health, while paying the maintainers of the exact packages you +use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-phpmailer-phpmailer?utm_source=packagist-phpmailer-phpmailer&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +## Changelog +See [changelog](changelog.md). + +## History +- PHPMailer was originally written in 2001 by Brent R. Matzelle as a [SourceForge project](https://sourceforge.net/projects/phpmailer/). +- [Marcus Bointon](https://github.com/Synchro) (`coolbru` on SF) and Andy Prevost (`codeworxtech`) took over the project in 2004. +- Became an Apache incubator project on Google Code in 2010, managed by Jim Jagielski. +- Marcus created [his fork on GitHub](https://github.com/Synchro/PHPMailer) in 2008. +- Jim and Marcus decide to join forces and use GitHub as the canonical and official repo for PHPMailer in 2013. +- PHPMailer moves to [the PHPMailer organisation](https://github.com/PHPMailer) on GitHub in 2013. + +### What's changed since moving from SourceForge? +- Official successor to the SourceForge and Google Code projects. +- Test suite. +- Continuous integration with GitHub Actions. +- Composer support. +- Public development. +- Additional languages and language strings. +- CRAM-MD5 authentication support. +- Preserves full repo history of authors, commits, and branches from the original SourceForge project. diff --git a/api/vendor/phpmailer/phpmailer/SECURITY.md b/api/vendor/phpmailer/phpmailer/SECURITY.md new file mode 100644 index 00000000..4f34026d --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/SECURITY.md @@ -0,0 +1,37 @@ +# Security notices relating to PHPMailer + +Please disclose any security issues or vulnerabilities found through [Tidelift's coordinated disclosure system](https://tidelift.com/security) or to the maintainers privately. + +PHPMailer 6.4.1 and earlier contain a vulnerability that can result in untrusted code being called (if such code is injected into the host project's scope by other means). If the `$patternselect` parameter to `validateAddress()` is set to `'php'` (the default, defined by `PHPMailer::$validator`), and the global namespace contains a function called `php`, it will be called in preference to the built-in validator of the same name. Mitigated in PHPMailer 6.5.0 by denying the use of simple strings as validator function names. Recorded as [CVE-2021-3603](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2021-3603). Reported by [Vikrant Singh Chauhan](mailto:vi@hackberry.xyz) via [huntr.dev](https://www.huntr.dev/). + +PHPMailer versions 6.4.1 and earlier contain a possible remote code execution vulnerability through the `$lang_path` parameter of the `setLanguage()` method. If the `$lang_path` parameter is passed unfiltered from user input, it can be set to [a UNC path](https://docs.microsoft.com/en-us/dotnet/standard/io/file-path-formats#unc-paths), and if an attacker is also able to persuade the server to load a file from that UNC path, a script file under their control may be executed. This vulnerability only applies to systems that resolve UNC paths, typically only Microsoft Windows. +PHPMailer 6.5.0 mitigates this by no longer treating translation files as PHP code, but by parsing their text content directly. This approach avoids the possibility of executing unknown code while retaining backward compatibility. This isn't ideal, so the current translation format is deprecated and will be replaced in the next major release. Recorded as [CVE-2021-34551](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2021-34551). Reported by [Jilin Diting Information Technology Co., Ltd](https://listensec.com) via Tidelift. + +PHPMailer versions between 6.1.8 and 6.4.0 contain a regression of the earlier CVE-2018-19296 object injection vulnerability as a result of [a fix for Windows UNC paths in 6.1.8](https://github.com/PHPMailer/PHPMailer/commit/e2e07a355ee8ff36aba21d0242c5950c56e4c6f9). Recorded as [CVE-2020-36326](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2020-36326). Reported by Fariskhi Vidyan via Tidelift. 6.4.1 fixes this issue, and also enforces stricter checks for URL schemes in local path contexts. + +PHPMailer versions 6.1.5 and earlier contain an output escaping bug that occurs in `Content-Type` and `Content-Disposition` when filenames passed into `addAttachment` and other methods that accept attachment names contain double quote characters, in contravention of RFC822 3.4.1. No specific vulnerability has been found relating to this, but it could allow file attachments to bypass attachment filters that are based on matching filename extensions. Recorded as [CVE-2020-13625](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2020-13625). Reported by Elar Lang of Clarified Security. + +PHPMailer versions prior to 6.0.6 and 5.2.27 are vulnerable to an object injection attack by passing `phar://` paths into `addAttachment()` and other functions that may receive unfiltered local paths, possibly leading to RCE. Recorded as [CVE-2018-19296](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2018-19296). See [this article](https://knasmueller.net/5-answers-about-php-phar-exploitation) for more info on this type of vulnerability. Mitigated by blocking the use of paths containing URL-protocol style prefixes such as `phar://`. Reported by Sehun Oh of cyberone.kr. + +PHPMailer versions prior to 5.2.24 (released July 26th 2017) have an XSS vulnerability in one of the code examples, [CVE-2017-11503](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2017-11503). The `code_generator.phps` example did not filter user input prior to output. This file is distributed with a `.phps` extension, so it is not normally executable unless it is explicitly renamed, and the file is not included when PHPMailer is loaded through composer, so it is safe by default. There was also an undisclosed potential XSS vulnerability in the default exception handler (unused by default). Patches for both issues kindly provided by Patrick Monnerat of the Fedora Project. + +PHPMailer versions prior to 5.2.22 (released January 9th 2017) have a local file disclosure vulnerability, [CVE-2017-5223](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2017-5223). If content passed into `msgHTML()` is sourced from unfiltered user input, relative paths can map to absolute local file paths and added as attachments. Also note that `addAttachment` (just like `file_get_contents`, `passthru`, `unlink`, etc) should not be passed user-sourced params either! Reported by Yongxiang Li of Asiasecurity. + +PHPMailer versions prior to 5.2.20 (released December 28th 2016) are vulnerable to [CVE-2016-10045](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2016-10045) a remote code execution vulnerability, responsibly reported by [Dawid Golunski](https://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10045-Vuln-Patch-Bypass.html), and patched by Paul Buonopane (@Zenexer). + +PHPMailer versions prior to 5.2.18 (released December 2016) are vulnerable to [CVE-2016-10033](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2016-10033) a remote code execution vulnerability, responsibly reported by [Dawid Golunski](https://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10033-Vuln.html). + +PHPMailer versions prior to 5.2.14 (released November 2015) are vulnerable to [CVE-2015-8476](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2015-8476) an SMTP CRLF injection bug permitting arbitrary message sending. + +PHPMailer versions prior to 5.2.10 (released May 2015) are vulnerable to [CVE-2008-5619](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2008-5619), a remote code execution vulnerability in the bundled html2text library. This file was removed in 5.2.10, so if you are using a version prior to that and make use of the html2text function, it's vitally important that you upgrade and remove this file. + +PHPMailer versions prior to 2.0.7 and 2.2.1 are vulnerable to [CVE-2012-0796](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2012-0796), an email header injection attack. + +Joomla 1.6.0 uses PHPMailer in an unsafe way, allowing it to reveal local file paths, reported in [CVE-2011-3747](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2011-3747). + +PHPMailer didn't sanitise the `$lang_path` parameter in `SetLanguage`. This wasn't a problem in itself, but some apps (PHPClassifieds, ATutor) also failed to sanitise user-provided parameters passed to it, permitting semi-arbitrary local file inclusion, reported in [CVE-2010-4914](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2010-4914), [CVE-2007-2021](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2007-2021) and [CVE-2006-5734](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2006-5734). + +PHPMailer 1.7.2 and earlier contained a possible DDoS vulnerability reported in [CVE-2005-1807](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-1807). + +PHPMailer 1.7 and earlier (June 2003) have a possible vulnerability in the `SendmailSend` method where shell commands may not be sanitised. Reported in [CVE-2007-3215](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2007-3215). + diff --git a/api/vendor/phpmailer/phpmailer/VERSION b/api/vendor/phpmailer/phpmailer/VERSION new file mode 100644 index 00000000..5f54f91e --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/VERSION @@ -0,0 +1 @@ +6.9.3 diff --git a/api/vendor/phpmailer/phpmailer/composer.json b/api/vendor/phpmailer/phpmailer/composer.json new file mode 100644 index 00000000..7b008b7c --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/composer.json @@ -0,0 +1,80 @@ +{ + "name": "phpmailer/phpmailer", + "type": "library", + "description": "PHPMailer is a full-featured email creation and transfer class for PHP", + "authors": [ + { + "name": "Marcus Bointon", + "email": "phpmailer@synchromedia.co.uk" + }, + { + "name": "Jim Jagielski", + "email": "jimjag@gmail.com" + }, + { + "name": "Andy Prevost", + "email": "codeworxtech@users.sourceforge.net" + }, + { + "name": "Brent R. Matzelle" + } + ], + "funding": [ + { + "url": "https://github.com/Synchro", + "type": "github" + } + ], + "config": { + "allow-plugins": { + "dealerdirect/phpcodesniffer-composer-installer": true + }, + "lock": false + }, + "require": { + "php": ">=5.5.0", + "ext-ctype": "*", + "ext-filter": "*", + "ext-hash": "*" + }, + "require-dev": { + "dealerdirect/phpcodesniffer-composer-installer": "^1.0", + "doctrine/annotations": "^1.2.6 || ^1.13.3", + "php-parallel-lint/php-console-highlighter": "^1.0.0", + "php-parallel-lint/php-parallel-lint": "^1.3.2", + "phpcompatibility/php-compatibility": "^9.3.5", + "roave/security-advisories": "dev-latest", + "squizlabs/php_codesniffer": "^3.7.2", + "yoast/phpunit-polyfills": "^1.0.4" + }, + "suggest": { + "decomplexity/SendOauth2": "Adapter for using XOAUTH2 authentication", + "ext-mbstring": "Needed to send email in multibyte encoding charset or decode encoded addresses", + "ext-openssl": "Needed for secure SMTP sending and DKIM signing", + "greew/oauth2-azure-provider": "Needed for Microsoft Azure XOAUTH2 authentication", + "hayageek/oauth2-yahoo": "Needed for Yahoo XOAUTH2 authentication", + "league/oauth2-google": "Needed for Google XOAUTH2 authentication", + "psr/log": "For optional PSR-3 debug logging", + "thenetworg/oauth2-azure": "Needed for Microsoft XOAUTH2 authentication", + "symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)" + }, + "autoload": { + "psr-4": { + "PHPMailer\\PHPMailer\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "PHPMailer\\Test\\": "test/" + } + }, + "license": "LGPL-2.1-only", + "scripts": { + "check": "./vendor/bin/phpcs", + "test": "./vendor/bin/phpunit --no-coverage", + "coverage": "./vendor/bin/phpunit", + "lint": [ + "@php ./vendor/php-parallel-lint/php-parallel-lint/parallel-lint . --show-deprecated -e php,phps --exclude vendor --exclude .git --exclude build" + ] + } +} diff --git a/api/vendor/phpmailer/phpmailer/get_oauth_token.php b/api/vendor/phpmailer/phpmailer/get_oauth_token.php new file mode 100644 index 00000000..0e54a00b --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/get_oauth_token.php @@ -0,0 +1,182 @@ + + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2020 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +/** + * Get an OAuth2 token from an OAuth2 provider. + * * Install this script on your server so that it's accessible + * as [https/http]:////get_oauth_token.php + * e.g.: http://localhost/phpmailer/get_oauth_token.php + * * Ensure dependencies are installed with 'composer install' + * * Set up an app in your Google/Yahoo/Microsoft account + * * Set the script address as the app's redirect URL + * If no refresh token is obtained when running this file, + * revoke access to your app and run the script again. + */ + +namespace PHPMailer\PHPMailer; + +/** + * Aliases for League Provider Classes + * Make sure you have added these to your composer.json and run `composer install` + * Plenty to choose from here: + * @see https://oauth2-client.thephpleague.com/providers/thirdparty/ + */ +//@see https://github.com/thephpleague/oauth2-google +use League\OAuth2\Client\Provider\Google; +//@see https://packagist.org/packages/hayageek/oauth2-yahoo +use Hayageek\OAuth2\Client\Provider\Yahoo; +//@see https://github.com/stevenmaguire/oauth2-microsoft +use Stevenmaguire\OAuth2\Client\Provider\Microsoft; +//@see https://github.com/greew/oauth2-azure-provider +use Greew\OAuth2\Client\Provider\Azure; + +if (!isset($_GET['code']) && !isset($_POST['provider'])) { + ?> + + +
+

Select Provider

+ +
+ +
+ +
+ +
+

Enter id and secret

+

These details are obtained by setting up an app in your provider's developer console. +

+

ClientId:

+

ClientSecret:

+

TenantID (only relevant for Azure):

+ +
+ + + $clientId, + 'clientSecret' => $clientSecret, + 'redirectUri' => $redirectUri, + 'accessType' => 'offline' +]; + +$options = []; +$provider = null; + +switch ($providerName) { + case 'Google': + $provider = new Google($params); + $options = [ + 'scope' => [ + 'https://mail.google.com/' + ] + ]; + break; + case 'Yahoo': + $provider = new Yahoo($params); + break; + case 'Microsoft': + $provider = new Microsoft($params); + $options = [ + 'scope' => [ + 'wl.imap', + 'wl.offline_access' + ] + ]; + break; + case 'Azure': + $params['tenantId'] = $tenantId; + + $provider = new Azure($params); + $options = [ + 'scope' => [ + 'https://outlook.office.com/SMTP.Send', + 'offline_access' + ] + ]; + break; +} + +if (null === $provider) { + exit('Provider missing'); +} + +if (!isset($_GET['code'])) { + //If we don't have an authorization code then get one + $authUrl = $provider->getAuthorizationUrl($options); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: ' . $authUrl); + exit; + //Check given state against previously stored one to mitigate CSRF attack +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + unset($_SESSION['oauth2state']); + unset($_SESSION['provider']); + exit('Invalid state'); +} else { + unset($_SESSION['provider']); + //Try to get an access token (using the authorization code grant) + $token = $provider->getAccessToken( + 'authorization_code', + [ + 'code' => $_GET['code'] + ] + ); + //Use this to interact with an API on the users behalf + //Use this to get a new access token if the old one expires + echo 'Refresh Token: ', htmlspecialchars($token->getRefreshToken()); +} diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-af.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-af.php new file mode 100644 index 00000000..0b2a72d5 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-af.php @@ -0,0 +1,26 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'خطأ SMTP : لا يمكن تأكيد الهوية.'; +$PHPMAILER_LANG['connect_host'] = 'خطأ SMTP: لا يمكن الاتصال بالخادم SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'خطأ SMTP: لم يتم قبول المعلومات .'; +$PHPMAILER_LANG['empty_message'] = 'نص الرسالة فارغ'; +$PHPMAILER_LANG['encoding'] = 'ترميز غير معروف: '; +$PHPMAILER_LANG['execute'] = 'لا يمكن تنفيذ : '; +$PHPMAILER_LANG['file_access'] = 'لا يمكن الوصول للملف: '; +$PHPMAILER_LANG['file_open'] = 'خطأ في الملف: لا يمكن فتحه: '; +$PHPMAILER_LANG['from_failed'] = 'خطأ على مستوى عنوان المرسل : '; +$PHPMAILER_LANG['instantiate'] = 'لا يمكن توفير خدمة البريد.'; +$PHPMAILER_LANG['invalid_address'] = 'الإرسال غير ممكن لأن عنوان البريد الإلكتروني غير صالح: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' برنامج الإرسال غير مدعوم.'; +$PHPMAILER_LANG['provide_address'] = 'يجب توفير عنوان البريد الإلكتروني لمستلم واحد على الأقل.'; +$PHPMAILER_LANG['recipients_failed'] = 'خطأ SMTP: الأخطاء التالية فشل في الارسال لكل من : '; +$PHPMAILER_LANG['signing'] = 'خطأ في التوقيع: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() غير ممكن.'; +$PHPMAILER_LANG['smtp_error'] = 'خطأ على مستوى الخادم SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'لا يمكن تعيين أو إعادة تعيين متغير: '; +$PHPMAILER_LANG['extension_missing'] = 'الإضافة غير موجودة: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-as.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-as.php new file mode 100644 index 00000000..327dfbaf --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-as.php @@ -0,0 +1,35 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP ত্ৰুটি: প্ৰমাণীকৰণ কৰিব নোৱাৰি'; +$PHPMAILER_LANG['buggy_php'] = 'আপোনাৰ PHP সংস্কৰণ এটা বাগৰ দ্বাৰা প্ৰভাৱিত হয় যাৰ ফলত নষ্ট বাৰ্তা হব পাৰে । ইয়াক সমাধান কৰিবলে, প্ৰেৰণ কৰিবলে SMTP ব্যৱহাৰ কৰক, আপোনাৰ php.ini ত mail.add_x_header বিকল্প নিষ্ক্ৰিয় কৰক, MacOS বা Linux লৈ সলনি কৰক, বা আপোনাৰ PHP সংস্কৰণ 7.0.17+ বা 7.1.3+ লৈ সলনি কৰক ।'; +$PHPMAILER_LANG['connect_host'] = 'SMTP ত্ৰুটি: SMTP চাৰ্ভাৰৰ সৈতে সংযোগ কৰিবলে অক্ষম'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP ত্ৰুটি: তথ্য গ্ৰহণ কৰা হোৱা নাই'; +$PHPMAILER_LANG['empty_message'] = 'বাৰ্তাৰ মূখ্য অংশ খালী।'; +$PHPMAILER_LANG['encoding'] = 'অজ্ঞাত এনকোডিং: '; +$PHPMAILER_LANG['execute'] = 'এক্সিকিউট কৰিব নোৱাৰি: '; +$PHPMAILER_LANG['extension_missing'] = 'সম্প্ৰসাৰণ নোহোৱা হৈছে: '; +$PHPMAILER_LANG['file_access'] = 'ফাইল অভিগম কৰিবলে অক্ষম: '; +$PHPMAILER_LANG['file_open'] = 'ফাইল ত্ৰুটি: ফাইল খোলিবলৈ অক্ষম: '; +$PHPMAILER_LANG['from_failed'] = 'নিম্নলিখিত প্ৰেৰকৰ ঠিকনা(সমূহ) ব্যৰ্থ: '; +$PHPMAILER_LANG['instantiate'] = 'মেইল ফাংচনৰ এটা উদাহৰণ সৃষ্টি কৰিবলে অক্ষম'; +$PHPMAILER_LANG['invalid_address'] = 'প্ৰেৰণ কৰিব নোৱাৰি: অবৈধ ইমেইল ঠিকনা: '; +$PHPMAILER_LANG['invalid_header'] = 'অবৈধ হেডাৰৰ নাম বা মান'; +$PHPMAILER_LANG['invalid_hostentry'] = 'অবৈধ হোষ্টেন্ট্ৰি: '; +$PHPMAILER_LANG['invalid_host'] = 'অবৈধ হস্ট:'; +$PHPMAILER_LANG['mailer_not_supported'] = 'মেইলাৰ সমৰ্থিত নহয়।'; +$PHPMAILER_LANG['provide_address'] = 'আপুনি অন্ততঃ এটা গন্তব্য ইমেইল ঠিকনা দিব লাগিব'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP ত্ৰুটি: নিম্নলিখিত গন্তব্যস্থানসমূহ ব্যৰ্থ: '; +$PHPMAILER_LANG['signing'] = 'স্বাক্ষৰ কৰাত ব্যৰ্থ: '; +$PHPMAILER_LANG['smtp_code'] = 'SMTP কড: '; +$PHPMAILER_LANG['smtp_code_ex'] = 'অতিৰিক্ত SMTP তথ্য: '; +$PHPMAILER_LANG['smtp_detail'] = 'বিৱৰণ:'; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP সংযোগ() ব্যৰ্থ'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP চাৰ্ভাৰৰ ত্ৰুটি: '; +$PHPMAILER_LANG['variable_set'] = 'চলক নিৰ্ধাৰণ কৰিব পৰা নগল: '; +$PHPMAILER_LANG['extension_missing'] = 'অনুপস্থিত সম্প্ৰসাৰণ: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-az.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-az.php new file mode 100644 index 00000000..552167ef --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-az.php @@ -0,0 +1,27 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP Greška: Neuspjela prijava.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Greška: Nije moguće spojiti se sa SMTP serverom.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP Greška: Podatci nisu prihvaćeni.'; +$PHPMAILER_LANG['empty_message'] = 'Sadržaj poruke je prazan.'; +$PHPMAILER_LANG['encoding'] = 'Nepoznata kriptografija: '; +$PHPMAILER_LANG['execute'] = 'Nije moguće izvršiti naredbu: '; +$PHPMAILER_LANG['file_access'] = 'Nije moguće pristupiti datoteci: '; +$PHPMAILER_LANG['file_open'] = 'Nije moguće otvoriti datoteku: '; +$PHPMAILER_LANG['from_failed'] = 'SMTP Greška: Slanje sa navedenih e-mail adresa nije uspjelo: '; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Greška: Slanje na navedene e-mail adrese nije uspjelo: '; +$PHPMAILER_LANG['instantiate'] = 'Ne mogu pokrenuti mail funkcionalnost.'; +$PHPMAILER_LANG['invalid_address'] = 'E-mail nije poslan. Neispravna e-mail adresa: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer nije podržan.'; +$PHPMAILER_LANG['provide_address'] = 'Definišite barem jednu adresu primaoca.'; +$PHPMAILER_LANG['signing'] = 'Greška prilikom prijave: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Spajanje na SMTP server nije uspjelo.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP greška: '; +$PHPMAILER_LANG['variable_set'] = 'Nije moguće postaviti varijablu ili je vratiti nazad: '; +$PHPMAILER_LANG['extension_missing'] = 'Nedostaje ekstenzija: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-be.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-be.php new file mode 100644 index 00000000..9e92ddaa --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-be.php @@ -0,0 +1,27 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'Памылка SMTP: памылка ідэнтыфікацыі.'; +$PHPMAILER_LANG['connect_host'] = 'Памылка SMTP: нельга ўстанавіць сувязь з SMTP-серверам.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Памылка SMTP: звесткі непрынятыя.'; +$PHPMAILER_LANG['empty_message'] = 'Пустое паведамленне.'; +$PHPMAILER_LANG['encoding'] = 'Невядомая кадыроўка тэксту: '; +$PHPMAILER_LANG['execute'] = 'Нельга выканаць каманду: '; +$PHPMAILER_LANG['file_access'] = 'Няма доступу да файла: '; +$PHPMAILER_LANG['file_open'] = 'Нельга адкрыць файл: '; +$PHPMAILER_LANG['from_failed'] = 'Няправільны адрас адпраўніка: '; +$PHPMAILER_LANG['instantiate'] = 'Нельга прымяніць функцыю mail().'; +$PHPMAILER_LANG['invalid_address'] = 'Нельга даслаць паведамленне, няправільны email атрымальніка: '; +$PHPMAILER_LANG['provide_address'] = 'Запоўніце, калі ласка, правільны email атрымальніка.'; +$PHPMAILER_LANG['mailer_not_supported'] = ' - паштовы сервер не падтрымліваецца.'; +$PHPMAILER_LANG['recipients_failed'] = 'Памылка SMTP: няправільныя атрымальнікі: '; +$PHPMAILER_LANG['signing'] = 'Памылка подпісу паведамлення: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Памылка сувязі з SMTP-серверам.'; +$PHPMAILER_LANG['smtp_error'] = 'Памылка SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Нельга ўстанавіць або перамяніць значэнне пераменнай: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-bg.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-bg.php new file mode 100644 index 00000000..c41f675d --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-bg.php @@ -0,0 +1,27 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP грешка: Не може да се удостовери пред сървъра.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP грешка: Не може да се свърже с SMTP хоста.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP грешка: данните не са приети.'; +$PHPMAILER_LANG['empty_message'] = 'Съдържанието на съобщението е празно'; +$PHPMAILER_LANG['encoding'] = 'Неизвестно кодиране: '; +$PHPMAILER_LANG['execute'] = 'Не може да се изпълни: '; +$PHPMAILER_LANG['file_access'] = 'Няма достъп до файл: '; +$PHPMAILER_LANG['file_open'] = 'Файлова грешка: Не може да се отвори файл: '; +$PHPMAILER_LANG['from_failed'] = 'Следните адреси за подател са невалидни: '; +$PHPMAILER_LANG['instantiate'] = 'Не може да се инстанцира функцията mail.'; +$PHPMAILER_LANG['invalid_address'] = 'Невалиден адрес: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' - пощенски сървър не се поддържа.'; +$PHPMAILER_LANG['provide_address'] = 'Трябва да предоставите поне един email адрес за получател.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP грешка: Следните адреси за Получател са невалидни: '; +$PHPMAILER_LANG['signing'] = 'Грешка при подписване: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP провален connect().'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP сървърна грешка: '; +$PHPMAILER_LANG['variable_set'] = 'Не може да се установи или възстанови променлива: '; +$PHPMAILER_LANG['extension_missing'] = 'Липсва разширение: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-bn.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-bn.php new file mode 100644 index 00000000..47365108 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-bn.php @@ -0,0 +1,35 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP ত্রুটি: প্রমাণীকরণ করতে অক্ষম৷'; +$PHPMAILER_LANG['buggy_php'] = 'আপনার PHP সংস্করণ একটি বাগ দ্বারা প্রভাবিত হয় যার ফলে দূষিত বার্তা হতে পারে। এটি ঠিক করতে, পাঠাতে SMTP ব্যবহার করুন, আপনার php.ini এ mail.add_x_header বিকল্পটি নিষ্ক্রিয় করুন, MacOS বা Linux-এ স্যুইচ করুন, অথবা আপনার PHP সংস্করণকে 7.0.17+ বা 7.1.3+ এ পরিবর্তন করুন।'; +$PHPMAILER_LANG['connect_host'] = 'SMTP ত্রুটি: SMTP সার্ভারের সাথে সংযোগ করতে অক্ষম৷'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP ত্রুটি: ডেটা গ্রহণ করা হয়নি৷'; +$PHPMAILER_LANG['empty_message'] = 'বার্তার অংশটি খালি।'; +$PHPMAILER_LANG['encoding'] = 'অজানা এনকোডিং: '; +$PHPMAILER_LANG['execute'] = 'নির্বাহ করতে অক্ষম: '; +$PHPMAILER_LANG['extension_missing'] = 'এক্সটেনশন অনুপস্থিত:'; +$PHPMAILER_LANG['file_access'] = 'ফাইল অ্যাক্সেস করতে অক্ষম: '; +$PHPMAILER_LANG['file_open'] = 'ফাইল ত্রুটি: ফাইল খুলতে অক্ষম: '; +$PHPMAILER_LANG['from_failed'] = 'নিম্নলিখিত প্রেরকের ঠিকানা(গুলি) ব্যর্থ হয়েছে: '; +$PHPMAILER_LANG['instantiate'] = 'মেল ফাংশনের একটি উদাহরণ তৈরি করতে অক্ষম৷'; +$PHPMAILER_LANG['invalid_address'] = 'পাঠাতে অক্ষম: অবৈধ ইমেল ঠিকানা: '; +$PHPMAILER_LANG['invalid_header'] = 'অবৈধ হেডার নাম বা মান'; +$PHPMAILER_LANG['invalid_hostentry'] = 'অবৈধ হোস্টেন্ট্রি: '; +$PHPMAILER_LANG['invalid_host'] = 'অবৈধ হোস্ট:'; +$PHPMAILER_LANG['mailer_not_supported'] = 'মেইলার সমর্থিত নয়।'; +$PHPMAILER_LANG['provide_address'] = 'আপনাকে অবশ্যই অন্তত একটি গন্তব্য ইমেল ঠিকানা প্রদান করতে হবে৷'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP ত্রুটি: নিম্নলিখিত গন্তব্যগুলি ব্যর্থ হয়েছে: '; +$PHPMAILER_LANG['signing'] = 'স্বাক্ষর করতে ব্যর্থ হয়েছে: '; +$PHPMAILER_LANG['smtp_code'] = 'SMTP কোড: '; +$PHPMAILER_LANG['smtp_code_ex'] = 'অতিরিক্ত SMTP তথ্য:'; +$PHPMAILER_LANG['smtp_detail'] = 'বর্ণনা: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP সংযোগ() ব্যর্থ হয়েছে৷'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP সার্ভার ত্রুটি: '; +$PHPMAILER_LANG['variable_set'] = 'পরিবর্তনশীল সেট করা যায়নি: '; +$PHPMAILER_LANG['extension_missing'] = 'অনুপস্থিত এক্সটেনশন: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ca.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ca.php new file mode 100644 index 00000000..34684855 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ca.php @@ -0,0 +1,27 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'Error SMTP: No s’ha pogut autenticar.'; +$PHPMAILER_LANG['connect_host'] = 'Error SMTP: No es pot connectar al servidor SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Error SMTP: Dades no acceptades.'; +$PHPMAILER_LANG['empty_message'] = 'El cos del missatge està buit.'; +$PHPMAILER_LANG['encoding'] = 'Codificació desconeguda: '; +$PHPMAILER_LANG['execute'] = 'No es pot executar: '; +$PHPMAILER_LANG['file_access'] = 'No es pot accedir a l’arxiu: '; +$PHPMAILER_LANG['file_open'] = 'Error d’Arxiu: No es pot obrir l’arxiu: '; +$PHPMAILER_LANG['from_failed'] = 'La(s) següent(s) adreces de remitent han fallat: '; +$PHPMAILER_LANG['instantiate'] = 'No s’ha pogut crear una instància de la funció Mail.'; +$PHPMAILER_LANG['invalid_address'] = 'Adreça d’email invalida: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer no està suportat'; +$PHPMAILER_LANG['provide_address'] = 'S’ha de proveir almenys una adreça d’email com a destinatari.'; +$PHPMAILER_LANG['recipients_failed'] = 'Error SMTP: Els següents destinataris han fallat: '; +$PHPMAILER_LANG['signing'] = 'Error al signar: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Ha fallat el SMTP Connect().'; +$PHPMAILER_LANG['smtp_error'] = 'Error del servidor SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'No s’ha pogut establir o restablir la variable: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-cs.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-cs.php new file mode 100644 index 00000000..e770a1a2 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-cs.php @@ -0,0 +1,28 @@ + + * Rewrite and extension of the work by Mikael Stokkebro + * + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP fejl: Login mislykkedes.'; +$PHPMAILER_LANG['buggy_php'] = 'Din version af PHP er berørt af en fejl, som gør at dine beskeder muligvis vises forkert. For at rette dette kan du skifte til SMTP, slå mail.add_x_header headeren i din php.ini fil fra, skifte til MacOS eller Linux eller opgradere din version af PHP til 7.0.17+ eller 7.1.3+.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP fejl: Forbindelse til SMTP serveren kunne ikke oprettes.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP fejl: Data blev ikke accepteret.'; +$PHPMAILER_LANG['empty_message'] = 'Meddelelsen er uden indhold'; +$PHPMAILER_LANG['encoding'] = 'Ukendt encode-format: '; +$PHPMAILER_LANG['execute'] = 'Kunne ikke afvikle: '; +$PHPMAILER_LANG['extension_missing'] = 'Udvidelse mangler: '; +$PHPMAILER_LANG['file_access'] = 'Kunne ikke tilgå filen: '; +$PHPMAILER_LANG['file_open'] = 'Fil fejl: Kunne ikke åbne filen: '; +$PHPMAILER_LANG['from_failed'] = 'Følgende afsenderadresse er forkert: '; +$PHPMAILER_LANG['instantiate'] = 'Email funktionen kunne ikke initialiseres.'; +$PHPMAILER_LANG['invalid_address'] = 'Udgyldig adresse: '; +$PHPMAILER_LANG['invalid_header'] = 'Ugyldig header navn eller værdi'; +$PHPMAILER_LANG['invalid_hostentry'] = 'Ugyldig hostentry: '; +$PHPMAILER_LANG['invalid_host'] = 'Ugyldig vært: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer understøttes ikke.'; +$PHPMAILER_LANG['provide_address'] = 'Indtast mindst en modtagers email adresse.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP fejl: Følgende modtagere fejlede: '; +$PHPMAILER_LANG['signing'] = 'Signeringsfejl: '; +$PHPMAILER_LANG['smtp_code'] = 'SMTP kode: '; +$PHPMAILER_LANG['smtp_code_ex'] = 'Yderligere SMTP info: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() fejlede.'; +$PHPMAILER_LANG['smtp_detail'] = 'Detalje: '; +$PHPMAILER_LANG['smtp_error'] = 'SMTP server fejl: '; +$PHPMAILER_LANG['variable_set'] = 'Kunne ikke definere eller nulstille variablen: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-de.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-de.php new file mode 100644 index 00000000..e7e59d2b --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-de.php @@ -0,0 +1,28 @@ + + * @author Crystopher Glodzienski Cardoso + * @author Daniel Cruz + */ + +$PHPMAILER_LANG['authenticate'] = 'Error SMTP: Imposible autentificar.'; +$PHPMAILER_LANG['buggy_php'] = 'Tu versión de PHP está afectada por un bug que puede resultar en mensajes corruptos. Para arreglarlo, cambia a enviar usando SMTP, deshabilita la opción mail.add_x_header en tu php.ini, cambia a MacOS o Linux, o actualiza tu PHP a la versión 7.0.17+ o 7.1.3+.'; +$PHPMAILER_LANG['connect_host'] = 'Error SMTP: Imposible conectar al servidor SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Error SMTP: Datos no aceptados.'; +$PHPMAILER_LANG['empty_message'] = 'El cuerpo del mensaje está vacío.'; +$PHPMAILER_LANG['encoding'] = 'Codificación desconocida: '; +$PHPMAILER_LANG['execute'] = 'Imposible ejecutar: '; +$PHPMAILER_LANG['extension_missing'] = 'Extensión faltante: '; +$PHPMAILER_LANG['file_access'] = 'Imposible acceder al archivo: '; +$PHPMAILER_LANG['file_open'] = 'Error de Archivo: Imposible abrir el archivo: '; +$PHPMAILER_LANG['from_failed'] = 'La(s) siguiente(s) direcciones de remitente fallaron: '; +$PHPMAILER_LANG['instantiate'] = 'Imposible crear una instancia de la función Mail.'; +$PHPMAILER_LANG['invalid_address'] = 'Imposible enviar: dirección de email inválido: '; +$PHPMAILER_LANG['invalid_header'] = 'Nombre o valor de encabezado no válido'; +$PHPMAILER_LANG['invalid_hostentry'] = 'Hostentry inválido: '; +$PHPMAILER_LANG['invalid_host'] = 'Host inválido: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer no está soportado.'; +$PHPMAILER_LANG['provide_address'] = 'Debe proporcionar al menos una dirección de email de destino.'; +$PHPMAILER_LANG['recipients_failed'] = 'Error SMTP: Los siguientes destinos fallaron: '; +$PHPMAILER_LANG['signing'] = 'Error al firmar: '; +$PHPMAILER_LANG['smtp_code'] = 'Código del servidor SMTP: '; +$PHPMAILER_LANG['smtp_code_ex'] = 'Información adicional del servidor SMTP: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() falló.'; +$PHPMAILER_LANG['smtp_detail'] = 'Detalle: '; +$PHPMAILER_LANG['smtp_error'] = 'Error del servidor SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'No se pudo configurar la variable: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-et.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-et.php new file mode 100644 index 00000000..93addc9e --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-et.php @@ -0,0 +1,28 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP Viga: Autoriseerimise viga.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Viga: Ei õnnestunud luua ühendust SMTP serveriga.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP Viga: Vigased andmed.'; +$PHPMAILER_LANG['empty_message'] = 'Tühi kirja sisu'; +$PHPMAILER_LANG["encoding"] = 'Tundmatu kodeering: '; +$PHPMAILER_LANG['execute'] = 'Tegevus ebaõnnestus: '; +$PHPMAILER_LANG['file_access'] = 'Pole piisavalt õiguseid järgneva faili avamiseks: '; +$PHPMAILER_LANG['file_open'] = 'Faili Viga: Faili avamine ebaõnnestus: '; +$PHPMAILER_LANG['from_failed'] = 'Järgnev saatja e-posti aadress on vigane: '; +$PHPMAILER_LANG['instantiate'] = 'mail funktiooni käivitamine ebaõnnestus.'; +$PHPMAILER_LANG['invalid_address'] = 'Saatmine peatatud, e-posti address vigane: '; +$PHPMAILER_LANG['provide_address'] = 'Te peate määrama vähemalt ühe saaja e-posti aadressi.'; +$PHPMAILER_LANG['mailer_not_supported'] = ' maileri tugi puudub.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Viga: Järgnevate saajate e-posti aadressid on vigased: '; +$PHPMAILER_LANG["signing"] = 'Viga allkirjastamisel: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() ebaõnnestus.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP serveri viga: '; +$PHPMAILER_LANG['variable_set'] = 'Ei õnnestunud määrata või lähtestada muutujat: '; +$PHPMAILER_LANG['extension_missing'] = 'Nõutud laiendus on puudu: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-fa.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-fa.php new file mode 100644 index 00000000..295a47f9 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-fa.php @@ -0,0 +1,28 @@ + + * @author Mohammad Hossein Mojtahedi + */ + +$PHPMAILER_LANG['authenticate'] = 'خطای SMTP: احراز هویت با شکست مواجه شد.'; +$PHPMAILER_LANG['connect_host'] = 'خطای SMTP: اتصال به سرور SMTP برقرار نشد.'; +$PHPMAILER_LANG['data_not_accepted'] = 'خطای SMTP: داده‌ها نا‌درست هستند.'; +$PHPMAILER_LANG['empty_message'] = 'بخش متن پیام خالی است.'; +$PHPMAILER_LANG['encoding'] = 'کد‌گذاری نا‌شناخته: '; +$PHPMAILER_LANG['execute'] = 'امکان اجرا وجود ندارد: '; +$PHPMAILER_LANG['file_access'] = 'امکان دسترسی به فایل وجود ندارد: '; +$PHPMAILER_LANG['file_open'] = 'خطای File: امکان بازکردن فایل وجود ندارد: '; +$PHPMAILER_LANG['from_failed'] = 'آدرس فرستنده اشتباه است: '; +$PHPMAILER_LANG['instantiate'] = 'امکان معرفی تابع ایمیل وجود ندارد.'; +$PHPMAILER_LANG['invalid_address'] = 'آدرس ایمیل معتبر نیست: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer پشتیبانی نمی‌شود.'; +$PHPMAILER_LANG['provide_address'] = 'باید حداقل یک آدرس گیرنده وارد کنید.'; +$PHPMAILER_LANG['recipients_failed'] = 'خطای SMTP: ارسال به آدرس گیرنده با خطا مواجه شد: '; +$PHPMAILER_LANG['signing'] = 'خطا در امضا: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'خطا در اتصال به SMTP.'; +$PHPMAILER_LANG['smtp_error'] = 'خطا در SMTP Server: '; +$PHPMAILER_LANG['variable_set'] = 'امکان ارسال یا ارسال مجدد متغیر‌ها وجود ندارد: '; +$PHPMAILER_LANG['extension_missing'] = 'افزونه موجود نیست: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-fi.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-fi.php new file mode 100644 index 00000000..6d1e6373 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-fi.php @@ -0,0 +1,27 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP feilur: Kundi ikki góðkenna.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP feilur: Kundi ikki knýta samband við SMTP vert.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP feilur: Data ikki góðkent.'; +//$PHPMAILER_LANG['empty_message'] = 'Message body empty'; +$PHPMAILER_LANG['encoding'] = 'Ókend encoding: '; +$PHPMAILER_LANG['execute'] = 'Kundi ikki útføra: '; +$PHPMAILER_LANG['file_access'] = 'Kundi ikki tilganga fílu: '; +$PHPMAILER_LANG['file_open'] = 'Fílu feilur: Kundi ikki opna fílu: '; +$PHPMAILER_LANG['from_failed'] = 'fylgjandi Frá/From adressa miseydnaðist: '; +$PHPMAILER_LANG['instantiate'] = 'Kuni ikki instantiera mail funktión.'; +//$PHPMAILER_LANG['invalid_address'] = 'Invalid address: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' er ikki supporterað.'; +$PHPMAILER_LANG['provide_address'] = 'Tú skal uppgeva minst móttakara-emailadressu(r).'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Feilur: Fylgjandi móttakarar miseydnaðust: '; +//$PHPMAILER_LANG['signing'] = 'Signing Error: '; +//$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() failed.'; +//$PHPMAILER_LANG['smtp_error'] = 'SMTP server error: '; +//$PHPMAILER_LANG['variable_set'] = 'Cannot set or reset variable: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-fr.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-fr.php new file mode 100644 index 00000000..a6d582d8 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-fr.php @@ -0,0 +1,36 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'Erro SMTP: Non puido ser autentificado.'; +$PHPMAILER_LANG['connect_host'] = 'Erro SMTP: Non puido conectar co servidor SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Erro SMTP: Datos non aceptados.'; +$PHPMAILER_LANG['empty_message'] = 'Corpo da mensaxe vacía'; +$PHPMAILER_LANG['encoding'] = 'Codificación descoñecida: '; +$PHPMAILER_LANG['execute'] = 'Non puido ser executado: '; +$PHPMAILER_LANG['file_access'] = 'Nob puido acceder ó arquivo: '; +$PHPMAILER_LANG['file_open'] = 'Erro de Arquivo: No puido abrir o arquivo: '; +$PHPMAILER_LANG['from_failed'] = 'A(s) seguinte(s) dirección(s) de remitente(s) deron erro: '; +$PHPMAILER_LANG['instantiate'] = 'Non puido crear unha instancia da función Mail.'; +$PHPMAILER_LANG['invalid_address'] = 'Non puido envia-lo correo: dirección de email inválida: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer non está soportado.'; +$PHPMAILER_LANG['provide_address'] = 'Debe engadir polo menos unha dirección de email coma destino.'; +$PHPMAILER_LANG['recipients_failed'] = 'Erro SMTP: Os seguintes destinos fallaron: '; +$PHPMAILER_LANG['signing'] = 'Erro ó firmar: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() fallou.'; +$PHPMAILER_LANG['smtp_error'] = 'Erro do servidor SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Non puidemos axustar ou reaxustar a variábel: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-he.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-he.php new file mode 100644 index 00000000..b123aa5f --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-he.php @@ -0,0 +1,27 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'שגיאת SMTP: פעולת האימות נכשלה.'; +$PHPMAILER_LANG['connect_host'] = 'שגיאת SMTP: לא הצלחתי להתחבר לשרת SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'שגיאת SMTP: מידע לא התקבל.'; +$PHPMAILER_LANG['empty_message'] = 'גוף ההודעה ריק'; +$PHPMAILER_LANG['invalid_address'] = 'כתובת שגויה: '; +$PHPMAILER_LANG['encoding'] = 'קידוד לא מוכר: '; +$PHPMAILER_LANG['execute'] = 'לא הצלחתי להפעיל את: '; +$PHPMAILER_LANG['file_access'] = 'לא ניתן לגשת לקובץ: '; +$PHPMAILER_LANG['file_open'] = 'שגיאת קובץ: לא ניתן לגשת לקובץ: '; +$PHPMAILER_LANG['from_failed'] = 'כתובות הנמענים הבאות נכשלו: '; +$PHPMAILER_LANG['instantiate'] = 'לא הצלחתי להפעיל את פונקציית המייל.'; +$PHPMAILER_LANG['mailer_not_supported'] = ' אינה נתמכת.'; +$PHPMAILER_LANG['provide_address'] = 'חובה לספק לפחות כתובת אחת של מקבל המייל.'; +$PHPMAILER_LANG['recipients_failed'] = 'שגיאת SMTP: הנמענים הבאים נכשלו: '; +$PHPMAILER_LANG['signing'] = 'שגיאת חתימה: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() failed.'; +$PHPMAILER_LANG['smtp_error'] = 'שגיאת שרת SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'לא ניתן לקבוע או לשנות את המשתנה: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-hi.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-hi.php new file mode 100644 index 00000000..d2856e05 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-hi.php @@ -0,0 +1,35 @@ + + * Rewrite and extension of the work by Jayanti Suthar + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP त्रुटि: प्रामाणिकता की जांच नहीं हो सका। '; +$PHPMAILER_LANG['buggy_php'] = 'PHP का आपका संस्करण एक बग से प्रभावित है जिसके परिणामस्वरूप संदेश दूषित हो सकते हैं. इसे ठीक करने हेतु, भेजने के लिए SMTP का उपयोग करे, अपने php.ini में mail.add_x_header विकल्प को अक्षम करें, MacOS या Linux पर जाए, या अपने PHP संस्करण को 7.0.17+ या 7.1.3+ बदले.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP त्रुटि: SMTP सर्वर से कनेक्ट नहीं हो सका। '; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP त्रुटि: डेटा स्वीकार नहीं किया जाता है। '; +$PHPMAILER_LANG['empty_message'] = 'संदेश खाली है। '; +$PHPMAILER_LANG['encoding'] = 'अज्ञात एन्कोडिंग प्रकार। '; +$PHPMAILER_LANG['execute'] = 'आदेश को निष्पादित करने में विफल। '; +$PHPMAILER_LANG['extension_missing'] = 'एक्सटेन्षन गायब है: '; +$PHPMAILER_LANG['file_access'] = 'फ़ाइल उपलब्ध नहीं है। '; +$PHPMAILER_LANG['file_open'] = 'फ़ाइल त्रुटि: फाइल को खोला नहीं जा सका। '; +$PHPMAILER_LANG['from_failed'] = 'प्रेषक का पता गलत है। '; +$PHPMAILER_LANG['instantiate'] = 'मेल फ़ंक्शन कॉल नहीं कर सकता है।'; +$PHPMAILER_LANG['invalid_address'] = 'पता गलत है। '; +$PHPMAILER_LANG['invalid_header'] = 'अमान्य हेडर नाम या मान'; +$PHPMAILER_LANG['invalid_hostentry'] = 'अमान्य hostentry: '; +$PHPMAILER_LANG['invalid_host'] = 'अमान्य होस्ट: '; +$PHPMAILER_LANG['mailer_not_supported'] = 'मेल सर्वर के साथ काम नहीं करता है। '; +$PHPMAILER_LANG['provide_address'] = 'आपको कम से कम एक प्राप्तकर्ता का ई-मेल पता प्रदान करना होगा।'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP त्रुटि: निम्न प्राप्तकर्ताओं को पते भेजने में विफल। '; +$PHPMAILER_LANG['signing'] = 'साइनअप त्रुटि: '; +$PHPMAILER_LANG['smtp_code'] = 'SMTP कोड: '; +$PHPMAILER_LANG['smtp_code_ex'] = 'अतिरिक्त SMTP जानकारी: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP का connect () फ़ंक्शन विफल हुआ। '; +$PHPMAILER_LANG['smtp_detail'] = 'विवरण: '; +$PHPMAILER_LANG['smtp_error'] = 'SMTP सर्वर त्रुटि। '; +$PHPMAILER_LANG['variable_set'] = 'चर को बना या संशोधित नहीं किया जा सकता। '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-hr.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-hr.php new file mode 100644 index 00000000..cacb6c37 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-hr.php @@ -0,0 +1,27 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP Greška: Neuspjela autentikacija.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Greška: Ne mogu se spojiti na SMTP poslužitelj.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP Greška: Podatci nisu prihvaćeni.'; +$PHPMAILER_LANG['empty_message'] = 'Sadržaj poruke je prazan.'; +$PHPMAILER_LANG['encoding'] = 'Nepoznati encoding: '; +$PHPMAILER_LANG['execute'] = 'Nije moguće izvršiti naredbu: '; +$PHPMAILER_LANG['file_access'] = 'Nije moguće pristupiti datoteci: '; +$PHPMAILER_LANG['file_open'] = 'Nije moguće otvoriti datoteku: '; +$PHPMAILER_LANG['from_failed'] = 'SMTP Greška: Slanje s navedenih e-mail adresa nije uspjelo: '; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Greška: Slanje na navedenih e-mail adresa nije uspjelo: '; +$PHPMAILER_LANG['instantiate'] = 'Ne mogu pokrenuti mail funkcionalnost.'; +$PHPMAILER_LANG['invalid_address'] = 'E-mail nije poslan. Neispravna e-mail adresa: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer nije podržan.'; +$PHPMAILER_LANG['provide_address'] = 'Definirajte barem jednu adresu primatelja.'; +$PHPMAILER_LANG['signing'] = 'Greška prilikom prijave: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Spajanje na SMTP poslužitelj nije uspjelo.'; +$PHPMAILER_LANG['smtp_error'] = 'Greška SMTP poslužitelja: '; +$PHPMAILER_LANG['variable_set'] = 'Ne mogu postaviti varijablu niti ju vratiti nazad: '; +$PHPMAILER_LANG['extension_missing'] = 'Nedostaje proširenje: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-hu.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-hu.php new file mode 100644 index 00000000..e6b58b0d --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-hu.php @@ -0,0 +1,27 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP -ի սխալ: չհաջողվեց ստուգել իսկությունը.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP -ի սխալ: չհաջողվեց կապ հաստատել SMTP սերվերի հետ.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP -ի սխալ: տվյալները ընդունված չեն.'; +$PHPMAILER_LANG['empty_message'] = 'Հաղորդագրությունը դատարկ է'; +$PHPMAILER_LANG['encoding'] = 'Կոդավորման անհայտ տեսակ: '; +$PHPMAILER_LANG['execute'] = 'Չհաջողվեց իրականացնել հրամանը: '; +$PHPMAILER_LANG['file_access'] = 'Ֆայլը հասանելի չէ: '; +$PHPMAILER_LANG['file_open'] = 'Ֆայլի սխալ: ֆայլը չհաջողվեց բացել: '; +$PHPMAILER_LANG['from_failed'] = 'Ուղարկողի հետևյալ հասցեն սխալ է: '; +$PHPMAILER_LANG['instantiate'] = 'Հնարավոր չէ կանչել mail ֆունկցիան.'; +$PHPMAILER_LANG['invalid_address'] = 'Հասցեն սխալ է: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' փոստային սերվերի հետ չի աշխատում.'; +$PHPMAILER_LANG['provide_address'] = 'Անհրաժեշտ է տրամադրել գոնե մեկ ստացողի e-mail հասցե.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP -ի սխալ: չի հաջողվել ուղարկել հետևյալ ստացողների հասցեներին: '; +$PHPMAILER_LANG['signing'] = 'Ստորագրման սխալ: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP -ի connect() ֆունկցիան չի հաջողվել'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP սերվերի սխալ: '; +$PHPMAILER_LANG['variable_set'] = 'Չի հաջողվում ստեղծել կամ վերափոխել փոփոխականը: '; +$PHPMAILER_LANG['extension_missing'] = 'Հավելվածը բացակայում է: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-id.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-id.php new file mode 100644 index 00000000..212a11f1 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-id.php @@ -0,0 +1,31 @@ + + * @author @januridp + * @author Ian Mustafa + */ + +$PHPMAILER_LANG['authenticate'] = 'Kesalahan SMTP: Tidak dapat mengotentikasi.'; +$PHPMAILER_LANG['connect_host'] = 'Kesalahan SMTP: Tidak dapat terhubung ke host SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Kesalahan SMTP: Data tidak diterima.'; +$PHPMAILER_LANG['empty_message'] = 'Isi pesan kosong'; +$PHPMAILER_LANG['encoding'] = 'Pengkodean karakter tidak dikenali: '; +$PHPMAILER_LANG['execute'] = 'Tidak dapat menjalankan proses: '; +$PHPMAILER_LANG['file_access'] = 'Tidak dapat mengakses berkas: '; +$PHPMAILER_LANG['file_open'] = 'Kesalahan Berkas: Berkas tidak dapat dibuka: '; +$PHPMAILER_LANG['from_failed'] = 'Alamat pengirim berikut mengakibatkan kesalahan: '; +$PHPMAILER_LANG['instantiate'] = 'Tidak dapat menginisialisasi fungsi surel.'; +$PHPMAILER_LANG['invalid_address'] = 'Gagal terkirim, alamat surel tidak sesuai: '; +$PHPMAILER_LANG['invalid_hostentry'] = 'Gagal terkirim, entri host tidak sesuai: '; +$PHPMAILER_LANG['invalid_host'] = 'Gagal terkirim, host tidak sesuai: '; +$PHPMAILER_LANG['provide_address'] = 'Harus tersedia minimal satu alamat tujuan'; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer tidak didukung'; +$PHPMAILER_LANG['recipients_failed'] = 'Kesalahan SMTP: Alamat tujuan berikut menyebabkan kesalahan: '; +$PHPMAILER_LANG['signing'] = 'Kesalahan dalam penandatangan SSL: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() gagal.'; +$PHPMAILER_LANG['smtp_error'] = 'Kesalahan pada pelayan SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Tidak dapat mengatur atau mengatur ulang variabel: '; +$PHPMAILER_LANG['extension_missing'] = 'Ekstensi PHP tidak tersedia: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-it.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-it.php new file mode 100644 index 00000000..08a6b733 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-it.php @@ -0,0 +1,28 @@ + + * @author Stefano Sabatini + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP Error: Impossibile autenticarsi.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Error: Impossibile connettersi all\'host SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP Error: Dati non accettati dal server.'; +$PHPMAILER_LANG['empty_message'] = 'Il corpo del messaggio è vuoto'; +$PHPMAILER_LANG['encoding'] = 'Codifica dei caratteri sconosciuta: '; +$PHPMAILER_LANG['execute'] = 'Impossibile eseguire l\'operazione: '; +$PHPMAILER_LANG['file_access'] = 'Impossibile accedere al file: '; +$PHPMAILER_LANG['file_open'] = 'File Error: Impossibile aprire il file: '; +$PHPMAILER_LANG['from_failed'] = 'I seguenti indirizzi mittenti hanno generato errore: '; +$PHPMAILER_LANG['instantiate'] = 'Impossibile istanziare la funzione mail'; +$PHPMAILER_LANG['invalid_address'] = 'Impossibile inviare, l\'indirizzo email non è valido: '; +$PHPMAILER_LANG['provide_address'] = 'Deve essere fornito almeno un indirizzo ricevente'; +$PHPMAILER_LANG['mailer_not_supported'] = 'Mailer non supportato'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Error: I seguenti indirizzi destinatari hanno generato un errore: '; +$PHPMAILER_LANG['signing'] = 'Errore nella firma: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() fallita.'; +$PHPMAILER_LANG['smtp_error'] = 'Errore del server SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Impossibile impostare o resettare la variabile: '; +$PHPMAILER_LANG['extension_missing'] = 'Estensione mancante: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ja.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ja.php new file mode 100644 index 00000000..d01869ce --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ja.php @@ -0,0 +1,37 @@ + + * @author Yoshi Sakai + * @author Arisophy + * @author ARAKI Musashi + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTPエラー: 認証できませんでした。'; +$PHPMAILER_LANG['buggy_php'] = 'ご利用のバージョンのPHPには不具合があり、メッセージが破損するおそれがあります。問題の解決は以下のいずれかを行ってください。SMTPでの送信に切り替える。php.iniのmail.add_x_headerをoffにする。MacOSまたはLinuxに切り替える。PHPバージョン7.0.17以降または7.1.3以降にアップグレードする。'; +$PHPMAILER_LANG['connect_host'] = 'SMTPエラー: SMTPホストに接続できませんでした。'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTPエラー: データが受け付けられませんでした。'; +$PHPMAILER_LANG['empty_message'] = 'メール本文が空です。'; +$PHPMAILER_LANG['encoding'] = '不明なエンコーディング: '; +$PHPMAILER_LANG['execute'] = '実行できませんでした: '; +$PHPMAILER_LANG['extension_missing'] = '拡張機能が見つかりません: '; +$PHPMAILER_LANG['file_access'] = 'ファイルにアクセスできません: '; +$PHPMAILER_LANG['file_open'] = 'ファイルエラー: ファイルを開けません: '; +$PHPMAILER_LANG['from_failed'] = 'Fromアドレスを登録する際にエラーが発生しました: '; +$PHPMAILER_LANG['instantiate'] = 'メール関数が正常に動作しませんでした。'; +$PHPMAILER_LANG['invalid_address'] = '不正なメールアドレス: '; +$PHPMAILER_LANG['invalid_header'] = '不正なヘッダー名またはその内容'; +$PHPMAILER_LANG['invalid_hostentry'] = '不正なホストエントリー: '; +$PHPMAILER_LANG['invalid_host'] = '不正なホスト: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' メーラーがサポートされていません。'; +$PHPMAILER_LANG['provide_address'] = '少なくとも1つメールアドレスを 指定する必要があります。'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTPエラー: 次の受信者アドレスに 間違いがあります: '; +$PHPMAILER_LANG['signing'] = '署名エラー: '; +$PHPMAILER_LANG['smtp_code'] = 'SMTPコード: '; +$PHPMAILER_LANG['smtp_code_ex'] = 'SMTP追加情報: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP接続に失敗しました。'; +$PHPMAILER_LANG['smtp_detail'] = '詳細: '; +$PHPMAILER_LANG['smtp_error'] = 'SMTPサーバーエラー: '; +$PHPMAILER_LANG['variable_set'] = '変数が存在しません: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ka.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ka.php new file mode 100644 index 00000000..51fe403b --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ka.php @@ -0,0 +1,27 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP შეცდომა: ავტორიზაცია შეუძლებელია.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP შეცდომა: SMTP სერვერთან დაკავშირება შეუძლებელია.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP შეცდომა: მონაცემები არ იქნა მიღებული.'; +$PHPMAILER_LANG['encoding'] = 'კოდირების უცნობი ტიპი: '; +$PHPMAILER_LANG['execute'] = 'შეუძლებელია შემდეგი ბრძანების შესრულება: '; +$PHPMAILER_LANG['file_access'] = 'შეუძლებელია წვდომა ფაილთან: '; +$PHPMAILER_LANG['file_open'] = 'ფაილური სისტემის შეცდომა: არ იხსნება ფაილი: '; +$PHPMAILER_LANG['from_failed'] = 'გამგზავნის არასწორი მისამართი: '; +$PHPMAILER_LANG['instantiate'] = 'mail ფუნქციის გაშვება ვერ ხერხდება.'; +$PHPMAILER_LANG['provide_address'] = 'გთხოვთ მიუთითოთ ერთი ადრესატის e-mail მისამართი მაინც.'; +$PHPMAILER_LANG['mailer_not_supported'] = ' - საფოსტო სერვერის მხარდაჭერა არ არის.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP შეცდომა: შემდეგ მისამართებზე გაგზავნა ვერ მოხერხდა: '; +$PHPMAILER_LANG['empty_message'] = 'შეტყობინება ცარიელია'; +$PHPMAILER_LANG['invalid_address'] = 'არ გაიგზავნა, e-mail მისამართის არასწორი ფორმატი: '; +$PHPMAILER_LANG['signing'] = 'ხელმოწერის შეცდომა: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'შეცდომა SMTP სერვერთან დაკავშირებისას'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP სერვერის შეცდომა: '; +$PHPMAILER_LANG['variable_set'] = 'შეუძლებელია შემდეგი ცვლადის შექმნა ან შეცვლა: '; +$PHPMAILER_LANG['extension_missing'] = 'ბიბლიოთეკა არ არსებობს: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ko.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ko.php new file mode 100644 index 00000000..8c97dd94 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ko.php @@ -0,0 +1,27 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP 오류: 인증할 수 없습니다.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP 오류: SMTP 호스트에 접속할 수 없습니다.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP 오류: 데이터가 받아들여지지 않았습니다.'; +$PHPMAILER_LANG['empty_message'] = '메세지 내용이 없습니다'; +$PHPMAILER_LANG['encoding'] = '알 수 없는 인코딩: '; +$PHPMAILER_LANG['execute'] = '실행 불가: '; +$PHPMAILER_LANG['file_access'] = '파일 접근 불가: '; +$PHPMAILER_LANG['file_open'] = '파일 오류: 파일을 열 수 없습니다: '; +$PHPMAILER_LANG['from_failed'] = '다음 From 주소에서 오류가 발생했습니다: '; +$PHPMAILER_LANG['instantiate'] = 'mail 함수를 인스턴스화할 수 없습니다'; +$PHPMAILER_LANG['invalid_address'] = '잘못된 주소: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' 메일러는 지원되지 않습니다.'; +$PHPMAILER_LANG['provide_address'] = '적어도 한 개 이상의 수신자 메일 주소를 제공해야 합니다.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP 오류: 다음 수신자에서 오류가 발생했습니다: '; +$PHPMAILER_LANG['signing'] = '서명 오류: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP 연결을 실패하였습니다.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP 서버 오류: '; +$PHPMAILER_LANG['variable_set'] = '변수 설정 및 초기화 불가: '; +$PHPMAILER_LANG['extension_missing'] = '확장자 없음: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ku.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ku.php new file mode 100644 index 00000000..cf3bda69 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ku.php @@ -0,0 +1,27 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'هەڵەی SMTP : نەتوانرا کۆدەکە پشتڕاست بکرێتەوە '; +$PHPMAILER_LANG['connect_host'] = 'هەڵەی SMTP: نەتوانرا پەیوەندی بە سێرڤەرەوە بکات SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'هەڵەی SMTP: ئەو زانیاریانە قبوڵ نەکرا.'; +$PHPMAILER_LANG['empty_message'] = 'پەیامەکە بەتاڵە'; +$PHPMAILER_LANG['encoding'] = 'کۆدکردنی نەزانراو : '; +$PHPMAILER_LANG['execute'] = 'ناتوانرێت جێبەجێ بکرێت: '; +$PHPMAILER_LANG['file_access'] = 'ناتوانرێت دەستت بگات بە فایلەکە: '; +$PHPMAILER_LANG['file_open'] = 'هەڵەی پەڕگە(فایل): ناتوانرێت بکرێتەوە: '; +$PHPMAILER_LANG['from_failed'] = 'هەڵە لە ئاستی ناونیشانی نێرەر: '; +$PHPMAILER_LANG['instantiate'] = 'ناتوانرێت خزمەتگوزاری پۆستە پێشکەش بکرێت.'; +$PHPMAILER_LANG['invalid_address'] = 'نەتوانرا بنێردرێت ، چونکە ناونیشانی ئیمەیڵەکە نادروستە: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' مەیلەر پشتگیری ناکات'; +$PHPMAILER_LANG['provide_address'] = 'دەبێت ناونیشانی ئیمەیڵی لانیکەم یەک وەرگر دابین بکرێت.'; +$PHPMAILER_LANG['recipients_failed'] = ' هەڵەی SMTP: ئەم هەڵانەی خوارەوەشکستی هێنا لە ناردن بۆ هەردووکیان: '; +$PHPMAILER_LANG['signing'] = 'هەڵەی واژۆ: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect()پەیوەندی شکستی هێنا .'; +$PHPMAILER_LANG['smtp_error'] = 'هەڵەی ئاستی سێرڤەری SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'ناتوانرێت بیگۆڕیت یان دوبارە بینێریتەوە: '; +$PHPMAILER_LANG['extension_missing'] = 'درێژکراوە نەماوە: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-lt.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-lt.php new file mode 100644 index 00000000..4f115b1c --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-lt.php @@ -0,0 +1,27 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP klaida: autentifikacija nepavyko.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP klaida: nepavyksta prisijungti prie SMTP stoties.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP klaida: duomenys nepriimti.'; +$PHPMAILER_LANG['empty_message'] = 'Laiško turinys tuščias'; +$PHPMAILER_LANG['encoding'] = 'Neatpažinta koduotė: '; +$PHPMAILER_LANG['execute'] = 'Nepavyko įvykdyti komandos: '; +$PHPMAILER_LANG['file_access'] = 'Byla nepasiekiama: '; +$PHPMAILER_LANG['file_open'] = 'Bylos klaida: Nepavyksta atidaryti: '; +$PHPMAILER_LANG['from_failed'] = 'Neteisingas siuntėjo adresas: '; +$PHPMAILER_LANG['instantiate'] = 'Nepavyko paleisti mail funkcijos.'; +$PHPMAILER_LANG['invalid_address'] = 'Neteisingas adresas: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' pašto stotis nepalaikoma.'; +$PHPMAILER_LANG['provide_address'] = 'Nurodykite bent vieną gavėjo adresą.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP klaida: nepavyko išsiųsti šiems gavėjams: '; +$PHPMAILER_LANG['signing'] = 'Prisijungimo klaida: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP susijungimo klaida'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP stoties klaida: '; +$PHPMAILER_LANG['variable_set'] = 'Nepavyko priskirti reikšmės kintamajam: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-lv.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-lv.php new file mode 100644 index 00000000..679b18cf --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-lv.php @@ -0,0 +1,27 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP kļūda: Autorizācija neizdevās.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Kļūda: Nevar izveidot savienojumu ar SMTP serveri.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP Kļūda: Nepieņem informāciju.'; +$PHPMAILER_LANG['empty_message'] = 'Ziņojuma teksts ir tukšs'; +$PHPMAILER_LANG['encoding'] = 'Neatpazīts kodējums: '; +$PHPMAILER_LANG['execute'] = 'Neizdevās izpildīt komandu: '; +$PHPMAILER_LANG['file_access'] = 'Fails nav pieejams: '; +$PHPMAILER_LANG['file_open'] = 'Faila kļūda: Nevar atvērt failu: '; +$PHPMAILER_LANG['from_failed'] = 'Nepareiza sūtītāja adrese: '; +$PHPMAILER_LANG['instantiate'] = 'Nevar palaist sūtīšanas funkciju.'; +$PHPMAILER_LANG['invalid_address'] = 'Nepareiza adrese: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' sūtītājs netiek atbalstīts.'; +$PHPMAILER_LANG['provide_address'] = 'Lūdzu, norādiet vismaz vienu adresātu.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP kļūda: neizdevās nosūtīt šādiem saņēmējiem: '; +$PHPMAILER_LANG['signing'] = 'Autorizācijas kļūda: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP savienojuma kļūda'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP servera kļūda: '; +$PHPMAILER_LANG['variable_set'] = 'Nevar piešķirt mainīgā vērtību: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-mg.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-mg.php new file mode 100644 index 00000000..8a94f6a0 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-mg.php @@ -0,0 +1,27 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'Hadisoana SMTP: Tsy nahomby ny fanamarinana.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Error: Tsy afaka mampifandray amin\'ny mpampiantrano SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP diso: tsy voarakitra ny angona.'; +$PHPMAILER_LANG['empty_message'] = 'Tsy misy ny votoaty mailaka.'; +$PHPMAILER_LANG['encoding'] = 'Tsy fantatra encoding: '; +$PHPMAILER_LANG['execute'] = 'Tsy afaka manatanteraka ity baiko manaraka ity: '; +$PHPMAILER_LANG['file_access'] = 'Tsy nahomby ny fidirana amin\'ity rakitra ity: '; +$PHPMAILER_LANG['file_open'] = 'Hadisoana diso: Tsy afaka nanokatra ity file manaraka ity: '; +$PHPMAILER_LANG['from_failed'] = 'Ny adiresy iraka manaraka dia diso: '; +$PHPMAILER_LANG['instantiate'] = 'Tsy afaka nanomboka ny hetsika mail.'; +$PHPMAILER_LANG['invalid_address'] = 'Tsy mety ny adiresy: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer tsy manohana.'; +$PHPMAILER_LANG['provide_address'] = 'Alefaso azafady iray adiresy iray farafahakeliny.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Error: Tsy mety ireo mpanaraka ireto: '; +$PHPMAILER_LANG['signing'] = 'Error nandritra ny sonia:'; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Tsy nahomby ny fifandraisana tamin\'ny server SMTP.'; +$PHPMAILER_LANG['smtp_error'] = 'Fahadisoana tamin\'ny server SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Tsy azo atao ny mametraka na mamerina ny variable: '; +$PHPMAILER_LANG['extension_missing'] = 'Tsy hita ny ampahany: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-mn.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-mn.php new file mode 100644 index 00000000..04d262c7 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-mn.php @@ -0,0 +1,27 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'Ralat SMTP: Tidak dapat pengesahan.'; +$PHPMAILER_LANG['connect_host'] = 'Ralat SMTP: Tidak dapat menghubungi hos pelayan SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Ralat SMTP: Data tidak diterima oleh pelayan.'; +$PHPMAILER_LANG['empty_message'] = 'Tiada isi untuk mesej'; +$PHPMAILER_LANG['encoding'] = 'Pengekodan tidak diketahui: '; +$PHPMAILER_LANG['execute'] = 'Tidak dapat melaksanakan: '; +$PHPMAILER_LANG['file_access'] = 'Tidak dapat mengakses fail: '; +$PHPMAILER_LANG['file_open'] = 'Ralat Fail: Tidak dapat membuka fail: '; +$PHPMAILER_LANG['from_failed'] = 'Berikut merupakan ralat dari alamat e-mel: '; +$PHPMAILER_LANG['instantiate'] = 'Tidak dapat memberi contoh fungsi e-mel.'; +$PHPMAILER_LANG['invalid_address'] = 'Alamat emel tidak sah: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' jenis penghantar emel tidak disokong.'; +$PHPMAILER_LANG['provide_address'] = 'Anda perlu menyediakan sekurang-kurangnya satu alamat e-mel penerima.'; +$PHPMAILER_LANG['recipients_failed'] = 'Ralat SMTP: Penerima e-mel berikut telah gagal: '; +$PHPMAILER_LANG['signing'] = 'Ralat pada tanda tangan: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() telah gagal.'; +$PHPMAILER_LANG['smtp_error'] = 'Ralat pada pelayan SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Tidak boleh menetapkan atau menetapkan semula pembolehubah: '; +$PHPMAILER_LANG['extension_missing'] = 'Sambungan hilang: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-nb.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-nb.php new file mode 100644 index 00000000..c9621a16 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-nb.php @@ -0,0 +1,33 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP-fout: authenticatie mislukt.'; +$PHPMAILER_LANG['buggy_php'] = 'PHP versie gededecteerd die onderhavig is aan een bug die kan resulteren in gecorrumpeerde berichten. Om dit te voorkomen, gebruik SMTP voor het verzenden van berichten, zet de mail.add_x_header optie in uw php.ini file uit, gebruik MacOS of Linux, of pas de gebruikte PHP versie aan naar versie 7.0.17+ or 7.1.3+.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP-fout: kon niet verbinden met SMTP-host.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP-fout: data niet geaccepteerd.'; +$PHPMAILER_LANG['empty_message'] = 'Berichttekst is leeg'; +$PHPMAILER_LANG['encoding'] = 'Onbekende codering: '; +$PHPMAILER_LANG['execute'] = 'Kon niet uitvoeren: '; +$PHPMAILER_LANG['extension_missing'] = 'Extensie afwezig: '; +$PHPMAILER_LANG['file_access'] = 'Kreeg geen toegang tot bestand: '; +$PHPMAILER_LANG['file_open'] = 'Bestandsfout: kon bestand niet openen: '; +$PHPMAILER_LANG['from_failed'] = 'Het volgende afzendersadres is mislukt: '; +$PHPMAILER_LANG['instantiate'] = 'Kon mailfunctie niet initialiseren.'; +$PHPMAILER_LANG['invalid_address'] = 'Ongeldig adres: '; +$PHPMAILER_LANG['invalid_header'] = 'Ongeldige header naam of waarde'; +$PHPMAILER_LANG['invalid_hostentry'] = 'Ongeldige hostentry: '; +$PHPMAILER_LANG['invalid_host'] = 'Ongeldige host: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer wordt niet ondersteund.'; +$PHPMAILER_LANG['provide_address'] = 'Er moet minstens één ontvanger worden opgegeven.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP-fout: de volgende ontvangers zijn mislukt: '; +$PHPMAILER_LANG['signing'] = 'Signeerfout: '; +$PHPMAILER_LANG['smtp_code'] = 'SMTP code: '; +$PHPMAILER_LANG['smtp_code_ex'] = 'Aanvullende SMTP informatie: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Verbinding mislukt.'; +$PHPMAILER_LANG['smtp_detail'] = 'Detail: '; +$PHPMAILER_LANG['smtp_error'] = 'SMTP-serverfout: '; +$PHPMAILER_LANG['variable_set'] = 'Kan de volgende variabele niet instellen of resetten: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-pl.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-pl.php new file mode 100644 index 00000000..cb7b2c21 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-pl.php @@ -0,0 +1,33 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'Erro do SMTP: Não foi possível realizar a autenticação.'; +$PHPMAILER_LANG['connect_host'] = 'Erro do SMTP: Não foi possível realizar ligação com o servidor SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Erro do SMTP: Os dados foram rejeitados.'; +$PHPMAILER_LANG['empty_message'] = 'A mensagem no e-mail está vazia.'; +$PHPMAILER_LANG['encoding'] = 'Codificação desconhecida: '; +$PHPMAILER_LANG['execute'] = 'Não foi possível executar: '; +$PHPMAILER_LANG['file_access'] = 'Não foi possível aceder o ficheiro: '; +$PHPMAILER_LANG['file_open'] = 'Abertura do ficheiro: Não foi possível abrir o ficheiro: '; +$PHPMAILER_LANG['from_failed'] = 'Ocorreram falhas nos endereços dos seguintes remententes: '; +$PHPMAILER_LANG['instantiate'] = 'Não foi possível iniciar uma instância da função mail.'; +$PHPMAILER_LANG['invalid_address'] = 'Não foi enviado nenhum e-mail para o endereço de e-mail inválido: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer não é suportado.'; +$PHPMAILER_LANG['provide_address'] = 'Tem de fornecer pelo menos um endereço como destinatário do e-mail.'; +$PHPMAILER_LANG['recipients_failed'] = 'Erro do SMTP: O endereço do seguinte destinatário falhou: '; +$PHPMAILER_LANG['signing'] = 'Erro ao assinar: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() falhou.'; +$PHPMAILER_LANG['smtp_error'] = 'Erro de servidor SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Não foi possível definir ou redefinir a variável: '; +$PHPMAILER_LANG['extension_missing'] = 'Extensão em falta: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-pt_br.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-pt_br.php new file mode 100644 index 00000000..5239865a --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-pt_br.php @@ -0,0 +1,38 @@ + + * @author Lucas Guimarães + * @author Phelipe Alves + * @author Fabio Beneditto + * @author Geidson Benício Coelho + */ + +$PHPMAILER_LANG['authenticate'] = 'Erro de SMTP: Não foi possível autenticar.'; +$PHPMAILER_LANG['buggy_php'] = 'Sua versão do PHP é afetada por um bug que por resultar em messagens corrompidas. Para corrigir, mude para enviar usando SMTP, desative a opção mail.add_x_header em seu php.ini, mude para MacOS ou Linux, ou atualize seu PHP para versão 7.0.17+ ou 7.1.3+ '; +$PHPMAILER_LANG['connect_host'] = 'Erro de SMTP: Não foi possível conectar ao servidor SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Erro de SMTP: Dados rejeitados.'; +$PHPMAILER_LANG['empty_message'] = 'Mensagem vazia'; +$PHPMAILER_LANG['encoding'] = 'Codificação desconhecida: '; +$PHPMAILER_LANG['execute'] = 'Não foi possível executar: '; +$PHPMAILER_LANG['extension_missing'] = 'Extensão não existe: '; +$PHPMAILER_LANG['file_access'] = 'Não foi possível acessar o arquivo: '; +$PHPMAILER_LANG['file_open'] = 'Erro de Arquivo: Não foi possível abrir o arquivo: '; +$PHPMAILER_LANG['from_failed'] = 'Os seguintes remetentes falharam: '; +$PHPMAILER_LANG['instantiate'] = 'Não foi possível instanciar a função mail.'; +$PHPMAILER_LANG['invalid_address'] = 'Endereço de e-mail inválido: '; +$PHPMAILER_LANG['invalid_header'] = 'Nome ou valor de cabeçalho inválido'; +$PHPMAILER_LANG['invalid_hostentry'] = 'hostentry inválido: '; +$PHPMAILER_LANG['invalid_host'] = 'host inválido: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer não é suportado.'; +$PHPMAILER_LANG['provide_address'] = 'Você deve informar pelo menos um destinatário.'; +$PHPMAILER_LANG['recipients_failed'] = 'Erro de SMTP: Os seguintes destinatários falharam: '; +$PHPMAILER_LANG['signing'] = 'Erro de Assinatura: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() falhou.'; +$PHPMAILER_LANG['smtp_code'] = 'Código do servidor SMTP: '; +$PHPMAILER_LANG['smtp_error'] = 'Erro de servidor SMTP: '; +$PHPMAILER_LANG['smtp_code_ex'] = 'Informações adicionais do servidor SMTP: '; +$PHPMAILER_LANG['smtp_detail'] = 'Detalhes do servidor SMTP: '; +$PHPMAILER_LANG['variable_set'] = 'Não foi possível definir ou redefinir a variável: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ro.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ro.php new file mode 100644 index 00000000..45bef915 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ro.php @@ -0,0 +1,33 @@ + + * @author Foster Snowhill + * @author ProjectSoft + */ + +$PHPMAILER_LANG['authenticate'] = 'Ошибка SMTP: не удалось пройти аутентификацию.'; +$PHPMAILER_LANG['buggy_php'] = 'В вашей версии PHP есть ошибка, которая может привести к повреждению сообщений. Чтобы исправить, переключитесь на отправку по SMTP, отключите опцию mail.add_x_header в ваш php.ini, переключитесь на MacOS или Linux или обновите PHP до версии 7.0.17+ или 7.1.3+.'; +$PHPMAILER_LANG['connect_host'] = 'Ошибка SMTP: не удается подключиться к SMTP-серверу.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Ошибка SMTP: данные не приняты.'; +$PHPMAILER_LANG['empty_message'] = 'Пустое сообщение'; +$PHPMAILER_LANG['encoding'] = 'Неизвестная кодировка: '; +$PHPMAILER_LANG['execute'] = 'Невозможно выполнить команду: '; +$PHPMAILER_LANG['extension_missing'] = 'Расширение отсутствует: '; +$PHPMAILER_LANG['file_access'] = 'Нет доступа к файлу: '; +$PHPMAILER_LANG['file_open'] = 'Файловая ошибка: не удаётся открыть файл: '; +$PHPMAILER_LANG['from_failed'] = 'Неверный адрес отправителя: '; +$PHPMAILER_LANG['instantiate'] = 'Невозможно запустить функцию mail().'; +$PHPMAILER_LANG['invalid_address'] = 'Не отправлено из-за неправильного формата email-адреса: '; +$PHPMAILER_LANG['invalid_header'] = 'Неверное имя или значение заголовка'; +$PHPMAILER_LANG['invalid_hostentry'] = 'Неверная запись хоста: '; +$PHPMAILER_LANG['invalid_host'] = 'Неверный хост: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' — почтовый сервер не поддерживается.'; +$PHPMAILER_LANG['provide_address'] = 'Вы должны указать хотя бы один адрес электронной почты получателя.'; +$PHPMAILER_LANG['recipients_failed'] = 'Ошибка SMTP: Ошибка следующих получателей: '; +$PHPMAILER_LANG['signing'] = 'Ошибка подписи: '; +$PHPMAILER_LANG['smtp_code'] = 'Код SMTP: '; +$PHPMAILER_LANG['smtp_code_ex'] = 'Дополнительная информация SMTP: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Ошибка соединения с SMTP-сервером.'; +$PHPMAILER_LANG['smtp_detail'] = 'Детали: '; +$PHPMAILER_LANG['smtp_error'] = 'Ошибка SMTP-сервера: '; +$PHPMAILER_LANG['variable_set'] = 'Невозможно установить или сбросить переменную: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-si.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-si.php new file mode 100644 index 00000000..dce502aa --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-si.php @@ -0,0 +1,34 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP දෝෂය: සත්‍යාපනය අසාර්ථක විය.'; +$PHPMAILER_LANG['buggy_php'] = 'ඔබගේ PHP version එකෙහි පවතින දෝෂයක් නිසා email පණිවිඩ දෝෂ සහගත වීමේ හැකියාවක් ඇත. මෙය විසදීම සදහා SMTP භාවිතා කිරීම, mail.add_x_header INI setting එක අක්‍රීය කිරීම, MacOS හෝ Linux වලට මාරු වීම, හෝ ඔබගේ PHP version එක 7.0.17+ හෝ 7.1.3+ වලට අලුත් කිරීම කරගන්න.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP දෝෂය: සම්බන්ධ වීමට නොහැකි විය.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP දෝෂය: දත්ත පිළිගනු නොලැබේ.'; +$PHPMAILER_LANG['empty_message'] = 'පණිවිඩ අන්තර්ගතය හිස්'; +$PHPMAILER_LANG['encoding'] = 'නොදන්නා කේතනය: '; +$PHPMAILER_LANG['execute'] = 'ක්‍රියාත්මක කළ නොහැකි විය: '; +$PHPMAILER_LANG['extension_missing'] = 'Extension එක නොමැත: '; +$PHPMAILER_LANG['file_access'] = 'File එකට ප්‍රවේශ විය නොහැකි විය: '; +$PHPMAILER_LANG['file_open'] = 'File දෝෂය: File එක විවෘත කළ නොහැක: '; +$PHPMAILER_LANG['from_failed'] = 'පහත From ලිපිනයන් අසාර්ථක විය: '; +$PHPMAILER_LANG['instantiate'] = 'mail function එක ක්‍රියාත්මක කළ නොහැක.'; +$PHPMAILER_LANG['invalid_address'] = 'වලංගු නොවන ලිපිනය: '; +$PHPMAILER_LANG['invalid_header'] = 'වලංගු නොවන header නාමයක් හෝ අගයක්'; +$PHPMAILER_LANG['invalid_hostentry'] = 'වලංගු නොවන hostentry එකක්: '; +$PHPMAILER_LANG['invalid_host'] = 'වලංගු නොවන host එකක්: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer සහාය නොදක්වයි.'; +$PHPMAILER_LANG['provide_address'] = 'ඔබ අවම වශයෙන් එක් ලබන්නෙකුගේ ඊමේල් ලිපිනයක් සැපයිය යුතුය.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP දෝෂය: පහත ලබන්නන් අසමත් විය: '; +$PHPMAILER_LANG['signing'] = 'Sign කිරීමේ දෝෂය: '; +$PHPMAILER_LANG['smtp_code'] = 'SMTP කේතය: '; +$PHPMAILER_LANG['smtp_code_ex'] = 'අමතර SMTP තොරතුරු: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP සම්බන්ධය අසාර්ථක විය.'; +$PHPMAILER_LANG['smtp_detail'] = 'තොරතුරු: '; +$PHPMAILER_LANG['smtp_error'] = 'SMTP දෝෂය: '; +$PHPMAILER_LANG['variable_set'] = 'Variable එක සැකසීමට හෝ නැවත සැකසීමට නොහැක: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-sk.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-sk.php new file mode 100644 index 00000000..028f5bc4 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-sk.php @@ -0,0 +1,30 @@ + + * @author Peter Orlický + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP Error: Chyba autentifikácie.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Error: Nebolo možné nadviazať spojenie so SMTP serverom.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP Error: Dáta neboli prijaté'; +$PHPMAILER_LANG['empty_message'] = 'Prázdne telo správy.'; +$PHPMAILER_LANG['encoding'] = 'Neznáme kódovanie: '; +$PHPMAILER_LANG['execute'] = 'Nedá sa vykonať: '; +$PHPMAILER_LANG['file_access'] = 'Súbor nebol nájdený: '; +$PHPMAILER_LANG['file_open'] = 'File Error: Súbor sa otvoriť pre čítanie: '; +$PHPMAILER_LANG['from_failed'] = 'Následujúca adresa From je nesprávna: '; +$PHPMAILER_LANG['instantiate'] = 'Nedá sa vytvoriť inštancia emailovej funkcie.'; +$PHPMAILER_LANG['invalid_address'] = 'Neodoslané, emailová adresa je nesprávna: '; +$PHPMAILER_LANG['invalid_hostentry'] = 'Záznam hostiteľa je nesprávny: '; +$PHPMAILER_LANG['invalid_host'] = 'Hostiteľ je nesprávny: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' emailový klient nieje podporovaný.'; +$PHPMAILER_LANG['provide_address'] = 'Musíte zadať aspoň jednu emailovú adresu príjemcu.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Error: Adresy príjemcov niesu správne '; +$PHPMAILER_LANG['signing'] = 'Chyba prihlasovania: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() zlyhalo.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP chyba serveru: '; +$PHPMAILER_LANG['variable_set'] = 'Nemožno nastaviť alebo resetovať premennú: '; +$PHPMAILER_LANG['extension_missing'] = 'Chýba rozšírenie: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-sl.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-sl.php new file mode 100644 index 00000000..3e00c259 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-sl.php @@ -0,0 +1,36 @@ + + * @author Filip Š + * @author Blaž Oražem + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP napaka: Avtentikacija ni uspela.'; +$PHPMAILER_LANG['buggy_php'] = 'Na vašo PHP različico vpliva napaka, ki lahko povzroči poškodovana sporočila. Če želite težavo odpraviti, preklopite na pošiljanje prek SMTP, onemogočite možnost mail.add_x_header v vaši php.ini datoteki, preklopite na MacOS ali Linux, ali nadgradite vašo PHP zaličico na 7.0.17+ ali 7.1.3+.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP napaka: Vzpostavljanje povezave s SMTP gostiteljem ni uspelo.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP napaka: Strežnik zavrača podatke.'; +$PHPMAILER_LANG['empty_message'] = 'E-poštno sporočilo nima vsebine.'; +$PHPMAILER_LANG['encoding'] = 'Nepoznan tip kodiranja: '; +$PHPMAILER_LANG['execute'] = 'Operacija ni uspela: '; +$PHPMAILER_LANG['extension_missing'] = 'Manjkajoča razširitev: '; +$PHPMAILER_LANG['file_access'] = 'Nimam dostopa do datoteke: '; +$PHPMAILER_LANG['file_open'] = 'Ne morem odpreti datoteke: '; +$PHPMAILER_LANG['from_failed'] = 'Neveljaven e-naslov pošiljatelja: '; +$PHPMAILER_LANG['instantiate'] = 'Ne morem inicializirati mail funkcije.'; +$PHPMAILER_LANG['invalid_address'] = 'E-poštno sporočilo ni bilo poslano. E-naslov je neveljaven: '; +$PHPMAILER_LANG['invalid_header'] = 'Neveljavno ime ali vrednost glave'; +$PHPMAILER_LANG['invalid_hostentry'] = 'Neveljaven vnos gostitelja: '; +$PHPMAILER_LANG['invalid_host'] = 'Neveljaven gostitelj: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer ni podprt.'; +$PHPMAILER_LANG['provide_address'] = 'Prosimo, vnesite vsaj enega naslovnika.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP napaka: Sledeči naslovniki so neveljavni: '; +$PHPMAILER_LANG['signing'] = 'Napaka pri podpisovanju: '; +$PHPMAILER_LANG['smtp_code'] = 'SMTP koda: '; +$PHPMAILER_LANG['smtp_code_ex'] = 'Dodatne informacije o SMTP: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Ne morem vzpostaviti povezave s SMTP strežnikom.'; +$PHPMAILER_LANG['smtp_detail'] = 'Podrobnosti: '; +$PHPMAILER_LANG['smtp_error'] = 'Napaka SMTP strežnika: '; +$PHPMAILER_LANG['variable_set'] = 'Ne morem nastaviti oz. ponastaviti spremenljivke: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-sr.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-sr.php new file mode 100644 index 00000000..0b5280f7 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-sr.php @@ -0,0 +1,28 @@ + + * @author Miloš Milanović + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP грешка: аутентификација није успела.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP грешка: повезивање са SMTP сервером није успело.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP грешка: подаци нису прихваћени.'; +$PHPMAILER_LANG['empty_message'] = 'Садржај поруке је празан.'; +$PHPMAILER_LANG['encoding'] = 'Непознато кодирање: '; +$PHPMAILER_LANG['execute'] = 'Није могуће извршити наредбу: '; +$PHPMAILER_LANG['file_access'] = 'Није могуће приступити датотеци: '; +$PHPMAILER_LANG['file_open'] = 'Није могуће отворити датотеку: '; +$PHPMAILER_LANG['from_failed'] = 'SMTP грешка: слање са следећих адреса није успело: '; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP грешка: слање на следеће адресе није успело: '; +$PHPMAILER_LANG['instantiate'] = 'Није могуће покренути mail функцију.'; +$PHPMAILER_LANG['invalid_address'] = 'Порука није послата. Неисправна адреса: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' мејлер није подржан.'; +$PHPMAILER_LANG['provide_address'] = 'Дефинишите бар једну адресу примаоца.'; +$PHPMAILER_LANG['signing'] = 'Грешка приликом пријаве: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Повезивање са SMTP сервером није успело.'; +$PHPMAILER_LANG['smtp_error'] = 'Грешка SMTP сервера: '; +$PHPMAILER_LANG['variable_set'] = 'Није могуће задати нити ресетовати променљиву: '; +$PHPMAILER_LANG['extension_missing'] = 'Недостаје проширење: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-sr_latn.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-sr_latn.php new file mode 100644 index 00000000..62138329 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-sr_latn.php @@ -0,0 +1,28 @@ + + * @author Miloš Milanović + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP greška: autentifikacija nije uspela.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP greška: povezivanje sa SMTP serverom nije uspelo.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP greška: podaci nisu prihvaćeni.'; +$PHPMAILER_LANG['empty_message'] = 'Sadržaj poruke je prazan.'; +$PHPMAILER_LANG['encoding'] = 'Nepoznato kodiranje: '; +$PHPMAILER_LANG['execute'] = 'Nije moguće izvršiti naredbu: '; +$PHPMAILER_LANG['file_access'] = 'Nije moguće pristupiti datoteci: '; +$PHPMAILER_LANG['file_open'] = 'Nije moguće otvoriti datoteku: '; +$PHPMAILER_LANG['from_failed'] = 'SMTP greška: slanje sa sledećih adresa nije uspelo: '; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP greška: slanje na sledeće adrese nije uspelo: '; +$PHPMAILER_LANG['instantiate'] = 'Nije moguće pokrenuti mail funkciju.'; +$PHPMAILER_LANG['invalid_address'] = 'Poruka nije poslata. Neispravna adresa: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' majler nije podržan.'; +$PHPMAILER_LANG['provide_address'] = 'Definišite bar jednu adresu primaoca.'; +$PHPMAILER_LANG['signing'] = 'Greška prilikom prijave: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Povezivanje sa SMTP serverom nije uspelo.'; +$PHPMAILER_LANG['smtp_error'] = 'Greška SMTP servera: '; +$PHPMAILER_LANG['variable_set'] = 'Nije moguće zadati niti resetovati promenljivu: '; +$PHPMAILER_LANG['extension_missing'] = 'Nedostaje proširenje: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-sv.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-sv.php new file mode 100644 index 00000000..9872c192 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-sv.php @@ -0,0 +1,27 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP fel: Kunde inte autentisera.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP fel: Kunde inte ansluta till SMTP-server.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP fel: Data accepterades inte.'; +//$PHPMAILER_LANG['empty_message'] = 'Message body empty'; +$PHPMAILER_LANG['encoding'] = 'Okänt encode-format: '; +$PHPMAILER_LANG['execute'] = 'Kunde inte köra: '; +$PHPMAILER_LANG['file_access'] = 'Ingen åtkomst till fil: '; +$PHPMAILER_LANG['file_open'] = 'Fil fel: Kunde inte öppna fil: '; +$PHPMAILER_LANG['from_failed'] = 'Följande avsändaradress är felaktig: '; +$PHPMAILER_LANG['instantiate'] = 'Kunde inte initiera e-postfunktion.'; +$PHPMAILER_LANG['invalid_address'] = 'Felaktig adress: '; +$PHPMAILER_LANG['provide_address'] = 'Du måste ange minst en mottagares e-postadress.'; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer stöds inte.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP fel: Följande mottagare är felaktig: '; +$PHPMAILER_LANG['signing'] = 'Signeringsfel: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() misslyckades.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP serverfel: '; +$PHPMAILER_LANG['variable_set'] = 'Kunde inte definiera eller återställa variabel: '; +$PHPMAILER_LANG['extension_missing'] = 'Tillägg ej tillgängligt: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-tl.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-tl.php new file mode 100644 index 00000000..d15bed1c --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-tl.php @@ -0,0 +1,28 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP Error: Hindi mapatotohanan.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP Error: Hindi makakonekta sa SMTP host.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP Error: Ang datos ay hindi naitanggap.'; +$PHPMAILER_LANG['empty_message'] = 'Walang laman ang mensahe'; +$PHPMAILER_LANG['encoding'] = 'Hindi alam ang encoding: '; +$PHPMAILER_LANG['execute'] = 'Hindi maisasagawa: '; +$PHPMAILER_LANG['file_access'] = 'Hindi ma-access ang file: '; +$PHPMAILER_LANG['file_open'] = 'File Error: Hindi mabuksan ang file: '; +$PHPMAILER_LANG['from_failed'] = 'Ang sumusunod na address ay nabigo: '; +$PHPMAILER_LANG['instantiate'] = 'Hindi maisimulan ang instance ng mail function.'; +$PHPMAILER_LANG['invalid_address'] = 'Hindi wasto ang address na naibigay: '; +$PHPMAILER_LANG['mailer_not_supported'] = 'Ang mailer ay hindi suportado.'; +$PHPMAILER_LANG['provide_address'] = 'Kailangan mong magbigay ng kahit isang email address na tatanggap.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP Error: Ang mga sumusunod na tatanggap ay nabigo: '; +$PHPMAILER_LANG['signing'] = 'Hindi ma-sign: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Ang SMTP connect() ay nabigo.'; +$PHPMAILER_LANG['smtp_error'] = 'Ang server ng SMTP ay nabigo: '; +$PHPMAILER_LANG['variable_set'] = 'Hindi matatakda o ma-reset ang mga variables: '; +$PHPMAILER_LANG['extension_missing'] = 'Nawawala ang extension: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-tr.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-tr.php new file mode 100644 index 00000000..3c45bc1c --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-tr.php @@ -0,0 +1,38 @@ + + * @fixed by Boris Yurchenko + */ + +$PHPMAILER_LANG['authenticate'] = 'Помилка SMTP: помилка авторизації.'; +$PHPMAILER_LANG['connect_host'] = 'Помилка SMTP: не вдається під\'єднатися до SMTP-серверу.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Помилка SMTP: дані не прийнято.'; +$PHPMAILER_LANG['encoding'] = 'Невідоме кодування: '; +$PHPMAILER_LANG['execute'] = 'Неможливо виконати команду: '; +$PHPMAILER_LANG['file_access'] = 'Немає доступу до файлу: '; +$PHPMAILER_LANG['file_open'] = 'Помилка файлової системи: не вдається відкрити файл: '; +$PHPMAILER_LANG['from_failed'] = 'Невірна адреса відправника: '; +$PHPMAILER_LANG['instantiate'] = 'Неможливо запустити функцію mail().'; +$PHPMAILER_LANG['provide_address'] = 'Будь ласка, введіть хоча б одну email-адресу отримувача.'; +$PHPMAILER_LANG['mailer_not_supported'] = ' - поштовий сервер не підтримується.'; +$PHPMAILER_LANG['recipients_failed'] = 'Помилка SMTP: не вдалося відправлення для таких отримувачів: '; +$PHPMAILER_LANG['empty_message'] = 'Пусте повідомлення'; +$PHPMAILER_LANG['invalid_address'] = 'Не відправлено через неправильний формат email-адреси: '; +$PHPMAILER_LANG['signing'] = 'Помилка підпису: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Помилка з\'єднання з SMTP-сервером'; +$PHPMAILER_LANG['smtp_error'] = 'Помилка SMTP-сервера: '; +$PHPMAILER_LANG['variable_set'] = 'Неможливо встановити або скинути змінну: '; +$PHPMAILER_LANG['extension_missing'] = 'Розширення відсутнє: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ur.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ur.php new file mode 100644 index 00000000..0b9de0f1 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-ur.php @@ -0,0 +1,30 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP خرابی: تصدیق کرنے سے قاصر۔'; +$PHPMAILER_LANG['connect_host'] = 'SMTP خرابی: سرور سے منسلک ہونے سے قاصر۔'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP خرابی: ڈیٹا قبول نہیں کیا گیا۔'; +$PHPMAILER_LANG['empty_message'] = 'پیغام کی باڈی خالی ہے۔'; +$PHPMAILER_LANG['encoding'] = 'نامعلوم انکوڈنگ: '; +$PHPMAILER_LANG['execute'] = 'عمل کرنے کے قابل نہیں '; +$PHPMAILER_LANG['file_access'] = 'فائل تک رسائی سے قاصر:'; +$PHPMAILER_LANG['file_open'] = 'فائل کی خرابی: فائل کو کھولنے سے قاصر:'; +$PHPMAILER_LANG['from_failed'] = 'درج ذیل بھیجنے والے کا پتہ ناکام ہو گیا:'; +$PHPMAILER_LANG['instantiate'] = 'میل فنکشن کی مثال بنانے سے قاصر۔'; +$PHPMAILER_LANG['invalid_address'] = 'بھیجنے سے قاصر: غلط ای میل پتہ:'; +$PHPMAILER_LANG['mailer_not_supported'] = ' میلر تعاون یافتہ نہیں ہے۔'; +$PHPMAILER_LANG['provide_address'] = 'آپ کو کم از کم ایک منزل کا ای میل پتہ فراہم کرنا چاہیے۔'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP خرابی: درج ذیل پتہ پر نہیں بھیجا جاسکا: '; +$PHPMAILER_LANG['signing'] = 'دستخط کی خرابی: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP ملنا ناکام ہوا'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP سرور کی خرابی: '; +$PHPMAILER_LANG['variable_set'] = 'متغیر سیٹ نہیں کیا جا سکا: '; +$PHPMAILER_LANG['extension_missing'] = 'ایکٹینشن موجود نہیں ہے۔ '; +$PHPMAILER_LANG['smtp_code'] = 'SMTP سرور کوڈ: '; +$PHPMAILER_LANG['smtp_code_ex'] = 'اضافی SMTP سرور کی معلومات:'; +$PHPMAILER_LANG['invalid_header'] = 'غلط ہیڈر کا نام یا قدر'; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-vi.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-vi.php new file mode 100644 index 00000000..d65576e2 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-vi.php @@ -0,0 +1,27 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'Lỗi SMTP: Không thể xác thực.'; +$PHPMAILER_LANG['connect_host'] = 'Lỗi SMTP: Không thể kết nối máy chủ SMTP.'; +$PHPMAILER_LANG['data_not_accepted'] = 'Lỗi SMTP: Dữ liệu không được chấp nhận.'; +$PHPMAILER_LANG['empty_message'] = 'Không có nội dung'; +$PHPMAILER_LANG['encoding'] = 'Mã hóa không xác định: '; +$PHPMAILER_LANG['execute'] = 'Không thực hiện được: '; +$PHPMAILER_LANG['file_access'] = 'Không thể truy cập tệp tin '; +$PHPMAILER_LANG['file_open'] = 'Lỗi Tập tin: Không thể mở tệp tin: '; +$PHPMAILER_LANG['from_failed'] = 'Lỗi địa chỉ gửi đi: '; +$PHPMAILER_LANG['instantiate'] = 'Không dùng được các hàm gửi thư.'; +$PHPMAILER_LANG['invalid_address'] = 'Đại chỉ emai không đúng: '; +$PHPMAILER_LANG['mailer_not_supported'] = ' trình gửi thư không được hỗ trợ.'; +$PHPMAILER_LANG['provide_address'] = 'Bạn phải cung cấp ít nhất một địa chỉ người nhận.'; +$PHPMAILER_LANG['recipients_failed'] = 'Lỗi SMTP: lỗi địa chỉ người nhận: '; +$PHPMAILER_LANG['signing'] = 'Lỗi đăng nhập: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'Lỗi kết nối với SMTP'; +$PHPMAILER_LANG['smtp_error'] = 'Lỗi máy chủ smtp '; +$PHPMAILER_LANG['variable_set'] = 'Không thể thiết lập hoặc thiết lập lại biến: '; +//$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-zh.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-zh.php new file mode 100644 index 00000000..35e4e700 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-zh.php @@ -0,0 +1,29 @@ + + * @author Peter Dave Hello <@PeterDaveHello/> + * @author Jason Chiang + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP 錯誤:登入失敗。'; +$PHPMAILER_LANG['connect_host'] = 'SMTP 錯誤:無法連線到 SMTP 主機。'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP 錯誤:無法接受的資料。'; +$PHPMAILER_LANG['empty_message'] = '郵件內容為空'; +$PHPMAILER_LANG['encoding'] = '未知編碼: '; +$PHPMAILER_LANG['execute'] = '無法執行:'; +$PHPMAILER_LANG['file_access'] = '無法存取檔案:'; +$PHPMAILER_LANG['file_open'] = '檔案錯誤:無法開啟檔案:'; +$PHPMAILER_LANG['from_failed'] = '發送地址錯誤:'; +$PHPMAILER_LANG['instantiate'] = '未知函數呼叫。'; +$PHPMAILER_LANG['invalid_address'] = '因為電子郵件地址無效,無法傳送: '; +$PHPMAILER_LANG['mailer_not_supported'] = '不支援的發信客戶端。'; +$PHPMAILER_LANG['provide_address'] = '必須提供至少一個收件人地址。'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP 錯誤:以下收件人地址錯誤:'; +$PHPMAILER_LANG['signing'] = '電子簽章錯誤: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP 連線失敗'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP 伺服器錯誤: '; +$PHPMAILER_LANG['variable_set'] = '無法設定或重設變數: '; +$PHPMAILER_LANG['extension_missing'] = '遺失模組 Extension: '; diff --git a/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-zh_cn.php b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-zh_cn.php new file mode 100644 index 00000000..03d49116 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/language/phpmailer.lang-zh_cn.php @@ -0,0 +1,36 @@ + + * @author young + * @author Teddysun + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP 错误:登录失败。'; +$PHPMAILER_LANG['buggy_php'] = '您的 PHP 版本存在漏洞,可能会导致消息损坏。为修复此问题,请切换到使用 SMTP 发送,在您的 php.ini 中禁用 mail.add_x_header 选项。切换到 MacOS 或 Linux,或将您的 PHP 升级到 7.0.17+ 或 7.1.3+ 版本。'; +$PHPMAILER_LANG['connect_host'] = 'SMTP 错误:无法连接到 SMTP 主机。'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP 错误:数据不被接受。'; +$PHPMAILER_LANG['empty_message'] = '邮件正文为空。'; +$PHPMAILER_LANG['encoding'] = '未知编码:'; +$PHPMAILER_LANG['execute'] = '无法执行:'; +$PHPMAILER_LANG['extension_missing'] = '缺少扩展名:'; +$PHPMAILER_LANG['file_access'] = '无法访问文件:'; +$PHPMAILER_LANG['file_open'] = '文件错误:无法打开文件:'; +$PHPMAILER_LANG['from_failed'] = '发送地址错误:'; +$PHPMAILER_LANG['instantiate'] = '未知函数调用。'; +$PHPMAILER_LANG['invalid_address'] = '发送失败,电子邮箱地址是无效的:'; +$PHPMAILER_LANG['mailer_not_supported'] = '发信客户端不被支持。'; +$PHPMAILER_LANG['provide_address'] = '必须提供至少一个收件人地址。'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP 错误:收件人地址错误:'; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP服务器连接失败。'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP服务器出错:'; +$PHPMAILER_LANG['variable_set'] = '无法设置或重置变量:'; +$PHPMAILER_LANG['invalid_header'] = '无效的标题名称或值'; +$PHPMAILER_LANG['invalid_hostentry'] = '无效的hostentry: '; +$PHPMAILER_LANG['invalid_host'] = '无效的主机:'; +$PHPMAILER_LANG['signing'] = '签名错误:'; +$PHPMAILER_LANG['smtp_code'] = 'SMTP代码: '; +$PHPMAILER_LANG['smtp_code_ex'] = '附加SMTP信息: '; +$PHPMAILER_LANG['smtp_detail'] = '详情:'; diff --git a/api/vendor/phpmailer/phpmailer/src/DSNConfigurator.php b/api/vendor/phpmailer/phpmailer/src/DSNConfigurator.php new file mode 100644 index 00000000..7058c1f0 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/src/DSNConfigurator.php @@ -0,0 +1,245 @@ + + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2023 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +namespace PHPMailer\PHPMailer; + +/** + * Configure PHPMailer with DSN string. + * + * @see https://en.wikipedia.org/wiki/Data_source_name + * + * @author Oleg Voronkovich + */ +class DSNConfigurator +{ + /** + * Create new PHPMailer instance configured by DSN. + * + * @param string $dsn DSN + * @param bool $exceptions Should we throw external exceptions? + * + * @return PHPMailer + */ + public static function mailer($dsn, $exceptions = null) + { + static $configurator = null; + + if (null === $configurator) { + $configurator = new DSNConfigurator(); + } + + return $configurator->configure(new PHPMailer($exceptions), $dsn); + } + + /** + * Configure PHPMailer instance with DSN string. + * + * @param PHPMailer $mailer PHPMailer instance + * @param string $dsn DSN + * + * @return PHPMailer + */ + public function configure(PHPMailer $mailer, $dsn) + { + $config = $this->parseDSN($dsn); + + $this->applyConfig($mailer, $config); + + return $mailer; + } + + /** + * Parse DSN string. + * + * @param string $dsn DSN + * + * @throws Exception If DSN is malformed + * + * @return array Configuration + */ + private function parseDSN($dsn) + { + $config = $this->parseUrl($dsn); + + if (false === $config || !isset($config['scheme']) || !isset($config['host'])) { + throw new Exception('Malformed DSN'); + } + + if (isset($config['query'])) { + parse_str($config['query'], $config['query']); + } + + return $config; + } + + /** + * Apply configuration to mailer. + * + * @param PHPMailer $mailer PHPMailer instance + * @param array $config Configuration + * + * @throws Exception If scheme is invalid + */ + private function applyConfig(PHPMailer $mailer, $config) + { + switch ($config['scheme']) { + case 'mail': + $mailer->isMail(); + break; + case 'sendmail': + $mailer->isSendmail(); + break; + case 'qmail': + $mailer->isQmail(); + break; + case 'smtp': + case 'smtps': + $mailer->isSMTP(); + $this->configureSMTP($mailer, $config); + break; + default: + throw new Exception( + sprintf( + 'Invalid scheme: "%s". Allowed values: "mail", "sendmail", "qmail", "smtp", "smtps".', + $config['scheme'] + ) + ); + } + + if (isset($config['query'])) { + $this->configureOptions($mailer, $config['query']); + } + } + + /** + * Configure SMTP. + * + * @param PHPMailer $mailer PHPMailer instance + * @param array $config Configuration + */ + private function configureSMTP($mailer, $config) + { + $isSMTPS = 'smtps' === $config['scheme']; + + if ($isSMTPS) { + $mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; + } + + $mailer->Host = $config['host']; + + if (isset($config['port'])) { + $mailer->Port = $config['port']; + } elseif ($isSMTPS) { + $mailer->Port = SMTP::DEFAULT_SECURE_PORT; + } + + $mailer->SMTPAuth = isset($config['user']) || isset($config['pass']); + + if (isset($config['user'])) { + $mailer->Username = $config['user']; + } + + if (isset($config['pass'])) { + $mailer->Password = $config['pass']; + } + } + + /** + * Configure options. + * + * @param PHPMailer $mailer PHPMailer instance + * @param array $options Options + * + * @throws Exception If option is unknown + */ + private function configureOptions(PHPMailer $mailer, $options) + { + $allowedOptions = get_object_vars($mailer); + + unset($allowedOptions['Mailer']); + unset($allowedOptions['SMTPAuth']); + unset($allowedOptions['Username']); + unset($allowedOptions['Password']); + unset($allowedOptions['Hostname']); + unset($allowedOptions['Port']); + unset($allowedOptions['ErrorInfo']); + + $allowedOptions = \array_keys($allowedOptions); + + foreach ($options as $key => $value) { + if (!in_array($key, $allowedOptions)) { + throw new Exception( + sprintf( + 'Unknown option: "%s". Allowed values: "%s"', + $key, + implode('", "', $allowedOptions) + ) + ); + } + + switch ($key) { + case 'AllowEmpty': + case 'SMTPAutoTLS': + case 'SMTPKeepAlive': + case 'SingleTo': + case 'UseSendmailOptions': + case 'do_verp': + case 'DKIM_copyHeaderFields': + $mailer->$key = (bool) $value; + break; + case 'Priority': + case 'SMTPDebug': + case 'WordWrap': + $mailer->$key = (int) $value; + break; + default: + $mailer->$key = $value; + break; + } + } + } + + /** + * Parse a URL. + * Wrapper for the built-in parse_url function to work around a bug in PHP 5.5. + * + * @param string $url URL + * + * @return array|false + */ + protected function parseUrl($url) + { + if (\PHP_VERSION_ID >= 50600 || false === strpos($url, '?')) { + return parse_url($url); + } + + $chunks = explode('?', $url); + if (is_array($chunks)) { + $result = parse_url($chunks[0]); + if (is_array($result)) { + $result['query'] = $chunks[1]; + } + return $result; + } + + return false; + } +} diff --git a/api/vendor/phpmailer/phpmailer/src/Exception.php b/api/vendor/phpmailer/phpmailer/src/Exception.php new file mode 100644 index 00000000..09c1a2cf --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/src/Exception.php @@ -0,0 +1,40 @@ + + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2020 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +namespace PHPMailer\PHPMailer; + +/** + * PHPMailer exception handler. + * + * @author Marcus Bointon + */ +class Exception extends \Exception +{ + /** + * Prettify error message output. + * + * @return string + */ + public function errorMessage() + { + return '' . htmlspecialchars($this->getMessage(), ENT_COMPAT | ENT_HTML401) . "
\n"; + } +} diff --git a/api/vendor/phpmailer/phpmailer/src/OAuth.php b/api/vendor/phpmailer/phpmailer/src/OAuth.php new file mode 100644 index 00000000..a7e95886 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/src/OAuth.php @@ -0,0 +1,139 @@ + + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2020 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +namespace PHPMailer\PHPMailer; + +use League\OAuth2\Client\Grant\RefreshToken; +use League\OAuth2\Client\Provider\AbstractProvider; +use League\OAuth2\Client\Token\AccessToken; + +/** + * OAuth - OAuth2 authentication wrapper class. + * Uses the oauth2-client package from the League of Extraordinary Packages. + * + * @see https://oauth2-client.thephpleague.com + * + * @author Marcus Bointon (Synchro/coolbru) + */ +class OAuth implements OAuthTokenProvider +{ + /** + * An instance of the League OAuth Client Provider. + * + * @var AbstractProvider + */ + protected $provider; + + /** + * The current OAuth access token. + * + * @var AccessToken + */ + protected $oauthToken; + + /** + * The user's email address, usually used as the login ID + * and also the from address when sending email. + * + * @var string + */ + protected $oauthUserEmail = ''; + + /** + * The client secret, generated in the app definition of the service you're connecting to. + * + * @var string + */ + protected $oauthClientSecret = ''; + + /** + * The client ID, generated in the app definition of the service you're connecting to. + * + * @var string + */ + protected $oauthClientId = ''; + + /** + * The refresh token, used to obtain new AccessTokens. + * + * @var string + */ + protected $oauthRefreshToken = ''; + + /** + * OAuth constructor. + * + * @param array $options Associative array containing + * `provider`, `userName`, `clientSecret`, `clientId` and `refreshToken` elements + */ + public function __construct($options) + { + $this->provider = $options['provider']; + $this->oauthUserEmail = $options['userName']; + $this->oauthClientSecret = $options['clientSecret']; + $this->oauthClientId = $options['clientId']; + $this->oauthRefreshToken = $options['refreshToken']; + } + + /** + * Get a new RefreshToken. + * + * @return RefreshToken + */ + protected function getGrant() + { + return new RefreshToken(); + } + + /** + * Get a new AccessToken. + * + * @return AccessToken + */ + protected function getToken() + { + return $this->provider->getAccessToken( + $this->getGrant(), + ['refresh_token' => $this->oauthRefreshToken] + ); + } + + /** + * Generate a base64-encoded OAuth token. + * + * @return string + */ + public function getOauth64() + { + //Get a new token if it's not available or has expired + if (null === $this->oauthToken || $this->oauthToken->hasExpired()) { + $this->oauthToken = $this->getToken(); + } + + return base64_encode( + 'user=' . + $this->oauthUserEmail . + "\001auth=Bearer " . + $this->oauthToken . + "\001\001" + ); + } +} diff --git a/api/vendor/phpmailer/phpmailer/src/OAuthTokenProvider.php b/api/vendor/phpmailer/phpmailer/src/OAuthTokenProvider.php new file mode 100644 index 00000000..cbda1a12 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/src/OAuthTokenProvider.php @@ -0,0 +1,44 @@ + + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2020 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +namespace PHPMailer\PHPMailer; + +/** + * OAuthTokenProvider - OAuth2 token provider interface. + * Provides base64 encoded OAuth2 auth strings for SMTP authentication. + * + * @see OAuth + * @see SMTP::authenticate() + * + * @author Peter Scopes (pdscopes) + * @author Marcus Bointon (Synchro/coolbru) + */ +interface OAuthTokenProvider +{ + /** + * Generate a base64-encoded OAuth token ensuring that the access token has not expired. + * The string to be base 64 encoded should be in the form: + * "user=\001auth=Bearer \001\001" + * + * @return string + */ + public function getOauth64(); +} diff --git a/api/vendor/phpmailer/phpmailer/src/PHPMailer.php b/api/vendor/phpmailer/phpmailer/src/PHPMailer.php new file mode 100644 index 00000000..4a6077c0 --- /dev/null +++ b/api/vendor/phpmailer/phpmailer/src/PHPMailer.php @@ -0,0 +1,5248 @@ + + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2020 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +namespace PHPMailer\PHPMailer; + +/** + * PHPMailer - PHP email creation and transport class. + * + * @author Marcus Bointon (Synchro/coolbru) + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + */ +class PHPMailer +{ + const CHARSET_ASCII = 'us-ascii'; + const CHARSET_ISO88591 = 'iso-8859-1'; + const CHARSET_UTF8 = 'utf-8'; + + const CONTENT_TYPE_PLAINTEXT = 'text/plain'; + const CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar'; + const CONTENT_TYPE_TEXT_HTML = 'text/html'; + const CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative'; + const CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed'; + const CONTENT_TYPE_MULTIPART_RELATED = 'multipart/related'; + + const ENCODING_7BIT = '7bit'; + const ENCODING_8BIT = '8bit'; + const ENCODING_BASE64 = 'base64'; + const ENCODING_BINARY = 'binary'; + const ENCODING_QUOTED_PRINTABLE = 'quoted-printable'; + + const ENCRYPTION_STARTTLS = 'tls'; + const ENCRYPTION_SMTPS = 'ssl'; + + const ICAL_METHOD_REQUEST = 'REQUEST'; + const ICAL_METHOD_PUBLISH = 'PUBLISH'; + const ICAL_METHOD_REPLY = 'REPLY'; + const ICAL_METHOD_ADD = 'ADD'; + const ICAL_METHOD_CANCEL = 'CANCEL'; + const ICAL_METHOD_REFRESH = 'REFRESH'; + const ICAL_METHOD_COUNTER = 'COUNTER'; + const ICAL_METHOD_DECLINECOUNTER = 'DECLINECOUNTER'; + + /** + * Email priority. + * Options: null (default), 1 = High, 3 = Normal, 5 = low. + * When null, the header is not set at all. + * + * @var int|null + */ + public $Priority; + + /** + * The character set of the message. + * + * @var string + */ + public $CharSet = self::CHARSET_ISO88591; + + /** + * The MIME Content-type of the message. + * + * @var string + */ + public $ContentType = self::CONTENT_TYPE_PLAINTEXT; + + /** + * The message encoding. + * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable". + * + * @var string + */ + public $Encoding = self::ENCODING_8BIT; + + /** + * Holds the most recent mailer error message. + * + * @var string + */ + public $ErrorInfo = ''; + + /** + * The From email address for the message. + * + * @var string + */ + public $From = ''; + + /** + * The From name of the message. + * + * @var string + */ + public $FromName = ''; + + /** + * The envelope sender of the message. + * This will usually be turned into a Return-Path header by the receiver, + * and is the address that bounces will be sent to. + * If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP. + * + * @var string + */ + public $Sender = ''; + + /** + * The Subject of the message. + * + * @var string + */ + public $Subject = ''; + + /** + * An HTML or plain text message body. + * If HTML then call isHTML(true). + * + * @var string + */ + public $Body = ''; + + /** + * The plain-text message body. + * This body can be read by mail clients that do not have HTML email + * capability such as mutt & Eudora. + * Clients that can read HTML will view the normal Body. + * + * @var string + */ + public $AltBody = ''; + + /** + * An iCal message part body. + * Only supported in simple alt or alt_inline message types + * To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator. + * + * @see https://kigkonsult.se/iCalcreator/ + * + * @var string + */ + public $Ical = ''; + + /** + * Value-array of "method" in Contenttype header "text/calendar" + * + * @var string[] + */ + protected static $IcalMethods = [ + self::ICAL_METHOD_REQUEST, + self::ICAL_METHOD_PUBLISH, + self::ICAL_METHOD_REPLY, + self::ICAL_METHOD_ADD, + self::ICAL_METHOD_CANCEL, + self::ICAL_METHOD_REFRESH, + self::ICAL_METHOD_COUNTER, + self::ICAL_METHOD_DECLINECOUNTER, + ]; + + /** + * The complete compiled MIME message body. + * + * @var string + */ + protected $MIMEBody = ''; + + /** + * The complete compiled MIME message headers. + * + * @var string + */ + protected $MIMEHeader = ''; + + /** + * Extra headers that createHeader() doesn't fold in. + * + * @var string + */ + protected $mailHeader = ''; + + /** + * Word-wrap the message body to this number of chars. + * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance. + * + * @see static::STD_LINE_LENGTH + * + * @var int + */ + public $WordWrap = 0; + + /** + * Which method to use to send mail. + * Options: "mail", "sendmail", or "smtp". + * + * @var string + */ + public $Mailer = 'mail'; + + /** + * The path to the sendmail program. + * + * @var string + */ + public $Sendmail = '/usr/sbin/sendmail'; + + /** + * Whether mail() uses a fully sendmail-compatible MTA. + * One which supports sendmail's "-oi -f" options. + * + * @var bool + */ + public $UseSendmailOptions = true; + + /** + * The email address that a reading confirmation should be sent to, also known as read receipt. + * + * @var string + */ + public $ConfirmReadingTo = ''; + + /** + * The hostname to use in the Message-ID header and as default HELO string. + * If empty, PHPMailer attempts to find one with, in order, + * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value + * 'localhost.localdomain'. + * + * @see PHPMailer::$Helo + * + * @var string + */ + public $Hostname = ''; + + /** + * An ID to be used in the Message-ID header. + * If empty, a unique id will be generated. + * You can set your own, but it must be in the format "", + * as defined in RFC5322 section 3.6.4 or it will be ignored. + * + * @see https://www.rfc-editor.org/rfc/rfc5322#section-3.6.4 + * + * @var string + */ + public $MessageID = ''; + + /** + * The message Date to be used in the Date header. + * If empty, the current date will be added. + * + * @var string + */ + public $MessageDate = ''; + + /** + * SMTP hosts. + * Either a single hostname or multiple semicolon-delimited hostnames. + * You can also specify a different port + * for each host by using this format: [hostname:port] + * (e.g. "smtp1.example.com:25;smtp2.example.com"). + * You can also specify encryption type, for example: + * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465"). + * Hosts will be tried in order. + * + * @var string + */ + public $Host = 'localhost'; + + /** + * The default SMTP server port. + * + * @var int + */ + public $Port = 25; + + /** + * The SMTP HELO/EHLO name used for the SMTP connection. + * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find + * one with the same method described above for $Hostname. + * + * @see PHPMailer::$Hostname + * + * @var string + */ + public $Helo = ''; + + /** + * What kind of encryption to use on the SMTP connection. + * Options: '', static::ENCRYPTION_STARTTLS, or static::ENCRYPTION_SMTPS. + * + * @var string + */ + public $SMTPSecure = ''; + + /** + * Whether to enable TLS encryption automatically if a server supports it, + * even if `SMTPSecure` is not set to 'tls'. + * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid. + * + * @var bool + */ + public $SMTPAutoTLS = true; + + /** + * Whether to use SMTP authentication. + * Uses the Username and Password properties. + * + * @see PHPMailer::$Username + * @see PHPMailer::$Password + * + * @var bool + */ + public $SMTPAuth = false; + + /** + * Options array passed to stream_context_create when connecting via SMTP. + * + * @var array + */ + public $SMTPOptions = []; + + /** + * SMTP username. + * + * @var string + */ + public $Username = ''; + + /** + * SMTP password. + * + * @var string + */ + public $Password = ''; + + /** + * SMTP authentication type. Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2. + * If not specified, the first one from that list that the server supports will be selected. + * + * @var string + */ + public $AuthType = ''; + + /** + * SMTP SMTPXClient command attributes + * + * @var array + */ + protected $SMTPXClient = []; + + /** + * An implementation of the PHPMailer OAuthTokenProvider interface. + * + * @var OAuthTokenProvider + */ + protected $oauth; + + /** + * The SMTP server timeout in seconds. + * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2. + * + * @var int + */ + public $Timeout = 300; + + /** + * Comma separated list of DSN notifications + * 'NEVER' under no circumstances a DSN must be returned to the sender. + * If you use NEVER all other notifications will be ignored. + * 'SUCCESS' will notify you when your mail has arrived at its destination. + * 'FAILURE' will arrive if an error occurred during delivery. + * 'DELAY' will notify you if there is an unusual delay in delivery, but the actual + * delivery's outcome (success or failure) is not yet decided. + * + * @see https://www.rfc-editor.org/rfc/rfc3461.html#section-4.1 for more information about NOTIFY + */ + public $dsn = ''; + + /** + * SMTP class debug output mode. + * Debug output level. + * Options: + * @see SMTP::DEBUG_OFF: No output + * @see SMTP::DEBUG_CLIENT: Client messages + * @see SMTP::DEBUG_SERVER: Client and server messages + * @see SMTP::DEBUG_CONNECTION: As SERVER plus connection status + * @see SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed + * + * @see SMTP::$do_debug + * + * @var int + */ + public $SMTPDebug = 0; + + /** + * How to handle debug output. + * Options: + * * `echo` Output plain-text as-is, appropriate for CLI + * * `html` Output escaped, line breaks converted to `
`, appropriate for browser output + * * `error_log` Output to error log as configured in php.ini + * By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise. + * Alternatively, you can provide a callable expecting two params: a message string and the debug level: + * + * ```php + * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; + * ``` + * + * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug` + * level output is used: + * + * ```php + * $mail->Debugoutput = new myPsr3Logger; + * ``` + * + * @see SMTP::$Debugoutput + * + * @var string|callable|\Psr\Log\LoggerInterface + */ + public $Debugoutput = 'echo'; + + /** + * Whether to keep the SMTP connection open after each message. + * If this is set to true then the connection will remain open after a send, + * and closing the connection will require an explicit call to smtpClose(). + * It's a good idea to use this if you are sending multiple messages as it reduces overhead. + * See the mailing list example for how to use it. + * + * @var bool + */ + public $SMTPKeepAlive = false; + + /** + * Whether to split multiple to addresses into multiple messages + * or send them all in one message. + * Only supported in `mail` and `sendmail` transports, not in SMTP. + * + * @var bool + * + * @deprecated 6.0.0 PHPMailer isn't a mailing list manager! + */ + public $SingleTo = false; + + /** + * Storage for addresses when SingleTo is enabled. + * + * @var array + */ + protected $SingleToArray = []; + + /** + * Whether to generate VERP addresses on send. + * Only applicable when sending via SMTP. + * + * @see https://en.wikipedia.org/wiki/Variable_envelope_return_path + * @see https://www.postfix.org/VERP_README.html Postfix VERP info + * + * @var bool + */ + public $do_verp = false; + + /** + * Whether to allow sending messages with an empty body. + * + * @var bool + */ + public $AllowEmpty = false; + + /** + * DKIM selector. + * + * @var string + */ + public $DKIM_selector = ''; + + /** + * DKIM Identity. + * Usually the email address used as the source of the email. + * + * @var string + */ + public $DKIM_identity = ''; + + /** + * DKIM passphrase. + * Used if your key is encrypted. + * + * @var string + */ + public $DKIM_passphrase = ''; + + /** + * DKIM signing domain name. + * + * @example 'example.com' + * + * @var string + */ + public $DKIM_domain = ''; + + /** + * DKIM Copy header field values for diagnostic use. + * + * @var bool + */ + public $DKIM_copyHeaderFields = true; + + /** + * DKIM Extra signing headers. + * + * @example ['List-Unsubscribe', 'List-Help'] + * + * @var array + */ + public $DKIM_extraHeaders = []; + + /** + * DKIM private key file path. + * + * @var string + */ + public $DKIM_private = ''; + + /** + * DKIM private key string. + * + * If set, takes precedence over `$DKIM_private`. + * + * @var string + */ + public $DKIM_private_string = ''; + + /** + * Callback Action function name. + * + * The function that handles the result of the send email action. + * It is called out by send() for each email sent. + * + * Value can be any php callable: https://www.php.net/is_callable + * + * Parameters: + * bool $result result of the send action + * array $to email addresses of the recipients + * array $cc cc email addresses + * array $bcc bcc email addresses + * string $subject the subject + * string $body the email body + * string $from email address of sender + * string $extra extra information of possible use + * "smtp_transaction_id' => last smtp transaction id + * + * @var string + */ + public $action_function = ''; + + /** + * What to put in the X-Mailer header. + * Options: An empty string for PHPMailer default, whitespace/null for none, or a string to use. + * + * @var string|null + */ + public $XMailer = ''; + + /** + * Which validator to use by default when validating email addresses. + * May be a callable to inject your own validator, but there are several built-in validators. + * The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option. + * + * @see PHPMailer::validateAddress() + * + * @var string|callable + */ + public static $validator = 'php'; + + /** + * An instance of the SMTP sender class. + * + * @var SMTP + */ + protected $smtp; + + /** + * The array of 'to' names and addresses. + * + * @var array + */ + protected $to = []; + + /** + * The array of 'cc' names and addresses. + * + * @var array + */ + protected $cc = []; + + /** + * The array of 'bcc' names and addresses. + * + * @var array + */ + protected $bcc = []; + + /** + * The array of reply-to names and addresses. + * + * @var array + */ + protected $ReplyTo = []; + + /** + * An array of all kinds of addresses. + * Includes all of $to, $cc, $bcc. + * + * @see PHPMailer::$to + * @see PHPMailer::$cc + * @see PHPMailer::$bcc + * + * @var array + */ + protected $all_recipients = []; + + /** + * An array of names and addresses queued for validation. + * In send(), valid and non duplicate entries are moved to $all_recipients + * and one of $to, $cc, or $bcc. + * This array is used only for addresses with IDN. + * + * @see PHPMailer::$to + * @see PHPMailer::$cc + * @see PHPMailer::$bcc + * @see PHPMailer::$all_recipients + * + * @var array + */ + protected $RecipientsQueue = []; + + /** + * An array of reply-to names and addresses queued for validation. + * In send(), valid and non duplicate entries are moved to $ReplyTo. + * This array is used only for addresses with IDN. + * + * @see PHPMailer::$ReplyTo + * + * @var array + */ + protected $ReplyToQueue = []; + + /** + * The array of attachments. + * + * @var array + */ + protected $attachment = []; + + /** + * The array of custom headers. + * + * @var array + */ + protected $CustomHeader = []; + + /** + * The most recent Message-ID (including angular brackets). + * + * @var string + */ + protected $lastMessageID = ''; + + /** + * The message's MIME type. + * + * @var string + */ + protected $message_type = ''; + + /** + * The array of MIME boundary strings. + * + * @var array + */ + protected $boundary = []; + + /** + * The array of available text strings for the current language. + * + * @var array + */ + protected $language = []; + + /** + * The number of errors encountered. + * + * @var int + */ + protected $error_count = 0; + + /** + * The S/MIME certificate file path. + * + * @var string + */ + protected $sign_cert_file = ''; + + /** + * The S/MIME key file path. + * + * @var string + */ + protected $sign_key_file = ''; + + /** + * The optional S/MIME extra certificates ("CA Chain") file path. + * + * @var string + */ + protected $sign_extracerts_file = ''; + + /** + * The S/MIME password for the key. + * Used only if the key is encrypted. + * + * @var string + */ + protected $sign_key_pass = ''; + + /** + * Whether to throw exceptions for errors. + * + * @var bool + */ + protected $exceptions = false; + + /** + * Unique ID used for message ID and boundaries. + * + * @var string + */ + protected $uniqueid = ''; + + /** + * The PHPMailer Version number. + * + * @var string + */ + const VERSION = '6.9.3'; + + /** + * Error severity: message only, continue processing. + * + * @var int + */ + const STOP_MESSAGE = 0; + + /** + * Error severity: message, likely ok to continue processing. + * + * @var int + */ + const STOP_CONTINUE = 1; + + /** + * Error severity: message, plus full stop, critical error reached. + * + * @var int + */ + const STOP_CRITICAL = 2; + + /** + * The SMTP standard CRLF line break. + * If you want to change line break format, change static::$LE, not this. + */ + const CRLF = "\r\n"; + + /** + * "Folding White Space" a white space string used for line folding. + */ + const FWS = ' '; + + /** + * SMTP RFC standard line ending; Carriage Return, Line Feed. + * + * @var string + */ + protected static $LE = self::CRLF; + + /** + * The maximum line length supported by mail(). + * + * Background: mail() will sometimes corrupt messages + * with headers longer than 65 chars, see #818. + * + * @var int + */ + const MAIL_MAX_LINE_LENGTH = 63; + + /** + * The maximum line length allowed by RFC 2822 section 2.1.1. + * + * @var int + */ + const MAX_LINE_LENGTH = 998; + + /** + * The lower maximum line length allowed by RFC 2822 section 2.1.1. + * This length does NOT include the line break + * 76 means that lines will be 77 or 78 chars depending on whether + * the line break format is LF or CRLF; both are valid. + * + * @var int + */ + const STD_LINE_LENGTH = 76; + + /** + * Constructor. + * + * @param bool $exceptions Should we throw external exceptions? + */ + public function __construct($exceptions = null) + { + if (null !== $exceptions) { + $this->exceptions = (bool) $exceptions; + } + //Pick an appropriate debug output format automatically + $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html'); + } + + /** + * Destructor. + */ + public function __destruct() + { + //Close any open SMTP connection nicely + $this->smtpClose(); + } + + /** + * Call mail() in a safe_mode-aware fashion. + * Also, unless sendmail_path points to sendmail (or something that + * claims to be sendmail), don't pass params (not a perfect fix, + * but it will do). + * + * @param string $to To + * @param string $subject Subject + * @param string $body Message Body + * @param string $header Additional Header(s) + * @param string|null $params Params + * + * @return bool + */ + private function mailPassthru($to, $subject, $body, $header, $params) + { + //Check overloading of mail function to avoid double-encoding + if ((int)ini_get('mbstring.func_overload') & 1) { + $subject = $this->secureHeader($subject); + } else { + $subject = $this->encodeHeader($this->secureHeader($subject)); + } + //Calling mail() with null params breaks + $this->edebug('Sending with mail()'); + $this->edebug('Sendmail path: ' . ini_get('sendmail_path')); + $this->edebug("Envelope sender: {$this->Sender}"); + $this->edebug("To: {$to}"); + $this->edebug("Subject: {$subject}"); + $this->edebug("Headers: {$header}"); + if (!$this->UseSendmailOptions || null === $params) { + $result = @mail($to, $subject, $body, $header); + } else { + $this->edebug("Additional params: {$params}"); + $result = @mail($to, $subject, $body, $header, $params); + } + $this->edebug('Result: ' . ($result ? 'true' : 'false')); + return $result; + } + + /** + * Output debugging info via a user-defined method. + * Only generates output if debug output is enabled. + * + * @see PHPMailer::$Debugoutput + * @see PHPMailer::$SMTPDebug + * + * @param string $str + */ + protected function edebug($str) + { + if ($this->SMTPDebug <= 0) { + return; + } + //Is this a PSR-3 logger? + if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) { + $this->Debugoutput->debug(rtrim($str, "\r\n")); + + return; + } + //Avoid clash with built-in function names + if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) { + call_user_func($this->Debugoutput, $str, $this->SMTPDebug); + + return; + } + switch ($this->Debugoutput) { + case 'error_log': + //Don't output, just log + /** @noinspection ForgottenDebugOutputInspection */ + error_log($str); + break; + case 'html': + //Cleans up output a bit for a better looking, HTML-safe output + echo htmlentities( + preg_replace('/[\r\n]+/', '', $str), + ENT_QUOTES, + 'UTF-8' + ), "
\n"; + break; + case 'echo': + default: + //Normalize line breaks + $str = preg_replace('/\r\n|\r/m', "\n", $str); + echo gmdate('Y-m-d H:i:s'), + "\t", + //Trim trailing space + trim( + //Indent for readability, except for trailing break + str_replace( + "\n", + "\n \t ", + trim($str) + ) + ), + "\n"; + } + } + + /** + * Sets message type to HTML or plain. + * + * @param bool $isHtml True for HTML mode + */ + public function isHTML($isHtml = true) + { + if ($isHtml) { + $this->ContentType = static::CONTENT_TYPE_TEXT_HTML; + } else { + $this->ContentType = static::CONTENT_TYPE_PLAINTEXT; + } + } + + /** + * Send messages using SMTP. + */ + public function isSMTP() + { + $this->Mailer = 'smtp'; + } + + /** + * Send messages using PHP's mail() function. + */ + public function isMail() + { + $this->Mailer = 'mail'; + } + + /** + * Send messages using $Sendmail. + */ + public function isSendmail() + { + $ini_sendmail_path = ini_get('sendmail_path'); + + if (false === stripos($ini_sendmail_path, 'sendmail')) { + $this->Sendmail = '/usr/sbin/sendmail'; + } else { + $this->Sendmail = $ini_sendmail_path; + } + $this->Mailer = 'sendmail'; + } + + /** + * Send messages using qmail. + */ + public function isQmail() + { + $ini_sendmail_path = ini_get('sendmail_path'); + + if (false === stripos($ini_sendmail_path, 'qmail')) { + $this->Sendmail = '/var/qmail/bin/qmail-inject'; + } else { + $this->Sendmail = $ini_sendmail_path; + } + $this->Mailer = 'qmail'; + } + + /** + * Add a "To" address. + * + * @param string $address The email address to send to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + public function addAddress($address, $name = '') + { + return $this->addOrEnqueueAnAddress('to', $address, $name); + } + + /** + * Add a "CC" address. + * + * @param string $address The email address to send to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + public function addCC($address, $name = '') + { + return $this->addOrEnqueueAnAddress('cc', $address, $name); + } + + /** + * Add a "BCC" address. + * + * @param string $address The email address to send to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + public function addBCC($address, $name = '') + { + return $this->addOrEnqueueAnAddress('bcc', $address, $name); + } + + /** + * Add a "Reply-To" address. + * + * @param string $address The email address to reply to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + public function addReplyTo($address, $name = '') + { + return $this->addOrEnqueueAnAddress('Reply-To', $address, $name); + } + + /** + * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer + * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still + * be modified after calling this function), addition of such addresses is delayed until send(). + * Addresses that have been added already return false, but do not throw exceptions. + * + * @param string $kind One of 'to', 'cc', 'bcc', or 'Reply-To' + * @param string $address The email address + * @param string $name An optional username associated with the address + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + protected function addOrEnqueueAnAddress($kind, $address, $name) + { + $pos = false; + if ($address !== null) { + $address = trim($address); + $pos = strrpos($address, '@'); + } + if (false === $pos) { + //At-sign is missing. + $error_message = sprintf( + '%s (%s): %s', + $this->lang('invalid_address'), + $kind, + $address + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + if ($name !== null && is_string($name)) { + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + } else { + $name = ''; + } + $params = [$kind, $address, $name]; + //Enqueue addresses with IDN until we know the PHPMailer::$CharSet. + //Domain is assumed to be whatever is after the last @ symbol in the address + if (static::idnSupported() && $this->has8bitChars(substr($address, ++$pos))) { + if ('Reply-To' !== $kind) { + if (!array_key_exists($address, $this->RecipientsQueue)) { + $this->RecipientsQueue[$address] = $params; + + return true; + } + } elseif (!array_key_exists($address, $this->ReplyToQueue)) { + $this->ReplyToQueue[$address] = $params; + + return true; + } + + return false; + } + + //Immediately add standard addresses without IDN. + return call_user_func_array([$this, 'addAnAddress'], $params); + } + + /** + * Set the boundaries to use for delimiting MIME parts. + * If you override this, ensure you set all 3 boundaries to unique values. + * The default boundaries include a "=_" sequence which cannot occur in quoted-printable bodies, + * as suggested by https://www.rfc-editor.org/rfc/rfc2045#section-6.7 + * + * @return void + */ + public function setBoundaries() + { + $this->uniqueid = $this->generateId(); + $this->boundary[1] = 'b1=_' . $this->uniqueid; + $this->boundary[2] = 'b2=_' . $this->uniqueid; + $this->boundary[3] = 'b3=_' . $this->uniqueid; + } + + /** + * Add an address to one of the recipient arrays or to the ReplyTo array. + * Addresses that have been added already return false, but do not throw exceptions. + * + * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' + * @param string $address The email address to send, resp. to reply to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + protected function addAnAddress($kind, $address, $name = '') + { + if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) { + $error_message = sprintf( + '%s: %s', + $this->lang('Invalid recipient kind'), + $kind + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + if (!static::validateAddress($address)) { + $error_message = sprintf( + '%s (%s): %s', + $this->lang('invalid_address'), + $kind, + $address + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + if ('Reply-To' !== $kind) { + if (!array_key_exists(strtolower($address), $this->all_recipients)) { + $this->{$kind}[] = [$address, $name]; + $this->all_recipients[strtolower($address)] = true; + + return true; + } + } elseif (!array_key_exists(strtolower($address), $this->ReplyTo)) { + $this->ReplyTo[strtolower($address)] = [$address, $name]; + + return true; + } + + return false; + } + + /** + * Parse and validate a string containing one or more RFC822-style comma-separated email addresses + * of the form "display name
" into an array of name/address pairs. + * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available. + * Note that quotes in the name part are removed. + * + * @see https://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation + * + * @param string $addrstr The address list string + * @param bool $useimap Whether to use the IMAP extension to parse the list + * @param string $charset The charset to use when decoding the address list string. + * + * @return array + */ + public static function parseAddresses($addrstr, $useimap = true, $charset = self::CHARSET_ISO88591) + { + $addresses = []; + if ($useimap && function_exists('imap_rfc822_parse_adrlist')) { + //Use this built-in parser if it's available + $list = imap_rfc822_parse_adrlist($addrstr, ''); + // Clear any potential IMAP errors to get rid of notices being thrown at end of script. + imap_errors(); + foreach ($list as $address) { + if ( + '.SYNTAX-ERROR.' !== $address->host && + static::validateAddress($address->mailbox . '@' . $address->host) + ) { + //Decode the name part if it's present and encoded + if ( + property_exists($address, 'personal') && + //Check for a Mbstring constant rather than using extension_loaded, which is sometimes disabled + defined('MB_CASE_UPPER') && + preg_match('/^=\?.*\?=$/s', $address->personal) + ) { + $origCharset = mb_internal_encoding(); + mb_internal_encoding($charset); + //Undo any RFC2047-encoded spaces-as-underscores + $address->personal = str_replace('_', '=20', $address->personal); + //Decode the name + $address->personal = mb_decode_mimeheader($address->personal); + mb_internal_encoding($origCharset); + } + + $addresses[] = [ + 'name' => (property_exists($address, 'personal') ? $address->personal : ''), + 'address' => $address->mailbox . '@' . $address->host, + ]; + } + } + } else { + //Use this simpler parser + $list = explode(',', $addrstr); + foreach ($list as $address) { + $address = trim($address); + //Is there a separate name part? + if (strpos($address, '<') === false) { + //No separate name, just use the whole thing + if (static::validateAddress($address)) { + $addresses[] = [ + 'name' => '', + 'address' => $address, + ]; + } + } else { + list($name, $email) = explode('<', $address); + $email = trim(str_replace('>', '', $email)); + $name = trim($name); + if (static::validateAddress($email)) { + //Check for a Mbstring constant rather than using extension_loaded, which is sometimes disabled + //If this name is encoded, decode it + if (defined('MB_CASE_UPPER') && preg_match('/^=\?.*\?=$/s', $name)) { + $origCharset = mb_internal_encoding(); + mb_internal_encoding($charset); + //Undo any RFC2047-encoded spaces-as-underscores + $name = str_replace('_', '=20', $name); + //Decode the name + $name = mb_decode_mimeheader($name); + mb_internal_encoding($origCharset); + } + $addresses[] = [ + //Remove any surrounding quotes and spaces from the name + 'name' => trim($name, '\'" '), + 'address' => $email, + ]; + } + } + } + } + + return $addresses; + } + + /** + * Set the From and FromName properties. + * + * @param string $address + * @param string $name + * @param bool $auto Whether to also set the Sender address, defaults to true + * + * @throws Exception + * + * @return bool + */ + public function setFrom($address, $name = '', $auto = true) + { + $address = trim((string)$address); + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + //Don't validate now addresses with IDN. Will be done in send(). + $pos = strrpos($address, '@'); + if ( + (false === $pos) + || ((!$this->has8bitChars(substr($address, ++$pos)) || !static::idnSupported()) + && !static::validateAddress($address)) + ) { + $error_message = sprintf( + '%s (From): %s', + $this->lang('invalid_address'), + $address + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + $this->From = $address; + $this->FromName = $name; + if ($auto && empty($this->Sender)) { + $this->Sender = $address; + } + + return true; + } + + /** + * Return the Message-ID header of the last email. + * Technically this is the value from the last time the headers were created, + * but it's also the message ID of the last sent message except in + * pathological cases. + * + * @return string + */ + public function getLastMessageID() + { + return $this->lastMessageID; + } + + /** + * Check that a string looks like an email address. + * Validation patterns supported: + * * `auto` Pick best pattern automatically; + * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0; + * * `pcre` Use old PCRE implementation; + * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; + * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements. + * * `noregex` Don't use a regex: super fast, really dumb. + * Alternatively you may pass in a callable to inject your own validator, for example: + * + * ```php + * PHPMailer::validateAddress('user@example.com', function($address) { + * return (strpos($address, '@') !== false); + * }); + * ``` + * + * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator. + * + * @param string $address The email address to check + * @param string|callable $patternselect Which pattern to use + * + * @return bool + */ + public static function validateAddress($address, $patternselect = null) + { + if (null === $patternselect) { + $patternselect = static::$validator; + } + //Don't allow strings as callables, see SECURITY.md and CVE-2021-3603 + if (is_callable($patternselect) && !is_string($patternselect)) { + return call_user_func($patternselect, $address); + } + //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321 + if (strpos($address, "\n") !== false || strpos($address, "\r") !== false) { + return false; + } + switch ($patternselect) { + case 'pcre': //Kept for BC + case 'pcre8': + /* + * A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL + * is based. + * In addition to the addresses allowed by filter_var, also permits: + * * dotless domains: `a@b` + * * comments: `1234 @ local(blah) .machine .example` + * * quoted elements: `'"test blah"@example.org'` + * * numeric TLDs: `a@b.123` + * * unbracketed IPv4 literals: `a@192.168.0.1` + * * IPv6 literals: 'first.last@[IPv6:a1::]' + * Not all of these will necessarily work for sending! + * + * @copyright 2009-2010 Michael Rushton + * Feel free to use and redistribute this code. But please keep this copyright notice. + */ + return (bool) preg_match( + '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' . + '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' . + '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' . + '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' . + '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' . + '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' . + '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' . + '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' . + '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', + $address + ); + case 'html5': + /* + * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements. + * + * @see https://html.spec.whatwg.org/#e-mail-state-(type=email) + */ + return (bool) preg_match( + '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' . + '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD', + $address + ); + case 'php': + default: + return filter_var($address, FILTER_VALIDATE_EMAIL) !== false; + } + } + + /** + * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the + * `intl` and `mbstring` PHP extensions. + * + * @return bool `true` if required functions for IDN support are present + */ + public static function idnSupported() + { + return function_exists('idn_to_ascii') && function_exists('mb_convert_encoding'); + } + + /** + * Converts IDN in given email address to its ASCII form, also known as punycode, if possible. + * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet. + * This function silently returns unmodified address if: + * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form) + * - Conversion to punycode is impossible (e.g. required PHP functions are not available) + * or fails for any reason (e.g. domain contains characters not allowed in an IDN). + * + * @see PHPMailer::$CharSet + * + * @param string $address The email address to convert + * + * @return string The encoded address in ASCII form + */ + public function punyencodeAddress($address) + { + //Verify we have required functions, CharSet, and at-sign. + $pos = strrpos($address, '@'); + if ( + !empty($this->CharSet) && + false !== $pos && + static::idnSupported() + ) { + $domain = substr($address, ++$pos); + //Verify CharSet string is a valid one, and domain properly encoded in this CharSet. + if ($this->has8bitChars($domain) && @mb_check_encoding($domain, $this->CharSet)) { + //Convert the domain from whatever charset it's in to UTF-8 + $domain = mb_convert_encoding($domain, self::CHARSET_UTF8, $this->CharSet); + //Ignore IDE complaints about this line - method signature changed in PHP 5.4 + $errorcode = 0; + if (defined('INTL_IDNA_VARIANT_UTS46')) { + //Use the current punycode standard (appeared in PHP 7.2) + $punycode = idn_to_ascii( + $domain, + \IDNA_DEFAULT | \IDNA_USE_STD3_RULES | \IDNA_CHECK_BIDI | + \IDNA_CHECK_CONTEXTJ | \IDNA_NONTRANSITIONAL_TO_ASCII, + \INTL_IDNA_VARIANT_UTS46 + ); + } elseif (defined('INTL_IDNA_VARIANT_2003')) { + //Fall back to this old, deprecated/removed encoding + $punycode = idn_to_ascii($domain, $errorcode, \INTL_IDNA_VARIANT_2003); + } else { + //Fall back to a default we don't know about + $punycode = idn_to_ascii($domain, $errorcode); + } + if (false !== $punycode) { + return substr($address, 0, $pos) . $punycode; + } + } + } + + return $address; + } + + /** + * Create a message and send it. + * Uses the sending method specified by $Mailer. + * + * @throws Exception + * + * @return bool false on error - See the ErrorInfo property for details of the error + */ + public function send() + { + try { + if (!$this->preSend()) { + return false; + } + + return $this->postSend(); + } catch (Exception $exc) { + $this->mailHeader = ''; + $this->setError($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return false; + } + } + + /** + * Prepare a message for sending. + * + * @throws Exception + * + * @return bool + */ + public function preSend() + { + if ( + 'smtp' === $this->Mailer + || ('mail' === $this->Mailer && (\PHP_VERSION_ID >= 80000 || stripos(PHP_OS, 'WIN') === 0)) + ) { + //SMTP mandates RFC-compliant line endings + //and it's also used with mail() on Windows + static::setLE(self::CRLF); + } else { + //Maintain backward compatibility with legacy Linux command line mailers + static::setLE(PHP_EOL); + } + //Check for buggy PHP versions that add a header with an incorrect line break + if ( + 'mail' === $this->Mailer + && ((\PHP_VERSION_ID >= 70000 && \PHP_VERSION_ID < 70017) + || (\PHP_VERSION_ID >= 70100 && \PHP_VERSION_ID < 70103)) + && ini_get('mail.add_x_header') === '1' + && stripos(PHP_OS, 'WIN') === 0 + ) { + trigger_error($this->lang('buggy_php'), E_USER_WARNING); + } + + try { + $this->error_count = 0; //Reset errors + $this->mailHeader = ''; + + //Dequeue recipient and Reply-To addresses with IDN + foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) { + $params[1] = $this->punyencodeAddress($params[1]); + call_user_func_array([$this, 'addAnAddress'], $params); + } + if (count($this->to) + count($this->cc) + count($this->bcc) < 1) { + throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL); + } + + //Validate From, Sender, and ConfirmReadingTo addresses + foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) { + if ($this->{$address_kind} === null) { + $this->{$address_kind} = ''; + continue; + } + $this->{$address_kind} = trim($this->{$address_kind}); + if (empty($this->{$address_kind})) { + continue; + } + $this->{$address_kind} = $this->punyencodeAddress($this->{$address_kind}); + if (!static::validateAddress($this->{$address_kind})) { + $error_message = sprintf( + '%s (%s): %s', + $this->lang('invalid_address'), + $address_kind, + $this->{$address_kind} + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + } + + //Set whether the message is multipart/alternative + if ($this->alternativeExists()) { + $this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE; + } + + $this->setMessageType(); + //Refuse to send an empty message unless we are specifically allowing it + if (!$this->AllowEmpty && empty($this->Body)) { + throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL); + } + + //Trim subject consistently + $this->Subject = trim($this->Subject); + //Create body before headers in case body makes changes to headers (e.g. altering transfer encoding) + $this->MIMEHeader = ''; + $this->MIMEBody = $this->createBody(); + //createBody may have added some headers, so retain them + $tempheaders = $this->MIMEHeader; + $this->MIMEHeader = $this->createHeader(); + $this->MIMEHeader .= $tempheaders; + + //To capture the complete message when using mail(), create + //an extra header list which createHeader() doesn't fold in + if ('mail' === $this->Mailer) { + if (count($this->to) > 0) { + $this->mailHeader .= $this->addrAppend('To', $this->to); + } else { + $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;'); + } + $this->mailHeader .= $this->headerLine( + 'Subject', + $this->encodeHeader($this->secureHeader($this->Subject)) + ); + } + + //Sign with DKIM if enabled + if ( + !empty($this->DKIM_domain) + && !empty($this->DKIM_selector) + && (!empty($this->DKIM_private_string) + || (!empty($this->DKIM_private) + && static::isPermittedPath($this->DKIM_private) + && file_exists($this->DKIM_private) + ) + ) + ) { + $header_dkim = $this->DKIM_Add( + $this->MIMEHeader . $this->mailHeader, + $this->encodeHeader($this->secureHeader($this->Subject)), + $this->MIMEBody + ); + $this->MIMEHeader = static::stripTrailingWSP($this->MIMEHeader) . static::$LE . + static::normalizeBreaks($header_dkim) . static::$LE; + } + + return true; + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return false; + } + } + + /** + * Actually send a message via the selected mechanism. + * + * @throws Exception + * + * @return bool + */ + public function postSend() + { + try { + //Choose the mailer and send through it + switch ($this->Mailer) { + case 'sendmail': + case 'qmail': + return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody); + case 'smtp': + return $this->smtpSend($this->MIMEHeader, $this->MIMEBody); + case 'mail': + return $this->mailSend($this->MIMEHeader, $this->MIMEBody); + default: + $sendMethod = $this->Mailer . 'Send'; + if (method_exists($this, $sendMethod)) { + return $this->{$sendMethod}($this->MIMEHeader, $this->MIMEBody); + } + + return $this->mailSend($this->MIMEHeader, $this->MIMEBody); + } + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + $this->edebug($exc->getMessage()); + if ($this->Mailer === 'smtp' && $this->SMTPKeepAlive == true && $this->smtp->connected()) { + $this->smtp->reset(); + } + if ($this->exceptions) { + throw $exc; + } + } + + return false; + } + + /** + * Send mail using the $Sendmail program. + * + * @see PHPMailer::$Sendmail + * + * @param string $header The message headers + * @param string $body The message body + * + * @throws Exception + * + * @return bool + */ + protected function sendmailSend($header, $body) + { + if ($this->Mailer === 'qmail') { + $this->edebug('Sending with qmail'); + } else { + $this->edebug('Sending with sendmail'); + } + $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; + //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver + //A space after `-f` is optional, but there is a long history of its presence + //causing problems, so we don't use one + //Exim docs: https://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html + //Sendmail docs: https://www.sendmail.org/~ca/email/man/sendmail.html + //Example problem: https://www.drupal.org/node/1057954 + + //PHP 5.6 workaround + $sendmail_from_value = ini_get('sendmail_from'); + if (empty($this->Sender) && !empty($sendmail_from_value)) { + //PHP config has a sender address we can use + $this->Sender = ini_get('sendmail_from'); + } + //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. + if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) { + if ($this->Mailer === 'qmail') { + $sendmailFmt = '%s -f%s'; + } else { + $sendmailFmt = '%s -oi -f%s -t'; + } + } else { + //allow sendmail to choose a default envelope sender. It may + //seem preferable to force it to use the From header as with + //SMTP, but that introduces new problems (see + //), and + //it has historically worked this way. + $sendmailFmt = '%s -oi -t'; + } + + $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender); + $this->edebug('Sendmail path: ' . $this->Sendmail); + $this->edebug('Sendmail command: ' . $sendmail); + $this->edebug('Envelope sender: ' . $this->Sender); + $this->edebug("Headers: {$header}"); + + if ($this->SingleTo) { + foreach ($this->SingleToArray as $toAddr) { + $mail = @popen($sendmail, 'w'); + if (!$mail) { + throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + $this->edebug("To: {$toAddr}"); + fwrite($mail, 'To: ' . $toAddr . "\n"); + fwrite($mail, $header); + fwrite($mail, $body); + $result = pclose($mail); + $addrinfo = static::parseAddresses($toAddr, true, $this->CharSet); + $this->doCallback( + ($result === 0), + [[$addrinfo['address'], $addrinfo['name']]], + $this->cc, + $this->bcc, + $this->Subject, + $body, + $this->From, + [] + ); + $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); + if (0 !== $result) { + throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + } else { + $mail = @popen($sendmail, 'w'); + if (!$mail) { + throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + fwrite($mail, $header); + fwrite($mail, $body); + $result = pclose($mail); + $this->doCallback( + ($result === 0), + $this->to, + $this->cc, + $this->bcc, + $this->Subject, + $body, + $this->From, + [] + ); + $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); + if (0 !== $result) { + throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + + return true; + } + + /** + * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters. + * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows. + * + * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report + * + * @param string $string The string to be validated + * + * @return bool + */ + protected static function isShellSafe($string) + { + //It's not possible to use shell commands safely (which includes the mail() function) without escapeshellarg, + //but some hosting providers disable it, creating a security problem that we don't want to have to deal with, + //so we don't. + if (!function_exists('escapeshellarg') || !function_exists('escapeshellcmd')) { + return false; + } + + if ( + escapeshellcmd($string) !== $string + || !in_array(escapeshellarg($string), ["'$string'", "\"$string\""]) + ) { + return false; + } + + $length = strlen($string); + + for ($i = 0; $i < $length; ++$i) { + $c = $string[$i]; + + //All other characters have a special meaning in at least one common shell, including = and +. + //Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here. + //Note that this does permit non-Latin alphanumeric characters based on the current locale. + if (!ctype_alnum($c) && strpos('@_-.', $c) === false) { + return false; + } + } + + return true; + } + + /** + * Check whether a file path is of a permitted type. + * Used to reject URLs and phar files from functions that access local file paths, + * such as addAttachment. + * + * @param string $path A relative or absolute path to a file + * + * @return bool + */ + protected static function isPermittedPath($path) + { + //Matches scheme definition from https://www.rfc-editor.org/rfc/rfc3986#section-3.1 + return !preg_match('#^[a-z][a-z\d+.-]*://#i', $path); + } + + /** + * Check whether a file path is safe, accessible, and readable. + * + * @param string $path A relative or absolute path to a file + * + * @return bool + */ + protected static function fileIsAccessible($path) + { + if (!static::isPermittedPath($path)) { + return false; + } + $readable = is_file($path); + //If not a UNC path (expected to start with \\), check read permission, see #2069 + if (strpos($path, '\\\\') !== 0) { + $readable = $readable && is_readable($path); + } + return $readable; + } + + /** + * Send mail using the PHP mail() function. + * + * @see https://www.php.net/manual/en/book.mail.php + * + * @param string $header The message headers + * @param string $body The message body + * + * @throws Exception + * + * @return bool + */ + protected function mailSend($header, $body) + { + $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; + + $toArr = []; + foreach ($this->to as $toaddr) { + $toArr[] = $this->addrFormat($toaddr); + } + $to = trim(implode(', ', $toArr)); + + //If there are no To-addresses (e.g. when sending only to BCC-addresses) + //the following should be added to get a correct DKIM-signature. + //Compare with $this->preSend() + if ($to === '') { + $to = 'undisclosed-recipients:;'; + } + + $params = null; + //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver + //A space after `-f` is optional, but there is a long history of its presence + //causing problems, so we don't use one + //Exim docs: https://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html + //Sendmail docs: https://www.sendmail.org/~ca/email/man/sendmail.html + //Example problem: https://www.drupal.org/node/1057954 + //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. + + //PHP 5.6 workaround + $sendmail_from_value = ini_get('sendmail_from'); + if (empty($this->Sender) && !empty($sendmail_from_value)) { + //PHP config has a sender address we can use + $this->Sender = ini_get('sendmail_from'); + } + if (!empty($this->Sender) && static::validateAddress($this->Sender)) { + if (self::isShellSafe($this->Sender)) { + $params = sprintf('-f%s', $this->Sender); + } + $old_from = ini_get('sendmail_from'); + ini_set('sendmail_from', $this->Sender); + } + $result = false; + if ($this->SingleTo && count($toArr) > 1) { + foreach ($toArr as $toAddr) { + $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params); + $addrinfo = static::parseAddresses($toAddr, true, $this->CharSet); + $this->doCallback( + $result, + [[$addrinfo['address'], $addrinfo['name']]], + $this->cc, + $this->bcc, + $this->Subject, + $body, + $this->From, + [] + ); + } + } else { + $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params); + $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []); + } + if (isset($old_from)) { + ini_set('sendmail_from', $old_from); + } + if (!$result) { + throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL); + } + + return true; + } + + /** + * Get an instance to use for SMTP operations. + * Override this function to load your own SMTP implementation, + * or set one with setSMTPInstance. + * + * @return SMTP + */ + public function getSMTPInstance() + { + if (!is_object($this->smtp)) { + $this->smtp = new SMTP(); + } + + return $this->smtp; + } + + /** + * Provide an instance to use for SMTP operations. + * + * @return SMTP + */ + public function setSMTPInstance(SMTP $smtp) + { + $this->smtp = $smtp; + + return $this->smtp; + } + + /** + * Provide SMTP XCLIENT attributes + * + * @param string $name Attribute name + * @param ?string $value Attribute value + * + * @return bool + */ + public function setSMTPXclientAttribute($name, $value) + { + if (!in_array($name, SMTP::$xclient_allowed_attributes)) { + return false; + } + if (isset($this->SMTPXClient[$name]) && $value === null) { + unset($this->SMTPXClient[$name]); + } elseif ($value !== null) { + $this->SMTPXClient[$name] = $value; + } + + return true; + } + + /** + * Get SMTP XCLIENT attributes + * + * @return array + */ + public function getSMTPXclientAttributes() + { + return $this->SMTPXClient; + } + + /** + * Send mail via SMTP. + * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. + * + * @see PHPMailer::setSMTPInstance() to use a different class. + * + * @uses \PHPMailer\PHPMailer\SMTP + * + * @param string $header The message headers + * @param string $body The message body + * + * @throws Exception + * + * @return bool + */ + protected function smtpSend($header, $body) + { + $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; + $bad_rcpt = []; + if (!$this->smtpConnect($this->SMTPOptions)) { + throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL); + } + //Sender already validated in preSend() + if ('' === $this->Sender) { + $smtp_from = $this->From; + } else { + $smtp_from = $this->Sender; + } + if (count($this->SMTPXClient)) { + $this->smtp->xclient($this->SMTPXClient); + } + if (!$this->smtp->mail($smtp_from)) { + $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); + throw new Exception($this->ErrorInfo, self::STOP_CRITICAL); + } + + $callbacks = []; + //Attempt to send to all recipients + foreach ([$this->to, $this->cc, $this->bcc] as $togroup) { + foreach ($togroup as $to) { + if (!$this->smtp->recipient($to[0], $this->dsn)) { + $error = $this->smtp->getError(); + $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']]; + $isSent = false; + } else { + $isSent = true; + } + + $callbacks[] = ['issent' => $isSent, 'to' => $to[0], 'name' => $to[1]]; + } + } + + //Only send the DATA command if we have viable recipients + if ((count($this->all_recipients) > count($bad_rcpt)) && !$this->smtp->data($header . $body)) { + throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL); + } + + $smtp_transaction_id = $this->smtp->getLastTransactionID(); + + if ($this->SMTPKeepAlive) { + $this->smtp->reset(); + } else { + $this->smtp->quit(); + $this->smtp->close(); + } + + foreach ($callbacks as $cb) { + $this->doCallback( + $cb['issent'], + [[$cb['to'], $cb['name']]], + [], + [], + $this->Subject, + $body, + $this->From, + ['smtp_transaction_id' => $smtp_transaction_id] + ); + } + + //Create error message for any bad addresses + if (count($bad_rcpt) > 0) { + $errstr = ''; + foreach ($bad_rcpt as $bad) { + $errstr .= $bad['to'] . ': ' . $bad['error']; + } + throw new Exception($this->lang('recipients_failed') . $errstr, self::STOP_CONTINUE); + } + + return true; + } + + /** + * Initiate a connection to an SMTP server. + * Returns false if the operation failed. + * + * @param array $options An array of options compatible with stream_context_create() + * + * @throws Exception + * + * @uses \PHPMailer\PHPMailer\SMTP + * + * @return bool + */ + public function smtpConnect($options = null) + { + if (null === $this->smtp) { + $this->smtp = $this->getSMTPInstance(); + } + + //If no options are provided, use whatever is set in the instance + if (null === $options) { + $options = $this->SMTPOptions; + } + + //Already connected? + if ($this->smtp->connected()) { + return true; + } + + $this->smtp->setTimeout($this->Timeout); + $this->smtp->setDebugLevel($this->SMTPDebug); + $this->smtp->setDebugOutput($this->Debugoutput); + $this->smtp->setVerp($this->do_verp); + if ($this->Host === null) { + $this->Host = 'localhost'; + } + $hosts = explode(';', $this->Host); + $lastexception = null; + + foreach ($hosts as $hostentry) { + $hostinfo = []; + if ( + !preg_match( + '/^(?:(ssl|tls):\/\/)?(.+?)(?::(\d+))?$/', + trim($hostentry), + $hostinfo + ) + ) { + $this->edebug($this->lang('invalid_hostentry') . ' ' . trim($hostentry)); + //Not a valid host entry + continue; + } + //$hostinfo[1]: optional ssl or tls prefix + //$hostinfo[2]: the hostname + //$hostinfo[3]: optional port number + //The host string prefix can temporarily override the current setting for SMTPSecure + //If it's not specified, the default value is used + + //Check the host name is a valid name or IP address before trying to use it + if (!static::isValidHost($hostinfo[2])) { + $this->edebug($this->lang('invalid_host') . ' ' . $hostinfo[2]); + continue; + } + $prefix = ''; + $secure = $this->SMTPSecure; + $tls = (static::ENCRYPTION_STARTTLS === $this->SMTPSecure); + if ('ssl' === $hostinfo[1] || ('' === $hostinfo[1] && static::ENCRYPTION_SMTPS === $this->SMTPSecure)) { + $prefix = 'ssl://'; + $tls = false; //Can't have SSL and TLS at the same time + $secure = static::ENCRYPTION_SMTPS; + } elseif ('tls' === $hostinfo[1]) { + $tls = true; + //TLS doesn't use a prefix + $secure = static::ENCRYPTION_STARTTLS; + } + //Do we need the OpenSSL extension? + $sslext = defined('OPENSSL_ALGO_SHA256'); + if (static::ENCRYPTION_STARTTLS === $secure || static::ENCRYPTION_SMTPS === $secure) { + //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled + if (!$sslext) { + throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL); + } + } + $host = $hostinfo[2]; + $port = $this->Port; + if ( + array_key_exists(3, $hostinfo) && + is_numeric($hostinfo[3]) && + $hostinfo[3] > 0 && + $hostinfo[3] < 65536 + ) { + $port = (int) $hostinfo[3]; + } + if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) { + try { + if ($this->Helo) { + $hello = $this->Helo; + } else { + $hello = $this->serverHostname(); + } + $this->smtp->hello($hello); + //Automatically enable TLS encryption if: + //* it's not disabled + //* we are not connecting to localhost + //* we have openssl extension + //* we are not already using SSL + //* the server offers STARTTLS + if ( + $this->SMTPAutoTLS && + $this->Host !== 'localhost' && + $sslext && + $secure !== 'ssl' && + $this->smtp->getServerExt('STARTTLS') + ) { + $tls = true; + } + if ($tls) { + if (!$this->smtp->startTLS()) { + $message = $this->getSmtpErrorMessage('connect_host'); + throw new Exception($message); + } + //We must resend EHLO after TLS negotiation + $this->smtp->hello($hello); + } + if ( + $this->SMTPAuth && !$this->smtp->authenticate( + $this->Username, + $this->Password, + $this->AuthType, + $this->oauth + ) + ) { + throw new Exception($this->lang('authenticate')); + } + + return true; + } catch (Exception $exc) { + $lastexception = $exc; + $this->edebug($exc->getMessage()); + //We must have connected, but then failed TLS or Auth, so close connection nicely + $this->smtp->quit(); + } + } + } + //If we get here, all connection attempts have failed, so close connection hard + $this->smtp->close(); + //As we've caught all exceptions, just report whatever the last one was + if ($this->exceptions && null !== $lastexception) { + throw $lastexception; + } + if ($this->exceptions) { + // no exception was thrown, likely $this->smtp->connect() failed + $message = $this->getSmtpErrorMessage('connect_host'); + throw new Exception($message); + } + + return false; + } + + /** + * Close the active SMTP session if one exists. + */ + public function smtpClose() + { + if ((null !== $this->smtp) && $this->smtp->connected()) { + $this->smtp->quit(); + $this->smtp->close(); + } + } + + /** + * Set the language for error messages. + * The default language is English. + * + * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr") + * Optionally, the language code can be enhanced with a 4-character + * script annotation and/or a 2-character country annotation. + * @param string $lang_path Path to the language file directory, with trailing separator (slash) + * Do not set this from user input! + * + * @return bool Returns true if the requested language was loaded, false otherwise. + */ + public function setLanguage($langcode = 'en', $lang_path = '') + { + //Backwards compatibility for renamed language codes + $renamed_langcodes = [ + 'br' => 'pt_br', + 'cz' => 'cs', + 'dk' => 'da', + 'no' => 'nb', + 'se' => 'sv', + 'rs' => 'sr', + 'tg' => 'tl', + 'am' => 'hy', + ]; + + if (array_key_exists($langcode, $renamed_langcodes)) { + $langcode = $renamed_langcodes[$langcode]; + } + + //Define full set of translatable strings in English + $PHPMAILER_LANG = [ + 'authenticate' => 'SMTP Error: Could not authenticate.', + 'buggy_php' => 'Your version of PHP is affected by a bug that may result in corrupted messages.' . + ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' . + ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.', + 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', + 'data_not_accepted' => 'SMTP Error: data not accepted.', + 'empty_message' => 'Message body empty', + 'encoding' => 'Unknown encoding: ', + 'execute' => 'Could not execute: ', + 'extension_missing' => 'Extension missing: ', + 'file_access' => 'Could not access file: ', + 'file_open' => 'File Error: Could not open file: ', + 'from_failed' => 'The following From address failed: ', + 'instantiate' => 'Could not instantiate mail function.', + 'invalid_address' => 'Invalid address: ', + 'invalid_header' => 'Invalid header name or value', + 'invalid_hostentry' => 'Invalid hostentry: ', + 'invalid_host' => 'Invalid host: ', + 'mailer_not_supported' => ' mailer is not supported.', + 'provide_address' => 'You must provide at least one recipient email address.', + 'recipients_failed' => 'SMTP Error: The following recipients failed: ', + 'signing' => 'Signing Error: ', + 'smtp_code' => 'SMTP code: ', + 'smtp_code_ex' => 'Additional SMTP info: ', + 'smtp_connect_failed' => 'SMTP connect() failed.', + 'smtp_detail' => 'Detail: ', + 'smtp_error' => 'SMTP server error: ', + 'variable_set' => 'Cannot set or reset variable: ', + ]; + if (empty($lang_path)) { + //Calculate an absolute path so it can work if CWD is not here + $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR; + } + + //Validate $langcode + $foundlang = true; + $langcode = strtolower($langcode); + if ( + !preg_match('/^(?P[a-z]{2})(?P