<?php
// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: pmb.php,v 1.4.4.3 2026/04/10 14:18:49 dgoron Exp $

$base_path = ".";
require_once "{$base_path}/includes/init.inc.php";

// fichiers nécessaires au bon fonctionnement de l'environnement
require_once "{$base_path}/includes/common_includes.inc.php";

global $class_path, $from, $opac_empr_password_salt;
global $hash, $url, $id;
global $opac_url_base, $utm_source, $utm_medium, $utm_campaign;

if ('' == $opac_empr_password_salt) {
    password::gen_salt_base();
}

if (!empty($hash) && !empty($url) && !empty($id)) {
    require_once "{$class_path}/campaigns/campaigns_controller.class.php";
    campaigns_controller::proceed($hash, $url, $id);
} elseif (!empty($hash) && !empty($url)) {
    if (!isset($from)) {
        $from = '';
    }

    if ($hash == md5("{$opac_empr_password_salt}_{$url}_{$from}")) {
        //Enregistrement du log
        generate_log('pmb', [], true);

        $location_url = html_entity_decode($url);
        if (strpos(trim($location_url), trim($opac_url_base)) === 0) {
            if (!empty($utm_source) || !empty($utm_medium) || !empty($utm_campaign)) {
                // Décomposer l'URL
                $parsed = parse_url($location_url);
                // Récupérer les paramètres existants
                $queryParams = [];
                if (!empty($parsed['query'])) {
                    parse_str($parsed['query'], $queryParams);
                }
                // Ajouter / écraser les UTM
                if (!empty($utm_source)) {
                    $queryParams['utm_source'] = $utm_source;
                }
                if (!empty($utm_medium)) {
                    $queryParams['utm_medium'] = $utm_medium;
                }
                if (!empty($utm_campaign)) {
                    $queryParams['utm_campaign'] = $utm_campaign;
                }
                // Reconstruire la query string (encodage propre)
                $newQuery = http_build_query($queryParams);
                
                // Reconstruire l'URL complète
                $location_url =
                (isset($parsed['scheme']) ? $parsed['scheme'] . '://' : '') .
                ($parsed['host'] ?? '') .
                ($parsed['path'] ?? '') .
                (!empty($newQuery) ? '?' . $newQuery : '') .
                (isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '');
            }
        }
        header('Location: '.$location_url);
    } else {
        http_response_code(404);
    }
} else {
    http_response_code(404);
}
