Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Represent the url for each method and the encoding of the parameters and response.
19
 *
20
 * @package    core_badges
21
 * @copyright  2012 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 * @author     Yuliya Bozhko <yuliya.bozhko@totaralms.com>
24
 */
25
 
26
namespace core_badges;
27
 
28
defined('MOODLE_INTERNAL') || die();
29
 
30
global $CFG;
31
require_once($CFG->libdir . '/filelib.php');
32
 
33
use context_system;
34
use curl;
35
 
36
/**
37
 * Represent a single method for the remote api.
38
 *
39
 * @package    core_badges
40
 * @copyright  2012 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
41
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42
 */
43
class backpack_api_mapping {
44
 
45
    /** @var string The action of this method. */
46
    public $action;
47
 
48
    /** @var string The base url of this backpack. */
49
    private $url;
50
 
51
    /** @var array List of parameters for this method. */
52
    public $params;
53
 
54
    /** @var string Name of a class to export parameters for this method. */
55
    public $requestexporter;
56
 
57
    /** @var string Name of a class to export response for this method. */
58
    public $responseexporter;
59
 
60
    /** @var boolean This method returns an array of responses. */
61
    public $multiple;
62
 
63
    /** @var string get or post methods. */
64
    public $method;
65
 
66
    /** @var boolean json decode the response. */
67
    public $json;
68
 
69
    /** @var boolean Authentication is required for this request. */
70
    public $authrequired;
71
 
72
    /** @var boolean Differentiate the function that can be called on a user backpack or a site backpack. */
73
    private $isuserbackpack;
74
 
75
    /** @var string Error string from authentication request. */
76
    private static $authenticationerror = '';
77
 
78
    /** @var mixed List of parameters for this method. */
79
    protected $postparams;
80
 
1441 ariadna 81
    /** @var int OpenBadges version. */
1 efrain 82
    protected $backpackapiversion;
83
 
1441 ariadna 84
    /** @var array Errors encountered during the request. */
85
    protected $errors = [];
86
 
1 efrain 87
    /**
88
     * Create a mapping.
89
     *
90
     * @param string $action The action of this method.
91
     * @param string $url The base url of this backpack.
92
     * @param mixed $postparams List of parameters for this method.
93
     * @param string $requestexporter Name of a class to export parameters for this method.
94
     * @param string $responseexporter Name of a class to export response for this method.
95
     * @param boolean $multiple This method returns an array of responses.
96
     * @param string $method get or post methods.
97
     * @param boolean $json json decode the response.
98
     * @param boolean $authrequired Authentication is required for this request.
99
     * @param boolean $isuserbackpack user backpack or a site backpack.
1441 ariadna 100
     * @param integer $backpackapiversion OpenBadges version.
1 efrain 101
     */
102
    public function __construct($action, $url, $postparams, $requestexporter, $responseexporter,
103
                                $multiple, $method, $json, $authrequired, $isuserbackpack, $backpackapiversion) {
104
        $this->action = $action;
105
        $this->url = $url;
106
        $this->postparams = $postparams;
107
        $this->requestexporter = $requestexporter;
108
        $this->responseexporter = $responseexporter;
109
        $this->multiple = $multiple;
110
        $this->method = $method;
111
        $this->json = $json;
112
        $this->authrequired = $authrequired;
113
        $this->isuserbackpack = $isuserbackpack;
114
        $this->backpackapiversion = $backpackapiversion;
115
    }
116
 
117
    /**
118
     * Get the unique key for the token.
119
     *
120
     * @param string $type The type of token.
121
     * @return string
122
     */
123
    private function get_token_key($type) {
124
        $prefix = 'badges_';
125
        if ($this->isuserbackpack) {
126
            $prefix .= 'user_backpack_';
127
        } else {
128
            $prefix .= 'site_backpack_';
129
        }
130
        $prefix .= $type . '_token';
131
        return $prefix;
132
    }
133
 
134
    /**
135
     * Remember the error message in a static variable.
136
     *
137
     * @param string $msg The message.
138
     */
139
    public static function set_authentication_error($msg) {
140
        self::$authenticationerror = $msg;
141
    }
142
 
143
    /**
144
     * Get the last authentication error in this request.
145
     *
146
     * @return string
147
     */
148
    public static function get_authentication_error() {
149
        return self::$authenticationerror;
150
    }
151
 
152
    /**
1441 ariadna 153
     * Get the errors encountered during the request.
154
     *
155
     * @return array The list of errors.
156
     */
157
    public function get_errors() {
158
        return $this->errors;
159
    }
160
 
161
    /**
162
     * Add an error to the list of errors.
163
     *
164
     * @param string $error The error message.
165
     * @return self This instance for method chaining.
166
     */
167
    public function add_error(string $error): self {
168
        $this->errors[] = $error;
169
        return $this;
170
    }
171
 
172
    /**
1 efrain 173
     * Does the action match this mapping?
174
     *
175
     * @param string $action The action.
176
     * @return boolean
177
     */
178
    public function is_match($action) {
179
        return $this->action == $action;
180
    }
181
 
182
    /**
183
     * Parse the method url and insert parameters.
184
     *
185
     * @param string $apiurl The raw apiurl.
186
     * @param string $param1 The first parameter.
187
     * @param string $param2 The second parameter.
188
     * @return string
189
     */
190
    private function get_url($apiurl, $param1, $param2) {
191
        $urlscheme = parse_url($apiurl, PHP_URL_SCHEME);
192
        $urlhost = parse_url($apiurl, PHP_URL_HOST);
193
 
194
        $url = $this->url;
195
        $url = str_replace('[SCHEME]', $urlscheme, $url);
196
        $url = str_replace('[HOST]', $urlhost, $url);
197
        $url = str_replace('[URL]', $apiurl, $url);
198
        $url = str_replace('[PARAM1]', $param1 ?? '', $url);
199
        $url = str_replace('[PARAM2]', $param2 ?? '', $url);
200
 
201
        return $url;
202
    }
203
 
204
    /**
205
     * Parse the post parameters and insert replacements.
206
     *
207
     * @param string $email The api username.
208
     * @param string $password The api password.
209
     * @param string $param The parameter.
210
     * @return mixed
211
     */
212
    private function get_post_params($email, $password, $param) {
213
        global $PAGE;
214
 
215
        if ($this->method == 'get') {
216
            return '';
217
        }
218
 
219
        $request = $this->postparams;
220
        if ($request === '[PARAM]') {
221
            $value = $param;
222
            foreach ($value as $key => $keyvalue) {
223
                if (gettype($value[$key]) == 'array') {
224
                    $newkey = 'related_' . $key;
225
                    $value[$newkey] = $value[$key];
226
                    unset($value[$key]);
227
                }
228
            }
229
        } else if (is_array($request)) {
230
            foreach ($request as $key => $value) {
231
                if ($value == '[EMAIL]') {
232
                    $value = $email;
233
                    $request[$key] = $value;
234
                } else if ($value == '[PASSWORD]') {
235
                    $value = $password;
236
                    $request[$key] = $value;
237
                } else if ($value == '[PARAM]') {
238
                    $request[$key] = is_array($param) ? $param[0] : $param;
239
                }
240
            }
241
        }
242
        $context = context_system::instance();
243
        $exporter = $this->requestexporter;
244
        $output = $PAGE->get_renderer('core', 'badges');
245
        if (!empty($exporter)) {
246
            $exporterinstance = new $exporter($value, ['context' => $context]);
247
            $request = $exporterinstance->export($output);
248
        }
249
        if ($this->json) {
250
            return json_encode($request);
251
        }
252
        return $request;
253
    }
254
 
255
    /**
256
     * Get the user id from a previous user request.
257
     *
258
     * @return integer
259
     */
260
    private function get_auth_user_id() {
261
        global $USER;
262
 
263
        if ($this->isuserbackpack) {
264
            return $USER->id;
265
        } else {
266
            // The access tokens for the system backpack are shared.
267
            return -1;
268
        }
269
    }
270
 
271
    /**
272
     * Parse the response from an openbadges 2 login.
273
     *
274
     * @param string $response The request response data.
275
     * @param integer $backpackid The id of the backpack.
276
     * @return mixed
277
     */
278
    private function oauth_token_response($response, $backpackid) {
279
        global $SESSION;
280
 
281
        if (isset($response->access_token) && isset($response->refresh_token)) {
282
            // Remember the tokens.
283
            $accesskey = $this->get_token_key(BADGE_ACCESS_TOKEN);
284
            $refreshkey = $this->get_token_key(BADGE_REFRESH_TOKEN);
285
            $expireskey = $this->get_token_key(BADGE_EXPIRES_TOKEN);
286
            $useridkey = $this->get_token_key(BADGE_USER_ID_TOKEN);
287
            $backpackidkey = $this->get_token_key(BADGE_BACKPACK_ID_TOKEN);
288
            if (isset($response->expires_in)) {
289
                $timeout = $response->expires_in;
290
            } else {
291
                $timeout = 15 * 60; // 15 minute timeout if none set.
292
            }
293
            $expires = $timeout + time();
294
 
295
            $SESSION->$expireskey = $expires;
296
            $SESSION->$useridkey = $this->get_auth_user_id();
297
            $SESSION->$accesskey = $response->access_token;
298
            $SESSION->$refreshkey = $response->refresh_token;
299
            $SESSION->$backpackidkey = $backpackid;
300
            return -1;
301
        } else if (isset($response->error_description)) {
302
            self::set_authentication_error($response->error_description);
303
        }
304
        return $response;
305
    }
306
 
307
    /**
308
     * Standard options used for all curl requests.
309
     *
310
     * @return array
311
     */
312
    private function get_curl_options() {
313
        return array(
314
            'FRESH_CONNECT'     => true,
315
            'RETURNTRANSFER'    => true,
316
            'FOLLOWLOCATION'    => true,
317
            'FORBID_REUSE'      => true,
318
            'HEADER'            => 0,
319
            'CONNECTTIMEOUT'    => 3,
320
            'CONNECTTIMEOUT'    => 3,
321
            // Follow redirects with the same type of request when sent 301, or 302 redirects.
322
            'CURLOPT_POSTREDIR' => 3,
323
        );
324
    }
325
 
326
    /**
327
     * Make an api request and parse the response.
328
     *
329
     * @param string $apiurl Raw request url.
330
     * @param string $urlparam1 Parameter for the request.
331
     * @param string $urlparam2 Parameter for the request.
332
     * @param string $email User email for authentication.
333
     * @param string $password for authentication.
334
     * @param mixed $postparam Raw data for the post body.
335
     * @param string $backpackid the id of the backpack to use.
336
     * @return mixed
337
     */
338
    public function request($apiurl, $urlparam1, $urlparam2, $email, $password, $postparam, $backpackid) {
339
        global $SESSION, $PAGE;
340
 
341
        $curl = new curl();
342
 
343
        $url = $this->get_url($apiurl, $urlparam1, $urlparam2);
344
 
345
        if ($this->authrequired) {
346
            $accesskey = $this->get_token_key(BADGE_ACCESS_TOKEN);
347
            if (isset($SESSION->$accesskey)) {
348
                $token = $SESSION->$accesskey;
349
                $curl->setHeader('Authorization: Bearer ' . $token);
350
            }
351
        }
352
        if ($this->json) {
353
            $curl->setHeader(array('Content-type: application/json'));
354
        }
355
        $curl->setHeader(array('Accept: application/json', 'Expect:'));
356
        $options = $this->get_curl_options();
357
 
358
        $post = $this->get_post_params($email, $password, $postparam);
359
 
360
        if ($this->method == 'get') {
361
            $response = $curl->get($url, $post, $options);
362
        } else if ($this->method == 'post') {
363
            $response = $curl->post($url, $post, $options);
364
        } else if ($this->method == 'put') {
365
            $response = $curl->put($url, $post, $options);
366
        }
367
        $response = json_decode($response);
1441 ariadna 368
        if ($response === null) {
369
            $this->add_error(get_string('invalidrequest', 'error'));
370
            return null;
371
        }
372
        if (isset($response->status) && isset($response->status->success) && $response->status->success != true) {
373
            // If the response wasn't successful, store the errors and return null.
374
            if (isset($response->validationErrors)) {
375
                $error = implode(', ', $response->validationErrors);
376
            } else if (isset($response->status->description)) {
377
                $error = $response->status->description;
378
            } else {
379
                $error = get_string('invalidrequest', 'error');
380
            }
381
            $this->add_error($error);
382
            return null;
383
        }
384
 
1 efrain 385
        if (isset($response->result)) {
386
            $response = $response->result;
387
        }
388
        $context = context_system::instance();
389
        $exporter = $this->responseexporter;
390
        if (class_exists($exporter)) {
391
            $output = $PAGE->get_renderer('core', 'badges');
392
            if (!$this->multiple) {
393
                if (count($response)) {
394
                    $response = $response[0];
395
                }
396
                if (empty($response)) {
397
                    return null;
398
                }
399
                $apidata = $exporter::map_external_data($response, $this->backpackapiversion);
400
                $exporterinstance = new $exporter($apidata, ['context' => $context]);
401
                $data = $exporterinstance->export($output);
402
                return $data;
403
            } else {
404
                $multiple = [];
405
                if (empty($response)) {
406
                    return $multiple;
407
                }
408
                foreach ($response as $data) {
409
                    $apidata = $exporter::map_external_data($data, $this->backpackapiversion);
410
                    $exporterinstance = new $exporter($apidata, ['context' => $context]);
411
                    $multiple[] = $exporterinstance->export($output);
412
                }
413
                return $multiple;
414
            }
415
        } else if (method_exists($this, $exporter)) {
416
            return $this->$exporter($response, $backpackid);
417
        }
418
        return $response;
419
    }
420
}