<?php

error_reporting(0);

//Fonction exécutant l'action demandée
function executeAction($client, $version_client, $sigb, $action)
{
    $result = 0;
    switch ($action) {
        case 'login' :
            $client->returnLog('Réponse (v' . $version_client . ') >> decryptParams(' . $_GET['clientid'] . ', ' . $_GET['edata'] . ')');
            if ($version_client != 'standalone') $tabParams = $client->decryptParams($_GET['clientid'], $_GET['edata']);
            else $tabParams = $_GET;
            $result = $sigb->login($tabParams['username'], $tabParams['password']);
            break;
        case 'getVersion' :
            $client->returnLog('Réponse (v' . $version_client . ') >> getVersion()');
            $result = $sigb->getVersion();
            break;
        case 'getSigbConfiguration' :
            $client->returnLog('Réponse (v' . $version_client . ') >> getSigbConfiguration(' . $_GET['clientid'] . ')');
            $result = $sigb->getSigbConfiguration($_GET['clientid']);
            break;
        case 'accountDetails' :
            $client->returnLog('Réponse (v' . $version_client . ') >> accountDetails(' . $_GET['userid'] . ')');
            $result = $sigb->accountDetails($_GET['userid']);
            break;
        case 'accountDetailsGroup' :
            $client->returnLog('Réponse (v' . $version_client . ') >> accountDetailsGroup(' . $_GET['groupid'] . ')');
            $result = $sigb->accountDetailsGroup($_GET['groupid']);
            break;
        case 'getUserDetailsFromGroup' :
            $client->returnLog('Réponse (v' . $version_client . ') >> getUserDetailsFromGroup(' . $_GET['userid'] . ', ' . $_GET['groupid'] . ', ' . $_GET['usertype'] . ')');
            $result = $sigb->getUserDetailsFromGroup($_GET['userid'], $_GET['groupid'], $_GET['usertype']);
            break;
        case 'getGroupLoansAndBookings' :
            $client->returnLog('Réponse (v' . $version_client . ') >> getGroupLoansAndBookings(' . $_GET['groupid'] . ')');
            $result = $sigb->getGroupLoansAndBookings($_GET['groupid']);
            break;
        case 'getGroupLoansHistory' :
            $client->returnLog('Réponse (v' . $version_client . ') >> getGroupLoansHistory(' . $_GET['groupid'] . ')');
            $result = $sigb->getGroupLoansHistory($_GET['groupid']);
            break;
        case 'getUserLoans' :
            $client->returnLog('Réponse (v' . $version_client . ') >> getUserLoans(' . $_GET['user'] . ')');
            $result = $sigb->getUserLoans($_GET['userid'], $_GET['serialized']);
            break;
        case 'getUserLoansHistory' :
            $client->returnLog('Réponse (v' . $version_client . ') >> getUserLoansHistory(' . $_GET['user'] . ')');
            $result = $sigb->getUserLoansHistory($_GET['userid'], $_GET['serialized']);
            break;
        case 'updateAccount' :
            $client->returnLog('Réponse (v' . $version_client . ') >> decryptParams(' . $_GET['clientid'] . ', ' . $_GET['edata'] . ')');
            if ($version_client != 'standalone') {
                $formDatas = $client->decryptParams($_GET['clientid'], $_GET['edata']);
                $formDatas = array_merge($formDatas, $_GET);
            } else $formDatas = $_GET;
            $result = $sigb->updateAccount($formDatas);
            break;
        case 'updateGroupAccount' :
            $client->returnLog('Réponse (v' . $version_client . ') >> decryptParams(' . $_GET['clientid'] . ', ' . $_GET['edata'] . ')');
            if ($version_client != 'standalone') {
                $formDatas = $client->decryptParams($_GET['clientid'], $_GET['edata']);
                $formDatas = array_merge($formDatas, $_GET);
            } else $formDatas = $_GET;
            $result = $sigb->updateGroupAccount($formDatas);
            break;
        case 'userLostPassword' :
            $client->returnLog('Réponse (v' . $version_client . ') >> userLostPassword(' . $_GET['email'] . ')');
            $result = $sigb->userLostPassword($_GET['email']);
            break;
        case 'launchExportISO' :
            if ($client->activateExport != 'F') {

                //on recupère la date du serveur
                $dateserveur = $sigb->getDateServeur();

                if (file_exists($client->isoexportPath . $client->idclient . '/lock') && file_exists($client->isoexportPath . $client->idclient . '/exports_full.log')) {
                    $infos = stat($client->isoexportPath . $client->idclient . '/lock');
                    $total = time() - $infos['mtime'];

                    if ($total > 21600) {
                        unlink($client->isoexportPath . $client->idclient . '/lock');
                    }
                }


                set_time_limit(36000);
                ini_set('default_socket_timeout', 36000);
                if (!file_exists($client->isoexportPath)) mkdir($client->isoexportPath);
                if (!file_exists($client->isoexportPath . $client->idclient)) mkdir($client->isoexportPath . $client->idclient);
                if (!file_exists($client->isoexportPath . $client->idclient . '/lock')) {
                    //Mise en place d'un lock
                    touch($client->isoexportPath . $client->idclient . '/lock');
                    $retour = $sigb->launchExportISO($client->isoexportCall, $client->isoexportPath . $client->idclient . '/', $_GET['type'], $client->allowedExportTime);
                    $returnCode = $retour['error'];
                    $nameFile = $retour['namefile'];
                    $typeExport = $retour['export'];
                    $exportPath = $retour['fullExportPath'];
                    //Remise par défaut des variables ini
                    ini_restore('max_execution_time');
                    ini_restore('default_socket_timeout');
                    if ($returnCode == 0 && !empty($nameFile)) {
                        if (file_exists($exportPath . $nameFile . ".xml")) {
                            //Ajout des informations dans le XML
                            if ($etablissement = $sigb->updateXML($client->isoexportPath . $client->idclient . '/', $nameFile, $typeExport, $client->isoexportPath . $client->idclient . '/', $dateserveur)) {
                                $client->returnLog('Réponse (v' . $version_client . ') >> Fichier ISO créé');
                                if ($client->compressExport == 'T') {
                                    $result = $client->zip($exportPath, $nameFile);
                                    $ext = array('zip');
                                } else $ext = array('iso', 'xml');
                                $client->sendExport($etablissement, $client->methodSendExport, $exportPath, $client->dirSendExport, $ext);
                                $result .= '|' . $client->methodSendExport;
                            } else {
                                $client->returnError('XML Export ISO non généré', '802');
                            }
                        } else $client->returnError('Export ISO non généré', '801');
                    } elseif ($returnCode == -1) $client->returnError('Erreur processus d\'export : ' . $retour['errorLog'], '800');
                    //Suppression du lock
                    if (file_exists($client->isoexportPath . $client->idclient . '/lock')) unlink($client->isoexportPath . $client->idclient . '/lock');
                } else {
                    //Si on a un lock et aussi le fichier temporaire d'indisponibilité de la base, on les supprime pour réessayer la prochaine fois
                    if (file_exists('unavailable_' . $sigb->infos() . '_database.tmp')) {
                        unlink('unavailable_' . $sigb->infos() . '_database.tmp');
                        unlink($client->isoexportPath . $client->idclient . '/lock');
                    }
                }
            }
            break;
        case 'nextCompleteExportISO' :
            $client->returnLog('Réponse (v' . $version_client . ') >> nextCompleteExportISO()');
            $sigb->nextCompleteExportISO($client->isoexportPath . $client->idclient . '/');
            break;
        case 'copyDetails' :
            $client->returnLog('Réponse (v' . $version_client . ') >> copyDetails(' . $_GET['nn'] . ', ' . $_GET['institution'] . ')');
            $result = $sigb->copyDetails($_GET['nn'], $_GET['institution'], $_GET['userid']);
            break;
        case 'getDamInfos' :
            $client->returnLog('Réponse (v' . $version_client . ') >> ' . $action . '(' . $_GET['ids'] . ')');
            $result = $sigb->$action($_GET['clientid'], $_GET['ids']);
            break;
        case 'getNotice' :
            $client->returnLog('Réponse (v' . $version_client . ') >> ' . $action . '(' . $_GET['nn'] . ')');
            $result = $sigb->$action($_GET['nn']);
            break;
        case 'getOeuvre' :
            $client->returnLog('Réponse (v' . $version_client . ') >> ' . $action . '(' . $_GET['nn'] . ')');
            $result = $sigb->$action($_GET['nn']);
            break;
        case 'prolongLoan' :
            $client->returnLog('Réponse (v' . $version_client . ') >> ' . $action . '(' . $_GET['loanid'] . ', ' . $_GET['userid'] . ')');
            $result = $sigb->$action($_GET['loanid'], $_GET['userid']);
            break;
        case 'getAvailableSuggestion' :
            $client->returnLog('Réponse (v' . $version_client . ') >> ' . $action);
            $result = $sigb->$action();
            break;
        case 'suggestDocument' :
            $client->returnLog('Réponse (v' . $version_client . ') >> ' . $action);
            $result = $sigb->$action($_GET);
            break;
        case 'reserveInfo' :
            $client->returnLog('Réponse (v' . $version_client . ') >> ' . $action . '(' . $_GET['nn'] . ', ' . $_GET['userid'] . ')');
            $result = $sigb->$action($_GET['nn'], $_GET['userid']);
            break;
        case 'reserveElectronicals' :
            $client->returnLog('Réponse (v' . $version_client . ') >> ' . $action . '(' . $_GET['idelectronicals'] . ', ' . $_GET['userid'] . ')');
            $result = $sigb->$action($_GET['idelectronicals'], $_GET['mode'], $_GET['userid']);
            break;
        case 'reserveDocument' :
            $client->returnLog('Réponse (v' . $version_client . ') >> ' . $action . '(' . $_GET['nn'] . ', ' . $_GET['userid'] . ', ' . $_GET['site'] . ')');
            $result = $sigb->$action($_GET['nn'], $_GET['userid'], $_GET['site']);
            break;
        case 'reserveCancel' :
            $client->returnLog('Réponse (v' . $version_client . ') >> ' . $action . '(' . $_GET['resid'] . ', ' . $_GET['userid'] . ')');
            $result = $sigb->$action($_GET['resid'], $_GET['userid']);
            break;
        case 'sendMessage' :
            $client->returnLog('Réponse (v' . $version_client . ') >> ' . $action . '(' . $_GET['userid'] . ', ' . $_GET['IDs'] . ', ' . $_GET['Action'] . ', ' . $_GET['Object'] . ', ' . $_GET['Text'] . ', ' . $_GET['SuggTitle'] . ', ' . $_GET['SuggAuthor'] . ', ' . $_GET['SuggEditor'] . ', ' . $_GET['SuggDocTypeCode'] . ')');
            $result = $sigb->$action($_GET['userid'], $_GET['IDs'], $_GET['Action'], $_GET['Object'], $_GET['Text'], $_GET['SuggTitle'], $_GET['SuggAuthor'], $_GET['SuggEditor'], $_GET['SuggDocTypeCode']);
            break;
        case 'importAB' :
            $client->returnLog('Réponse (v' . $version_client . ') >> ' . $action . '(' . $_GET['na'] . ', ' . $_GET['nom'] . ', ' . $_GET['pn'] . ', ' . $_GET['ccivilite'] . ', ' . $_GET['sexe'] . ', ' . $_GET['datnais'] . ', ' . $_GET['adresse1'] . ', ' . $_GET['adresse2'] . ', ' . $_GET['cp'] . ', ' . $_GET['ville'] . ', ' . $_GET['tel1'] . ', ' . $_GET['tel2'] . ', ' . $_GET['email'] . ', ' . $_GET['ccat1'] . ', ' . $_GET['ccat2'] . ', ' . $_GET['ccat3'] . ', ' . $_GET['ccat4'] . ', ' . $_GET['cannexe'] . ', ' . $_GET['ccotis'] . ', ' . $_GET['debut'] . ', ' . $_GET['fin'] . ')');
            $result = $sigb->$action($_GET['na'], $_GET['nom'], $_GET['pn'], $_GET['ccivilite'], $_GET['sexe'], $_GET['datnais'], $_GET['adresse1'], $_GET['adresse2'], $_GET['cp'], $_GET['ville'], $_GET['tel1'], $_GET['tel2'], $_GET['email'], $_GET['ccat1'], $_GET['ccat2'], $_GET['ccat3'], $_GET['ccat4'], $_GET['cannexe'], $_GET['ccotis'], $_GET['debut'], $_GET['fin']);
            break;
        default :
            $client->returnLog('Réponse (v' . $version_client . ') >> ' . $action . '()');
            $result = $sigb->$action($_GET);
            break;
    }
    return $result;
}

function fatalErrorShutdownHandler()
{
    $last_error = error_get_last();
    if ($last_error['type'] === E_ERROR) {
        file_put_contents(dirname(__FILE__) . '/logs/errors.log', date("Ymd-H:i:s") . ' >> Fatal Error Exception : ' . $last_error['message'] . ' (' . $last_error['file'] . ', ligne ' . $last_error['line'] . ')' . "\n", FILE_APPEND);
        exit('install');
    }
}

//Gestion des paramètres en cas d'appel CLI
if (count($_GET) == 0 && $_SERVER['argc'] > 1) {
    $_REQUEST['idclient'] = $_SERVER['argv'][1];
    $_GET['idclient'] = $_SERVER['argv'][1];
    $_REQUEST['sigb'] = $_SERVER['argv'][2];
    $_GET['sigb'] = $_SERVER['argv'][2];
    $_REQUEST['action'] = $_SERVER['argv'][3];
    $_GET['action'] = $_SERVER['argv'][3];
}

//Include des classes
require("class/client.class.php");

//Instanciation du client
$client = new client(isset($_REQUEST['idclient']) ? $_REQUEST['idclient'] : '', isset($_REQUEST['sigb']) ? $_REQUEST['sigb'] : '');
$result = 0;

//Réception de requête cURL pour la MAJ/config
if (isset($_POST['mode']) && ($_POST['mode'] == 'maj' || $_POST['mode'] == 'config')) {
    $pathFile = '';
    if ($_POST['mode'] == 'maj') $pathFile = $client->classPath;
    if ($_POST['mode'] == 'config' && !empty($_POST['idclient'])) {
        switch ($_POST['typeconfig']) {
            case 'general' :
                $pathFile = 'config/' . $_POST['idclient'] . '/';
                break;
            case 'monitoring' :
                $pathFile = '../monitoring/';
                break;
        }
    }
    //Vérification de l'existence de $_FILES qui contient les informations sur le fichier envoyé
    if (isset($_FILES['file']) && !empty($pathFile)) {
        if (!file_exists($pathFile)) mkdir($pathFile);
        if (is_uploaded_file($_FILES['file']['tmp_name'])) {
            //Déplacement du fichier
            move_uploaded_file($_FILES['file']['tmp_name'], $pathFile . $_FILES['file']['name']);
            if ($_POST['mode'] == 'config') {
                if (!file_exists($pathFile)) mkdir($pathFile);
                //$client->decryptConfig($pathFile.$_FILES['file']['name'], substr($_POST['ip'], -11));
                $client->decryptConfig($pathFile . $_FILES['file']['name'], (strlen($_POST['ip']) < 11 ? $_POST['ip'] : substr($_POST['ip'], -11)));
            }
        }
    } else {
        echo $client->returnError('Aucun fichier reçu pour ' . $_POST['mode'], '404', true);
    }
}

//Opérations normales
if (isset($_GET['sigb']) && isset($_GET['action']) && isset($_GET['version']) && isset($_GET['key'])) {
    //Préparation des paramètres
    $classname = $_GET['sigb'];
    $version = $_GET['version'];
    $action = $_GET['action'];
    $key = $_GET['key'];
    $go_on = true;

    //Vérification de la clé
    if ($client->checkKey($key)) {
        //Cas du unzip
        if (isset($_GET['zip']) && $_GET['zip'] == '1' && isset($_GET['file']) && isset($_GET['md5file'])) {
            $client->returnLog('Demande de MAJ de classe reçue');
            if (!$client->unzip($_GET['file'], $_GET['md5file'])) {
                $go_on = false;
                $result = -1;
            }
            if ($action == 'forceUpdate') $action = '';
        }
        //Cas du force update
        if ($action == 'forceUpdate') {
            @unlink("sigb_class/Stats.class.php");
            @unlink("sigb_class/sigb.class.php");
            @unlink("sigb_class/" . $classname . ".class.php");
            if ($classname == 'gabi') @unlink("sigb_class/JsonHttpClient.class.php");
        }
        if ($go_on) {
            //Include de la bonne classe SIGB
            register_shutdown_function('fatalErrorShutdownHandler');
            @include("sigb_class/Stats.class.php");
            @include("sigb_class/sigb.class.php");
            @include("sigb_class/" . $classname . ".class.php");
            $classnameBK = $classname . 'BK';
            if (class_exists($classnameBK)) {
                $version_client = call_user_func(array($classnameBK, 'version'));
                if ($version != $version_client) {
                    $client->returnError('Version de classe cliente obsolète. Mise à jour nécessaire de v' . $version_client . ' vers v' . $version, '501');
                    $result = 'maj';
                } elseif ($action != '') {
                    $sigb = new $classnameBK();
                    $sigb->databaseName = $client->databaseName;
                    $sigb->databaseID = $client->databaseID;
                    $sigb->hostData = $client->hostData;
                    $sigb->portData = $client->portData;
                    $sigb->userData = $client->userData;
                    $sigb->passData = $client->passData;
                    $sigb->hostApi = $client->hostApi;
                    $sigb->portApi = $client->portApi;
                    $sigb->keyApi = $client->keyApi;
                    $sigb->institutionId = $client->institutionId;
                    $sigb->wsPath = $client->wsPath;
                    $sigb->idClient = $client->idclient;
                    if (method_exists($sigb, $action)) {
                        $result = executeAction($client, $version_client, $sigb, $action);
                    } else {
                        $client->returnError('Méthode non implémentée', '404');
                        $result = -1;
                    }
                }
            } else {
                $client->returnError('Classe cliente inexistante. Installation nécessaire en v' . $version, '502');
                $result = 'install';
            }
        } else {
            $client->returnError('Problème de mise à jour de classe, impossible de continuer', '530');
            $result = -1;
        }
    } else {
        $client->returnError('Erreur authentification key', '500');
        $result = -1;
    }
} elseif (isset($_GET['sigb']) && isset($_GET['action'])) { //Cas standalone d'export ISO par le client
    //Include de la bonne classe SIGB
    @include("sigb_class/Stats.class.php");
    @include("sigb_class/sigb.class.php");
    @include("sigb_class/" . $_GET['sigb'] . ".class.php");
    $classnameBK = $_GET['sigb'] . 'BK';
    if (class_exists($classnameBK)) {
        $sigb = new $classnameBK();
        $sigb->databaseName = $client->databaseName;
        $sigb->databaseID = $client->databaseID;
        $sigb->hostData = $client->hostData;
        $sigb->portData = $client->portData;
        $sigb->userData = $client->userData;
        $sigb->passData = $client->passData;
        $sigb->hostApi = $client->hostApi;
        $sigb->portApi = $client->portApi;
        $sigb->keyApi = $client->keyApi;
        $sigb->institutionId = $client->institutionId;
        $sigb->wsPath = $client->wsPath;
        $sigb->idClient = $client->idclient;
        $result = executeAction($client, 'standalone', $sigb, $_GET['action']);
    }
} elseif ($_POST['action'] = 'infosclass') {
    @include("sigb_class/Stats.class.php");
    @include("sigb_class/sigb.class.php");

    if (file_exists("sigb_class/ktm.class.php")) {
        @include("sigb_class/ktm.class.php");
        $classnameBK = "ktmBK";
    } elseif (file_exists("sigb_class/karvi.class.php")) {
        @include("sigb_class/karvi.class.php");
        $classnameBK = "karviBK";
    } elseif (file_exists("sigb_class/agate.class.php")) {
        @include("sigb_class/agate.class.php");
        $classnameBK = "agateBK";
    } elseif (file_exists("sigb_class/aloes.class.php")) {
        @include("sigb_class/aloes.class.php");
        $classnameBK = "aloesBK";
    } elseif (file_exists("sigb_class/koha.class.php")) {
        @include("sigb_class/koha.class.php");
        $classnameBK = "kohaBK";
    } elseif (file_exists("sigb_class/flora.class.php")) {
        @include("sigb_class/flora.class.php");
        $classnameBK = "floraBK";
    }

    $sigb = new $classnameBK();
    $version = $sigb->version();
    $classname = $sigb->infos();
    $result = $classname . "|" . $version;
}

//Affichage du résultat
echo $result;