Proyectos de Subversion Moodle

Rev

Rev 1 | Mostrar el archivo completo | | | Autoría | Ultima modificación | Ver Log |

Rev 1 Rev 1441
Línea 12... Línea 12...
12
// GNU General Public License for more details.
12
// GNU General Public License for more details.
13
//
13
//
14
// You should have received a copy of the GNU General Public License
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/>.
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
Línea 16... Línea -...
16
 
-
 
17
/**
-
 
18
 * Communicate with backpacks.
-
 
19
 *
-
 
20
 * @copyright  2012 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
-
 
21
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
-
 
22
 * @author     Yuliya Bozhko <yuliya.bozhko@totaralms.com>
-
 
23
 */
-
 
24
 
16
 
Línea 25... Línea 17...
25
namespace core_badges;
17
namespace core_badges;
Línea 26... Línea 18...
26
 
18
 
Línea 27... Línea 19...
27
defined('MOODLE_INTERNAL') || die();
19
defined('MOODLE_INTERNAL') || die();
28
 
20
 
29
require_once($CFG->libdir . '/filelib.php');
-
 
30
 
-
 
31
use cache;
21
require_once($CFG->libdir . '/filelib.php');
32
use coding_exception;
22
 
33
use core_badges\external\assertion_exporter;
-
 
34
use core_badges\external\collection_exporter;
23
use cache;
35
use core_badges\external\issuer_exporter;
24
use coding_exception;
Línea 36... Línea 25...
36
use core_badges\external\badgeclass_exporter;
25
use core_badges\external\issuer_exporter;
37
use curl;
26
use core_badges\external\badgeclass_exporter;
Línea 45... Línea 34...
45
define('BADGE_EXPIRES_TOKEN', 'expires');
34
define('BADGE_EXPIRES_TOKEN', 'expires');
Línea 46... Línea 35...
46
 
35
 
47
/**
36
/**
48
 * Class for communicating with backpacks.
37
 * Class for communicating with backpacks.
49
 *
38
 *
-
 
39
 * @package    core_badges
50
 * @package   core_badges
40
 * @author     Yuliya Bozhko <yuliya.bozhko@totaralms.com>
51
 * @copyright  2012 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
41
 * @copyright  2012 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
52
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53
 */
43
 */
-
 
44
class backpack_api {
-
 
45
    /** @var int Canvas Credentials backpack provider */
-
 
46
    public const PROVIDER_CANVAS_CREDENTIALS = 0;
-
 
47
 
-
 
48
    /** @var int Other backpack provider */
-
 
49
    public const PROVIDER_OTHER = 1;
-
 
50
 
-
 
51
    /** @var int Empty provider */
-
 
52
    public const PROVIDER_EMPTY = -1;
-
 
53
 
-
 
54
    /** @var int Empty region */
Línea 54... Línea 55...
54
class backpack_api {
55
    public const REGION_EMPTY = -1;
55
 
56
 
Línea 56... Línea 57...
56
    /** @var string The email address of the issuer or the backpack owner. */
57
    /** @var string The email address of the issuer or the backpack owner. */
Línea 69... Línea 70...
69
    private $isuserbackpack;
70
    private $isuserbackpack;
Línea 70... Línea 71...
70
 
71
 
71
    /** @var integer The id of the backpack we are talking to. */
72
    /** @var integer The id of the backpack we are talking to. */
Línea 72... Línea 73...
72
    private $backpackid;
73
    private $backpackid;
73
 
74
 
Línea 74... Línea 75...
74
    /** @var \backpack_api_mapping[] List of apis for the user or site using api version 1 or 2. */
75
    /** @var \core_badges\backpack_api_mapping[] List of apis for the user or site using api version 2. */
75
    private $mappings = [];
76
    private $mappings = [];
76
 
77
 
Línea 106... Línea 107...
106
 
107
 
107
    /**
108
    /**
108
     * Define the mappings supported by this usage and api version.
109
     * Define the mappings supported by this usage and api version.
109
     */
110
     */
110
    private function define_mappings() {
-
 
111
        if ($this->backpackapiversion == OPEN_BADGES_V2) {
111
    private function define_mappings() {
112
            if ($this->isuserbackpack) {
112
        if ($this->isuserbackpack) {
113
                $mapping = [];
113
            $mapping = [];
114
                $mapping[] = [
114
            $mapping[] = [
115
                    'collections',                              // Action.
115
                'collections',                              // Action.
116
                    '[URL]/backpack/collections',               // URL
116
                '[URL]/backpack/collections',               // URL.
117
                    [],                                         // Post params.
117
                [],                                         // Post params.
118
                    '',                                         // Request exporter.
118
                '',                                         // Request exporter.
119
                    'core_badges\external\collection_exporter', // Response exporter.
119
                'core_badges\external\collection_exporter', // Response exporter.
120
                    true,                                       // Multiple.
120
                true,                                       // Multiple.
121
                    'get',                                      // Method.
121
                'get',                                      // Method.
122
                    true,                                       // JSON Encoded.
122
                true,                                       // JSON Encoded.
123
                    true                                        // Auth required.
123
                true,                                       // Auth required.
124
                ];
124
            ];
125
                $mapping[] = [
125
            $mapping[] = [
126
                    'user',                                     // Action.
126
                'user',                                     // Action.
127
                    '[SCHEME]://[HOST]/o/token',                // URL
127
                '[SCHEME]://[HOST]/o/token',                // URL.
128
                    ['username' => '[EMAIL]', 'password' => '[PASSWORD]'], // Post params.
128
                ['username' => '[EMAIL]', 'password' => '[PASSWORD]'], // Post params.
129
                    '',                                         // Request exporter.
129
                '',                                         // Request exporter.
130
                    'oauth_token_response',                     // Response exporter.
130
                'oauth_token_response',                     // Response exporter.
131
                    false,                                      // Multiple.
131
                false,                                      // Multiple.
132
                    'post',                                     // Method.
132
                'post',                                     // Method.
133
                    false,                                      // JSON Encoded.
133
                false,                                      // JSON Encoded.
134
                    false,                                      // Auth required.
134
                false,                                      // Auth required.
135
                ];
135
            ];
136
                $mapping[] = [
136
            $mapping[] = [
137
                    'assertion',                                // Action.
137
                'assertion',                                // Action.
138
                    // Badgr.io does not return the public information about a badge
138
                // Badgr.io does not return the public information about a badge
139
                    // if the issuer is associated with another user. We need to pass
139
                // if the issuer is associated with another user. We need to pass
140
                    // the expand parameters which are not in any specification to get
140
                // the expand parameters which are not in any specification to get
141
                    // additional information about the assertion in a single request.
141
                // additional information about the assertion in a single request.
142
                    '[URL]/backpack/assertions/[PARAM2]?expand=badgeclass&expand=issuer',
142
                '[URL]/backpack/assertions/[PARAM2]?expand=badgeclass&expand=issuer',
143
                    [],                                         // Post params.
143
                [],                                         // Post params.
144
                    '',                                         // Request exporter.
144
                '',                                         // Request exporter.
145
                    'core_badges\external\assertion_exporter',  // Response exporter.
145
                'core_badges\external\assertion_exporter',  // Response exporter.
146
                    false,                                      // Multiple.
146
                false,                                      // Multiple.
147
                    'get',                                      // Method.
147
                'get',                                      // Method.
148
                    true,                                       // JSON Encoded.
148
                true,                                       // JSON Encoded.
149
                    true                                        // Auth required.
149
                true,                                       // Auth required.
150
                ];
150
            ];
151
                $mapping[] = [
151
            $mapping[] = [
152
                    'importbadge',                                // Action.
152
                'importbadge',                                // Action.
153
                    // Badgr.io does not return the public information about a badge
153
                // Badgr.io does not return the public information about a badge
154
                    // if the issuer is associated with another user. We need to pass
154
                // if the issuer is associated with another user. We need to pass
155
                    // the expand parameters which are not in any specification to get
155
                // the expand parameters which are not in any specification to get
156
                    // additional information about the assertion in a single request.
156
                // additional information about the assertion in a single request.
157
                    '[URL]/backpack/import',
157
                '[URL]/backpack/import',
158
                    ['url' => '[PARAM]'],  // Post params.
158
                ['url' => '[PARAM]'],  // Post params.
159
                    '',                                             // Request exporter.
159
                '',                                             // Request exporter.
160
                    'core_badges\external\assertion_exporter',      // Response exporter.
160
                'core_badges\external\assertion_exporter',      // Response exporter.
161
                    false,                                          // Multiple.
161
                false,                                          // Multiple.
162
                    'post',                                         // Method.
162
                'post',                                         // Method.
163
                    true,                                           // JSON Encoded.
163
                true,                                           // JSON Encoded.
164
                    true                                            // Auth required.
164
                true,                                           // Auth required.
165
                ];
165
            ];
166
                $mapping[] = [
166
            $mapping[] = [
167
                    'badges',                                   // Action.
167
                'badges',                                   // Action.
168
                    '[URL]/backpack/collections/[PARAM1]',      // URL
168
                '[URL]/backpack/collections/[PARAM1]',      // URL.
169
                    [],                                         // Post params.
169
                [],                                         // Post params.
170
                    '',                                         // Request exporter.
170
                '',                                         // Request exporter.
171
                    'core_badges\external\collection_exporter', // Response exporter.
171
                'core_badges\external\collection_exporter', // Response exporter.
172
                    true,                                       // Multiple.
172
                true,                                       // Multiple.
173
                    'get',                                      // Method.
173
                'get',                                      // Method.
174
                    true,                                       // JSON Encoded.
174
                true,                                       // JSON Encoded.
175
                    true                                        // Auth required.
175
                true,                                       // Auth required.
176
                ];
176
            ];
177
                foreach ($mapping as $map) {
177
            foreach ($mapping as $map) {
178
                    $map[] = true; // User api function.
-
 
179
                    $map[] = OPEN_BADGES_V2; // V2 function.
-
 
180
                    $this->mappings[] = new backpack_api_mapping(...$map);
-
 
181
                }
-
 
182
            } else {
-
 
183
                $mapping = [];
-
 
184
                $mapping[] = [
-
 
185
                    'user',                                     // Action.
-
 
186
                    '[SCHEME]://[HOST]/o/token',                // URL
-
 
187
                    ['username' => '[EMAIL]', 'password' => '[PASSWORD]'], // Post params.
-
 
188
                    '',                                         // Request exporter.
-
 
189
                    'oauth_token_response',                     // Response exporter.
-
 
190
                    false,                                      // Multiple.
-
 
191
                    'post',                                     // Method.
-
 
192
                    false,                                      // JSON Encoded.
-
 
193
                    false                                       // Auth required.
-
 
194
                ];
-
 
195
                $mapping[] = [
-
 
196
                    'issuers',                                  // Action.
-
 
197
                    '[URL]/issuers',                            // URL
-
 
198
                    '[PARAM]',                                  // Post params.
-
 
199
                    'core_badges\external\issuer_exporter',     // Request exporter.
-
 
200
                    'core_badges\external\issuer_exporter',     // Response exporter.
-
 
201
                    false,                                      // Multiple.
-
 
202
                    'post',                                     // Method.
-
 
203
                    true,                                       // JSON Encoded.
-
 
204
                    true                                        // Auth required.
-
 
205
                ];
-
 
206
                $mapping[] = [
-
 
207
                    'badgeclasses',                             // Action.
-
 
208
                    '[URL]/issuers/[PARAM2]/badgeclasses',      // URL
-
 
209
                    '[PARAM]',                                  // Post params.
-
 
210
                    'core_badges\external\badgeclass_exporter', // Request exporter.
-
 
211
                    'core_badges\external\badgeclass_exporter', // Response exporter.
-
 
212
                    false,                                      // Multiple.
-
 
213
                    'post',                                     // Method.
-
 
214
                    true,                                       // JSON Encoded.
-
 
215
                    true                                        // Auth required.
-
 
216
                ];
-
 
217
                $mapping[] = [
-
 
218
                    'assertions',                               // Action.
-
 
219
                    '[URL]/badgeclasses/[PARAM2]/assertions',   // URL
-
 
220
                    '[PARAM]',                                  // Post params.
-
 
221
                    'core_badges\external\assertion_exporter', // Request exporter.
-
 
222
                    'core_badges\external\assertion_exporter', // Response exporter.
-
 
223
                    false,                                      // Multiple.
-
 
224
                    'post',                                     // Method.
-
 
225
                    true,                                       // JSON Encoded.
-
 
226
                    true                                        // Auth required.
-
 
227
                ];
-
 
228
                $mapping[] = [
-
 
229
                    'updateassertion',                                // Action.
-
 
230
                    '[URL]/assertions/[PARAM2]?expand=badgeclass&expand=issuer',
-
 
231
                    '[PARAM]',                                  // Post params.
-
 
232
                    'core_badges\external\assertion_exporter', // Request exporter.
-
 
233
                    'core_badges\external\assertion_exporter', // Response exporter.
-
 
234
                    false,                                      // Multiple.
-
 
235
                    'put',                                     // Method.
-
 
236
                    true,                                       // JSON Encoded.
-
 
237
                    true                                        // Auth required.
-
 
238
                ];
-
 
239
                foreach ($mapping as $map) {
-
 
240
                    $map[] = false; // Site api function.
178
                $map[] = true; // User api function.
241
                    $map[] = OPEN_BADGES_V2; // V2 function.
179
                $map[] = OPEN_BADGES_V2; // V2 function.
242
                    $this->mappings[] = new backpack_api_mapping(...$map);
-
 
243
                }
180
                $this->mappings[] = new backpack_api_mapping(...$map);
244
            }
181
            }
245
        } else {
-
 
246
            if ($this->isuserbackpack) {
182
        } else {
247
                $mapping = [];
183
            $mapping = [];
248
                $mapping[] = [
184
            $mapping[] = [
249
                    'user',                                     // Action.
185
                'user',                                     // Action.
250
                    '[URL]/displayer/convert/email',            // URL
186
                '[SCHEME]://[HOST]/o/token',                // URL.
251
                    ['email' => '[EMAIL]'],                     // Post params.
187
                ['username' => '[EMAIL]', 'password' => '[PASSWORD]'], // Post params.
252
                    '',                                         // Request exporter.
188
                '',                                         // Request exporter.
253
                    'convert_email_response',                   // Response exporter.
189
                'oauth_token_response',                     // Response exporter.
254
                    false,                                      // Multiple.
190
                false,                                      // Multiple.
255
                    'post',                                     // Method.
191
                'post',                                     // Method.
256
                    false,                                      // JSON Encoded.
192
                false,                                      // JSON Encoded.
257
                    false                                       // Auth required.
193
                false,                                      // Auth required.
258
                ];
194
            ];
259
                $mapping[] = [
195
            $mapping[] = [
260
                    'groups',                                   // Action.
196
                'issuers',                                  // Action.
261
                    '[URL]/displayer/[PARAM1]/groups.json',     // URL
197
                '[URL]/issuers',                            // URL.
262
                    [],                                         // Post params.
198
                '[PARAM]',                                  // Post params.
263
                    '',                                         // Request exporter.
199
                'core_badges\external\issuer_exporter',     // Request exporter.
264
                    '',                                         // Response exporter.
200
                'core_badges\external\issuer_exporter',     // Response exporter.
265
                    false,                                      // Multiple.
201
                false,                                      // Multiple.
266
                    'get',                                      // Method.
202
                'post',                                     // Method.
267
                    true,                                       // JSON Encoded.
203
                true,                                       // JSON Encoded.
268
                    true                                        // Auth required.
204
                true,                                       // Auth required.
269
                ];
205
            ];
270
                $mapping[] = [
206
            $mapping[] = [
271
                    'badges',                                   // Action.
207
                'badgeclasses',                             // Action.
272
                    '[URL]/displayer/[PARAM2]/group/[PARAM1].json',     // URL
208
                '[URL]/issuers/[PARAM2]/badgeclasses',      // URL.
273
                    [],                                         // Post params.
209
                '[PARAM]',                                  // Post params.
274
                    '',                                         // Request exporter.
210
                'core_badges\external\badgeclass_exporter', // Request exporter.
275
                    '',                                         // Response exporter.
211
                'core_badges\external\badgeclass_exporter', // Response exporter.
276
                    false,                                      // Multiple.
212
                false,                                      // Multiple.
277
                    'get',                                      // Method.
213
                'post',                                     // Method.
278
                    true,                                       // JSON Encoded.
214
                true,                                       // JSON Encoded.
279
                    true                                        // Auth required.
215
                true,                                       // Auth required.
280
                ];
216
            ];
281
                foreach ($mapping as $map) {
217
            $mapping[] = [
282
                    $map[] = true; // User api function.
218
                'assertions',                               // Action.
283
                    $map[] = OPEN_BADGES_V1; // V1 function.
219
                '[URL]/badgeclasses/[PARAM2]/assertions',   // URL.
-
 
220
                '[PARAM]',                                  // Post params.
-
 
221
                'core_badges\external\assertion_exporter',  // Request exporter.
284
                    $this->mappings[] = new backpack_api_mapping(...$map);
222
                'core_badges\external\assertion_exporter',  // Response exporter.
285
                }
223
                false,                                      // Multiple.
-
 
224
                'post',                                     // Method.
-
 
225
                true,                                       // JSON Encoded.
286
            } else {
226
                true,                                       // Auth required.
287
                $mapping = [];
227
            ];
288
                $mapping[] = [
228
            $mapping[] = [
289
                    'user',                                     // Action.
229
                'updateassertion',                          // Action.
290
                    '[URL]/displayer/convert/email',            // URL
230
                '[URL]/assertions/[PARAM2]?expand=badgeclass&expand=issuer',
291
                    ['email' => '[EMAIL]'],                     // Post params.
231
                '[PARAM]',                                  // Post params.
292
                    '',                                         // Request exporter.
232
                'core_badges\external\assertion_exporter',  // Request exporter.
293
                    'convert_email_response',                   // Response exporter.
233
                'core_badges\external\assertion_exporter',  // Response exporter.
294
                    false,                                      // Multiple.
234
                false,                                      // Multiple.
295
                    'post',                                     // Method.
235
                'put',                                      // Method.
296
                    false,                                      // JSON Encoded.
236
                true,                                       // JSON Encoded.
297
                    false                                       // Auth required.
237
                true,                                       // Auth required.
298
                ];
238
            ];
299
                foreach ($mapping as $map) {
239
            foreach ($mapping as $map) {
300
                    $map[] = false; // Site api function.
240
                $map[] = false; // Site api function.
301
                    $map[] = OPEN_BADGES_V1; // V1 function.
241
                $map[] = OPEN_BADGES_V2; // V2 function.
302
                    $this->mappings[] = new backpack_api_mapping(...$map);
-
 
303
                }
242
                $this->mappings[] = new backpack_api_mapping(...$map);
304
            }
243
            }
305
        }
244
        }
Línea 306... Línea 245...
306
    }
245
    }
Línea 313... Línea 252...
313
     * @param string $entityid An api parameter
252
     * @param string $entityid An api parameter
314
     * @param string $postdata The body of the api request.
253
     * @param string $postdata The body of the api request.
315
     * @return mixed
254
     * @return mixed
316
     */
255
     */
317
    private function curl_request($action, $collection = null, $entityid = null, $postdata = null) {
256
    private function curl_request($action, $collection = null, $entityid = null, $postdata = null) {
318
        global $CFG, $SESSION;
-
 
319
 
-
 
320
        $curl = new curl();
-
 
321
        $authrequired = false;
-
 
322
        if ($this->backpackapiversion == OPEN_BADGES_V1) {
-
 
323
            $useridkey = $this->get_token_key(BADGE_USER_ID_TOKEN);
-
 
324
            if (isset($SESSION->$useridkey)) {
-
 
325
                if ($collection == null) {
-
 
326
                    $collection = $SESSION->$useridkey;
-
 
327
                } else {
-
 
328
                    $entityid = $SESSION->$useridkey;
-
 
329
                }
-
 
330
            }
-
 
331
        }
-
 
332
        foreach ($this->mappings as $mapping) {
257
        foreach ($this->mappings as $mapping) {
333
            if ($mapping->is_match($action)) {
258
            if ($mapping->is_match($action)) {
334
                return $mapping->request(
259
                return $mapping->request(
335
                    $this->backpackapiurl,
260
                    $this->backpackapiurl,
336
                    $collection,
261
                    $collection,
Línea 379... Línea 304...
379
        $prefix .= $type . '_token';
304
        $prefix .= $type . '_token';
380
        return $prefix;
305
        return $prefix;
381
    }
306
    }
Línea 382... Línea 307...
382
 
307
 
383
    /**
-
 
384
     * Normalise the return from a missing user request.
-
 
385
     *
-
 
386
     * @param string $status
-
 
387
     * @return mixed
-
 
388
     */
-
 
389
    private function check_status($status) {
-
 
390
        // V1 ONLY.
-
 
391
        switch($status) {
-
 
392
            case "missing":
-
 
393
                $response = array(
-
 
394
                    'status'  => $status,
-
 
395
                    'message' => get_string('error:nosuchuser', 'badges')
-
 
396
                );
-
 
397
                return $response;
-
 
398
        }
-
 
399
        return false;
-
 
400
    }
-
 
401
 
-
 
402
    /**
308
    /**
403
     * Make an api request to get an assertion
309
     * Make an api request to get an assertion
404
     *
310
     *
405
     * @param string $entityid The id of the assertion.
311
     * @param string $entityid The id of the assertion.
406
     * @return mixed
312
     * @return mixed
407
     */
313
     */
408
    public function get_assertion($entityid) {
-
 
409
        // V2 Only.
-
 
410
        if ($this->backpackapiversion == OPEN_BADGES_V1) {
-
 
411
            throw new coding_exception('Not supported in this backpack API');
-
 
412
        }
-
 
413
 
314
    public function get_assertion($entityid) {
414
        return $this->curl_request('assertion', null, $entityid);
315
        return $this->curl_request('assertion', null, $entityid);
Línea 415... Línea 316...
415
    }
316
    }
416
 
317
 
Línea 420... Línea 321...
420
     * @param string $entityid The id of the badge class.
321
     * @param string $entityid The id of the badge class.
421
     * @param string $data The structure of the badge class assertion.
322
     * @param string $data The structure of the badge class assertion.
422
     * @return mixed
323
     * @return mixed
423
     */
324
     */
424
    public function put_badgeclass_assertion($entityid, $data) {
325
    public function put_badgeclass_assertion($entityid, $data) {
425
        // V2 Only.
-
 
426
        if ($this->backpackapiversion == OPEN_BADGES_V1) {
-
 
427
            throw new coding_exception('Not supported in this backpack API');
-
 
428
        }
-
 
429
 
-
 
430
        return $this->curl_request('assertions', null, $entityid, $data);
326
        return $this->curl_request('assertions', null, $entityid, $data);
431
    }
327
    }
Línea 432... Línea 328...
432
 
328
 
433
    /**
329
    /**
Línea 436... Línea 332...
436
     * @param string $entityid The id of the badge class.
332
     * @param string $entityid The id of the badge class.
437
     * @param array $data The structure of the badge class assertion.
333
     * @param array $data The structure of the badge class assertion.
438
     * @return mixed
334
     * @return mixed
439
     */
335
     */
440
    public function update_assertion(string $entityid, array $data) {
336
    public function update_assertion(string $entityid, array $data) {
441
        // V2 Only.
-
 
442
        if ($this->backpackapiversion == OPEN_BADGES_V1) {
-
 
443
            throw new coding_exception('Not supported in this backpack API');
-
 
444
        }
-
 
445
 
-
 
446
        return $this->curl_request('updateassertion', null, $entityid, $data);
337
        return $this->curl_request('updateassertion', null, $entityid, $data);
447
    }
338
    }
Línea 448... Línea 339...
448
 
339
 
449
    /**
340
    /**
Línea 452... Línea 343...
452
     * @param string $data The structure of the badge class assertion.
343
     * @param string $data The structure of the badge class assertion.
453
     * @return mixed
344
     * @return mixed
454
     * @throws coding_exception
345
     * @throws coding_exception
455
     */
346
     */
456
    public function import_badge_assertion(string $data) {
347
    public function import_badge_assertion(string $data) {
457
        // V2 Only.
-
 
458
        if ($this->backpackapiversion == OPEN_BADGES_V1) {
-
 
459
            throw new coding_exception('Not supported in this backpack API');
-
 
460
        }
-
 
461
 
-
 
462
        return $this->curl_request('importbadge', null, null, $data);
348
        return $this->curl_request('importbadge', null, null, $data);
463
    }
349
    }
Línea 464... Línea 350...
464
 
350
 
465
    /**
351
    /**
Línea 480... Línea 366...
480
 
366
 
481
        // Insert selected collections if they are not in database yet.
367
        // Insert selected collections if they are not in database yet.
482
        foreach ($collections as $collection) {
368
        foreach ($collections as $collection) {
483
            $obj = new stdClass();
369
            $obj = new stdClass();
484
            $obj->backpackid = $backpackid;
-
 
485
            if ($this->backpackapiversion == OPEN_BADGES_V1) {
-
 
486
                $obj->collectionid = (int) $collection;
-
 
487
            } else {
370
            $obj->backpackid = $backpackid;
488
                $obj->entityid = $collection;
371
            $obj->entityid = $collection;
489
                $obj->collectionid = -1;
-
 
490
            }
372
            $obj->collectionid = -1;
491
            if (!$DB->record_exists('badge_external', (array) $obj)) {
373
            if (!$DB->record_exists('badge_external', (array) $obj)) {
492
                $DB->insert_record('badge_external', $obj);
374
                $DB->insert_record('badge_external', $obj);
493
            }
375
            }
494
        }
376
        }
Línea 502... Línea 384...
502
     * @param string $entityid The id of the entity.
384
     * @param string $entityid The id of the entity.
503
     * @param string $data The structure of the badge class.
385
     * @param string $data The structure of the badge class.
504
     * @return mixed
386
     * @return mixed
505
     */
387
     */
506
    public function put_badgeclass($entityid, $data) {
388
    public function put_badgeclass($entityid, $data) {
507
        // V2 Only.
-
 
508
        if ($this->backpackapiversion == OPEN_BADGES_V1) {
-
 
509
            throw new coding_exception('Not supported in this backpack API');
-
 
510
        }
-
 
511
 
-
 
512
        return $this->curl_request('badgeclasses', null, $entityid, $data);
389
        return $this->curl_request('badgeclasses', null, $entityid, $data);
513
    }
390
    }
Línea 514... Línea 391...
514
 
391
 
515
    /**
392
    /**
516
     * Create an issuer
393
     * Create an issuer
517
     *
394
     *
518
     * @param string $data The structure of the issuer.
395
     * @param string $data The structure of the issuer.
519
     * @return mixed
396
     * @return mixed
520
     */
397
     */
521
    public function put_issuer($data) {
-
 
522
        // V2 Only.
-
 
523
        if ($this->backpackapiversion == OPEN_BADGES_V1) {
-
 
524
            throw new coding_exception('Not supported in this backpack API');
-
 
525
        }
-
 
526
 
398
    public function put_issuer($data) {
527
        return $this->curl_request('issuers', null, null, $data);
399
        return $this->curl_request('issuers', null, null, $data);
Línea 528... Línea 400...
528
    }
400
    }
529
 
401
 
Línea 584... Línea 456...
584
     * Get all collections in this backpack.
456
     * Get all collections in this backpack.
585
     *
457
     *
586
     * @return stdClass[] The collections.
458
     * @return stdClass[] The collections.
587
     */
459
     */
588
    public function get_collections() {
460
    public function get_collections() {
589
        global $PAGE;
-
 
590
 
-
 
591
        if ($this->authenticate()) {
461
        if ($this->authenticate()) {
592
            if ($this->backpackapiversion == OPEN_BADGES_V1) {
-
 
593
                $result = $this->curl_request('groups');
-
 
594
                if (isset($result->groups)) {
-
 
595
                    $result = $result->groups;
-
 
596
                }
-
 
597
            } else {
-
 
598
                $result = $this->curl_request('collections');
462
            $result = $this->curl_request('collections');
599
            }
-
 
600
            if ($result) {
463
            if ($result) {
601
                return $result;
464
                return $result;
602
            }
465
            }
603
        }
466
        }
604
        return [];
467
        return [];
Línea 606... Línea 469...
606
 
469
 
607
    /**
470
    /**
608
     * Get one collection by id.
471
     * Get one collection by id.
609
     *
472
     *
610
     * @param integer $collectionid
473
     * @param integer $collectionid
611
     * @return stdClass The collection.
474
     * @return array The collection.
612
     */
475
     */
613
    public function get_collection_record($collectionid) {
476
    public function get_collection_record($collectionid) {
Línea 614... Línea -...
614
        global $DB;
-
 
615
 
-
 
616
        if ($this->backpackapiversion == OPEN_BADGES_V1) {
-
 
617
            return $DB->get_fieldset_select('badge_external', 'collectionid', 'backpackid = :bid', array('bid' => $collectionid));
477
        global $DB;
618
        } else {
-
 
619
            return $DB->get_fieldset_select('badge_external', 'entityid', 'backpackid = :bid', array('bid' => $collectionid));
478
 
Línea 620... Línea 479...
620
        }
479
        return $DB->get_fieldset_select('badge_external', 'entityid', 'backpackid = :bid', ['bid' => $collectionid]);
621
    }
480
    }
622
 
481
 
Línea 650... Línea 509...
650
     *
509
     *
651
     * @param stdClass $data The response data.
510
     * @param stdClass $data The response data.
652
     * @return string The collection id.
511
     * @return string The collection id.
653
     */
512
     */
654
    public function get_collection_id_from_response($data) {
513
    public function get_collection_id_from_response($data) {
655
        if ($this->backpackapiversion == OPEN_BADGES_V1) {
-
 
656
            return $data->groupId;
-
 
657
        } else {
-
 
658
            return $data->entityId;
514
        return $data->entityId;
659
        }
-
 
660
    }
515
    }
Línea 661... Línea 516...
661
 
516
 
662
    /**
517
    /**
663
     * Get the last error message returned during an authentication request.
518
     * Get the last error message returned during an authentication request.
Línea 667... Línea 522...
667
    public function get_authentication_error() {
522
    public function get_authentication_error() {
668
        return backpack_api_mapping::get_authentication_error();
523
        return backpack_api_mapping::get_authentication_error();
669
    }
524
    }
Línea 670... Línea 525...
670
 
525
 
-
 
526
    /**
-
 
527
     * List all errors occurred during the requests to the backpack.
-
 
528
     *
-
 
529
     * @return array The list of errors.
-
 
530
     */
-
 
531
    public function get_errors(): array {
-
 
532
        $errors = [];
-
 
533
        foreach ($this->mappings as $mapping) {
-
 
534
            $errors = array_merge($errors, $mapping->get_errors());
-
 
535
        }
-
 
536
 
-
 
537
        return $errors;
-
 
538
    }
-
 
539
 
671
    /**
540
    /**
672
     * Get the list of badges in a collection.
541
     * Get the list of badges in a collection.
673
     *
542
     *
674
     * @param stdClass $collection The collection to deal with.
543
     * @param stdClass $collection The collection to deal with.
675
     * @param boolean $expanded Fetch all the sub entities.
544
     * @param boolean $expanded Fetch all the sub entities.
676
     * @return stdClass[]
545
     * @return stdClass[]
677
     */
546
     */
678
    public function get_badges($collection, $expanded = false) {
547
    public function get_badges($collection, $expanded = false) {
Línea 679... Línea 548...
679
        global $PAGE;
548
        global $PAGE;
680
 
-
 
681
        if ($this->authenticate()) {
-
 
682
            if ($this->backpackapiversion == OPEN_BADGES_V1) {
-
 
683
                if (empty($collection->collectionid)) {
-
 
684
                    return [];
-
 
685
                }
-
 
686
                $result = $this->curl_request('badges', $collection->collectionid);
-
 
687
                return $result->badges;
549
 
688
            } else {
550
        if ($this->authenticate()) {
689
                if (empty($collection->entityid)) {
551
            if (empty($collection->entityid)) {
690
                    return [];
552
                return [];
691
                }
553
            }
692
                // Now we can make requests.
554
            // Now we can make requests.
693
                $badges = $this->curl_request('badges', $collection->entityid);
555
            $badges = $this->curl_request('badges', $collection->entityid);
694
                if (count($badges) == 0) {
556
            if (count($badges) == 0) {
695
                    return [];
557
                return [];
696
                }
558
            }
697
                $badges = $badges[0];
559
            $badges = $badges[0];
698
                if ($expanded) {
560
            if ($expanded) {
699
                    $publicassertions = [];
561
                $publicassertions = [];
700
                    $context = context_system::instance();
562
                $context = context_system::instance();
701
                    $output = $PAGE->get_renderer('core', 'badges');
563
                $output = $PAGE->get_renderer('core', 'badges');
702
                    foreach ($badges->assertions as $assertion) {
564
                foreach ($badges->assertions as $assertion) {
703
                        $remoteassertion = $this->get_assertion($assertion);
565
                    $remoteassertion = $this->get_assertion($assertion);
704
                        // Remote badge was fetched nested in the assertion.
566
                    // Remote badge was fetched nested in the assertion.
705
                        $remotebadge = $remoteassertion->badgeclass;
567
                    $remotebadge = $remoteassertion->badgeclass;
706
                        if (!$remotebadge) {
-
 
707
                            continue;
-
 
708
                        }
-
 
709
                        $apidata = badgeclass_exporter::map_external_data($remotebadge, $this->backpackapiversion);
-
 
710
                        $exporterinstance = new badgeclass_exporter($apidata, ['context' => $context]);
-
 
711
                        $remotebadge = $exporterinstance->export($output);
-
 
712
 
-
 
713
                        $remoteissuer = $remotebadge->issuer;
-
 
714
                        $apidata = issuer_exporter::map_external_data($remoteissuer, $this->backpackapiversion);
-
 
715
                        $exporterinstance = new issuer_exporter($apidata, ['context' => $context]);
-
 
716
                        $remoteissuer = $exporterinstance->export($output);
-
 
717
 
-
 
718
                        $badgeclone = clone $remotebadge;
-
 
719
                        $badgeclone->issuer = $remoteissuer;
-
 
720
                        $remoteassertion->badge = $badgeclone;
-
 
721
                        $remotebadge->assertion = $remoteassertion;
568
                    if (!$remotebadge) {
-
 
569
                        continue;
-
 
570
                    }
-
 
571
                    $apidata = badgeclass_exporter::map_external_data($remotebadge, $this->backpackapiversion);
-
 
572
                    $exporterinstance = new badgeclass_exporter($apidata, ['context' => $context]);
-
 
573
                    $remotebadge = $exporterinstance->export($output);
-
 
574
 
-
 
575
                    $remoteissuer = $remotebadge->issuer;
-
 
576
                    $apidata = issuer_exporter::map_external_data($remoteissuer, $this->backpackapiversion);
-
 
577
                    $exporterinstance = new issuer_exporter($apidata, ['context' => $context]);
-
 
578
                    $remoteissuer = $exporterinstance->export($output);
-
 
579
 
-
 
580
                    $badgeclone = clone $remotebadge;
722
                        $publicassertions[] = $remotebadge;
581
                    $badgeclone->issuer = $remoteissuer;
-
 
582
                    $remoteassertion->badge = $badgeclone;
723
                    }
583
                    $remotebadge->assertion = $remoteassertion;
-
 
584
                    $publicassertions[] = $remotebadge;
-
 
585
                }
724
                    $badges = $publicassertions;
586
                $badges = $publicassertions;
-
 
587
            }
-
 
588
            return $badges;
-
 
589
        }
-
 
590
 
-
 
591
        return [];
-
 
592
    }
-
 
593
 
-
 
594
    /**
-
 
595
     *  Get list of backpack providers for OBv2.0.
-
 
596
     *
-
 
597
     * @return string[] Array with the OBv2.0 backpack providers.
-
 
598
     */
-
 
599
    public static function get_providers(): array {
-
 
600
        $allproviders = [
-
 
601
            self::PROVIDER_CANVAS_CREDENTIALS => 'canvascredentialsprovider',
-
 
602
            self::PROVIDER_OTHER => 'otherprovider',
-
 
603
        ];
-
 
604
 
-
 
605
        foreach ($allproviders as $key => $value) {
-
 
606
            if (get_string_manager()->string_exists($value, 'badges')) {
-
 
607
                $providers[$key] = get_string($value, 'badges');
-
 
608
            } else {
725
                }
609
                // If the string does not exist, use the key as a fallback.
726
                return $badges;
610
                $providers[$key] = $value;
-
 
611
            }
-
 
612
        }
-
 
613
        return $providers;
-
 
614
    }
-
 
615
 
-
 
616
    /**
-
 
617
     * Get list of regions for backpack providers.
-
 
618
     *
-
 
619
     * @return array Regions with the following information: name, url and apiurl.
-
 
620
     */
-
 
621
    public static function get_regions() {
-
 
622
        global $CFG;
-
 
623
 
-
 
624
        $regions = [];
-
 
625
        if (empty(trim($CFG->badges_canvasregions))) {
-
 
626
            return $regions;
-
 
627
        }
-
 
628
 
-
 
629
        $entries = explode("\n", $CFG->badges_canvasregions);
-
 
630
        foreach ($entries as $entry) {
-
 
631
            if (empty(trim($entry)) || substr_count($entry, '|') != 2) {
-
 
632
                continue;
-
 
633
            }
-
 
634
            $entry = trim($entry);
-
 
635
            $parts = explode('|', $entry);
-
 
636
            $regions[] = [
-
 
637
                'name' => $parts[0],
-
 
638
                'url' => rtrim($parts[1], '/'),
-
 
639
                'apiurl' => rtrim($parts[2], '/'),
-
 
640
            ];
-
 
641
        }
-
 
642
 
-
 
643
        return $regions;
-
 
644
    }
-
 
645
 
-
 
646
    /**
-
 
647
     * Whether the Canvas Credentials fields should be displayed or not in the backpack form.
-
 
648
     *
-
 
649
     * @return bool True if the fields should be displayed; false otherwise.
-
 
650
     */
-
 
651
    public static function display_canvas_credentials_fields(): bool {
-
 
652
        return !empty(self::get_providers()) && !empty(self::get_regions());
-
 
653
    }
-
 
654
 
-
 
655
    /**
-
 
656
     * Get backpack URL for a given regionid.
-
 
657
     *
-
 
658
     * @param int $regionid The region identifier.
-
 
659
     * @return string|null The backpack URL.
-
 
660
     */
-
 
661
    public static function get_region_url(int $regionid): ?string {
-
 
662
        $regions = self::get_regions();
-
 
663
        if (!array_key_exists($regionid, $regions)) {
-
 
664
            return null;
-
 
665
        }
-
 
666
        return $regions[$regionid]['url'];
-
 
667
    }
-
 
668
 
-
 
669
    /**
-
 
670
     * Get backpack API URL for a given regionid.
-
 
671
     *
-
 
672
     * @param int $regionid The region identifier.
-
 
673
     * @return string|null The backpack API URL.
-
 
674
     */
-
 
675
    public static function get_region_api_url(int $regionid): ?string {
-
 
676
        $regions = self::get_regions();
-
 
677
        if (!array_key_exists($regionid, $regions)) {
-
 
678
            return null;
-
 
679
        }
-
 
680
        return $regions[$regionid]['apiurl'];
-
 
681
    }
-
 
682
 
-
 
683
    /**
-
 
684
     * Get region identifier from a given backpack URL.
-
 
685
     * When the URL is not found, the last region index is returned.
-
 
686
     *
-
 
687
     * @param string $url The backpack URL.
-
 
688
     * @return int The region identifier associated to the given backpack URL or the last region index if not found.
-
 
689
     */
-
 
690
    public static function get_regionid_from_url(string $url): int {
-
 
691
        $regions = self::get_regions();
-
 
692
        if (empty($regions)) {
-
 
693
            return self::REGION_EMPTY;
-
 
694
        }
-
 
695
 
-
 
696
        // Normalize the URL by removing the trailing slash.
-
 
697
        $normalizedurl = rtrim($url, '/');
-
 
698
        $regionurl = array_search($normalizedurl, array_column($regions, 'url'));
-
 
699
        return $regionurl !== false ? (int)$regionurl : count($regions) - 1;
-
 
700
    }
-
 
701
 
-
 
702
    /**
-
 
703
     * Check whether the given URL is a Canvas Credentials one.
-
 
704
     *
-
 
705
     * @param string $url The backpack URL.
-
 
706
     * @return bool True is the given URL is a Canvas Credentials region; false otherwise.
-
 
707
     */
-
 
708
    public static function is_canvas_credentials_region(string $url): bool {
727
            }
709
        $regions = self::get_regions();
728
        }
710
        return in_array($url, array_column($regions, 'url'));