<?php
/* 
 * Fichier appelé en Ajax pour lire et écrire la cinfig Broker
 */

header('Content-type: text/xml');
include('adminBroker.class.php');
define('INI_CLIENT', '/webservices/client/config/encryptConfig.php');
$idclient = explode("|", $_GET['idclient'], 3);
$idclient = $idclient[0];
$ipclient = $_GET['ipclient'];
$action = $_GET['action'];
$typeconfig = $_GET['typeconfig'];

if (!empty($ipclient)) {
    if (!file_exists('cache')) mkdir('cache');
    $adminBroker = new adminBroker();
    $xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><root></root>');
    if (strpos($ipclient, ":")) {
        $ipclientnoport = substr($ipclient, 0, strpos($ipclient, ":"));
    }
    elseif (strpos($ipclient, "/")) {
        $ipclientnoport = substr($ipclient, 0, strpos($ipclient, "/"));
    }
    else $ipclientnoport = $ipclient;
    if ($action == 'read') {
        try {
            $opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n"));
            $context = stream_context_create($opts);
            if (!$iniFileEncrypted = @file_get_contents('http://'.$ipclient.INI_CLIENT.'?ip='.$ipclientnoport.'&idclient='.$idclient.'&typeconfig='.$typeconfig, false, $context)) throw new Exception('Impossible de lire la configuration distante');
            $iniFileGen = 'cache/config_'.$ipclientnoport.'.ini';
            $iniFileDecrypted = $adminBroker->decrypt($iniFileEncrypted, (strlen($ipclientnoport) < 11 ? $ipclientnoport : substr($ipclientnoport, -11)));
            if (!@file_put_contents($iniFileGen, $iniFileDecrypted)) throw new Exception('Impossible de stocker la configuration temporaire en local');
            $tabConfig = $adminBroker->readConfig($iniFileGen);
        }
        catch (Exception $e) {
            exit('<root><result>0</result><errorMsg>'.$e->getMessage().'</errorMsg></root>');
        }
        unlink($iniFileGen);
        if (empty($iniFileDecrypted) || !$tabConfig) $xml->addChild('result', 0);
        else {
            $xml->addChild('result', 1);
            foreach ($tabConfig as $part => $ssTabConfig) {
                $xmlPart = $xml->addChild($part);
                foreach ($ssTabConfig as $key => $value) {
                    $xmlPart->addChild($key, $value);
                }
            }
        }
    }
    if ($action == 'write') {
        $configJSON = urldecode($_POST['config']);
        $configJSON = str_replace('""', '"', $configJSON);
        $newTabConfig = json_decode($configJSON, true);
        //Réorganisation du tableau
        $tabConfigFinal = array();
        foreach ($newTabConfig as $key => $value) {
            if (strpos($value, "|")) $value = '"'.$value.'"'; //Protège si champs spéciaux
            list($section, $cle) = explode("_", $key, 2);
            $tabConfigFinal[$section][$cle] = $value;
        }
        $stringConfig = $adminBroker->writeConfig($tabConfigFinal);
        //Encryptage du fichier
        $stringConfig = $adminBroker->encrypt($stringConfig, $ipclientnoport);
        try {
            if (!file_exists('cache/'.$ipclientnoport)) mkdir('cache/'.$ipclientnoport);
            if (!@file_put_contents('cache/'.$ipclientnoport.'/config.ini', $stringConfig)) throw new Exception('Impossible d\'écrire dans cache/'.$ipclientnoport.'/config.ini (local)');
            $retour = $adminBroker->sendConfig($typeconfig, $idclient, $ipclient, 'cache/'.$ipclientnoport.'/config.ini');
            if ($retour[0]) {
                $xml->addChild('result', 1);
                $xml->addChild('confirmMsg', $retour[1]);
            }
            else {
                $xml->addChild('result', 0);
                $xml->addChild('errorMsg', $retour[1]);
            }
            unlink('cache/'.$ipclientnoport.'/config.ini');
        }
        catch (Exception $e) {
            $xml->addChild('result', 0);
            $xml->addChild('errorMsg', $e->getMessage());
        }
    }
    echo $xml->asXML();
}

?>
