<?php 
######################################################################
# ZW3B.Site v7.1.2 : The Web Sites Management System
# --------------------------------------------------------------------
#
# Copyright (c) 2023 by LAB3W : O.Romain Jaillet-ramey - (orj+zw3bApiClient@lab3w.fr)
#
# file : zw3bApiClient.class.php
#
# Date Create : 2022/07/20
# Date Modify : 2023/07/09
#
# Web Domain : lab3w.fr
# Web Domain : lab3w.com
#
# Web Domain : zw3b.fr
# Web Domain : zw3b.tv
# Web Domain : zw3b.com
# Web Domain : zw3b.net
# Web Domain : zw3b.blog
# Web Domain : zw3b.eu
#
# Web Domain : ipv01.net
# Web Domain : ipv10.net
#
# This module is to manage ---------------------------- :: Descripton
#
# This program is free software. You can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License.
######################################################################

######################################################################
# ZW3B API CLIENT : TO RECOVER SITE CONTENT/RESOURCE
# IN PARALLEL DEVELOPMENT ZW3B API SERVER
######################################################################

/*******************************************************************
 * Class zw3bApiClientConfig - RESTful API Client ZW3B
 * 
 * // BETA-TESTERS (Wilcard Origins)
 *
 * // Minimun config
 * $config['api_name'] = 'BETA-TESTERS';
 * $config['client_project']['name'] = 'ZW3B-API-BETA-TESTERS';
 *
 */
class zw3bApiClientConfig {
    
    public $config = array(
                            'api_name' => null,
                            'api_key' => null,
                            'client_id' => null,
                            'client_secret' => null,
                            'client_project' => array(
                                                    'name' => null, 
                                                    'origins' => array(),
                                                    'redirection_url' => array(),
                            ),
                    );
    
    public function __construct() {

        
    }
    
    public function ClientConfigSet($config) {
        
        $configuration = (object)array();
        
        $configuration->api_name = isset($config['api_name']) ? $config['api_name'] : null;
        $configuration->api_key = isset($config['api_key']) ? $config['api_key'] : null;
        
        $configuration->client_id = isset($config['client_id']) ? $config['client_id'] : null;
        $configuration->client_secret = isset($config['client_secret']) ? $config['client_secret'] : null;
        
        $configuration->client_project = (object)array();
        
        $configuration->client_project->name = isset($config['client_project']['name']) ? $config['client_project']['name'] : null;
        $configuration->client_project->origins = isset($config['client_project']['origins']) ? $config['client_project']['origins'] : null;
        $configuration->client_project->redirection_url = isset($config['client_project']['redirection_url']) ? $config['client_project']['redirection_url'] : null;
        
        
        $this->config = $configuration;
        
        
    }
    
    public function ClientConfigGet() {
        
        return $this->config;
    }
    
    
}

/*******************************************************************
 * Class zw3bApiClient - RESTful API Client ZW3B
 * 
 * // CLIENT API CALL
 * 
 * $zw3bApiClient = new zw3bApiClient();
 * $my_client = $zw3bApiClient->ClientModUsr($config);
 * 
 * // CLIENT API CALL
 * 
 */
class zw3bApiClient extends zw3bApiClientConfig {
    
    //public $name, $date, $url, $rev;
    
    //public $scopes;
    
    public $contents;
    public $reports;
    
    public function __construct() {
        
        $this->name = 'ZW3B/Api.Client-0.1';
        $this->date = '2023/07/09';
        $this->url  = 'https://api.zw3b.fr';
        $this->rev  = '1.0';
        
        $this->config = new zw3bApiClientConfig();
   
    }
    
    public function ClientModUsr($config) {
        
        $this->config->ClientConfigSet($config);
        
        $this->config = $this->config->ClientConfigGet();
     
        $this->infos = $this->infos();
        
        $this->usr = new zw3bApiClientModUsr($this->config, $this->infos);
        
        //echo 'zw3bApiClient > ClientModUsr : <pre>'.print_r($this->usr,1).'</pre>';
        
        return $this->usr;

    }
    
    public function infos() {
        
        $this->infos = new stdClass();
        
        $this->infos->name = $this->name;
        $this->infos->date = $this->date;
        $this->infos->url = $this->url;
        $this->infos->rev = $this->rev;
        
        return $this->infos;
        
    }
    
    public function tools() {
        
        $this->tools = new zw3bTools();
        
        return $this->tools;
        
    }
    
    public function usr() {
        
        if($this->usr->auth === true)
            return $this->usr;
        else
            return false;
    }

    public function contents() {
        
        $this->contents = new zw3bApiClientModContents($this->usr);
        
        return $this->contents;
        
    }
    
    public function reports() {
        
        $this->reports = new zw3bApiClientModReports($this->usr);
        
        return $this->reports;
        
    }

    
}

/*******************************************************************
 * Class zw3bApiClientModUsr - RESTful API Client ZW3B
 * 
 * 
 */
class zw3bApiClientModUsr extends zw3bApiClient {
    
    public $auth = false;
    
    public $uid = '65535';
    public $gid = '65535';
    
    public $uname = 'internaute';
    public $umail = 'internaute@zw3b.site';
    
    public function __construct($config, $infos) {
        
        $this->auth = $this->zw3bApiClientModUsrAuthentification($config, $infos);
        
        //echo 'zw3bApiClientModUsr > __construct : <pre>'.print_r($this,1).'</pre>'; //exit;
        
    }
    
    public function auth() {
        
        return $this->auth;
    }
    
    private function authentification() {
        
        return $this->authentification;
    }
    
    /******
     * Serveur Authentification 
     */
    private function zw3bApiClientModUsrAuthentification($config = null, $infos = null) {
        
        $this->config = isset($config) ? $config : array();
        $this->infos = isset($infos) ? $infos : array();
        
        $this->action = new zw3bApiClientModUsrActions($this->config, $this->infos);
        
        $this->action->zw3bApiClientModUsrActionsAuthentification();

        $this->authentification = json_decode($this->action->authentification);

        //echo '<pre>'.print_r($this->authentification,1).'</pre>';
        
        $this->auth = false;
        
        if(isset($this->authentification) && isset($this->authentification->reason))
        {
            
            if($this->authentification->reason->status === '200')
            {
                $this->auth = true;
                
                $this->uid = $this->authentification->client->id;
                $this->gid = $this->authentification->client->id;
                $this->uname = $this->authentification->client->name;
            }
            
            
            if($this->authentification->reason->status !== '200') 
            {
                //echo '<pre>'.print_r($this->status,1).'</pre>';
                //echo $this->action->authentification; exit;
                //echo $this->user; 
                //exit;
                
                $this->auth = false;
            }
        }
        //throw new Exception('Error : <pre>'.print_r($this,1)).'</pre>';
        
        return $this->auth;
        
    }
    
    
}

/*******************************************************************
 * Class zw3bApiClientModUsrActions - RESTful API Client ZW3B
 *
 *
 */
class zw3bApiClientModUsrActions extends zw3bApiClientModUsr {
    
    protected $action = null;
    
    public function __construct($config, $infos) {
        
        $this->config = $config;
        $this->infos = $infos;
        
    }
    
    /******
     * 
     */
    protected function zw3bApiClientModUsrActionsAuthentification() {
        
        $url = 'https://www.zw3b.fr/actions/usr/api/authentification';
        
        //------------------------------------------------
        $cURLConnection = curl_init();
        
        $headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Origin: '.$this->tools()->protocole(),
            'Referer: '.$this->tools()->url(),
            'User-Agent: '.$_SERVER['HTTP_USER_AGENT'].' '.$this->infos->name.' ('.$this->infos->date.'; +'.$this->infos->url.'; rv:'.$this->infos->rev.')',
        );
        
        $body = '{}';
        $body = json_encode($this->config);
        
        curl_setopt($cURLConnection, CURLOPT_URL, $url);
        curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($cURLConnection, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($cURLConnection, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $body);
        
        // Timeout in seconds
        curl_setopt($cURLConnection, CURLOPT_TIMEOUT, 30);
        
        $data = curl_exec($cURLConnection);
        
        curl_close($cURLConnection);
        
        //------------------------------------------------
        
        return $this->authentification = isset($data) ? $data : null;
        
    }
    
    /******
     * TODO
     */
    protected function zw3bApiClientModUsrActionsDeconnection() {
        
        
    }
    
    /******
     * TODO
     */
    protected function zw3bApiClientModUsrActionsResfreshToken() {
        
        
    }
    
}


/*******************************************************************
 * Class zw3bApiClientModReports - RESTful API Client ZW3B
 *
 * $reports = new zw3bApiClientModReports($my_client);
 * 
 */
class zw3bApiClientModReports extends zw3bApiClient {
    
    public $dmarc;
    
    public function __construct($usr) {
        
        $this->usr = $usr;
        
        $this->infos = isset($this->infos) ? $this->infos : $this->usr->infos;
          
    }
    
    public function dmarc() {
        
        $this->dmarc = new zw3bApiClientModReportsDmarc($this->usr);
        
        return $this->dmarc;
    }
    
    
    
}

/*******************************************************************
 * Class zw3bApiClientModReportsDmarc - RESTful API Client ZW3B
 *
 * $dmarc_analysis = $reports->dmarc('analysis', array());
 * 
 */
class zw3bApiClientModReportsDmarc extends zw3bApiClientModReports {
    
    public function analysis($args = array()) {
        
        if($this->usr->auth === true)
        {
            
        $url = 'https://www.zw3b.fr/api/reports/dmarc/analysis';
        
        if(isset($args) && is_array($args)) {
            $query = '?';
            $i=0;
            foreach($args as $clef => $value) {
                $query.= $clef.'='.$value.(count($args)-1 > $i ? '&' : '');
                $i++;
            }
            $url = $url.$query;
        }
        
        //------------------------------------------------
        $cURLConnection = curl_init();
        
        $headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Origin: '.$this->tools()->protocole(),
            'Referer: '.$this->tools()->url(),
            'User-Agent: '.$_SERVER['HTTP_USER_AGENT'].' '.$this->infos->name.' ('.$this->infos->date.'; +'.$this->infos->url.'; rv:'.$this->infos->rev.')',
        );
        
        //echo 'zw3bApiClientModReportsDmarc: analysis<pre>'.print_r(($this->usr),1).'</pre>';
        
        $body = '{}';
        //$this->usr = json_decode($this->usr);
        //$body = json_encode($this->usr);
        //$body = $this->usr;
        $body = json_encode($this->usr->authentification);
        
        curl_setopt($cURLConnection, CURLOPT_URL, $url);
        curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($cURLConnection, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($cURLConnection, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $body);
        
        // Timeout in seconds
        curl_setopt($cURLConnection, CURLOPT_TIMEOUT, 30);
        
        $data = curl_exec($cURLConnection);
        
        curl_close($cURLConnection);
        
        //------------------------------------------------
        
        }
        
        return $data = isset($data) ? $data : null;
    }

}

/*******************************************************************
 * Class zw3bApiClientModContents - RESTful API Client ZW3B
 *
 * $contents = new zw3bApiClientModContents($my_client);
 * 
 */
 class zw3bApiClientModContents extends zw3bApiClient {
    
    public $news, $docs, $links, $gallery, $videos, $channels;
    
    public function __construct($usr) {
        
        //echo 'zw3bApiClientModContents >  __construct : <pre>'.print_r(($usr),1).'</pre>';
        
        $this->usr = $usr;
        
        $this->infos = isset($this->infos) ? $this->infos : $this->usr->infos;
        
    }

    public function news() {
        
        $this->news = new zw3bApiClientModContentsNews($this->usr);
        
        return $this->news;
    }
    
    public function docs() {
        
        $this->docs = new zw3bApiClientModContentsDocs($this->usr);
        
        return $this->docs;
    }
    
    public function links() {
        
        $this->links = new zw3bApiClientModContentsLinks($this->usr);
        
        return $this->links;
    }

    public function gallery() {
        
        $this->gallery = new zw3bApiClientModContentsGallery($this->usr);
        
        return $this->gallery;
    }
    
    public function videos() {
        
        $this->videos = new zw3bApiClientModContentsVideos($this->usr);
        
        return $this->videos;
    }
    
    public function channels() {
        
        $this->channels = new zw3bApiClientModContentsChannels($this->usr);
        
        return $this->channels;
    }
}

/*******************************************************************
 * Class zw3bApiClientModContentsNews - RESTful API Client ZW3B
 *
 * $news = $contents->news()->lst(array('offset' => 0, 'limit' => 10, 'l' => 'ES'));
 * 
 */
class zw3bApiClientModContentsNews extends zw3bApiClientModContents {
    
    public function lst($args = array()) {
        
        if($this->usr->auth === true)
        {
            
            $url = 'https://www.zw3b.fr/api/contents/news/lst';
            
            if(isset($args) && is_array($args)) {
                $query = '?';
                $i=0;
                foreach($args as $clef => $value) {
                    $query.= $clef.'='.$value.(count($args)-1 > $i ? '&' : '');
                    $i++;
                }
                $url = $url.$query;
            }
            
            //------------------------------------------------
            $headers = array(
                //'Accept: application/json',
                //'Content-Type: application/json',
                'Origin: '.$this->tools()->protocole(),
                'Referer: '.$this->tools()->url(),
                'User-Agent: '.$_SERVER['HTTP_USER_AGENT'].' '.$this->infos->name.' ('.$this->infos->date.'; +'.$this->infos->url.'; rv:'.$this->infos->rev.')',
            );
            
            $cURLConnection = curl_init();
            
            curl_setopt($cURLConnection, CURLOPT_URL, $url);
            curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($cURLConnection, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, $headers);
            
            $data = curl_exec($cURLConnection);
            curl_close($cURLConnection);
            
            //------------------------------------------------
            
        }
        
        return $data = isset($data) ? $data : null;
    }
      
}

/*******************************************************************
 * Class zw3bApiClientModContentsDocs - RESTful API Client ZW3B
 *
 * $docs = $contents->docs()->lst(array('offset' => 0, 'limit' => 10, 'l' => 'ES'));
 * 
 */
class zw3bApiClientModContentsDocs extends zw3bApiClientModContents {
    
    public function lst($args = array()) {
        
        if($this->usr->auth === true)
        {
        
        $url = 'https://www.zw3b.fr/api/contents/docs/lst';
        
        if(isset($args) && is_array($args)) {
            $query = '?';
            $i=0;
            foreach($args as $clef => $value) {
                $query.= $clef.'='.$value.(count($args)-1 > $i ? '&' : '');
                $i++;
            }
            $url = $url.$query;
        }
        
        //------------------------------------------------
        $headers = array(
            //'Accept: application/json',
            //'Content-Type: application/json',
            'Origin: '.$this->tools()->protocole(),
            'Referer: '.$this->tools()->url(),
            'User-Agent: '.$_SERVER['HTTP_USER_AGENT'].' '.$this->infos->name.' ('.$this->infos->date.'; +'.$this->infos->url.'; rv:'.$this->infos->rev.')',
        );
        
        $cURLConnection = curl_init();
        
        curl_setopt($cURLConnection, CURLOPT_URL, $url);
        curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($cURLConnection, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, $headers);
        
        $data = curl_exec($cURLConnection);
        curl_close($cURLConnection);
        
        //------------------------------------------------
        
        }
        
        return $data = isset($data) ? $data : null;
    }
    
    /******
     * TODO
     */
    public function get($args = array()) {
        
        if($this->usr->auth === true)
        {
            
        $url = 'https://www.zw3b.fr/api/contents/docs/cid/';
        
        if(isset($args) && is_array($args)) {
            $query = '?';
            $i=0;
            foreach($args as $clef => $value) {
                if($clef === 'cid')
                    $cid = $value;
                else {
                    $query.= $clef.'='.$value.(count($args)-1 > $i ? '&' : '');  
                }
                $i++;
            }
        }

        $url = $url.(isset($cid) ? $cid : null).$query;
        
        //------------------------------------------------
        if(isset($cid)):
        
            $cURLConnection = curl_init();
            
            $headers = array(
                'Accept: application/json',
                'Content-Type: application/json',
                'Origin: '.$this->tools()->protocole(),
                'Referer: '.$this->tools()->url(),
                'User-Agent: '.$_SERVER['HTTP_USER_AGENT'].' '.$this->infos->name.' ('.$this->infos->date.'; +'.$this->infos->url.'; rv:'.$this->infos->rev.')',
            );
            
            //echo 'zw3bApiClientModReportsDmarc: analysis<pre>'.print_r(($this->usr),1).'</pre>';
            
            $body = '{}';
            //$this->usr = json_decode($this->usr);
            //$body = json_encode($this->usr);
            //$body = $this->usr;
            $body = json_encode($this->usr->authentification);
            
            curl_setopt($cURLConnection, CURLOPT_URL, $url);
            curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($cURLConnection, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($cURLConnection, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $body);
            
            
            // Timeout in seconds
            curl_setopt($cURLConnection, CURLOPT_TIMEOUT, 30);
            
            $data = curl_exec($cURLConnection);
            
            curl_close($cURLConnection);
        
        endif;
        //------------------------------------------------
        
        //echo 'zw3bApiClientModContentsDocs: get<pre>'.print_r(($data),1).'</pre>';
        
        }
        
        return $data = isset($data) ? $data : null;
        
    }
    
    
}

/*******************************************************************
 * Class zw3bApiClientModContentsLinks - RESTful API Client ZW3B
 *
 * $links = $contents->links()->lst(array('offset' => 0, 'limit' => 10, 'l' => 'ES'));
 * 
 */
class zw3bApiClientModContentsLinks extends zw3bApiClientModContents {
    
    public function lst($args = array()) {
        
        if($this->usr->auth === true)
        {
            
            $url = 'https://www.zw3b.fr/api/contents/links/lst';
            
            if(isset($args) && is_array($args)) {
                $query = '?';
                $i=0;
                foreach($args as $clef => $value) {
                    $query.= $clef.'='.$value.(count($args)-1 > $i ? '&' : '');
                    $i++;
                }
                $url = $url.$query;
            }
            
            //------------------------------------------------
            $headers = array(
                //'Accept: application/json',
                //'Content-Type: application/json',
                'Origin: '.$this->tools()->protocole(),
                'Referer: '.$this->tools()->url(),
                'User-Agent: '.$_SERVER['HTTP_USER_AGENT'].' '.$this->infos->name.' ('.$this->infos->date.'; +'.$this->infos->url.'; rv:'.$this->infos->rev.')',
            );
            
            $cURLConnection = curl_init();
            
            curl_setopt($cURLConnection, CURLOPT_URL, $url);
            curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($cURLConnection, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, $headers);
            
            $data = curl_exec($cURLConnection);
            curl_close($cURLConnection);
            
            //------------------------------------------------
            
        }
        
        return $data = isset($data) ? $data : null;
    }
    
}

/*******************************************************************
 * Class zw3bApiClientModContentsGallery - RESTful API Client ZW3B
 *
 * $gallery = $contents->gallery()->lst(array('offset' => 0, 'limit' => 10, 'l' => 'ES'));
 * 
 */
class zw3bApiClientModContentsGallery extends zw3bApiClientModContents {
    
    public function lst($args = array()) {
        
        if($this->usr->auth === true)
        {
            
            $url = 'https://www.zw3b.fr/api/contents/gallery/lst';
            
            if(isset($args) && is_array($args)) {
                $query = '?';
                $i=0;
                foreach($args as $clef => $value) {
                    $query.= $clef.'='.$value.(count($args)-1 > $i ? '&' : '');
                    $i++;
                }
                $url = $url.$query;
            }
            
            //------------------------------------------------
            $headers = array(
                //'Accept: application/json',
                //'Content-Type: application/json',
                'Origin: '.$this->tools()->protocole(),
                'Referer: '.$this->tools()->url(),
                'User-Agent: '.$_SERVER['HTTP_USER_AGENT'].' '.$this->infos->name.' ('.$this->infos->date.'; +'.$this->infos->url.'; rv:'.$this->infos->rev.')',
            );
            
            $cURLConnection = curl_init();
            
            curl_setopt($cURLConnection, CURLOPT_URL, $url);
            curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($cURLConnection, CURLOPT_SSL_VERIFYPEER, true); 
            curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, $headers);
            
            $data = curl_exec($cURLConnection);
            curl_close($cURLConnection);
            
            //------------------------------------------------
            
        }
        
        return $data = isset($data) ? $data : null;
    }
    
}

/*******************************************************************
 * Class zw3bApiClientModContentsVideos - RESTful API Client ZW3B
 *
 * $videos = $contents->videos()->lst(array('offset' => 0, 'limit' => 10, 'l' => 'ES'));
 * 
 */
class zw3bApiClientModContentsVideos extends zw3bApiClientModContents {
    
    public function lst($args = array()) {
        
        if($this->usr->auth === true)
        {
            
            $url = 'https://www.zw3b.fr/api/contents/videos/lst';
            
            if(isset($args) && is_array($args)) {
                $query = '?';
                $i=0;
                foreach($args as $clef => $value) {
                    $query.= $clef.'='.$value.(count($args)-1 > $i ? '&' : '');
                    $i++;
                }
                $url = $url.$query;
            }
            
            //------------------------------------------------
            $headers = array(
                //'Accept: application/json',
                //'Content-Type: application/json',
                'Origin: '.$this->tools()->protocole(),
                'Referer: '.$this->tools()->url(),
                'User-Agent: '.$_SERVER['HTTP_USER_AGENT'].' '.$this->infos->name.' ('.$this->infos->date.'; +'.$this->infos->url.'; rv:'.$this->infos->rev.')',
            );
            
            $cURLConnection = curl_init();
            
            curl_setopt($cURLConnection, CURLOPT_URL, $url);
            curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($cURLConnection, CURLOPT_SSL_VERIFYPEER, true); 
            curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, $headers);
            
            $data = curl_exec($cURLConnection);
            curl_close($cURLConnection);
            
            //------------------------------------------------
            
        }
        
        return $data = isset($data) ? $data : null;
    }
    
}

/*******************************************************************
 * Class zw3bApiClientModContentsChannels - RESTful API Client ZW3B
 *
 * $channels = $contents->channels()->lst(array('offset' => 0, 'limit' => 10, 'l' => 'ES'));
 * 
 */
class zw3bApiClientModContentsChannels extends zw3bApiClientModContents {
    
    public function lst($args = array()) {
        
        if($this->usr->auth === true)
        {
            
            $url = 'https://www.zw3b.fr/api/contents/channels/lst';
            
            if(isset($args) && is_array($args)) {
                $query = '?';
                $i=0;
                foreach($args as $clef => $value) {
                    $query.= $clef.'='.$value.(count($args)-1 > $i ? '&' : '');
                    $i++;
                }
                $url = $url.$query;
            }
            
            //------------------------------------------------
            $headers = array(
                //'Accept: application/json',
                //'Content-Type: application/json',
                'Origin: '.$this->tools()->protocole(),
                'Referer: '.$this->tools()->url(),
                'User-Agent: '.$_SERVER['HTTP_USER_AGENT'].' '.$this->infos->name.' ('.$this->infos->date.'; +'.$this->infos->url.'; rv:'.$this->infos->rev.')',
            );
            
            $cURLConnection = curl_init();
            
            curl_setopt($cURLConnection, CURLOPT_URL, $url);
            curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($cURLConnection, CURLOPT_SSL_VERIFYPEER, true); 
            curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, $headers);
            
            $data = curl_exec($cURLConnection);
            curl_close($cURLConnection);
            
            //------------------------------------------------
            
        }
        
        return $data = isset($data) ? $data : null;
    }
    
}



/*******************************************************************
 * Class zw3bApiClientAuthorization - RESTful API Client ZW3B
 *
 *
 */
class zw3bApiClientAuthorization extends zw3bApiClientModUsr {
    
    
    public function zw3bApiClientAuthorizationScopes() {
        
        
    }
    
    public function zw3bApiClientAuthorizationToken() {
        
        
    }
    
    public function zw3bApiClientAuthorizationRefresh() {
        
        
    }
    
    
    
}




/*******************************************************************
 * Class zw3bTools - RESTful API Client ZW3B
 *
 * $tools = $client->tools();
 *
 */
class zw3bTools extends zw3bApiClient
{
    //----------------------------------------------------------------
    public function protocole($site=null, $force_https = false)
    {
        if (!isset($site) or empty($site)) $site = $_SERVER['HTTP_HOST'];
        
        $https = @$_SERVER["HTTPS"];
        $port = @$_SERVER["SERVER_PORT"];
        if ($https == 'on') {
            if( !empty($port) && $port != 443 )
                $this_host = 'https://'.$site.':'.$port;
                else
                    $this_host = 'https://'.$site;
        } else
            $this_host = 'http://'.$site;
            
            return $this_host;
    }
    
    public function url()
    {
        return $this->protocole().$_SERVER["REQUEST_URI"];
    }
    //----------------------------------------------------------------
    
    /***********
     * Methode link_replace_callback(string)
     * 
     * Links parse/create :
     * 
     * - http(s)://www.domain.tld/link
     * - ftp(s)://ftp.domain.tld
     * - ftp(s).domain.tld
     * - www.domain.tld
     * - <a href="(http|ftp)(s)://url.domain.tld/link">link</a> except the anchors
     * - couriel@domain.tld
     * - #hastags
     * 
     * Checks HTML <pre> and <code> tags and does not parse links
     * 
     * - Encode in htmlentities, more, more
     * 
     * ex : https://www.zw3b.net/links-contents.php
     * 
     ****/
    public function link_replace_callback($text) {
        
        $text = self::parseTagsRecursive($text);
        
        // for img
        $text = preg_replace_callback("#<(img|IMG) (.*?)src=\"([^\#](.*?))\"(.*?)alt=\"(.*?)\"(.*?)>#", "self::html_image", $text);

        $text = preg_replace_callback("#<(a|A) (.*?)href=\"([^\#](.*?))\"(.*?)>(.*?)<\/(a|A)>#", "self::html_link", $text);
        
        $text = preg_replace_callback("#(([^=\"])?)(^|[ \n\r\t>)])((http(s?)://)(www\.)?([a-zA-Z0-9_-]+(\.[a-z0-9_-]+)+)(/[^/ \n\r<]*)*)#","self::html_link_brut", $text);
        $text = preg_replace_callback("#(^|[ \n\r\t>])([^\"])((ftp(s?)://)(www\.)?([a-zA-Z0-9_-]+(\.[a-z0-9_-]+)+)(/[^/ \n\r<]*)*)#","self::html_link_brut", $text);
        
        $text = preg_replace_callback("#([a-z_-][a-z0-9+\._-]*@[a-z0-9_-]+(\.[a-zA-Z0-9_-]+)+)#","self::html_link_mailto", $text);
        
        $text = preg_replace_callback("#(^|[ \n\r\t>])([^\"])?((www\.)([a-z0-9_-]+(\.[a-zA-Z0-9_-]+)+)(/[^/ \n\r<]*)*)#","self::html_link_brut", $text);
        $text = preg_replace_callback("#(^|[ \n\r\t>])([^\"])?((ftp\.)([a-z0-9_-]+(\.[a-zA-Z0-9_-]+)+)(/[^/ \n\r<]*)*)#","self::html_link_brut", $text);
        $text = preg_replace_callback("#(^|[ \n\r\t>])([^\"])?((ftps\.)([a-z0-9_-]+(\.[a-zA-Z0-9_-]+)+)(/[^/ \n\r<]*)*)#","self::html_link_brut", $text);
        
        // for no iframe
        //$text = preg_replace_callback("#<(iframe|IFRAME)(.*?)src=\"([^\#](.*?))\"(.*?)>(.*?)<\/(iframe|IFRAME)>#", "self::html_iframe", $text);
        
        $text = preg_replace_callback("#(^|[ \n\r\t>])\#([^\d\s]{1}[A-Za-z0-9_ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ]{1,}+)#","self::html_link_hastag", $text);
        
        $text = preg_replace_callback("#(?<!=|\b|&)\@\[([A-Za-z0-9]+)+([:]{1})+([0-9]{2,4})+([:]{1})+([^]]+)\]#","self::html_link_facebook_id", $text);
        
        //$text = nl2br($text);
        
        return $text;
    }
    //----------------------------------------------------------------
    
    //----------------------------------------------------------------
    private function html_iframe($value) {
        
        $link = $value[3];
        $link = preg_replace("#(\?|\&)autoplay=(0|1)#", "", $link);
        
        //$mysql = une_autre_class::db_link_count_rows($url=$link) != 0 ? db_link_update($url=$link) : une_autre_class::db_link_insert($url=$link);
        
        $iframe = 'IFRAME : <a href="'.$link.'" />'.$link.'</a>';
        
        return $iframe;
    }
    
    private function html_image($value) {
        
        $src = $value[3];
        $alt = $value[6];
        
        //$mysql = une_autre_class::db_link_count_rows($url=$link) != 0 ? db_link_update($url=$link) : une_autre_class::db_link_insert($url=$link);
        
        $href = '<img src="'.$src.'" alt="'.$alt.'" />';
        
        return $href;
    }
    
    private function html_link($value) {
        
        //echo '<pre>LINK: '.print_r($value,1).'</pre>';
        
        $reference = $value[6];
        $link = $value[3];
        
        if(preg_match('#(^(mailto:)([a-z_-][a-z0-9+\._-]*@[a-z0-9_-]+(\.[a-z0-9_-]+)+))(.*)#', $link, $matches)) {
            
            //echo '<pre>LINK: '.print_r($matches,1).'</pre>';
            
            $encoded = bin2hex($matches[3]);
            $encoded = chunk_split($encoded, 2, '%');
            $encoded = '%' . substr($encoded, 0, strlen($encoded) - 1);
            
            $link = 'mailto:'.$encoded.''.$matches[5];
            
            $codes[0] = '/@/';
            $codes[1] = '/\./';
            $replacements[0] = ' (at) ';
            $replacements[1] = ' (dot) ';
            
            $reference = preg_replace($codes, $replacements, $reference);
        }
        
        $reference = preg_match('#(^(http(s?)://))#', $value[6]) ? str_replace(array('/', '\\'), array('&sol;', '&bsol;'), $reference) : $reference;
        
        //$mysql = une_autre_class::db_link_count_rows($url=$link) != 0 ? db_link_update($url=$link) : une_autre_class::db_link_insert($url=$link);
        
        $href = '<a '.$value[2].' href="'.$link.'" '.$value[5].' target="_blank" class="ahref html">'.$reference.'</a> <span class="count link html"></span>';
        
        return $href;
    }
    
    private function html_link_brut($value) {
        
        //echo '<pre>BRUT '.substr($value[0], 0, 1).' : '.print_r($value,1).'</pre>';
        
        //$link = $value[2];
        $link = $value[4];

        $link = preg_match('#(^|[ \n\r\t>])(www\.([a-z0-9_-]+(\.[a-z0-9_-]+)+)(/([^/ \n\r]*[^/ \n\r\.])*)?)#', $link) ? 'http://'.$link : $link;
        $link = preg_match('#(^|[ \n\r\t])(ftp\.([a-z0-9_-]+(\.[a-z0-9_-]+)+)(/[^/ \n\r]*)*)#', $link) ? 'ftp://'.$link : $link;
        $link = preg_match('#(^|[ \n\r\t])(ftps\.([a-z0-9_-]+(\.[a-z0-9_-]+)+)(/[^/ \n\r]*)*)#', $link) ? 'ftps://'.$link : $link;
        
        //$mysql = une_autre_class::db_link_count_rows($url=$link) != 0 ? db_link_update($url=$link) : une_autre_class::db_link_insert($url=$link);
        
        $href = $value[2].$value[3].'<a href="'.$link.'" target="_blank" class="ahref brut">'.$link.'</a> <span class="count link brut"></span>';
        
        return $href;
        
    }
    
    private function html_link_mailto($value) {
        
        $codes[0] = '/@/';
        $codes[1] = '/\./';
        $replacements[0] = ' (at) ';
        $replacements[1] = ' (dot) ';
        
        $text = preg_replace($codes, $replacements, $value[1]);
        
        $encoded = bin2hex($value[1]);
        $encoded = chunk_split($encoded, 2, '%');
        $encoded = '%' . substr($encoded, 0, strlen($encoded) - 1);
        
        $mail = $encoded;
        
        $href = '<a href="mailto:'.$mail.'" class="ahref mailto">'.$text.'</a> <span class="count link mailto"></span>';
        
        return $href;
    }
    
    private function html_link_facebook_id($value) {
        
        $link = 'https://www.facebook.com/'.$value[1];
        
        //$mysql = une_autre_class::db_link_count_rows($url=$link) != 0 ? une_autre_class::db_link_update($url=$link) : une_autre_class::db_link_insert($url=$link);
        
        $href = '<a href="'.$link.'" title="FB Page : '.$value[5].'" target="_blank" class="ahref facebook page">'.$value[5].'</a> <span class="count link facebook page"></span>';
        
        return $href;
    }
    
    private function html_link_hastag($value) {
        
        //echo '<pre>'.print_r($value,1).'</pre>';
        
        $platform[0] = 'https://www.zw3b.net/?hashtag&v=';
        $platform[1] = 'https://twitter.com/hashtag/';
        $platform[2] = 'https://www.facebook.com/hashtag/';
        $platform[3] = 'https://www.linkedin.com/feed/hashtag/';
        //$platform[4] = 'https://www.debian-fr.org/tag/';
        
        $random = rand(0,3);
        
        $link = $platform[$random].$value[2];
        
        $ahref_class = $random === 0 ? 'zw3b hastag' : null;
        $ahref_class = $random === 1 ? 'twitter hastag' : $ahref_class;
        $ahref_class = $random === 2 ? 'facebook hastag' : $ahref_class;
        $ahref_class = $random === 3 ? 'linkedin hastag' : $ahref_class;
        $ahref_class = $random === 4 ? 'debianfr hastag' : $ahref_class;
        
        //$mysql = une_autre_class::db_link_count_rows($url=$link) != 0 ? une_autre_class::db_link_update($url=$link) : une_autre_class::db_link_insert($url=$link);
        
        $href = $value[1].'<a href="'.$link.'" title="Hastag : '.$value[2].'" target="_blank"  class="ahref '.$ahref_class.'">#'.$value[2].'</a> <span class="count link '.$ahref_class.'"></span>';
        
        return $href;
    }
    
    //----------------------------------------------------------------
    private function parseTagsRecursive($text)
    {
        $regex_pre = "#<((pre|PRE))>(.*?)<\/\\1>#s"; # Error : Stops at the 1st </pre> and breaks the parsing if I add in the script a <pre></pre>
        $regex_code = "#<((code|code))>(.*?)<\/\\1>#s"; # Error : Stops at the 1st </code> and breaks the parsing if I add in the script a <code></code>
        
        $text = preg_replace_callback($regex_code, 'self::parse_codeFormated', $text, -1 , $count);
        $text = preg_replace_callback($regex_pre, 'self::parse_preFormated', $text, -1 , $count);
        
        return $text;
    }
    
    private function parse_codeFormated($value) {
        
        //echo '<pre>'.print_r($value,1).'</pre>';
        
        $script_temp = $value[3];
        //$script_temp = utf8_encode($script_temp);
        
        $script = htmlentities($script_temp, ENT_QUOTES | ENT_SUBSTITUTE | ENT_XHTML, null, false);
        
        $script = str_replace(array('/', '\\', '\'', '@', '.'), array('&sol;', '&#92;', '&apos;', '&#64;', '&#46;'), $script);
        
        $script = '<code class="code">'.$script.'</code>';
        
        return $script;
    }
    
    private function parse_preFormated($value) {
        
        //echo '<pre>'.print_r($value,1).'</pre>';
        
        $script_temp = $value[3];
        //$script_temp = utf8_encode($script_temp);
        
        $script = htmlentities($script_temp, ENT_QUOTES | ENT_SUBSTITUTE | ENT_XHTML, null, false);
        
        $script = str_replace(array('/', '\\', '\'', '@', '.'), array('&sol;', '&#92;', '&apos;', '&#64;', '&#46;'), $script);
        
        $script = preg_replace("#(^|[ \n\r\t])\#([^\d\s]{1}[A-Za-z0-9_ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ]{1,}+)#", '&#35;${2}', $script);
        
        $script = self::parse_preFormateLine($script);
        
        //$script = '<pre class="code" id="code2">'.$script.'</pre>';
        
        return $script;
    }
    
    private function parse_preFormateLine($script) {
        
        global $compte;
        
        $compte++;
        $script = nl2br($script, true);
        $script = str_replace ('<br />', '\r', $script);
        
        $lignes = explode('\r', $script);
        $nombre = count($lignes);
        
        $nombre = ($nombre-1);
        if(isset($nombre) && $nombre == 0) {
            $nombre = 1;
            //$lignes = array_push($lignes, '<br/>');
        }
        
        $debut_de_script = true;
        $retour = '';
        $numero_de_ligne = 0;
        for ($i = 0; $i < sizeof($lignes); $i++)
        {
            $lignes[$i] = trim($lignes[$i], "\n\r\v\0");
            if(!empty($lignes[$i]))
                $debut_de_script = false;
                
            if($debut_de_script == false && $i != 0)
                $retour .= "\r";
                
            if ($debut_de_script == false && $i == sizeof($lignes)-1 && empty($lignes[$i]))
                break;
                
            // NUMERO DE LIGNE
            $numero_de_ligne = $debut_de_script == false ? $numero_de_ligne+1 : null;
            if ($debut_de_script == false && strlen($numero_de_ligne)<2) $numero_de_ligne = '0'.$numero_de_ligne;
            if ($debut_de_script == false && strlen($numero_de_ligne)<3) $numero_de_ligne = '0'.$numero_de_ligne;
            
            if($debut_de_script == false)
                $retour .= '<span class="numero-de-ligne">'.$numero_de_ligne.'</span>';
                
            if ($debut_de_script == false && $i >= 0 && !empty($lignes[$i]))
            {
                
                //$retour.= !empty($lignes[$i]) ? $lignes[$i] : '<-- vide -->';
                
                if(!empty($lignes[$i]))
                    $retour.= $lignes[$i];
            }
                            
        }
        
        $nombre = round($numero_de_ligne);
        
        $text = '<p id="pcode'.$compte.'" class="pcode">Script avec '.$nombre.' ligne'.($nombre > 1 ? 's' : '').'</p>'."\n";
        $text.= '<pre id="code'.$compte.'" class="code">'."\n";
        $text.= $retour;
        $text.= '</pre>'."\n";
        $text.= '<div class="retirer-numeros-de-lignes"><a href="#" onclick="hidenumbers(\'code'.$compte.'\'); return false;">Retirer les num&eacute;ros de lignes</a></div>';
        
        return $text;
        
    }
    
    //----------------------------------------------------------------
}



?>