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

if (stristr($_SERVER['REQUEST_URI'], ".class.php")) die("no access");

global $class_path;
require_once($class_path."/campaigns/campaign_recipient.class.php");

class campaign_proxy {
    
    protected $utm_source;
    
    protected $utm_medium;
    
    protected $utm_campaign;
    
    /**
     *
     * @var campaign_recipient
     */
    protected $campaign_recipient;
    
    public function __construct() {
    }
    
    protected function get_builded_url($url) {
        global $opac_url_base, $database;
        
        $recipient_hash = $this->campaign_recipient->get_hash();
        $id = $this->campaign_recipient->get_id();
        $url = $opac_url_base."pmb.php?hash=".urlencode(static::gen_hash($recipient_hash, $url))."&url=".urlencode($url)."&id=".$id;
        if(!empty($database)) {
            $url .= "&database=" . $database;
        }
        if(!empty($this->utm_source)) {
            $url .= "&utm_source=" . urlencode($this->utm_source);
        }
        if(!empty($this->utm_medium)) {
            $url .= "&utm_medium=" . urlencode($this->utm_medium);
        }
        if(!empty($this->utm_campaign)) {
            $url .= "&utm_campaign=" . urlencode($this->utm_campaign);
        }
        return $url;
    }
    
    public function replace_links($html) {
        $matches = array();
        $links = preg_match_all('/<a [^>]*href=[\'"]([^\'"]+)[\'"]/i', $html, $matches);
        if(count($matches[1])) {
            for($j=0; $j<count($matches[1]); $j++) {
                if(substr($matches[1][$j], 0, 1) != '#') {
                    $html = str_replace("'".$matches[1][$j]."'", "'".$this->get_builded_url($matches[1][$j])."'", $html);
                    $html = str_replace('"'.$matches[1][$j].'"', '"'.$this->get_builded_url($matches[1][$j]).'"', $html);
                }
            }
        }
        return $html;
    }
    
    public function proxyfication($corps) {
        $proxified_content = '';
        
        $proxified_content = $this->replace_links($corps);
        $proxified_content .= $this->get_white_pixel();
        return $proxified_content;
    }
    
    protected function get_white_pixel() {
        global $opac_url_base;
        
        $image_url = $opac_url_base."pixel.php";
        return "<img src='".$this->get_builded_url($image_url)."' alt='' />";
    }
    
    protected static function gen_hash($recipient_hash, $url) {
        global $opac_empr_password_salt;
        if ('' == $opac_empr_password_salt) {
            password::gen_salt_base();
        }
        return md5("{$opac_empr_password_salt}_{$recipient_hash}_{$url}");
    }
    
    public static function check($hash, $url, $id) {
        $campaign_recipient = new campaign_recipient($id);
        if($hash == static::gen_hash($campaign_recipient->get_hash(), $url)) {
            return true;
        }
        return false;
    }
    
    public function redirect($url) {
        global $opac_url_base;
        
        $location_url = html_entity_decode($url);
        if (strpos(trim($location_url), trim($opac_url_base)) === 0) {
            if (!empty($this->utm_source) || !empty($this->utm_medium) || !empty($this->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($this->utm_source)) {
                    $queryParams['utm_source'] = $this->utm_source;
                }
                if (!empty($this->utm_medium)) {
                    $queryParams['utm_medium'] = $this->utm_medium;
                }
                if (!empty($this->utm_campaign)) {
                    $queryParams['utm_campaign'] = $this->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);
    }
    
    public function set_utm_source($utm_source) {
        $this->utm_source = $utm_source;
        return $this;
    }
    
    public function set_utm_medium($utm_medium) {
        $this->utm_medium = $utm_medium;
        return $this;
    }
    
    public function set_utm_campaign($utm_campaign) {
        $this->utm_campaign = $utm_campaign;
        return $this;
    }
    
    public function set_campaign_recipient($campaign_recipient) {
        $this->campaign_recipient = $campaign_recipient;
        return $this;
    }
}