<?php

class gabiBK implements sigb {

    const version = "1.3.25";
    const nameClass = "eppk";

    public $hostData;
    public $portData;
    public $userData;
    public $passData;
    public $ext_path;

    public $hostApi;
    public $portApi;
    public $keyApi;

    private $oJSON;
    private $bStandalone;

    function __construct($sExtPath = './') {
        $this->ext_path = $sExtPath;
        $this->bStandalone = false;
    }

    private function connect($sHost, $iPort, $sUser, $sPass) {
        require_once ($this->ext_path."sigb_class/JsonHttpClient.class.php"); //Classe JSON
        file_put_contents('C:/Projects/PortailAgents/trunk/serveur/serveur.log', 'host : ' . $sHost . 'port : ' . $iPort, FILE_APPEND);
        if ($iPort == 443) {
            $this->oJSON = new JsonHttpClientSsl($sHost, $iPort);
        } else {
            $this->oJSON = new JsonHttpClient($sHost, $iPort);
        }
        $this->oJSON->setDebug(false);
        //$this->authentification($sUser, $sPass);
    }

    private function buildPath($path) {
        $urlPrefix = '/eppk-web' . '/rest';
        return $urlPrefix . $path;
    }

    private function buildPathApi($path) {
        $urlPrefix = 'https://'.$this->hostApi.'/ws.php?_action_=publicapi&path=/v1';
        return $urlPrefix . $path;
    }

    private function decodeResponse($client) {
        if ($client->getStatus() != 200) {
            if (false) {
                throw new Exception('http status code is not 200');
            } else {
                $res = array('error' => 'Backend call error', 'stacktrace' => array());
                return (object) array('success' => false, 'res' => $res);
            }
        }
        $jsonresponse = json_decode($client->getContent());
        return $jsonresponse;
    }

    //Demande de la date du serveur biblio
    public function getDateServeur(){

        $date_serveur="";

        //à  développer

        return $date_serveur;

    }

    static function version() {
        return self::version;
    }

    static function infos() {
        return self::nameClass;
    }

    static function fullInfos() {
        return 'SIGB : ePaprika<br />Agent SIGB : '.self::infos().' (version : '.self::version().')';
    }

    public function copyDetails($idNotice, $institution, $userInt="") {
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $this->oJSON->get($this->buildPath("/portal/catalog/bibrecord/".$idNotice."/items"));
        $jsonresponse = $this->decodeResponse($this->oJSON);

        return $this->formatResult($jsonresponse, 'copyDetails', '');
    }

    public function getVersion($serialize=true){
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $this->oJSON->get($this->buildPath("/version.json"));
        $jsonresponseDetails = $this->decodeResponse($this->oJSON);
        if ($serialize === true){
            $jsonresponseDetails = serialize($jsonresponseDetails);
        }
        return $jsonresponseDetails;
    }

    public function getVersionAgent() {
        return $this->formatResult(self::version, 'getVersionAgent');
    }

    public function getSigbConfiguration($clientid) {
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $this->oJSON->get($this->buildPath("/portal/network/" . $clientid));
        $jsonresponseDetails = $this->decodeResponse($this->oJSON);
        $jsonresponseDetails = serialize($jsonresponseDetails);
        return $jsonresponseDetails;
    }

    public function login($user, $pass, $ldap=false) {
        $version = $this->getVersion(false);
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        if ($version->res->major > 4 || ($version->res->major == 4 && $version->res->minor >= 5)){ // login regroupement
            $this->oJSON->setHeader('name', $user);
            $this->oJSON->setHeader('password', $pass);
            $this->oJSON->get($this->buildPath("/publicauth/login/"));
        } else { // login classique            
            $this->oJSON->setHeader('username', $user);
            $this->oJSON->setHeader('password', $pass);
            $this->oJSON->get($this->buildPath("/publicauth/"));
        }
        $jsonresponse = $this->decodeResponse($this->oJSON);
        if (!$jsonresponse->success) {
            //Erreur authentification
            return $this->formatResult($jsonresponse, 'login', 'failed');
        }
        else {
            return $this->formatResult($jsonresponse, 'login', $user);
        }
    }

    public function accountDetails($userInt, $history=true) {
        $version = $this->getVersion(false);
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $this->oJSON->get($this->buildPath("/portal/public/user/".$userInt), false);
        $jsonresponseDetails = $this->decodeResponse($this->oJSON);
        $jsonresponse = new stdClass();
        if (!$jsonresponseDetails->success) {
            $jsonresponse->details = $jsonresponseDetails->error;
        }
        else {
            $jsonresponse->details = $jsonresponseDetails->res;
        }

        //Ajout des autres information du compte : prêts et historiques
        $this->bStandalone = true;
        $jsonresponse->loans = $this->getUserLoans($userInt);
        if ($history == "true" || $history == true) {
            $jsonresponse->history = $this->getUserLoansHistory($userInt);
        }
        $jsonresponse->bookings = $this->getUserBookingsHistory($userInt);
        if ($version->res->major > 4 ||($version->res->major == 4 && $version->res->minor >= 11)){ // Prêts documents numériques
            $jsonresponse->loanElectronicals = $this->getUserLoanElectronicals($userInt);
        }

        return serialize($jsonresponse);
    }

    public function accountDetailsGroup($groupId) {
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $this->oJSON->get($this->buildPath("/portal/public/grouping/statistics/".$groupId), false);
        $jsonresponseDetails = $this->decodeResponse($this->oJSON);
        $jsonresponse = new stdClass();

        if (!$jsonresponseDetails->success) {
            $jsonresponse->details = $jsonresponseDetails->error;
        }
        else {
            $jsonresponse->details = $jsonresponseDetails->res;
        }
        return serialize($jsonresponse);
    }

    public function getUserDetailsFromGroup($userid, $groupid, $usertype) {
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        if ($usertype == 'regroupement'){
            $this->oJSON->get($this->buildPath("/portal/public/grouping/".$userid), false);
        } else {
            $this->oJSON->get($this->buildPath("/portal/public/user/".$userid), false);
        }
        $jsonresponseDetails = $this->decodeResponse($this->oJSON);
        $jsonresponse = new stdClass();
        if ($usertype != 'regroupement' && $groupid != $jsonresponseDetails->res->grouping->id){
            $jsonresponse->details = 'User Id and Group are not the same';
        } else {
            $userDetails = new stdClass();
            if ($usertype == 'regroupement'){
                $userDetails->id = $jsonresponseDetails->res->id;
                $userDetails->code = $jsonresponseDetails->res->code;
                $userDetails->email = $jsonresponseDetails->res->email;
                $userDetails->fullname = $jsonresponseDetails->res->name;
                $userDetails->groupingType = $jsonresponseDetails->res->groupingType->name;
                $userDetails->groupAdmin = '0';
                $userDetails->type = $usertype;
                $userDetails->groupId = $jsonresponseDetails->res->id;
            } else {
                $userDetails->id = $jsonresponseDetails->res->id;
                $userDetails->code = $jsonresponseDetails->res->code;
                $userDetails->email = $jsonresponseDetails->res->email;
                $userDetails->groupAdmin = '1';
                $userDetails->groupId = $groupid;
            }
            $jsonresponse->details = $userDetails;
        }

        return serialize($jsonresponse);
    }

    public function getGroupLoansAndBookings($groupId) {
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $this->oJSON->get($this->buildPath("/portal/public/grouping/loansAndBookings/".$groupId), false);
        $jsonresponseDetails = $this->decodeResponse($this->oJSON);
        $jsonresponse = new stdClass();
        if (!$jsonresponseDetails->success) {
            $jsonresponse->details = $jsonresponseDetails->error;
        }
        else {
            $jsonresponse->details = $jsonresponseDetails->res;
        }
        return serialize($jsonresponse);
    }

    public function getGroupLoansHistory($groupId) {
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $this->oJSON->get($this->buildPath("/portal/public/grouping/loansHistory/".$groupId), false);
        $jsonresponseDetails = $this->decodeResponse($this->oJSON);
        $jsonresponse = new stdClass();
        if (!$jsonresponseDetails->success) {
            $jsonresponse->details = $jsonresponseDetails->error;
        }
        else {
            $jsonresponse->details = $jsonresponseDetails->res;
        }
        return serialize($jsonresponse);
    }

    public function accountDetailsBarCode($params) {
        $version = $this->getVersion(false);
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $this->oJSON->get($this->buildPath("/portal/public/barcode/networks/".$params['institution']."/user/".$params['userbarcode']), false);
        $jsonresponseDetails = $this->decodeResponse($this->oJSON);
        $jsonresponse = new stdClass();

        if (!$jsonresponseDetails->success) {
            $jsonresponse->details = $jsonresponseDetails->error;
        }
        else {
            $jsonresponse->details = $jsonresponseDetails->res;
        }
        //Ajout des autres information du compte : prêts et historiques
        $this->bStandalone = true;
        $jsonresponse->loans = $this->getUserLoansBarCode($params);
        if ((isset($params['history']) && $params['history'] == true) || !isset($params['history'])) {
            $jsonresponse->history = $this->getUserLoansHistoryBarCode($params);
        }
        $jsonresponse->bookings = $this->getUserBookingsHistoryBarCode($params);
        if ($version->res->major > 4 ||($version->res->major == 4 && $version->res->minor >= 11)) { // Prêts documents numériques
            $jsonresponse->loanElectronicals = $this->getUserLoanElectronicalsBarCode($params);
        }

        return serialize($jsonresponse);
    }
    public function getUserLoans($userInt, $serialiszed = false) {
        if (!$this->bStandalone) $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $this->oJSON->get($this->buildPath("/portal/public/user/".$userInt."/loans"), false);
        $jsonresponse = $this->decodeResponse($this->oJSON);

        if (!$jsonresponse->success) {
            if ($serialiszed !== false){
                return serialize($jsonresponse->error);
            }
            return $jsonresponse->error;
        }
        else {
            if ($serialiszed !== false){
                return serialize($jsonresponse->res);
            }
            return $jsonresponse->res;
        }
    }
    public function getUserLoanElectronicals($userInt) {
        if (!$this->bStandalone) $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $this->oJSON->get($this->buildPath("/portal/public/user/".$userInt."/loanElectronicals"), false);

        $jsonresponse = $this->decodeResponse($this->oJSON);

        if (!$jsonresponse->success) {
            return $jsonresponse->error;
        }
        else {
            return $jsonresponse->res;
        }
    }
    public function getUserLoansBarCode($params) {
        if (!$this->bStandalone) $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $this->oJSON->get($this->buildPath("/portal/public/barcode/networks/".$params['institution']."/user/".$params['userbarcode']."/loans"), false);
        $jsonresponse = $this->decodeResponse($this->oJSON);

        if (!$jsonresponse->success) {
            return $jsonresponse->error;
        }
        else {
            return $jsonresponse->res;
        }
    }
    public function getUserLoansHistory($userInt, $serialiszed = false) {
        if (!$this->bStandalone) $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $this->oJSON->get($this->buildPath("/portal/public/user/".$userInt."/loansHistory"), false);
        $jsonresponse = $this->decodeResponse($this->oJSON);
        if (!$jsonresponse->success) {
            if ($serialiszed !== false){
                return serialize($jsonresponse->error);
            }
            return $jsonresponse->error;
        }
        else {
            if ($serialiszed !== false){
                return serialize($jsonresponse->res);
            }
            return $jsonresponse->res;
        }
    }
    public function getUserLoanElectronicalsBarCode($params) {
        if (!$this->bStandalone) $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $this->oJSON->get($this->buildPath("/portal/public/barcode/networks/".$params['institution']."/user/".$params['userbarcode']."/loanElectronicalsHistory"), false);
        $jsonresponse = $this->decodeResponse($this->oJSON);

        if (!$jsonresponse->success) {
            return $jsonresponse->error;
        }
        else {
            return $jsonresponse->res;
        }
    }
    public function getUserLoansHistoryBarCode($params) {
        if (!$this->bStandalone) $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $this->oJSON->get($this->buildPath("/portal/public/barcode/networks/".$params['institution']."/user/".$params['userbarcode']."/loansHistory"), false);
        $jsonresponse = $this->decodeResponse($this->oJSON);

        if (!$jsonresponse->success) {
            return $jsonresponse->error;
        }
        else {
            return $jsonresponse->res;
        }
    }
    public function getUserBookingsHistory($userInt) {
        if (!$this->bStandalone) $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $this->oJSON->get($this->buildPath("/portal/public/user/".$userInt."/bookingsHistory"), false);
        $jsonresponse = $this->decodeResponse($this->oJSON);
        if (!$jsonresponse->success) {
            return $jsonresponse->error;
        }
        else {
            return $jsonresponse->res;
        }
    }
    public function getUserBookingsHistoryBarCode($params) {
        if (!$this->bStandalone) $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $this->oJSON->get($this->buildPath("/portal/public/barcode/networks/".$params['institution']."/user/".$params['userbarcode']."/bookingsHistory"), false);
        $jsonresponse = $this->decodeResponse($this->oJSON);

        if (!$jsonresponse->success) {
            return $jsonresponse->error;
        }
        else {
            return $jsonresponse->res;
        }
    }

    public function updateAccount($formDatas) {
        $errorReturn = 0;
        if (isset($formDatas['password'])){
            //Vérification du mot de passe actuel
            $xmlOldPassString = $this->login($formDatas['username'], $formDatas['password']);
            $xmlOldPass = simplexml_load_string($xmlOldPassString);
            if ($xmlOldPass->login->error != '0') $errorReturn = 1;
            $login = $formDatas['username'];
            //Update password
            if ($errorReturn == 0) {
                $oldPassword = $formDatas['password'];
                if ($formDatas['newpassword'] != ''){
                    $data['password'] = $formDatas['newpassword'];
                } else {
                    $data['password'] = $oldPassword;
                }
                if ($formDatas['newlogin'] != ''){
                    $data['login'] = $formDatas['newlogin'];
                } else {
                    $data['login'] = $formDatas['username'];
                }
                if ($formDatas['type'] == 'regroupement'){
                    $this->oJSON->setHeader('groupingname', $login);
                } else {
                    $this->oJSON->setHeader('username', $login);
                }
                $this->oJSON->setHeader('password', $oldPassword);
                if ($formDatas['type'] == 'regroupement'){
                    $this->oJSON->put($this->buildPath("/publicauth/changeGroupingIdent"), $data);
                } else {
                    $this->oJSON->put($this->buildPath("/publicauth/changeIdent"), $data);
                }
                $jsonresponse = $this->decodeResponse($this->oJSON);

                if (!$jsonresponse->success) {
                    if (strpos($jsonresponse->msg,'already used') !== false){
                        $errorReturn = 3;
                    } else {
                        $errorReturn = -1;
                    }
                }
                if ($formDatas['newlogin'] != '' && $errorReturn != 3){
                    $newlogin = $formDatas['newlogin'];
                }
            }

        }

        $version = $this->getVersion(false);
        if ($version->res->major > 5 || ($version->res->major == 5 && $version->res->minor >= 2)){ // Maj des informations du compte abonnés pour la DSI
            if ($version->res->major > 5 || ($version->res->major == 5 && $version->res->minor >= 3)){
                $informationModified = array('email','mobileNumber','phoneNumber','allowSmsSending','allowInformationSms','allowInformationMail');
            } else {
                $informationModified = array('email','allowInformationMail');
            }
            $modifyDatas = false;
            $userid = $formDatas['userid'];
            $type = $formDatas['type'];
            $data = array();
            foreach ($informationModified as $dataName){
                if ($formDatas['new'.$dataName] != ''){
                    $data[$dataName] = $formDatas['new'.$dataName];
                    continue;
                }
                $data[$dataName] = $formDatas[$dataName];
            }
            $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
            if ($type == 'regroupement'){
                $this->oJSON->put($this->buildPath("/portal/public/grouping/".$userid), $data);
            } else {
                $this->oJSON->put($this->buildPath("/portal/public/user/".$userid), $data);
            }
            $jsonresponse = $this->decodeResponse($this->oJSON);
            unset($this->oJSON);
            if (!$jsonresponse->success) {
                $errorReturn = -1;
            }
        } else {
            if (isset($formDatas['email'])){
                $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
                //Update email
                $newEmail = $formDatas['email'];
                $data = array('email' => $newEmail);
                if ($formDatas['type'] == 'regroupement'){
                    $this->oJSON->put($this->buildPath("/portal/public/grouping/".$formDatas['userid']), $data);
                } else {
                    $this->oJSON->put($this->buildPath("/portal/public/user/".$formDatas['userid']), $data);
                }
                $jsonresponse = $this->decodeResponse($this->oJSON);
                unset($this->oJSON);
                if (!$jsonresponse->success) {
                    $errorReturn = -1;
                }
            }
        }
        return $this->formatResult($jsonresponse, 'updateAccount', array('username' => $formDatas['username'], 'errorCode' => $errorReturn, 'newlogin' => $newlogin));
    }

    public function updateGroupAccount($formDatas) {
        if (!$this->bStandalone) $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        if ($formDatas['members'] != ''){
            $members = json_decode(base64_decode($formDatas['members']),true);
        }
        $data['members'] = $members;
        $data['sortMembersBy'] = $formDatas['sortMembersBy'];
        $this->oJSON->put($this->buildPath("/portal/public/user/".$formDatas['userid']."/members"), $data);
        $jsonresponse = $this->decodeResponse($this->oJSON);
        unset($this->oJSON);
        if (!$jsonresponse->success) {
            $errorReturn = -1;
        }
        return $this->formatResult($jsonresponse, 'updateGroupAccount', array('errorCode' => $errorReturn));
    }

    public function userLostPassword($email) {
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $data = array('email' => $email);
        $this->oJSON->post($this->buildPath("/publicauth/lostPassword"), $data);
        $jsonresponse = $this->decodeResponse($this->oJSON);
        $result = '';

        if (!$jsonresponse->success) {
            $result = $jsonresponse->error;
        }
        else {
            $result = $jsonresponse->res;
        }
        return '<?xml version="1.0" encoding="utf-8"?><root><error>'.$result.'</error></root>';
    }

    private function authentification($sUser, $sPass) {
        $this->oJSON->setAuthentication($sUser, $sPass);
    }

    public function getNotice($sIdNotice) {
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $bResult = $this->oJSON->get($this->buildPath("/portal/catalog/bibrecord/".$sIdNotice));

        if ($bResult) {
            $jsonresponse = $this->decodeResponse($this->oJSON);
            return $this->formatResult($jsonresponse, 'getNotice');
        }
        else {
            return $this->oJSON->getError();
        }
    }

    public function getDamInfos($clientid, $ids) {
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $arrContextOptions = array(
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false
            ));
        try {
            $bResult = $this->_file_get_contents('http://'.$this->hostData."/daminfos/multiple/$clientid/".$ids, false, stream_context_create($arrContextOptions));
            if ($bResult['infos']['http_code'] == 500 ) {
                throw new Exception(htmlentities($bResult['return']), 500);
            }
            $bResult = mb_convert_encoding($bResult['return'], 'UTF-8',mb_detect_encoding($bResult['return'], 'UTF-8, ISO-8859-1', true)); // Conversion de la chaine en UTF8
            if ($bResult) {
                $jsonresponse = json_decode($bResult);
                $result = $this->formatResult($jsonresponse, 'getDamInfos', $clientid);
                return $result;
            }
        }
        catch (Exception $e) {
            return '<?xml version="1.0" encoding="utf-8"?><root><errorCode>'.$e->getCode().'</errorCode><errorMessage>'.$e->getMessage().'</errorMessage></root>';
        }
    }

    public function getOeuvre($sIdOeuvre) {
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $bResult = $this->oJSON->get($this->buildPath("/portal/catalog/work/".$sIdOeuvre));

        if ($bResult) {
            $jsonresponse = $this->decodeResponse($this->oJSON);
            return $this->formatResult($jsonresponse, 'getOeuvre');
        }
        else {
            return $this->oJSON->getError();
        }
    }

    public function prolongLoan($id, $userid="") {
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $bResult = $this->oJSON->post($this->buildPath("/portal/public/user/".$userid."/loans/".$id."/extend"), array());
        if ($bResult) {
            $jsonresponse = $this->decodeResponse($this->oJSON);
            return $this->formatResult($jsonresponse, 'prolongLoan');
        }
        else {
            return $this->oJSON->getError();
        }
    }

    // Récupère les domaines ayant les suggestions d'abonnés activées
    public function getAvailableSuggestion() {
        $this->connect($this->hostApi, $this->portApi, $this->userData, $this->passData);
        $this->oJSON->setHeader('apikey', $this->keyApi);
        $bResult = $this->oJSON->get($this->buildPathApi("/purchasing/libraries"));
        if ($bResult) {
            $jsonresponse = $this->decodeResponse($this->oJSON);
            return $this->formatResult($jsonresponse, 'getAvailableSuggestion');
        }
        else {
            return $this->oJSON->getError();
        }
    }

    // Envoie une suggestion d'achat
    public function suggestDocument($params) {
        $this->connect($this->hostApi, $this->portApi, $this->userData, $this->passData);
        $this->oJSON->setHeader('apikey', $this->keyApi);
        if (array_key_exists('docType', $params)) {
            switch (strtoupper($params['docType'])) {
                case 'BOOK':
                    $recordTypeId = "12543052963948867";
                    $commentDocType = "";
                    break;
                case 'COMIC':
                    $recordTypeId = "12543052963948867";
                    $commentDocType = "L'abonné souhaite une BD/Album. ";
                    break;
                case 'MOVIE':
                    $recordTypeId = "8314878538807798299";
                    $commentDocType = "";
                    break;
                case 'MUSIC':
                    $recordTypeId = "5593892708478059828";
                    $commentDocType = "";
                    break;
                case 'AUDIOBOOK':
                    $recordTypeId = "5593892708478059828";
                    $commentDocType = "L'abonné souhaite un livre lu. ";
                    break;
                case 'VIDEOGAME':
                    $recordTypeId = "2733053056215260601";
                    $commentDocType = "";
                    break;
                case 'GAME':
                    $recordTypeId = "125430529639488677";
                    $commentDocType = "";
                    break;
                default:
                    $recordTypeId = null;
                    $commentDocType = "";
            }
        } else {
            $recordTypeId = null;
            $commentDocType = "";
        }
        $data = array(
            'commercialCode' => (array_key_exists('commercialCode', $params) ? $params['commercialCode'] : null),
            'title' => (array_key_exists('title', $params) ? $params['title'] : null),
            'responsibles' => (array_key_exists('responsibles', $params) ? $params['responsibles'] : null),
            'editor' => (array_key_exists('editor', $params) ? $params['editor'] : null),
            'bibliographicRecordTypeId' => $recordTypeId,
            'libraryId' => (array_key_exists('libraryId', $params) ? $params['libraryId'] : null),
            'publicUserBarCode' => (array_key_exists('publicUserBarCode', $params) ? $params['publicUserBarCode'] : null),
            'deadline' => (array_key_exists('deadline', $params) ? $params['deadline'] : null),
            'comment' => (array_key_exists('comment', $params) ? $commentDocType.$params['comment'] : $commentDocType),
        );
        $bResult = $this->oJSON->post($this->buildPathApi("/purchasing/candidate"), $data);
        if ($bResult) {
            $jsonresponse = $this->decodeResponse($this->oJSON);
            return $this->formatResult($jsonresponse, 'suggestDocument', array());
        }
        else {
            return $this->oJSON->getError();
        }
    }

    public function reserveInfo($idNotice, $userInt) {
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $bResult = $this->oJSON->get($this->buildPath("/portal/public/user/".$userInt."/bookingPossibilities/".$idNotice));
        if ($bResult) {
            $jsonresponse = $this->decodeResponse($this->oJSON);
            return $this->formatResult($jsonresponse, 'reserveInfo', array($idNotice, $userInt));
        }
        else {
            return $this->oJSON->getError();
        }
    }

    public function reserveElectronicals($idElectronicals, $mode, $userInt) {
        $modeMap = array('download'=>'downloaded', 'streaming'=>'streamed');
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $data = array('itemElectronicalId'=>$idElectronicals);
        $bResult = $this->oJSON->post($this->buildPath("/portal/public/user/".$userInt."/loanElectronicals/".$modeMap[$mode]), $data);
        if ($bResult) {
            $jsonresponse = $this->decodeResponse($this->oJSON);
            return $this->formatResult($jsonresponse, 'reserveElectronicals', array($idElectronicals, $userInt));
        }
        else {
            return $this->oJSON->getError();
        }
    }

    public function reserveDocument($idNotice, $userInt, $site) {
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $data = array('recordId' => $idNotice,
            'widthDrawalLibraryId' => $site
        );
        $bResult = $this->oJSON->post($this->buildPath("/portal/public/user/".$userInt."/bookings"), $data);
        if ($bResult) {
            $jsonresponse = $this->decodeResponse($this->oJSON);
            return $this->formatResult($jsonresponse, 'reserveDocument', $userInt);
        }
        else {
            return $this->oJSON->getError();
        }
    }

    public function reserveCancel($resid, $userInt) {
        $this->connect($this->hostData, $this->portData, $this->userData, $this->passData);
        $bResult = $this->oJSON->delete($this->buildPath("/portal/public/user/".$userInt."/bookings/".$resid), false);
        if ($bResult) {
            $jsonresponse = $this->decodeResponse($this->oJSON);
            return $this->formatResult($jsonresponse, 'reserveCancel');
        }
    }

    public function getPreregLibraries() {
        $this->connect($this->hostApi, $this->portApi, $this->userData, $this->passData);
        $this->oJSON->setHeader('apikey', $this->keyApi);
        $bResult = $this->oJSON->get($this->buildPathApi("/preregistration/libraries"));
        if ($bResult) {
            $jsonresponse = $this->decodeResponse($this->oJSON);
            return $this->formatResult($jsonresponse, 'getPreregLibraries');
        } else {
            return $this->oJSON->getError();
        }
    }

    public function getPreregClassifications() {
        $this->connect($this->hostApi, $this->portApi, $this->userData, $this->passData);
        $this->oJSON->setHeader('apikey', $this->keyApi);
        $bResult = $this->oJSON->get($this->buildPathApi("/lov/publicuserclassificationtypes"));
        if ($bResult) {
            $jsonresponse = $this->decodeResponse($this->oJSON);
            return $this->formatResult($jsonresponse, 'getPreregClassifications');
        } else {
            return $this->oJSON->getError();
        }
    }

    public function getPreregClassificationsDetails($params) {
        $this->connect($this->hostApi, $this->portApi, $this->userData, $this->passData);
        $this->oJSON->setHeader('apikey', $this->keyApi);
        $bResult = $this->oJSON->get($this->buildPathApi("/lov/publicuserclassification/" . $params['classId'] . "&limit=50"));
        if ($bResult) {
            $jsonresponse = $this->decodeResponse($this->oJSON);
            return $this->formatResult($jsonresponse, 'getPreregClassificationsDetails');
        } else {
            return $this->oJSON->getError();
        }
    }

    public function postPreregistration($params) {
        $data = array();
        $fields = ['lastname', 'secondaryname', 'sex', 'email', 'subscriptionLibraryId', 'phoneNumber', 'mobileNumber', 'comment', 'birthDate', 'streetNumber', 'street',
            'complement', 'district', 'zipCode', 'city', 'publicUserClassificationIds'];
        foreach ($fields as $field) {
            if ($field == 'publicUserClassificationIds') {
                $data[$field] = "[" . $params[$field] . "]";
            } else {
                $data[$field] = $params[$field];
            }
        }
        $data['jsonParams'] = 'publicUserClassificationIds';

        $this->connect($this->hostApi, $this->portApi, $this->userData, $this->passData);
        $this->oJSON->setHeader('apikey', $this->keyApi);
        $this->oJSON->post($this->buildPathApi("/preregistration/publicuser"), $data);
        $jsonresponse = $this->decodeResponse($this->oJSON);
        return $this->formatResult($jsonresponse, 'postPreregistration');
    }

    public function getPreregistrationPublicUser($params) {
        $this->connect($this->hostApi, $this->portApi, $this->userData, $this->passData);
        $this->oJSON->setHeader('apikey', $this->keyApi);
        $bResult = $this->oJSON->get($this->buildPathApi("/preregistration/publicuser/" . $params['publicUserId']));
        if ($bResult) {
            $jsonresponse = $this->decodeResponse($this->oJSON);
            return $this->formatResult($jsonresponse, 'getPreregistrationPublicUser');
        } else {
            return $this->oJSON->getError();
        }
    }

    public function postDebtPay($params) {
        $data = array();
        $fields = ['publicUserId', 'paymentMode', 'paymentDate', 'libraryId', 'amount', 'debtsIds'];
        foreach ($fields as $field) {
            if ($field == 'debtsIds') {
                $data[$field] = "[" . $params[$field] . "]";
            } else {
                $data[$field] = $params[$field];
            }
        }

        $this->connect($this->hostApi, $this->portApi, $this->userData, $this->passData);
        $this->oJSON->setHeader('apikey', $this->keyApi);
        $this->oJSON->post($this->buildPathApi("/debt/pay"), $data);
        $jsonresponse = $this->decodeResponse($this->oJSON);
        return $this->formatResult($jsonresponse, 'postDebtPay');
    }

    public function sendMessage($userInt, $mailId, $action, $objet, $text, $suggTitle, $suggAuthor, $suggEditor, $suggDocType) {
        return null;
    }

    //Gestion des messages d'erreur
    private function returnMessages($oXML) {
        $message = '';
        if ($oXML->errors) {
            foreach ($oXML->errors as $type => $msg) {
                if ($msg) $message .= '<br />'.$type;
            }
        }
        return $message;
    }

    private function _file_get_contents($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        $retour = curl_exec($ch);
        $infos = curl_getinfo($ch);
        curl_close($ch);
        return array('return' => $retour, 'infos' => $infos);
    }

    //Formatage de la réponse pour le serveur
    private function formatResult($oResult, $sAction, $sTempVar = '') {
        $oXMLreturn = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><root></root>');
        if (!$oResult->error) {
            switch($sAction) {
                case 'login' :
                    $oXMLreturnLogin = $oXMLreturn->addChild('login');
                    $oXMLreturnLogin->addChild('sigb', self::nameClass);
                    if ($sTempVar != 'failed') {
                        if ($oResult->res->publicUserDto != ''){
                            $oXMLreturnLogin->addChild('user', $sTempVar);
                            $oXMLreturnLogin->addChild('id', $oResult->res->publicUserDto->id);
                            $oXMLreturnLogin->addChild('fullname', htmlspecialchars($oResult->res->publicUserDto->lastname).', '.htmlspecialchars($oResult->res->publicUserDto->secondaryname));
                            $oXMLreturnLogin->addChild('email', $oResult->res->publicUserDto->email);
                            $oXMLreturnLogin->addChild('birthdate', $oResult->res->publicUserDto->birthDate);
                            $oXMLreturnLogin->addChild('phoneNumber', $oResult->res->publicUserDto->phoneNumber);
                            $oXMLreturnLogin->addChild('mobileNumber', $oResult->res->publicUserDto->mobileNumber);
                            $oXMLreturnLogin->addChild('error', 0);
                            $oXMLreturnLogin->addChild('client_id', $oResult->res->publicUserDto->network->id);
                            $oXMLreturnLogin->addChild('code', $oResult->res->publicUserDto->code);
                        } else if ($oResult->res->publicUserGroupingDto != ''){
                            $oXMLreturnLogin->addChild('user', $sTempVar);
                            $oXMLreturnLogin->addChild('id', $oResult->res->publicUserGroupingDto->id);
                            $oXMLreturnLogin->addChild('groupId', $oResult->res->publicUserGroupingDto->id);
                            $oXMLreturnLogin->addChild('type', 'regroupement');
                            $oXMLreturnLogin->addChild('groupingType', $oResult->res->publicUserGroupingDto->groupingType->name);
                            $oXMLreturnLogin->addChild('fullname', htmlspecialchars($oResult->res->publicUserGroupingDto->name));
                            $oXMLreturnLogin->addChild('email', $oResult->res->publicUserGroupingDto->email);
                            $oXMLreturnLogin->addChild('error', 0);
                            $oXMLreturnLogin->addChild('client_id', $oResult->res->publicUserGroupingDto->network->id);
                            $oXMLreturnLogin->addChild('code', $oResult->res->publicUserGroupingDto->code);
                        } else { // old login -> remotve at 4.8 EPPK
                            $oXMLreturnLogin->addChild('user', $sTempVar);
                            $oXMLreturnLogin->addChild('id', $oResult->res->id);
                            $oXMLreturnLogin->addChild('fullname', htmlspecialchars($oResult->res->lastname).', '.htmlspecialchars($oResult->res->firstname));
                            $oXMLreturnLogin->addChild('error', 0);
                            $oXMLreturnLogin->addChild('client_id', $oResult->res->network->id);
                            $oXMLreturnLogin->addChild('code', $oResult->res->code);
                        }
                    }
                    break;
                case 'getDamInfos' :
                    $clientid = $sTempVar;
                    $damUrlTemplate = "https://{host}/damstorage/$clientid/{damLinkId}/{ressourcePath}";
                    $nameToFormat = array('tb_100_100.png'=>'thumbnail', 'tb_300_300.png'=>'url', 'zoomify'=>'zoomify', 'sample_60.mp4'=>'url', 'sample_60.mp3'=>'url');
                    $isOriginal = array('zoomify');
                    foreach ($oResult->res as $damLink){
                        $host = isset($damLink->storagePublicHost) ? $damLink->storagePublicHost : $this->hostData;
                        $ressourcePath = '';
                        $filetype = strtolower($damLink->filetype);
                        if ($filetype == 'other'){
                            continue;
                        }
                        $oXMLreturnLink = $oXMLreturn->addChild('link');
                        $oXMLreturnLink->addChild('id', $damLink->id);
                        $oXMLreturnLink->addChild('desc', $damLink->filename);
                        $oXMLreturnLink->addChild('filetype', $filetype);
                        if ($filetype == 'document'){
                            $filenameExplode = explode('.',$damLink->filename);
                            $fileExtension = $filenameExplode[count($filenameExplode)-1];
                            foreach ($damLink->variantNames as $name){
                                if ($name == 'tb_100_100.png'){
                                    $oXMLreturnLink->addChild('thumbnail', str_replace(array('{host}', '{damLinkId}', '{ressourcePath}'), array($host, $damLink->id, $name), $damUrlTemplate));
                                }
                            }
                            $version = $this->getVersion(false);
                            if ($version->res->major > 4 || ($version->res->major == 4 && $version->res->minor >= 10)){ // login regroupement
                                $ressourcePath = $damLink->originalFile;
                            } else {
                                $ressourcePath = 'original.'.$fileExtension;
                            }
                            if ($ressourcePath != ''){
                                $oXMLreturnLink->addChild('url', str_replace(array('{host}', '{damLinkId}', '{ressourcePath}'), array($host, $damLink->id, $ressourcePath), $damUrlTemplate));
                            }
                            continue;
                        }
                        foreach ($damLink->variantNames as $name){
                            $original = '';
                            if (in_array($name, $isOriginal)){
                                $original = '/original/';
                            }
                            if ($filetype == 'video' || $filetype == 'audio'){
                                if ($name == 'tb_100_100.png' || $name == 'tb_300_300.png'){
                                    continue;
                                }
                            }
                            if ($nameToFormat[$name] != ''){
                                $ressourcePath = $name.$original;
                                $oXMLreturnLink->addChild($nameToFormat[$name], str_replace(array('{host}', '{damLinkId}', '{ressourcePath}'), array($host, $damLink->id, $ressourcePath), $damUrlTemplate));
                            }
                        }
                    }
                    break;
                case 'getOeuvre' :
                    $oXMLreturn = simplexml_load_string('<?xml version="1.0" encoding="utf-8" ?><root>'.$oResult->res->xml.'</root>');
                    break;
                case 'copyDetails':
                    if ($oResult->res->success === false) $message = $this->returnMessages($oResult->res);
                    if ($oResult->res->items) {
                        foreach ($oResult->res->items as $item) {
                            $xmlItem .= '<item><library><name>'.$item->library->name.'</name><id>'.$item->library->id.'</id><network><name>'.$item->library->network->name.'</name><id>'.$item->library->network->id.'</id></network></library><code>'.$item->code.'</code><id>'.$item->id.'</id><cote>'.$item->cote.'</cote><targetAudience><name>'.$item->targetAudience->name.'</name><id>'.$item->targetAudience->id.'</id></targetAudience><note>'.$item->note.'</note><price>'.$item->price.'</price><inventoryDate>'.$item->creationDate.'</inventoryDate><localization><name>'.htmlspecialchars($item->localization->name).'</name><id>'.$item->localization->id.'</id></localization><sublocalization><name>'.htmlspecialchars($item->subLocalization->name).'</name><id>'.$item->subLocalization->id.'</id></sublocalization><support><name>'.$item->support->name.'</name><id>'.$item->support->id.'</id></support><loan>'.($item->computedPortalStatus ? $item->computedPortalStatus : $item->loanStatus).'</loan></item>';
                        }
                    }
                    if (count($oResult->res->itemElectronicals)) {
                        foreach ($oResult->res->itemElectronicals as $itemElectronicals) {
                            $xmlItemElectronical .= '<itemElectronicals><networkid>'.$itemElectronicals->networkId.'</networkid><id>'.$itemElectronicals->id.'</id><loanStatus>'.$itemElectronicals->loanStatus.'</loanStatus><electronicalProvider>'.$itemElectronicals->electronicalProvider.'</electronicalProvider><canBeDownloaded>'.$itemElectronicals->canBeDownloaded.'</canBeDownloaded><canBeStreamed>'.$itemElectronicals->canBeStreamed.'</canBeStreamed><pnbOrderLineId>'.$itemElectronicals->pnbOrderLineId.'</pnbOrderLineId><pnbEAN13>'.$itemElectronicals->pnbEAN13.'</pnbEAN13><pnbOrderId>'.$itemElectronicals->pnbOrderId.'</pnbOrderId><protection>'.$itemElectronicals->protection.'</protection><format>'.$itemElectronicals->format.'</format></itemElectronicals>';
                        }
                    }
                    $oXMLreturn = simplexml_load_string('<?xml version="1.0" encoding="utf-8" ?><root><items>'.$xmlItem.'</items><itemsElectronicals>'.$xmlItemElectronical.'</itemsElectronicals></root>');
                    break;
                case 'getNotice' :
                    if ($oResult->res->success === false) {
                        $addnode = '';
                        if ($oResult->res->msg) {
                            $addnode .= '<error>'.htmlspecialchars($oResult->res->msg).'</error>';
                            if ($oResult->res->msg=="The bibrecord is deleted") {
                                $addnode .= '<deleted>true</deleted>';
                            }
                        }
                        if ($addnode=='') $addnode = '<error/>';
                        $oXMLreturn = simplexml_load_string('<?xml version="1.0" encoding="utf-8" ?><root>'.$addnode.'</root>');
                    } else {
                        //Ajout des Items au XML
                        if ($oResult->res->items) {
                            foreach ($oResult->res->items as $item) {
                                $xmlItem .= '<item><library><name>'.$item->library->name.'</name><id>'.$item->library->id.'</id><network><name>'.$item->library->network->name.'</name><id>'.$item->library->network->id.'</id></network></library><code>'.$item->code.'</code><id>'.$item->id.'</id><cote>'.$item->cote.'</cote><targetAudience><name>'.$item->targetAudience->name.'</name><id>'.$item->targetAudience->id.'</id></targetAudience><note>'.htmlspecialchars($item->note).'</note><price>'.$item->price.'</price><inventoryDate>'.$item->creationDate.'</inventoryDate><localization><name>'.htmlspecialchars($item->localization->name).'</name><id>'.$item->localization->id.'</id></localization><sublocalization><name>'.htmlspecialchars($item->subLocalization->name).'</name><id>'.$item->subLocalization->id.'</id></sublocalization><support><name>'.$item->support->name.'</name><id>'.$item->support->id.'</id></support><loan>'.($item->computedPortalStatus ? $item->computedPortalStatus : $item->loanStatus).'</loan></item>';
                            }
                        }
                        if ($oResult->res->itemElectronicals) {
                            foreach ($oResult->res->itemElectronicals as $itemElectronicals) {
                                $xmlItemElectronical .= '<itemElectronicals><networkid>'.$itemElectronicals->networkId.'</networkid><id>'.$itemElectronicals->id.'</id><loanStatus>'.$itemElectronicals->loanStatus.'</loanStatus><electronicalProvider>'.$itemElectronicals->electronicalProvider.'</electronicalProvider><canBeDownloaded>'.$itemElectronicals->canBeDownloaded.'</canBeDownloaded><canBeStreamed>'.$itemElectronicals->canBeStreamed.'</canBeStreamed><pnbOrderLineId>'.$itemElectronicals->pnbOrderLineId.'</pnbOrderLineId><pnbEAN13>'.$itemElectronicals->pnbEAN13.'</pnbEAN13><pnbOrderId>'.$itemElectronicals->pnbOrderId.'</pnbOrderId><protection>'.$itemElectronicals->protection.'</protection><format>'.$itemElectronicals->format.'</format></itemElectronicals>';
                            }
                        }
                        if ($oResult->res->desc->parentId != ''){ // RÃ©cupÃ©ration des donnÃ©es du parent pour prendrel les exemplaires
                            $returnParent = $this->getNotice($oResult->res->desc->parentId);
                            $xmlParent = simplexml_load_string($returnParent);
                            if ($xmlParent->items){
                                foreach ($xmlParent->items->item as $item) {
                                    $xmlItem .= '<item><library><name>'.(string)$item->library->name.'</name><id>'.$item->library->id.'</id><network><name>'.$item->library->network->name.'</name><id>'.$item->library->network->id.'</id></network></library><code>'.$item->code.'</code><id>'.$item->id.'</id><cote>'.$item->cote.'</cote><targetAudience><name>'.$item->targetAudience->name.'</name><id>'.$item->targetAudience->id.'</id></targetAudience><note>'.htmlspecialchars($item->note).'</note><price>'.$item->price.'</price><inventoryDate>'.$item->creationDate.'</inventoryDate><localization><name>'.htmlspecialchars($item->localization->name).'</name><id>'.$item->localization->id.'</id></localization><support><name>'.$item->support->name.'</name><id>'.$item->support->id.'</id></support><loan>'.($item->loan).'</loan></item>';
                                }
                            }
                            if ($xmlParent->itemsElectronicals != false){
                                foreach ($xmlParent->itemsElectronicals->itemElectronicals as $itemElectronicals) {
                                    $xmlItemElectronical .= '<itemElectronicals><networkid>'.$itemElectronicals->networkId.'</networkid><id>'.$itemElectronicals->id.'</id><loanStatus>'.$itemElectronicals->loanStatus.'</loanStatus><electronicalProvider>'.$itemElectronicals->electronicalProvider.'</electronicalProvider><canBeDownloaded>'.$itemElectronicals->canBeDownloaded.'</canBeDownloaded><canBeStreamed>'.$itemElectronicals->canBeStreamed.'</canBeStreamed><pnbOrderLineId>'.$itemElectronicals->pnbOrderLineId.'</pnbOrderLineId><pnbEAN13>'.$itemElectronicals->pnbEAN13.'</pnbEAN13><pnbOrderId>'.$itemElectronicals->pnbOrderId.'</pnbOrderId><protection>'.$itemElectronicals->protection.'</protection><format>'.$itemElectronicals->format.'</format></itemElectronicals>';
                                }
                            }
                        }
                        $oXMLreturn = simplexml_load_string('<?xml version="1.0" encoding="utf-8" ?><root>'.$oResult->res->desc->xml.'<items>'.$xmlItem.'</items><itemsElectronicals>'.$xmlItemElectronical.'</itemsElectronicals></root>');
                    }
                    break;
                case 'reserveInfo' :
                    $message = '';
                    if ($oResult->res->errors->success === false) $message = $this->returnMessages($oResult->res);
                    $oXMLreturnResInfo = $oXMLreturn->addChild('reservationInfo');
                    $oXMLreturnResInfo->addChild('sigb', self::nameClass);
                    $oXMLreturnResInfo->addChild('user', $sTempVar[1]);
                    $oXMLreturnResInfo->addChild('nn', $sTempVar[0]);
                    if ($oResult->res->args->user->network->type){
                        $oXMLreturnResInfo->addChild('networkType', $oResult->res->args->user->network->type);
                    }
                    if (count($oResult->res->librariesWithMaxNbBookingsReached) > 0){
                        $oXMLreturnResInfo->addChild('maxBookingsReached', true);
                    }
                    if (empty($message)) {
                        if ($oResult->res->bibrecordSituation->bookings){
                            foreach ($oResult->res->bibrecordSituation->bookings as $bookings){
                                $nbBookings[$bookings->library->id] = $nbBookings[$bookings->library->id] + 1;
                            }
                        }
                        if ($oResult->res->args->bibRecord->items){
                            foreach ($oResult->res->args->bibRecord->items as $items){
                                $nbItems[$items->library->id] = $nbItems[$items->library->id] + 1;
                            }
                        }
                        $version = $this->getVersion(false);
                        if ($version->res->major > 4 || ($version->res->major == 4 && $version->res->minor >= 9)){ // login regroupement
                            if ($version->res->major > 6 || ($version->res->major == 6 && $version->res->minor >= 0)){ // rename eppk librairies -> libraries
                                if ($oResult->res->possibleLibrariesWithOriginList){
                                    foreach ($oResult->res->possibleLibrariesWithOriginList as $bib) {
                                        $oXMLreturnResInfoSite = $oXMLreturnResInfo->addChild('site', $bib->library->name);
                                        $oXMLreturnResInfoSite->addAttribute('id', $bib->library->id);
                                        $oXMLreturnResInfoSite->addAttribute('nbItems', $nbItems[$bib->library->id]);
                                        $oXMLreturnResInfoSite->addAttribute('nbBookings', $nbBookings[$bib->library->id]);
                                    }
                                }
                            } else {
                                if ($oResult->res->possibleLibrairiesWithOriginList){
                                    foreach ($oResult->res->possibleLibrairiesWithOriginList as $bib) {
                                        $oXMLreturnResInfoSite = $oXMLreturnResInfo->addChild('site', $bib->library->name);
                                        $oXMLreturnResInfoSite->addAttribute('id', $bib->library->id);
                                        $oXMLreturnResInfoSite->addAttribute('nbItems', $nbItems[$bib->library->id]);
                                        $oXMLreturnResInfoSite->addAttribute('nbBookings', $nbBookings[$bib->library->id]);
                                    }
                                }
                            }
                        } else {
                            if ($oResult->res->possibleLibrariesUnforced){
                                foreach ($oResult->res->possibleLibrariesUnforced as $bib) {
                                    $oXMLreturnResInfoSite = $oXMLreturnResInfo->addChild('site', $bib->library->name);
                                    $oXMLreturnResInfoSite->addAttribute('id', $bib->library->id);
                                    $oXMLreturnResInfoSite->addAttribute('nbItems', $nbItems[$bib->library->id]);
                                    $oXMLreturnResInfoSite->addAttribute('nbBookings', $nbBookings[$bib->library->id]);
                                }
                            }
                            if ($oResult->res->possibleLibrairiesWithAvailableItemUnforced){
                                foreach ($oResult->res->possibleLibrairiesWithAvailableItemUnforced  as $bib) {
                                    $oXMLreturnResInfoSite = $oXMLreturnResInfo->addChild('site', $bib->library->name);
                                    $oXMLreturnResInfoSite->addAttribute('id', $bib->library->id);
                                    $oXMLreturnResInfoSite->addAttribute('nbItems', $nbItems[$bib->library->id]);
                                    $oXMLreturnResInfoSite->addAttribute('nbBookings', $nbBookings[$bib->library->id]);
                                }
                            }
                        }
                        if ($oResult->res->notAssignableAvailableItemsUnforced){
                            foreach ($oResult->res->notAssignableAvailableItemsUnforced as $bib){
                                $oXMLreturnResInfoSite = $oXMLreturnResInfo->addChild('siteAvailableItems', $bib->library->name);
                            }
                        }
                    }
                    $oXMLreturnResInfo->addChild('error', (!empty($message) ? $message : 0));
                    $oXMLreturnResInfo->addChild('code', 0);
                    break;
                case 'reserveElectronicals' :
                    $oXMLreturn = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><root>'.json_encode((array)$oResult->res).'</root>');
//                    return json_encode((array)$oResult->res);
                    break;
                case 'reserveDocument' :
                    $message = '';
                    if ($oResult->res->success === false) $message = $this->returnMessages($oResult->res);
                    $oXMLreturnResDoc = $oXMLreturn->addChild('reservationDoc');
                    $oXMLreturnResDoc->addChild('sigb', self::nameClass);
                    $oXMLreturnResDoc->addChild('user', $sTempVar);
                    if (empty($message)) {
                        $oXMLreturnResDoc->addChild('infosres', 'OK');
                    }
                    $oXMLreturnResDoc->addChild('error', (!empty($message) ? $message : 1));
                    $oXMLreturnResDoc->addChild('code', 1);
                    break;
                case 'reserveCancel' :
                    $message = '';
                    if ($oResult->res->success === false) $message = $this->returnMessages($oResult->res);
                    $oXMLreturn = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><root></root>');
                    $oXMLreturnResCancel = $oXMLreturn->addChild('reservationCancel');
                    $oXMLreturnResCancel->addChild('sigb', self::nameClass);
                    $oXMLreturnResCancel->addChild('resid', $sTempVar);
                    $oXMLreturnResCancel->addChild('error', (empty($message) ? 0 : -1));
                    $oXMLreturnResCancel->addChild('code', 0);
                    break;
                case 'updateAccount' :
                    $oXMLreturn = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><root></root>');
                    $oXMLreturnUpdate = $oXMLreturn->addChild('updateAccount');
                    $oXMLreturnUpdate->addChild('sigb', self::nameClass);
                    $oXMLreturnUpdate->addChild('user', $sTempVar['username']);
                    $oXMLreturnUpdate->addChild('error', $sTempVar['errorCode']);
                    if ($sTempVar['newlogin'] != ''){
                        $oXMLreturnUpdate->addChild('newlogin', $sTempVar['newlogin']);
                    }
                    $oXMLreturnUpdate->addChild('code', 0);
                    break;

                case 'updateGroupAccount' :
                    $oXMLreturn = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><root></root>');
                    $oXMLreturnUpdate = $oXMLreturn->addChild('updateGroupAccount');
                    foreach ($oResult->res->members as $member){
                        $oXMLreturnMembers = $oXMLreturnUpdate->addChild('members');
                        foreach ($member as $memberValueName=>$memberValue){
                            $oXMLreturnMembers->addChild($memberValueName, $memberValue);
                        }
                    }
                    $oXMLreturnUpdate->addChild('error', $sTempVar['errorCode']);
                    $oXMLreturnUpdate->addChild('code', 0);
                    break;
                case 'prolongLoan' :
                    $message = '';
                    if ($oResult->res->success === false) $message = $this->returnMessages($oResult->res);
                    $oXMLreturn = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><root></root>');
                    $oXMLreturnResCancel = $oXMLreturn->addChild('prolongation');
                    $oXMLreturnResCancel->addChild('sigb', self::nameClass);
                    if (!empty($message)) $oXMLreturnResCancel->addChild('minrenewal', $oResult->res->minRenewal);
                    if ($oResult->res->args->loan->dueDate != '' && $oResult->res->state->rule->nbDaysBeforeEndLoan != ''){
                        $oXMLreturnResCancel->addChild('minDateProlong', date('d/m/Y',strtotime("- ".$oResult->res->state->rule->nbDaysBeforeEndLoan." days", strtotime($oResult->res->args->loan->dueDate))));
                    }
                    if ($oResult->res->args->loan->dueDate != '' && $oResult->res->state->rule->nbDaysAfterEndLoan != ''){
                        $oXMLreturnResCancel->addChild('maxDateProlong', date('d/m/Y',strtotime("+ ".$oResult->res->state->rule->nbDaysAfterEndLoan." days", strtotime($oResult->res->args->loan->dueDate))));
                    }
                    if ($oResult->res->state->rule->quota != ''){
                        $oXMLreturnResCancel->addChild('quota',  $oResult->res->state->rule->quota);
                    }
                    if ($oResult->res->state->rule->newQuota != ''){
                        $oXMLreturnResCancel->addChild('newQuota',  $oResult->res->state->rule->newQuota);
                    }
                    $oXMLreturnResCancel->addChild('error', (!empty($message) ? $message : 0));
                    $oXMLreturnResCancel->addChild('code', 0);
                    break;
                case 'getAvailableSuggestion' :
                    $xmlData = "";
                    foreach ($oResult->res as $res) {
                        $xmlData = $xmlData . '<item><name>' . $res->{'name'} . '</name><id>' . $res->{'id'} . '</id></item>';
                    }
                    $oXMLreturn = simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><root>' . $xmlData . '</root>');
                    break;
                case 'suggestDocument' :
                    $message = $oResult->success ? 0 : $oResult->msg;
                    $oXMLreturn = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><root></root>');
                    $oXMLreturn->addChild('error', $message);
                    if ($oResult->res->code != '') {
                        $oXMLreturn->addChild('code', $oResult->res->code);
                    }
                    break;
                case 'getPreregLibraries' :
                    $xmlData = "";
                    if (isset($oResult->res) && (count($oResult->res) > 0)) {
                        $xmlData .= "<libraries>";
                        foreach ($oResult->res as $res) {
                            $xmlData .= '<item><name>' . $res->{'name'} . '</name><id>' . $res->{'id'} . '</id></item>';
                        }
                        $xmlData .= "</libraries>";
                    }
                    $oXMLreturn = simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><root>' . $xmlData . '</root>');

                    break;
                case 'getPreregClassifications' :
                    $xmlData = "";
                    if (isset($oResult->res->list) && (count($oResult->res->list) > 0)) {
                        $xmlData .= "<classType>";
                        foreach ($oResult->res->list as $res) {
                            $xmlData .= '<item><name>' . $res->{'name'} . '</name><id>' . $res->{'id'} . '</id></item>';
                        }
                        $xmlData .= "</classType>";
                    }
                    $oXMLreturn = simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><root>' . $xmlData . '</root>');
                    break;
                case 'getPreregClassificationsDetails' :
                    $xmlData = "";
                    if (isset($oResult->res->list) && (count($oResult->res->list) > 0)) {
                        $xmlData .= "<details>";
                        foreach ($oResult->res->list as $res) {
                            $xmlData .= '<item><name>' . $res->{'name'} . '</name><id>' . $res->{'id'} . '</id><code>' . $res->{'code'} . '</code></item>';
                        }
                        $xmlData .= "</details>";
                    }
                    $oXMLreturn = simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><root>' . $xmlData . '</root>');
                    break;
                case 'postPreregistration':
                    if (isset($oResult->success) && ($oResult->success === true)) {
                        $xmlData = "<publicUserId>" . $oResult->res->{'id'} . "</publicUserId>";
                    } else {
                        $xmlData = "<errorCode>500</errorCode><errorMessage>" . $oResult->msg . "</errorMessage>";
                    }
                    $oXMLreturn = simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><root>' . $xmlData . '</root>');
                    break;
                case 'getPreregistrationPublicUser':
                    $xmlData = "";
                    if (isset($oResult->success)) {
                        $res = $oResult->res;
                        $xmlData .= "<publicUser>";
                        $fields = ['id', 'type', 'code', 'lastname', 'secondaryname', 'birthDate', 'sex', 'phoneNumber', 'mobileNumber', 'mobileNumberValid', 'email',
                            'isEmailValid', 'preRegistrationValidated', 'verifyHistoryForLoan', 'allowSmsSending', 'reminderMode', 'comment', 'firstSubscriptionDate',
                            'allowInformationMail', 'allowInformationSms', 'func', 'onlyLegalRepresentative', 'nbLegalRepresented', 'legalRepresentativeId', 'trap'];
                        foreach ($fields as $field) {
                            $xmlData .= '<' . $field . '>' . $res->{$field} . '</' . $field . '>';
                        }
                        $xmlData .= "<address>";
                        foreach (['streetNumber', 'complement', 'street', 'district', 'zipCode', 'city'] as $field) {
                            $xmlData .= '<' . $field . '>' . $res->address->{$field} . '</' . $field . '>';
                        }
                        $xmlData .= "</address><network>";
                        foreach (['id', 'name', 'street', 'type'] as $field) {
                            $xmlData .= '<' . $field . '>' . $res->network->{$field} . '</' . $field . '>';
                        }
                        $xmlData .= "</network><classifications>";
                        foreach ($res->classifications as $classification) {
                            $xmlData .= "<item>";
                            foreach (['id', 'name'] as $fieldClassification) {
                                $xmlData .= '<' . $fieldClassification . '>' . $classification->{$fieldClassification} . '</' . $fieldClassification . '>';
                            }
                            $xmlData .= "<type><item>";
                            foreach ($classification->type as $type) {
                                foreach (['id', 'name'] as $fieldType) {
                                    $xmlData .= '<' . $fieldType . '>' . $type->{$fieldType} . '</' . $fieldType . '>';
                                }
                            }
                            $xmlData .= "</item></type></item>";
                        }
                        $xmlData .= "</classifications><subscriptionLibrary>";
                        foreach (['id', 'name'] as $field) {
                            $xmlData .= '<' . $field . '>' . $res->subscriptionLibrary->{$field} . '</' . $field . '>';
                        }
                        $xmlData .= "</subscriptionLibrary><ban>";
                        foreach (['user', 'state', 'reason', 'untilDate', 'date'] as $field) {
                            $xmlData .= '<' . $field . '>' . $res->ban->{$field} . '</' . $field . '>';
                        }
                        $xmlData .= "</ban></publicUser>";
                    }
                    $oXMLreturn = simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><root>' . $xmlData . '</root>');
                    break;

                case 'getVersionAgent':
                    $oXMLreturn = simplexml_load_string('<?xml version="1.0" encoding="utf-8" ?><root><res>' . $oResult . '</res></root>');
                    break;
                case 'postDebtPay ':
                    if (isset($oResult->success) && ($oResult->success === true)) {
                        $xmlData = "<success>200</success>";
                    } else {
                        $xmlData = "<errorCode>500</errorCode><errorMessage>" . $oResult->msg . "</errorMessage>";
                    }
                    $oXMLreturn = simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><root>' . $xmlData . '</root>');
                    break;
                default :
                    return 'Commande inconnue';
            }
        }
        else {
            $oXMLreturn->addChild('error', $oResult->error);
        }
        return $oXMLreturn->asXML();
    }

}

?>