MDL-63262 badges: Coding style
[moodle.git] / badges / classes / backpack_api_mapping.php
CommitLineData
aae219ac
DW
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
26namespace core_badges;
27
28defined('MOODLE_INTERNAL') || die();
29
30global $CFG;
31require_once($CFG->libdir . '/filelib.php');
32
33use context_system;
34use core_badges\external\assertion_exporter;
35use core_badges\external\collection_exporter;
36use core_badges\external\issuer_exporter;
37use core_badges\external\badgeclass_exporter;
38use curl;
39
40/**
41 * Represent a single method for the remote api.
1837b1d5
DW
42 *
43 * @package core_badges
44 * @copyright 2012 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
45 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
aae219ac
DW
46 */
47class backpack_api_mapping {
48
49 /** @var string The action of this method. */
50 public $action;
51
52 /** @var string The base url of this backpack. */
53 private $url;
54
55 /** @var array List of parameters for this method. */
56 public $params;
57
58 /** @var string Name of a class to export parameters for this method. */
59 public $requestexporter;
60
61 /** @var string Name of a class to export response for this method. */
62 public $responseexporter;
63
64 /** @var boolean This method returns an array of responses. */
65 public $multiple;
66
67 /** @var string get or post methods. */
68 public $method;
69
70 /** @var boolean json decode the response. */
71 public $json;
72
73 /** @var boolean Authentication is required for this request. */
74 public $authrequired;
75
76 /** @var boolean Differentiate the function that can be called on a user backpack or a site backpack. */
77 private $isuserbackpack;
78
79 /**
80 * Create a mapping.
81 *
82 * @param string $action The action of this method.
83 * @param string $url The base url of this backpack.
84 * @param mixed $postparams List of parameters for this method.
85 * @param string $requestexporter Name of a class to export parameters for this method.
86 * @param string $responseexporter Name of a class to export response for this method.
87 * @param boolean $multiple This method returns an array of responses.
88 * @param string $method get or post methods.
89 * @param boolean $json json decode the response.
90 * @param boolean $authrequired Authentication is required for this request.
91 * @param boolean $isuserbackpack user backpack or a site backpack.
92 * @param integer $backpackapiversion OpenBadges version 1 or 2.
93 */
94 public function __construct($action, $url, $postparams, $requestexporter, $responseexporter,
95 $multiple, $method, $json, $authrequired, $isuserbackpack, $backpackapiversion) {
96 $this->action = $action;
97 $this->url = $url;
98 $this->postparams = $postparams;
99 $this->requestexporter = $requestexporter;
100 $this->responseexporter = $responseexporter;
101 $this->multiple = $multiple;
102 $this->method = $method;
103 $this->json = $json;
104 $this->authrequired = $authrequired;
105 $this->isuserbackpack = $isuserbackpack;
106 $this->backpackapiversion = $backpackapiversion;
107 }
108
109 /**
110 * Get the unique key for the token.
111 *
112 * @param string $type The type of token.
113 * @return string
114 */
115 private function get_token_key($type) {
116 $prefix = 'badges_';
117 if ($this->isuserbackpack) {
118 $prefix .= 'user_backpack_';
119 } else {
120 $prefix .= 'site_backpack_';
121 }
122 $prefix .= $type . '_token';
123 return $prefix;
124 }
125
126 /**
127 * Does the action match this mapping?
128 *
129 * @param string $action The action.
130 * @return boolean
131 */
132 public function is_match($action) {
133 return $this->action == $action;
134 }
135
136 /**
137 * Parse the method url and insert parameters.
138 *
139 * @param string $apiurl The raw apiurl.
140 * @param string $param1 The first parameter.
141 * @param string $param2 The second parameter.
142 * @return string
143 */
144 private function get_url($apiurl, $param1, $param2) {
145 $urlscheme = parse_url($apiurl, PHP_URL_SCHEME);
146 $urlhost = parse_url($apiurl, PHP_URL_HOST);
147
148 $url = $this->url;
149 $url = str_replace('[SCHEME]', $urlscheme, $url);
150 $url = str_replace('[HOST]', $urlhost, $url);
151 $url = str_replace('[URL]', $apiurl, $url);
152 $url = str_replace('[PARAM1]', $param1, $url);
153 $url = str_replace('[PARAM2]', $param2, $url);
154
155 return $url;
156 }
157
158 /**
159 * Parse the post parameters and insert replacements.
160 *
161 * @param string $email The api username.
162 * @param string $password The api password.
163 * @param string $param The parameter.
164 * @return mixed
165 */
166 private function get_post_params($email, $password, $param) {
167 global $PAGE;
168
169 if ($this->method == 'get') {
170 return '';
171 }
172
173 $request = $this->postparams;
174 if ($request === '[PARAM]') {
175 $value = $param;
176 foreach ($value as $key => $keyvalue) {
177 if (gettype($value[$key]) == 'array') {
178 $newkey = 'related_' . $key;
179 $value[$newkey] = $value[$key];
180 unset($value[$key]);
181 }
182 }
183 } else if (is_array($request)) {
184 foreach ($request as $key => $value) {
185 if ($value == '[EMAIL]') {
186 $value = $email;
187 $request[$key] = $value;
188 } else if ($value == '[PASSWORD]') {
189 $value = $password;
190 $request[$key] = $value;
191 }
192 }
193 }
194 $context = context_system::instance();
195 $exporter = $this->requestexporter;
196 $output = $PAGE->get_renderer('core', 'badges');
197 if (!empty($exporter)) {
198 $exporterinstance = new $exporter($value, ['context' => $context]);
199 $request = $exporterinstance->export($output);
200 }
201 if ($this->json) {
202 return json_encode($request);
203 }
204 return $request;
205 }
206
207 /**
208 * Read the response from a V1 user request and save the userID.
209 *
210 * @param string $response The request response.
211 * @param integer $backpackid The backpack id.
212 * @return boolean
213 */
214 private function convert_email_response($response, $backpackid) {
215 global $SESSION;
216
217 if (isset($response->status) && $response->status == 'okay') {
218
219 // Remember the tokens.
220 $useridkey = $this->get_token_key(BADGE_USER_ID_TOKEN);
221 $backpackidkey = $this->get_token_key(BADGE_BACKPACK_ID_TOKEN);
222
223 $SESSION->$useridkey = $response->userId;
224 $SESSION->$backpackidkey = $backpackid;
225 return $response->userId;
226 }
227 return false;
228 }
229
230 /**
231 * Get the user id from a previous user request.
232 *
233 * @return integer
234 */
235 private function get_auth_user_id() {
236 global $USER;
237
238 if ($this->isuserbackpack) {
239 return $USER->id;
240 } else {
241 // The access tokens for the system backpack are shared.
242 return -1;
243 }
244 }
245
246 /**
247 * Parse the response from an openbadges 2 login.
248 *
249 * @param string $response The request response data.
250 * @param integer $backpackid The id of the backpack.
251 * @return mixed
252 */
253 private function oauth_token_response($response, $backpackid) {
254 global $SESSION;
255
256 if (isset($response->access_token) && isset($response->refresh_token)) {
257 // Remember the tokens.
258 $accesskey = $this->get_token_key(BADGE_ACCESS_TOKEN);
259 $refreshkey = $this->get_token_key(BADGE_REFRESH_TOKEN);
260 $expireskey = $this->get_token_key(BADGE_EXPIRES_TOKEN);
261 $useridkey = $this->get_token_key(BADGE_USER_ID_TOKEN);
262 $backpackidkey = $this->get_token_key(BADGE_BACKPACK_ID_TOKEN);
263 if (isset($response->expires_in)) {
264 $timeout = $response->expires_in;
265 } else {
266 $timeout = 15 * 60; // 15 minute timeout if none set.
267 }
268 $expires = $timeout + time();
269
270 $SESSION->$expireskey = $expires;
271 $SESSION->$useridkey = $this->get_auth_user_id();
272 $SESSION->$accesskey = $response->access_token;
273 $SESSION->$refreshkey = $response->refresh_token;
274 $SESSION->$backpackidkey = $backpackid;
275 return -1;
276 }
277 return $response;
278 }
279
280 /**
281 * Standard options used for all curl requests.
282 *
283 * @return array
284 */
285 private function get_curl_options() {
286 return array(
287 'FRESH_CONNECT' => true,
288 'RETURNTRANSFER' => true,
289 'FORBID_REUSE' => true,
290 'HEADER' => 0,
291 'CONNECTTIMEOUT' => 3,
292 'CONNECTTIMEOUT' => 3,
293 // Follow redirects with the same type of request when sent 301, or 302 redirects.
294 'CURLOPT_POSTREDIR' => 3,
295 );
296 }
297
298 /**
299 * Make an api request and parse the response.
300 *
301 * @param string $apiurl Raw request url.
302 * @param string $urlparam1 Parameter for the request.
303 * @param string $urlparam2 Parameter for the request.
304 * @param string $email User email for authentication.
305 * @param string $password for authentication.
306 * @param mixed $postparam Raw data for the post body.
307 * @param string $backpackid the id of the backpack to use.
308 * @return mixed
309 */
310 public function request($apiurl, $urlparam1, $urlparam2, $email, $password, $postparam, $backpackid) {
311 global $SESSION, $PAGE;
312
313 $curl = new curl();
314
315 $url = $this->get_url($apiurl, $urlparam1, $urlparam2);
316
317 if ($this->authrequired) {
318 $accesskey = $this->get_token_key(BADGE_ACCESS_TOKEN);
319 if (isset($SESSION->$accesskey)) {
320 $token = $SESSION->$accesskey;
321 $curl->setHeader('Authorization: Bearer ' . $token);
322 }
323 }
324 if ($this->json) {
325 $curl->setHeader(array('Content-type: application/json'));
326 }
327 $curl->setHeader(array('Accept: application/json', 'Expect:'));
328 $options = $this->get_curl_options();
329
330 $post = $this->get_post_params($email, $password, $postparam);
331 if ($this->method == 'get') {
332 $response = $curl->get($url, $post, $options);
333 } else if ($this->method == 'post') {
334 $response = $curl->post($url, $post, $options);
335 }
336 $response = json_decode($response);
337
338 if (isset($response->result)) {
339 $response = $response->result;
340 }
341 $context = context_system::instance();
342 $exporter = $this->responseexporter;
343 if (class_exists($exporter)) {
344 $output = $PAGE->get_renderer('core', 'badges');
345 if (!$this->multiple) {
346 if (count($response)) {
347 $response = $response[0];
348 }
349 if (empty($response)) {
350 return null;
351 }
352 $apidata = $exporter::map_external_data($response, $this->backpackapiversion);
353 $exporterinstance = new $exporter($apidata, ['context' => $context]);
354 $data = $exporterinstance->export($output);
355 return $data;
356 } else {
357 $multiple = [];
358 if (empty($response)) {
359 return $multiple;
360 }
361 foreach ($response as $data) {
362 $apidata = $exporter::map_external_data($data, $this->backpackapiversion);
363 $exporterinstance = new $exporter($apidata, ['context' => $context]);
364 $multiple[] = $exporterinstance->export($output);
365 }
366 return $multiple;
367 }
368 } else if (method_exists($this, $exporter)) {
369 return $this->$exporter($response, $backpackid);
370 }
371 return $response;
372 }
373}