Client.php 14.4 KB
Newer Older
1
<?php
Ασπασία Κατσή's avatar
Ασπασία Κατσή committed
2
 
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
namespace Drupal\epal;

use Symfony\Component\HttpFoundation\Response;
use Exception;

use Drupal\epal\Crypt;

/**
 * Description of Client
 *
 */
class Client
{

    private $_settings = [
        'verbose' => false,
        'ws_endpoint' => '',
        'ws_username' => '',
        'ws_password' => '',
        'NO_SAFE_CURL' => false
    ];
    private $logger; // if this is set and settings sets verbose mode, it will be used for logging

    private $_token = null; // cache JWT
    private $_tokenExpirationTS = null; // try to calculate token expiration time

    public function __construct($settings = [], $logger = null)
    {
        $this->logger = $logger;
        $this->_settings = array_merge($this->_settings, $settings);
        $this->_settings['ws_endpoint_token'] = "{$this->_settings['ws_endpoint']}/oauth2/token";
        $this->_settings['ws_endpoint_token_granttype'] = 'password';
Ασπασία Κατσή's avatar
Ασπασία Κατσή committed
35
        $this->_settings['ws_endpoint_studentepalInfo'] = "{$this->_settings['ws_endpoint']}/api/epal/GetStudentEpalInfo";
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
        $this->_settings['ws_endpoint_studentepalpromotion'] = "{$this->_settings['ws_endpoint']}/api/epal/GetStudentEpalPromotion";
        $this->_settings['ws_endpoint_alldidactiyear'] = "{$this->_settings['ws_endpoint']}/api/general/GetAllDidactiYear";
    }

    /**
     * Λαμβάνει το authentication token
     *
     * @return string To authentication header (Bearer <token>) έτοιμο για να μπει στο authorization
     * @throws \Exception
     */
    public function getTokenBearer()
    {
        if ($this->_token !== null && $this->_tokenExpirationTS !== null && intval($this->_tokenExpirationTS) >= time()) {
            $this->log(__METHOD__ . " reusing token");
            return $this->_token;
        }
        $this->_token = null;
        $this->_tokenExpirationTS = null;

        $this->log(__METHOD__ . " new token");

        $headers = [
            'Accept: application/json',
            'Accept-Language: en-gb',
            'Audience: Any',
            // 'Content-Type: application/x-www-form-urlencoded' // should be set by post
            'User-Agent: OSTEAM Client/v1.1 osteam'
        ];

        $payload = http_build_query([
            'username' => $this->_settings['ws_username'],
            'password' => $this->_settings['ws_password'],
            'grant_type' => $this->_settings['ws_endpoint_token_granttype']
        ]);
        $result = $this->post($this->_settings['ws_endpoint_token'], $payload, $headers);
        if ($result['success'] === false) {
            $this->log(__METHOD__ . " Error while calling ws. Diagnostic: {$result['response']}. Response code: {$result['http_status']}", "error");
            throw new Exception("Προέκυψε λάθος κατά την άντληση των στοιχείων.");
        }

        if (($response = json_decode($result['response'], true)) !== null) {
            $this->_tokenExpirationTS = time() + intval($response['expires_in']) - 15; // skip 15 seconds... just in case
            $this->_token = ucfirst($response['token_type']) . " {$response['access_token']}";
            return $this->_token;
        } else {
            $this->log(__METHOD__ . " Error while getting token from response {$result['response']}.", "error");
            throw new Exception("Προέκυψε λάθος κατά την λήψη του token. Αδυναμία άντλησης του token από το response.");
        }
    }

    /**
     * Επιστρέφει λίστα των διδακτικών ετών με κλειδί το id και τιμή το λεκτικό.
     *
     * @return array Associative array με κλειδί το id και τιμή το λεκτικό. Π.χ.
     *  Array (
     *  [1] => 2008 - 2009
     *  [2] => 2011 - 2012
     *  [18] => 2013 - 2014
     *  [24] => 2016 - 2017
     * )
     *
     * @throws \Exception Σε περίπτωση οποιουδήποτε λάθους
     */
    public function getAllDidactiYear()
    {
        $this->log(__METHOD__);

        $headers = [
            'Accept: application/json',
            'Accept-Language: en-gb',
            'Audience: Any',
            'Authorization: ' . $this->getTokenBearer(),
            'User-Agent: OSTEAM Client/v1.1 osteam'
        ];

        $result = $this->get($this->_settings['ws_endpoint_alldidactiyear'], [], $headers); // data as path params...
        if ($result['success'] === false) {
            $this->log(__METHOD__ . " Error while calling ws. Diagnostic: {$result['response']}. Response code: {$result['http_status']}", "error");
            throw new Exception("Προέκυψε λάθος κατά την άντληση των στοιχείων.");
        }

        if (($response = json_decode($result['response'], true)) !== null) {
            return $response;
        } else {
            $this->log(__METHOD__ . " Error while getting data from response {$result['response']}.", "error");
            throw new Exception("Προέκυψε λάθος κατά την λήψη των στοιχείων. Αδυναμία άντλησης στοιχείων από την απάντηση.");
        }
    }

    /**
     *
     * @param string $endpoint_base_url web service url
     * @param int $didactic_year_id {@see getAllDidactiYear()}
     * @param string $lastname  μόνο χαρακτήρες, κενά και μεσαίες παύλες
     * @param string $firstname  μόνο χαρακτήρες, κενά και μεσαίες παύλες
     * @param string $father_firstname μόνο χαρακτήρες, κενά και μεσαίες παύλες
     * @param string $mother_firstname μόνο χαρακτήρες, κενά και μεσαίες παύλες
     * @param string $birthdate ημερομηνίες στη μορφή 4-1-1997 (d-M-yyyy)
     *
     * @return boolean|null
     * @throws \Exception Σε περίπτωση οποιουδήποτε λάθους
     */
Ασπασία Κατσή's avatar
Ασπασία Κατσή committed
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    public function getStudentEpalPromotionOrCertification($endpoint_base_url, $id)
    {
        
        if (mb_strlen($id) == 0) {
            $this->log(__METHOD__ . " Missing parameters", "error");
            throw new Exception('Όλες οι παράμετροι είναι υποχρεωτικοί!!!'.$id, Response::HTTP_BAD_REQUEST);
        }

        $headers = [
            'Accept: application/json',
            // 'Accept-Language: en-gb',
            'Accept-Language: {"Accept-Language":"en-gb"}', // as per spec provided...
            'Audience: Any',
            'Authorization: ' . $this->getTokenBearer(),
            'User-Agent: OSTEAM Client/v1.1 osteam'
        ];

        $endpoint = $endpoint_base_url."/".intval($id);
  
        $result = $this->get($endpoint, [], $headers); // data as path params...
        try {
            $crypt = new Crypt();
            $val = 'call:' . print_r($endpoint, true) . ':rcv:' . print_r($result, true);
            $val_enc = $crypt->encrypt($val); 
            $this->log(__METHOD__ . $val_enc, 'info');
        } catch (\Exception $e) {
            $this->log(__METHOD__ . " cannot log encrypted", 'info');
        }

        if ($result['success'] === false) {
            $this->log(__METHOD__ . " Error while calling ws. Diagnostic: {$result['response']}. Response code: {$result['http_status']}", "error");
            throw new Exception("Προέκυψε λάθος κατά την άντληση των στοιχείων.");
        }

        return $result['response'];
    }


    public function getStudentEpalInfoNew($endpoint_base_url, $didactic_year_id, $lastname, $firstname, $father_firstname, $mother_firstname, $birthdate, $registry_no, $registration_no)
177 178 179 180 181 182
    {
        $parts = explode('-', $birthdate, 3);
        if (($parts === false) || count($parts) != 3 || checkdate(intval($parts[1]), intval($parts[0]), intval($parts[2])) === false) {
            $this->log(__METHOD__ . " Mallformed birthdate", "error");
            throw new Exception('Η ημερομηνία γέννησης πρέπει να είναι της μορφής Η/Μ/Ε', Response::HTTP_BAD_REQUEST);
        }
Ασπασία Κατσή's avatar
Ασπασία Κατσή committed
183
        if (mb_strlen($registration_no) == 0 || mb_strlen($registry_no) == 0 ) {
184 185 186 187 188 189 190 191 192 193 194 195
            $this->log(__METHOD__ . " Missing parameters", "error");
            throw new Exception('Όλες οι παράμετροι είναι υποχρεωτικοί', Response::HTTP_BAD_REQUEST);
        }

        $data = [
            'DidacticYearId' => intval($didactic_year_id),
            'LastName' => $lastname,
            'FirstName' => $firstname,
            'FatherFirstName' => $father_firstname,
            'MotherFirstname' => $mother_firstname,
            'BirthDate' => $birthdate,
            'RegistryNo' => $registry_no,
Ασπασία Κατσή's avatar
Ασπασία Κατσή committed
196
            'RegistrationNo' => $registration_no
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
        ];

        $headers = [
            'Accept: application/json',
            // 'Accept-Language: en-gb',
            'Accept-Language: {"Accept-Language":"en-gb"}', // as per spec provided...
            'Audience: Any',
            'Authorization: ' . $this->getTokenBearer(),
            'User-Agent: OSTEAM Client/v1.1 osteam'
        ];

        $endpoint = $endpoint_base_url . array_reduce($data, function ($c, $v) {
            $c .= "/" . urlencode($v);
            return $c;
        }, '');

        $result = $this->get($endpoint, [], $headers); // data as path params...
        try {
            $crypt = new Crypt();
            $val = 'call:' . print_r($endpoint, true) . ':rcv:' . print_r($result, true);
            $val_enc = $crypt->encrypt($val); 
            $this->log(__METHOD__ . $val_enc, 'info');
        } catch (\Exception $e) {
            $this->log(__METHOD__ . " cannot log encrypted", 'info');
        }

        if ($result['success'] === false) {
            $this->log(__METHOD__ . " Error while calling ws. Diagnostic: {$result['response']}. Response code: {$result['http_status']}", "error");
            throw new Exception("Προέκυψε λάθος κατά την άντληση των στοιχείων.");
        }

        return $result['response'];
    }

Ασπασία Κατσή's avatar
Ασπασία Κατσή committed
231
    public function getStudentEpalInfo($didactic_year_id, $lastname, $firstname, $father_firstname, $mother_firstname, $birthdate, $registry_no, $registration_no)
232 233
    {
        $this->log(__METHOD__);
Ασπασία Κατσή's avatar
Ασπασία Κατσή committed
234
        return $this->getStudentEpalInfoNew($this->_settings['ws_endpoint_studentepalInfo'], $didactic_year_id, $lastname, $firstname, $father_firstname, $mother_firstname, $birthdate, $registry_no, $registration_no);
235 236
    }

Ασπασία Κατσή's avatar
Ασπασία Κατσή committed
237
    public function getStudentEpalCertification($id)
238 239
    {
        $this->log(__METHOD__);
Ασπασία Κατσή's avatar
Ασπασία Κατσή committed
240
        return $this->getStudentEpalPromotionOrCertification($this->_settings['ws_endpoint_studentepalpromotion'], $id);
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
    }

    protected function setCommonCurlOptions($ch, $uri, $headers)
    {
        curl_setopt($ch, CURLOPT_URL, $uri);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_USERAGENT, "OSTEAM Client/v1.1 osteam");
        if (isset($this->_settings['NO_SAFE_CURL']) && $this->_settings['NO_SAFE_CURL'] === true) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        }

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        if ($this->_settings['verbose']) {
            curl_setopt($ch, CURLOPT_VERBOSE, true);
        }
    }

    public function post($uri, $payload, $headers = [])
    {
        $ch = curl_init();

        $this->setCommonCurlOptions($ch, $uri, $headers);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($ch);

        // log url as appropriate
        try {
            $crypt = new Crypt();
            $uri = $crypt->encrypt($uri);
        } catch (\Exception $e) {
            $uri = '-cannot encrypt-';
        }

        if (curl_errno($ch)) {
            $this->log(__METHOD__ . " Error calling {$uri}. Curl error: " . curl_error($ch) . " Curl info: " . var_export(curl_getinfo($ch), true), "error");
            throw new Exception("Λάθος κατά την κλήση της υπηρεσίας.");
        }
        if (intval(($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) / 100) != 2) {
            return [
                'success' => false,
                'http_status' => $http_code,
                'response' => $result
            ];
        }
        curl_close($ch);
        return [
            'success' => true,
            'http_status' => $http_code,
            'response' => $result
        ];
    }

    public function get($uri, $params = [], $headers = [])
    {
        $ch = curl_init();

        if (is_array($params) && count($params) > 0) {
            $qs = '?' . http_build_query($params);
        } else {
            $qs = '';
        }
        $this->setCommonCurlOptions($ch, "{$uri}{$qs}", $headers);

        // curl_setopt($ch, CURLOPT_HTTPGET, true); // default
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($ch);

        // log url as appropriate
        try {
            $crypt = new Crypt();
            $uri = $crypt->encrypt($uri);
        } catch (\Exception $e) {
            $uri = '-cannot encrypt-';
        }

        if (curl_errno($ch)) {
            $this->log(__METHOD__ . " Error calling {$uri}. Curl error: " . curl_error($ch) . " Curl info: " . var_export(curl_getinfo($ch), true), "error");
            throw new Exception("Λάθος κατά την κλήση της υπηρεσίας.");
        }
        if (intval(($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) / 100) != 2) {
            return [
                'success' => false,
                'http_status' => $http_code,
                'response' => $result
            ];
        }
        curl_close($ch);
        return [
            'success' => true,
            'http_status' => $http_code,
            'response' => $result
        ];
    }

    protected function log($msg, $level = 'info')
    {
        if ($this->logger !== null && $this->_settings['verbose']) {
            switch ($level) {
                case 'info':
                case 'warning':
                case 'error':
                    $this->logger->$level($msg);
                    break;
                default:
                    $this->logger->error($msg);
                    break;
            }
        }
        return;
    }
}