2 // This file is part of BasicLTI4Moodle
4 // BasicLTI4Moodle is an IMS BasicLTI (Basic Learning Tools for Interoperability)
5 // consumer for Moodle 1.9 and Moodle 2.0. BasicLTI is a IMS Standard that allows web
6 // based learning tools to be easily integrated in LMS as native ones. The IMS BasicLTI
7 // specification is part of the IMS standard Common Cartridge 1.1 Sakai and other main LMS
8 // are already supporting or going to support BasicLTI. This project Implements the consumer
9 // for Moodle. Moodle is a Free Open source Learning Management System by Martin Dougiamas.
10 // BasicLTI4Moodle is a project iniciated and leaded by Ludo(Marc Alier) and Jordi Piguillem
11 // at the GESSI research group at UPC.
12 // SimpleLTI consumer for Moodle is an implementation of the early specification of LTI
13 // by Charles Severance (Dr Chuck) htp://dr-chuck.com , developed by Jordi Piguillem in a
14 // Google Summer of Code 2008 project co-mentored by Charles Severance and Marc Alier.
16 // BasicLTI4Moodle is copyright 2009 by Marc Alier Forment, Jordi Piguillem and Nikolas Galanis
17 // of the Universitat Politecnica de Catalunya http://www.upc.edu
18 // Contact info: Marc Alier Forment granludo @ gmail.com or marc.alier @ upc.edu
20 // OAuth.php is distributed under the MIT License
24 // Copyright (c) 2007 Andy Smith
26 // Permission is hereby granted, free of charge, to any person obtaining a copy
27 // of this software and associated documentation files (the "Software"), to deal
28 // in the Software without restriction, including without limitation the rights
29 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
30 // copies of the Software, and to permit persons to whom the Software is
31 // furnished to do so, subject to the following conditions:
33 // The above copyright notice and this permission notice shall be included in
34 // all copies or substantial portions of the Software.
36 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
37 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
38 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
39 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
40 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
41 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
44 // Moodle is free software: you can redistribute it and/or modify
45 // it under the terms of the GNU General Public License as published by
46 // the Free Software Foundation, either version 3 of the License, or
47 // (at your option) any later version.
49 // Moodle is distributed in the hope that it will be useful,
50 // but WITHOUT ANY WARRANTY; without even the implied warranty of
51 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
52 // GNU General Public License for more details.
54 // You should have received a copy of the GNU General Public License
55 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
57 namespace moodle\mod\lti
;//Using a namespace as the basicLTI module imports classes with the same names
59 defined('MOODLE_INTERNAL') ||
die;
61 $oauth_last_computed_signature = false;
63 /* Generic exception class
65 class OAuthException
extends \Exception
{
73 function __construct($key, $secret, $callback_url = null) {
75 $this->secret
= $secret;
76 $this->callback_url
= $callback_url;
79 function __toString() {
80 return "OAuthConsumer[key=$this->key,secret=$this->secret]";
85 // access tokens and request tokens
91 * secret = the token secret
93 function __construct($key, $secret) {
95 $this->secret
= $secret;
99 * generates the basic string serialization of a token that a server
100 * would respond to request_token and access_token calls with
102 function to_string() {
103 return "oauth_token=" .
104 OAuthUtil
::urlencode_rfc3986($this->key
) .
105 "&oauth_token_secret=" .
106 OAuthUtil
::urlencode_rfc3986($this->secret
);
109 function __toString() {
110 return $this->to_string();
114 class OAuthSignatureMethod
{
115 public function check_signature(&$request, $consumer, $token, $signature) {
116 $built = $this->build_signature($request, $consumer, $token);
117 return $built == $signature;
121 class OAuthSignatureMethod_HMAC_SHA1
extends OAuthSignatureMethod
{
122 function get_name() {
126 public function build_signature($request, $consumer, $token) {
127 global $oauth_last_computed_signature;
128 $oauth_last_computed_signature = false;
130 $base_string = $request->get_signature_base_string();
131 $request->base_string
= $base_string;
135 ($token) ?
$token->secret
: ""
138 $key_parts = OAuthUtil
::urlencode_rfc3986($key_parts);
139 $key = implode('&', $key_parts);
141 $computed_signature = base64_encode(hash_hmac('sha1', $base_string, $key, true));
142 $oauth_last_computed_signature = $computed_signature;
143 return $computed_signature;
148 class OAuthSignatureMethod_PLAINTEXT
extends OAuthSignatureMethod
{
149 public function get_name() {
153 public function build_signature($request, $consumer, $token) {
155 OAuthUtil
::urlencode_rfc3986($consumer->secret
)
159 array_push($sig, OAuthUtil
::urlencode_rfc3986($token->secret
));
161 array_push($sig, '');
164 $raw = implode("&", $sig);
165 // for debug purposes
166 $request->base_string
= $raw;
168 return OAuthUtil
::urlencode_rfc3986($raw);
172 class OAuthSignatureMethod_RSA_SHA1
extends OAuthSignatureMethod
{
173 public function get_name() {
177 protected function fetch_public_cert(&$request) {
178 // not implemented yet, ideas are:
179 // (1) do a lookup in a table of trusted certs keyed off of consumer
180 // (2) fetch via http using a url provided by the requester
181 // (3) some sort of specific discovery code based on request
183 // either way should return a string representation of the certificate
184 throw new OAuthException("fetch_public_cert not implemented");
187 protected function fetch_private_cert(&$request) {
188 // not implemented yet, ideas are:
189 // (1) do a lookup in a table of trusted certs keyed off of consumer
191 // either way should return a string representation of the certificate
192 throw new OAuthException("fetch_private_cert not implemented");
195 public function build_signature(&$request, $consumer, $token) {
196 $base_string = $request->get_signature_base_string();
197 $request->base_string
= $base_string;
199 // Fetch the private key cert based on the request
200 $cert = $this->fetch_private_cert($request);
202 // Pull the private key ID from the certificate
203 $privatekeyid = openssl_get_privatekey($cert);
205 // Sign using the key
206 $ok = openssl_sign($base_string, $signature, $privatekeyid);
208 // Release the key resource
209 openssl_free_key($privatekeyid);
211 return base64_encode($signature);
214 public function check_signature(&$request, $consumer, $token, $signature) {
215 $decoded_sig = base64_decode($signature);
217 $base_string = $request->get_signature_base_string();
219 // Fetch the public key cert based on the request
220 $cert = $this->fetch_public_cert($request);
222 // Pull the public key ID from the certificate
223 $publickeyid = openssl_get_publickey($cert);
225 // Check the computed signature against the one passed in the query
226 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
228 // Release the key resource
229 openssl_free_key($publickeyid);
237 private $http_method;
239 // for debug purposes
241 public static $version = '1.0';
242 public static $POST_INPUT = 'php://input';
244 function __construct($http_method, $http_url, $parameters = null) {
245 @$parameters or $parameters = array();
246 $this->parameters
= $parameters;
247 $this->http_method
= $http_method;
248 $this->http_url
= $http_url;
252 * attempt to build up a request from what was passed to the server
254 public static function from_request($http_method = null, $http_url = null, $parameters = null) {
255 $scheme = (!is_https()) ?
'http' : 'https';
257 if ($_SERVER['SERVER_PORT'] != "80" && $_SERVER['SERVER_PORT'] != "443" && strpos(':', $_SERVER['HTTP_HOST']) < 0) {
258 $port = ':' . $_SERVER['SERVER_PORT'];
260 @$http_url or $http_url = $scheme .
261 '://' . $_SERVER['HTTP_HOST'] .
263 $_SERVER['REQUEST_URI'];
264 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
266 // We weren't handed any parameters, so let's find the ones relevant to
268 // If you run XML-RPC or similar you should use this to provide your own
269 // parsed parameter-list
271 // Find request headers
272 $request_headers = OAuthUtil
::get_headers();
274 // Parse the query-string to find GET parameters
275 $parameters = OAuthUtil
::parse_parameters($_SERVER['QUERY_STRING']);
278 // Deal with magic_quotes
279 // http://www.php.net/manual/en/security.magicquotes.disabling.php
280 if (get_magic_quotes_gpc()) {
282 foreach ($_POST as $k => $v) {
283 $v = stripslashes($v);
287 // Add POST Parameters if they exist
288 $parameters = array_merge($parameters, $ourpost);
290 // We have a Authorization-header with OAuth data. Parse the header
291 // and add those overriding any duplicates from GET or POST
292 if (@substr
($request_headers['Authorization'], 0, 6) == "OAuth ") {
293 $header_parameters = OAuthUtil
::split_header($request_headers['Authorization']);
294 $parameters = array_merge($parameters, $header_parameters);
299 return new OAuthRequest($http_method, $http_url, $parameters);
303 * pretty much a helper function to set up the request
305 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters = null) {
306 @$parameters or $parameters = array();
308 "oauth_version" => self
::$version,
309 "oauth_nonce" => self
::generate_nonce(),
310 "oauth_timestamp" => self
::generate_timestamp(),
311 "oauth_consumer_key" => $consumer->key
314 $defaults['oauth_token'] = $token->key
;
317 $parameters = array_merge($defaults, $parameters);
319 // Parse the query-string to find and add GET parameters
320 $parts = parse_url($http_url);
321 if (isset($parts['query'])) {
322 $qparms = OAuthUtil
::parse_parameters($parts['query']);
323 $parameters = array_merge($qparms, $parameters);
326 return new OAuthRequest($http_method, $http_url, $parameters);
329 public function set_parameter($name, $value, $allow_duplicates = true) {
330 if ($allow_duplicates && isset($this->parameters
[$name])) {
331 // We have already added parameter(s) with this name, so add to the list
332 if (is_scalar($this->parameters
[$name])) {
333 // This is the first duplicate, so transform scalar (string)
334 // into an array so we can add the duplicates
335 $this->parameters
[$name] = array($this->parameters
[$name]);
338 $this->parameters
[$name][] = $value;
340 $this->parameters
[$name] = $value;
344 public function get_parameter($name) {
345 return isset($this->parameters
[$name]) ?
$this->parameters
[$name] : null;
348 public function get_parameters() {
349 return $this->parameters
;
352 public function unset_parameter($name) {
353 unset($this->parameters
[$name]);
357 * The request parameters, sorted and concatenated into a normalized string.
360 public function get_signable_parameters() {
361 // Grab all parameters
362 $params = $this->parameters
;
364 // Remove oauth_signature if present
365 // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
366 if (isset($params['oauth_signature'])) {
367 unset($params['oauth_signature']);
370 return OAuthUtil
::build_http_query($params);
374 * Returns the base string of this request
376 * The base string defined as the method, the url
377 * and the parameters (normalized), each urlencoded
378 * and the concated with &.
380 public function get_signature_base_string() {
382 $this->get_normalized_http_method(),
383 $this->get_normalized_http_url(),
384 $this->get_signable_parameters()
387 $parts = OAuthUtil
::urlencode_rfc3986($parts);
389 return implode('&', $parts);
393 * just uppercases the http method
395 public function get_normalized_http_method() {
396 return strtoupper($this->http_method
);
400 * parses the url and rebuilds it to be
403 public function get_normalized_http_url() {
404 $parts = parse_url($this->http_url
);
406 $port = @$parts['port'];
407 $scheme = $parts['scheme'];
408 $host = $parts['host'];
409 $path = @$parts['path'];
411 $port or $port = ($scheme == 'https') ?
'443' : '80';
413 if (($scheme == 'https' && $port != '443') ||
($scheme == 'http' && $port != '80')) {
414 $host = "$host:$port";
416 return "$scheme://$host$path";
420 * builds a url usable for a GET request
422 public function to_url() {
423 $post_data = $this->to_postdata();
424 $out = $this->get_normalized_http_url();
426 $out .= '?'.$post_data;
432 * builds the data one would send in a POST request
434 public function to_postdata() {
435 return OAuthUtil
::build_http_query($this->parameters
);
439 * builds the Authorization: header
441 public function to_header() {
442 $out = 'Authorization: OAuth realm=""';
444 foreach ($this->parameters
as $k => $v) {
445 if (substr($k, 0, 5) != "oauth") {
449 throw new OAuthException('Arrays not supported in headers');
452 OAuthUtil
::urlencode_rfc3986($k) .
454 OAuthUtil
::urlencode_rfc3986($v) .
460 public function __toString() {
461 return $this->to_url();
464 public function sign_request($signature_method, $consumer, $token) {
465 $this->set_parameter("oauth_signature_method", $signature_method->get_name(), false);
466 $signature = $this->build_signature($signature_method, $consumer, $token);
467 $this->set_parameter("oauth_signature", $signature, false);
470 public function build_signature($signature_method, $consumer, $token) {
471 $signature = $signature_method->build_signature($this, $consumer, $token);
476 * util function: current timestamp
478 private static function generate_timestamp() {
483 * util function: current nonce
485 private static function generate_nonce() {
489 return md5($mt.$rand); // md5s look nicer than numbers
494 protected $timestamp_threshold = 300; // in seconds, five minutes
495 protected $version = 1.0; // hi blaine
496 protected $signature_methods = array();
497 protected $data_store;
499 function __construct($data_store) {
500 $this->data_store
= $data_store;
503 public function add_signature_method($signature_method) {
504 $this->signature_methods
[$signature_method->get_name()] = $signature_method;
507 // high level functions
510 * process a request_token request
511 * returns the request token on success
513 public function fetch_request_token(&$request) {
514 $this->get_version($request);
516 $consumer = $this->get_consumer($request);
518 // no token required for the initial token request
521 $this->check_signature($request, $consumer, $token);
523 $new_token = $this->data_store
->new_request_token($consumer);
529 * process an access_token request
530 * returns the access token on success
532 public function fetch_access_token(&$request) {
533 $this->get_version($request);
535 $consumer = $this->get_consumer($request);
537 // requires authorized request token
538 $token = $this->get_token($request, $consumer, "request");
540 $this->check_signature($request, $consumer, $token);
542 $new_token = $this->data_store
->new_access_token($token, $consumer);
548 * verify an api call, checks all the parameters
550 public function verify_request(&$request) {
551 global $oauth_last_computed_signature;
552 $oauth_last_computed_signature = false;
553 $this->get_version($request);
554 $consumer = $this->get_consumer($request);
555 $token = $this->get_token($request, $consumer, "access");
556 $this->check_signature($request, $consumer, $token);
563 // Internals from here
567 private function get_version(&$request) {
568 $version = $request->get_parameter("oauth_version");
572 if ($version && $version != $this->version
) {
573 throw new OAuthException("OAuth version '$version' not supported");
579 * figure out the signature with some defaults
581 private function get_signature_method(&$request) {
582 $signature_method = @ $request->get_parameter("oauth_signature_method");
583 if (!$signature_method) {
584 $signature_method = "PLAINTEXT";
586 if (!in_array($signature_method, array_keys($this->signature_methods
))) {
587 throw new OAuthException("Signature method '$signature_method' not supported " .
588 "try one of the following: " .
589 implode(", ", array_keys($this->signature_methods
)));
591 return $this->signature_methods
[$signature_method];
595 * try to find the consumer for the provided request's consumer key
597 private function get_consumer(&$request) {
598 $consumer_key = @ $request->get_parameter("oauth_consumer_key");
599 if (!$consumer_key) {
600 throw new OAuthException("Invalid consumer key");
603 $consumer = $this->data_store
->lookup_consumer($consumer_key);
605 throw new OAuthException("Invalid consumer");
612 * try to find the token for the provided request's token key
614 private function get_token(&$request, $consumer, $token_type = "access") {
615 $token_field = @ $request->get_parameter('oauth_token');
619 $token = $this->data_store
->lookup_token($consumer, $token_type, $token_field);
621 throw new OAuthException("Invalid $token_type token: $token_field");
627 * all-in-one function to check the signature on a request
628 * should guess the signature method appropriately
630 private function check_signature(&$request, $consumer, $token) {
631 // this should probably be in a different method
632 global $oauth_last_computed_signature;
633 $oauth_last_computed_signature = false;
635 $timestamp = @ $request->get_parameter('oauth_timestamp');
636 $nonce = @ $request->get_parameter('oauth_nonce');
638 $this->check_timestamp($timestamp);
639 $this->check_nonce($consumer, $token, $nonce, $timestamp);
641 $signature_method = $this->get_signature_method($request);
643 $signature = $request->get_parameter('oauth_signature');
644 $valid_sig = $signature_method->check_signature($request, $consumer, $token, $signature);
647 $ex_text = "Invalid signature";
648 if ($oauth_last_computed_signature) {
649 $ex_text = $ex_text . " ours= $oauth_last_computed_signature yours=$signature";
651 throw new OAuthException($ex_text);
656 * check that the timestamp is new enough
658 private function check_timestamp($timestamp) {
659 // verify that timestamp is recentish
661 if ($now - $timestamp > $this->timestamp_threshold
) {
662 throw new OAuthException("Expired timestamp, yours $timestamp, ours $now");
667 * check that the nonce is not repeated
669 private function check_nonce($consumer, $token, $nonce, $timestamp) {
670 // verify that the nonce is uniqueish
671 $found = $this->data_store
->lookup_nonce($consumer, $token, $nonce, $timestamp);
673 throw new OAuthException("Nonce already used: $nonce");
679 class OAuthDataStore
{
680 function lookup_consumer($consumer_key) {
684 function lookup_token($consumer, $token_type, $token) {
688 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
692 function new_request_token($consumer) {
693 // return a new token attached to this consumer
696 function new_access_token($token, $consumer) {
697 // return a new access token attached to this consumer
698 // for the user associated with this token if the request token
700 // should also invalidate the request token
706 public static function urlencode_rfc3986($input) {
707 if (is_array($input)) {
708 return array_map(array(
709 'moodle\mod\lti\OAuthUtil',
713 if (is_scalar($input)) {
714 return str_replace('+', ' ', str_replace('%7E', '~', rawurlencode($input)));
721 // This decode function isn't taking into consideration the above
722 // modifications to the encoding process. However, this method doesn't
723 // seem to be used anywhere so leaving it as is.
724 public static function urldecode_rfc3986($string) {
725 return urldecode($string);
728 // Utility function for turning the Authorization: header into
729 // parameters, has to do some unescaping
730 // Can filter out any non-oauth parameters if needed (default behaviour)
731 public static function split_header($header, $only_allow_oauth_parameters = true) {
732 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
735 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE
, $offset) > 0) {
736 $match = $matches[0];
737 $header_name = $matches[2][0];
738 $header_content = (isset($matches[5])) ?
$matches[5][0] : $matches[4][0];
739 if (preg_match('/^oauth_/', $header_name) ||
!$only_allow_oauth_parameters) {
740 $params[$header_name] = self
::urldecode_rfc3986($header_content);
742 $offset = $match[1] +
strlen($match[0]);
745 if (isset($params['realm'])) {
746 unset($params['realm']);
752 // helper to try to sort out headers for people who aren't running apache
753 public static function get_headers() {
754 if (function_exists('apache_request_headers')) {
755 // we need this to get the actual Authorization: header
756 // because apache tends to tell us it doesn't exist
757 $in = apache_request_headers();
759 foreach ($in as $key => $value) {
760 $key = str_replace(" ", "-", ucwords(strtolower(str_replace("-", " ", $key))));
765 // otherwise we don't have apache and are just going to have to hope
766 // that $_SERVER actually contains what we need
768 foreach ($_SERVER as $key => $value) {
769 if (substr($key, 0, 5) == "HTTP_") {
770 // this is chaos, basically it is just there to capitalize the first
771 // letter of every word that is not an initial HTTP and strip HTTP
773 $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
780 // This function takes a input like a=b&a=c&d=e and returns the parsed
781 // parameters like this
782 // array('a' => array('b','c'), 'd' => 'e')
783 public static function parse_parameters($input) {
784 if (!isset($input) ||
!$input) {
788 $pairs = explode('&', $input);
790 $parsed_parameters = array();
791 foreach ($pairs as $pair) {
792 $split = explode('=', $pair, 2);
793 $parameter = self
::urldecode_rfc3986($split[0]);
794 $value = isset($split[1]) ? self
::urldecode_rfc3986($split[1]) : '';
796 if (isset($parsed_parameters[$parameter])) {
797 // We have already recieved parameter(s) with this name, so add to the list
798 // of parameters with this name
800 if (is_scalar($parsed_parameters[$parameter])) {
801 // This is the first duplicate, so transform scalar (string) into an array
802 // so we can add the duplicates
803 $parsed_parameters[$parameter] = array(
804 $parsed_parameters[$parameter]
808 $parsed_parameters[$parameter][] = $value;
810 $parsed_parameters[$parameter] = $value;
813 return $parsed_parameters;
816 public static function build_http_query($params) {
821 // Urlencode both keys and values
822 $keys = self
::urlencode_rfc3986(array_keys($params));
823 $values = self
::urlencode_rfc3986(array_values($params));
824 $params = array_combine($keys, $values);
826 // Parameters are sorted by name, using lexicographical byte value ordering.
827 // Ref: Spec: 9.1.1 (1)
828 uksort($params, 'strcmp');
831 foreach ($params as $parameter => $value) {
832 if (is_array($value)) {
833 // If two or more parameters share the same name, they are sorted by their value
834 // Ref: Spec: 9.1.1 (1)
836 foreach ($value as $duplicate_value) {
837 $pairs[] = $parameter . '=' . $duplicate_value;
840 $pairs[] = $parameter . '=' . $value;
843 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
844 // Each name-value pair is separated by an '&' character (ASCII code 38)
845 return implode('&', $pairs);