remove old readme
[atutor.git] / docs / mods / _standard / basiclti / launch / ims-blti / OAuth.php
1 <?php
2 // vim: foldmethod=marker
3
4 $OAuth_last_computed_siguature = false;
5
6 /* Generic exception class
7  */
8 class OAuthException extends Exception {
9   // pass
10 }
11
12 class OAuthConsumer {
13   public $key;
14   public $secret;
15
16   function __construct($key, $secret, $callback_url=NULL) {
17     $this->key = $key;
18     $this->secret = $secret;
19     $this->callback_url = $callback_url;
20   }
21
22   function __toString() {
23     return "OAuthConsumer[key=$this->key,secret=$this->secret]";
24   }
25 }
26
27 class OAuthToken {
28   // access tokens and request tokens
29   public $key;
30   public $secret;
31
32   /**
33    * key = the token
34    * secret = the token secret
35    */
36   function __construct($key, $secret) {
37     $this->key = $key;
38     $this->secret = $secret;
39   }
40
41   /**
42    * generates the basic string serialization of a token that a server
43    * would respond to request_token and access_token calls with
44    */
45   function to_string() {
46     return "oauth_token=" .
47            OAuthUtil::urlencode_rfc3986($this->key) .
48            "&oauth_token_secret=" .
49            OAuthUtil::urlencode_rfc3986($this->secret);
50   }
51
52   function __toString() {
53     return $this->to_string();
54   }
55 }
56
57 class OAuthSignatureMethod {
58   public function check_signature(&$request, $consumer, $token, $signature) {
59     $built = $this->build_signature($request, $consumer, $token);
60     return $built == $signature;
61   }
62 }
63
64 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
65   function get_name() {
66     return "HMAC-SHA1";
67   }
68
69   public function build_signature($request, $consumer, $token) {
70     global $OAuth_last_computed_signature;
71     $OAuth_last_computed_signature = false;
72
73     $base_string = $request->get_signature_base_string();
74     $request->base_string = $base_string;
75
76     $key_parts = array(
77       $consumer->secret,
78       ($token) ? $token->secret : ""
79     );
80
81     $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
82     $key = implode('&', $key_parts);
83
84     $computed_signature = base64_encode(hash_hmac('sha1', $base_string, $key, true));
85     $OAuth_last_computed_signature = $computed_signature;
86     return $computed_signature;
87   }
88
89 }
90
91 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
92   public function get_name() {
93     return "PLAINTEXT";
94   }
95
96   public function build_signature($request, $consumer, $token) {
97     $sig = array(
98       OAuthUtil::urlencode_rfc3986($consumer->secret)
99     );
100
101     if ($token) {
102       array_push($sig, OAuthUtil::urlencode_rfc3986($token->secret));
103     } else {
104       array_push($sig, '');
105     }
106
107     $raw = implode("&", $sig);
108     // for debug purposes
109     $request->base_string = $raw;
110
111     return OAuthUtil::urlencode_rfc3986($raw);
112   }
113 }
114
115 class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
116   public function get_name() {
117     return "RSA-SHA1";
118   }
119
120   protected function fetch_public_cert(&$request) {
121     // not implemented yet, ideas are:
122     // (1) do a lookup in a table of trusted certs keyed off of consumer
123     // (2) fetch via http using a url provided by the requester
124     // (3) some sort of specific discovery code based on request
125     //
126     // either way should return a string representation of the certificate
127     throw Exception("fetch_public_cert not implemented");
128   }
129
130   protected function fetch_private_cert(&$request) {
131     // not implemented yet, ideas are:
132     // (1) do a lookup in a table of trusted certs keyed off of consumer
133     //
134     // either way should return a string representation of the certificate
135     throw Exception("fetch_private_cert not implemented");
136   }
137
138   public function build_signature(&$request, $consumer, $token) {
139     $base_string = $request->get_signature_base_string();
140     $request->base_string = $base_string;
141
142     // Fetch the private key cert based on the request
143     $cert = $this->fetch_private_cert($request);
144
145     // Pull the private key ID from the certificate
146     $privatekeyid = openssl_get_privatekey($cert);
147
148     // Sign using the key
149     $ok = openssl_sign($base_string, $signature, $privatekeyid);
150
151     // Release the key resource
152     openssl_free_key($privatekeyid);
153
154     return base64_encode($signature);
155   }
156
157   public function check_signature(&$request, $consumer, $token, $signature) {
158     $decoded_sig = base64_decode($signature);
159
160     $base_string = $request->get_signature_base_string();
161
162     // Fetch the public key cert based on the request
163     $cert = $this->fetch_public_cert($request);
164
165     // Pull the public key ID from the certificate
166     $publickeyid = openssl_get_publickey($cert);
167
168     // Check the computed signature against the one passed in the query
169     $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
170
171     // Release the key resource
172     openssl_free_key($publickeyid);
173
174     return $ok == 1;
175   }
176 }
177
178 class OAuthRequest {
179   private $parameters;
180   private $http_method;
181   private $http_url;
182   // for debug purposes
183   public $base_string;
184   public static $version = '1.0';
185   public static $POST_INPUT = 'php://input';
186
187   function __construct($http_method, $http_url, $parameters=NULL) {
188     @$parameters or $parameters = array();
189     $this->parameters = $parameters;
190     $this->http_method = $http_method;
191     $this->http_url = $http_url;
192   }
193
194
195   /**
196    * attempt to build up a request from what was passed to the server
197    */
198   public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
199     $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
200               ? 'http'
201               : 'https';
202     $port = "";
203     if ( $_SERVER['SERVER_PORT'] != "80" && $_SERVER['SERVER_PORT'] != "443" &&
204         strpos(':', $_SERVER['HTTP_HOST']) < 0 ) {
205       $port =  ':' . $_SERVER['SERVER_PORT'] ;
206     }
207     @$http_url or $http_url = $scheme .
208                               '://' . $_SERVER['HTTP_HOST'] .
209                               $port .
210                               $_SERVER['REQUEST_URI'];
211     @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
212
213     // We weren't handed any parameters, so let's find the ones relevant to
214     // this request.
215     // If you run XML-RPC or similar you should use this to provide your own
216     // parsed parameter-list
217     if (!$parameters) {
218       // Find request headers
219       $request_headers = OAuthUtil::get_headers();
220
221       // Parse the query-string to find GET parameters
222       $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
223
224       $ourpost = $_POST;
225       // Deal with magic_quotes
226       // http://www.php.net/manual/en/security.magicquotes.disabling.php
227       if ( get_magic_quotes_gpc() ) {
228          $outpost = array();
229          foreach ($_POST as $k => $v) {
230             $v = stripslashes($v);
231             $ourpost[$k] = $v;
232          }
233       }
234      // Add POST Parameters if they exist
235       $parameters = array_merge($parameters, $ourpost);
236
237       // We have a Authorization-header with OAuth data. Parse the header
238       // and add those overriding any duplicates from GET or POST
239       if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
240         $header_parameters = OAuthUtil::split_header(
241           $request_headers['Authorization']
242         );
243         $parameters = array_merge($parameters, $header_parameters);
244       }
245
246     }
247
248     return new OAuthRequest($http_method, $http_url, $parameters);
249   }
250
251   /**
252    * pretty much a helper function to set up the request
253    */
254   public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
255     @$parameters or $parameters = array();
256     $defaults = array("oauth_version" => OAuthRequest::$version,
257                       "oauth_nonce" => OAuthRequest::generate_nonce(),
258                       "oauth_timestamp" => OAuthRequest::generate_timestamp(),
259                       "oauth_consumer_key" => $consumer->key);
260     if ($token)
261       $defaults['oauth_token'] = $token->key;
262
263     $parameters = array_merge($defaults, $parameters);
264
265     // Parse the query-string to find and add GET parameters
266     $parts = parse_url($http_url);
267     if ( $parts['query'] ) {
268       $qparms = OAuthUtil::parse_parameters($parts['query']);
269       $parameters = array_merge($qparms, $parameters);
270     }
271      
272
273     return new OAuthRequest($http_method, $http_url, $parameters);
274   }
275
276   public function set_parameter($name, $value, $allow_duplicates = true) {
277     if ($allow_duplicates && isset($this->parameters[$name])) {
278       // We have already added parameter(s) with this name, so add to the list
279       if (is_scalar($this->parameters[$name])) {
280         // This is the first duplicate, so transform scalar (string)
281         // into an array so we can add the duplicates
282         $this->parameters[$name] = array($this->parameters[$name]);
283       }
284
285       $this->parameters[$name][] = $value;
286     } else {
287       $this->parameters[$name] = $value;
288     }
289   }
290
291   public function get_parameter($name) {
292     return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
293   }
294
295   public function get_parameters() {
296     return $this->parameters;
297   }
298
299   public function unset_parameter($name) {
300     unset($this->parameters[$name]);
301   }
302
303   /**
304    * The request parameters, sorted and concatenated into a normalized string.
305    * @return string
306    */
307   public function get_signable_parameters() {
308     // Grab all parameters
309     $params = $this->parameters;
310
311     // Remove oauth_signature if present
312     // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
313     if (isset($params['oauth_signature'])) {
314       unset($params['oauth_signature']);
315     }
316
317     return OAuthUtil::build_http_query($params);
318   }
319
320   /**
321    * Returns the base string of this request
322    *
323    * The base string defined as the method, the url
324    * and the parameters (normalized), each urlencoded
325    * and the concated with &.
326    */
327   public function get_signature_base_string() {
328     $parts = array(
329       $this->get_normalized_http_method(),
330       $this->get_normalized_http_url(),
331       $this->get_signable_parameters()
332     );
333
334     $parts = OAuthUtil::urlencode_rfc3986($parts);
335
336     return implode('&', $parts);
337   }
338
339   /**
340    * just uppercases the http method
341    */
342   public function get_normalized_http_method() {
343     return strtoupper($this->http_method);
344   }
345
346   /**
347    * parses the url and rebuilds it to be
348    * scheme://host/path
349    */
350   public function get_normalized_http_url() {
351     $parts = parse_url($this->http_url);
352
353     $port = @$parts['port'];
354     $scheme = $parts['scheme'];
355     $host = $parts['host'];
356     $path = @$parts['path'];
357
358     $port or $port = ($scheme == 'https') ? '443' : '80';
359
360     if (($scheme == 'https' && $port != '443')
361         || ($scheme == 'http' && $port != '80')) {
362       $host = "$host:$port";
363     }
364     return "$scheme://$host$path";
365   }
366
367   /**
368    * builds a url usable for a GET request
369    */
370   public function to_url() {
371     $post_data = $this->to_postdata();
372     $out = $this->get_normalized_http_url();
373     if ($post_data) {
374       $out .= '?'.$post_data;
375     }
376     return $out;
377   }
378
379   /**
380    * builds the data one would send in a POST request
381    */
382   public function to_postdata() {
383     return OAuthUtil::build_http_query($this->parameters);
384   }
385
386   /**
387    * builds the Authorization: header
388    */
389   public function to_header() {
390     $out ='Authorization: OAuth realm=""';
391     $total = array();
392     foreach ($this->parameters as $k => $v) {
393       if (substr($k, 0, 5) != "oauth") continue;
394       if (is_array($v)) {
395         throw new OAuthException('Arrays not supported in headers');
396       }
397       $out .= ',' .
398               OAuthUtil::urlencode_rfc3986($k) .
399               '="' .
400               OAuthUtil::urlencode_rfc3986($v) .
401               '"';
402     }
403     return $out;
404   }
405
406   public function __toString() {
407     return $this->to_url();
408   }
409
410
411   public function sign_request($signature_method, $consumer, $token) {
412     $this->set_parameter(
413       "oauth_signature_method",
414       $signature_method->get_name(),
415       false
416     );
417     $signature = $this->build_signature($signature_method, $consumer, $token);
418     $this->set_parameter("oauth_signature", $signature, false);
419   }
420
421   public function build_signature($signature_method, $consumer, $token) {
422     $signature = $signature_method->build_signature($this, $consumer, $token);
423     return $signature;
424   }
425
426   /**
427    * util function: current timestamp
428    */
429   private static function generate_timestamp() {
430     return time();
431   }
432
433   /**
434    * util function: current nonce
435    */
436   private static function generate_nonce() {
437     $mt = microtime();
438     $rand = mt_rand();
439
440     return md5($mt . $rand); // md5s look nicer than numbers
441   }
442 }
443
444 class OAuthServer {
445   protected $timestamp_threshold = 300; // in seconds, five minutes
446   protected $version = 1.0;             // hi blaine
447   protected $signature_methods = array();
448
449   protected $data_store;
450
451   function __construct($data_store) {
452     $this->data_store = $data_store;
453   }
454
455   public function add_signature_method($signature_method) {
456     $this->signature_methods[$signature_method->get_name()] =
457       $signature_method;
458   }
459
460   // high level functions
461
462   /**
463    * process a request_token request
464    * returns the request token on success
465    */
466   public function fetch_request_token(&$request) {
467     $this->get_version($request);
468
469     $consumer = $this->get_consumer($request);
470
471     // no token required for the initial token request
472     $token = NULL;
473
474     $this->check_signature($request, $consumer, $token);
475
476     $new_token = $this->data_store->new_request_token($consumer);
477
478     return $new_token;
479   }
480
481   /**
482    * process an access_token request
483    * returns the access token on success
484    */
485   public function fetch_access_token(&$request) {
486     $this->get_version($request);
487
488     $consumer = $this->get_consumer($request);
489
490     // requires authorized request token
491     $token = $this->get_token($request, $consumer, "request");
492
493
494     $this->check_signature($request, $consumer, $token);
495
496     $new_token = $this->data_store->new_access_token($token, $consumer);
497
498     return $new_token;
499   }
500
501   /**
502    * verify an api call, checks all the parameters
503    */
504   public function verify_request(&$request) {
505     global $OAuth_last_computed_signature;
506     $OAuth_last_computed_signature = false;
507     $this->get_version($request);
508     $consumer = $this->get_consumer($request);
509     $token = $this->get_token($request, $consumer, "access");
510     $this->check_signature($request, $consumer, $token);
511     return array($consumer, $token);
512   }
513
514   // Internals from here
515   /**
516    * version 1
517    */
518   private function get_version(&$request) {
519     $version = $request->get_parameter("oauth_version");
520     if (!$version) {
521       $version = 1.0;
522     }
523     if ($version && $version != $this->version) {
524       throw new OAuthException("OAuth version '$version' not supported");
525     }
526     return $version;
527   }
528
529   /**
530    * figure out the signature with some defaults
531    */
532   private function get_signature_method(&$request) {
533     $signature_method =
534         @$request->get_parameter("oauth_signature_method");
535     if (!$signature_method) {
536       $signature_method = "PLAINTEXT";
537     }
538     if (!in_array($signature_method,
539                   array_keys($this->signature_methods))) {
540       throw new OAuthException(
541         "Signature method '$signature_method' not supported " .
542         "try one of the following: " .
543         implode(", ", array_keys($this->signature_methods))
544       );
545     }
546     return $this->signature_methods[$signature_method];
547   }
548
549   /**
550    * try to find the consumer for the provided request's consumer key
551    */
552   private function get_consumer(&$request) {
553     $consumer_key = @$request->get_parameter("oauth_consumer_key");
554     if (!$consumer_key) {
555       throw new OAuthException("Invalid consumer key");
556     }
557
558     $consumer = $this->data_store->lookup_consumer($consumer_key);
559     if (!$consumer) {
560       throw new OAuthException("Invalid consumer");
561     }
562
563     return $consumer;
564   }
565
566   /**
567    * try to find the token for the provided request's token key
568    */
569   private function get_token(&$request, $consumer, $token_type="access") {
570     $token_field = @$request->get_parameter('oauth_token');
571     if ( !$token_field) return false;
572     $token = $this->data_store->lookup_token(
573       $consumer, $token_type, $token_field
574     );
575     if (!$token) {
576       throw new OAuthException("Invalid $token_type token: $token_field");
577     }
578     return $token;
579   }
580
581   /**
582    * all-in-one function to check the signature on a request
583    * should guess the signature method appropriately
584    */
585   private function check_signature(&$request, $consumer, $token) {
586     // this should probably be in a different method
587     global $OAuth_last_computed_signature;
588     $OAuth_last_computed_signature = false;
589
590     $timestamp = @$request->get_parameter('oauth_timestamp');
591     $nonce = @$request->get_parameter('oauth_nonce');
592
593     $this->check_timestamp($timestamp);
594     $this->check_nonce($consumer, $token, $nonce, $timestamp);
595
596     $signature_method = $this->get_signature_method($request);
597
598     $signature = $request->get_parameter('oauth_signature');
599     $valid_sig = $signature_method->check_signature(
600       $request,
601       $consumer,
602       $token,
603       $signature
604     );
605
606     if (!$valid_sig) {
607       $ex_text = "Invalid signature";
608       if ( $OAuth_last_computed_signature ) {
609           $ex_text = $ex_text . " ours= $OAuth_last_computed_signature yours=$signature";
610       }
611       throw new OAuthException($ex_text);
612     }
613   }
614
615   /**
616    * check that the timestamp is new enough
617    */
618   private function check_timestamp($timestamp) {
619     // verify that timestamp is recentish
620     $now = time();
621     if ($now - $timestamp > $this->timestamp_threshold) {
622       throw new OAuthException(
623         "Expired timestamp, yours $timestamp, ours $now"
624       );
625     }
626   }
627
628   /**
629    * check that the nonce is not repeated
630    */
631   private function check_nonce($consumer, $token, $nonce, $timestamp) {
632     // verify that the nonce is uniqueish
633     $found = $this->data_store->lookup_nonce(
634       $consumer,
635       $token,
636       $nonce,
637       $timestamp
638     );
639     if ($found) {
640       throw new OAuthException("Nonce already used: $nonce");
641     }
642   }
643
644 }
645
646 class OAuthDataStore {
647   function lookup_consumer($consumer_key) {
648     // implement me
649   }
650
651   function lookup_token($consumer, $token_type, $token) {
652     // implement me
653   }
654
655   function lookup_nonce($consumer, $token, $nonce, $timestamp) {
656     // implement me
657   }
658
659   function new_request_token($consumer) {
660     // return a new token attached to this consumer
661   }
662
663   function new_access_token($token, $consumer) {
664     // return a new access token attached to this consumer
665     // for the user associated with this token if the request token
666     // is authorized
667     // should also invalidate the request token
668   }
669
670 }
671
672 class OAuthUtil {
673   public static function urlencode_rfc3986($input) {
674   if (is_array($input)) {
675     return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
676   } else if (is_scalar($input)) {
677     return str_replace(
678       '+',
679       ' ',
680       str_replace('%7E', '~', rawurlencode($input))
681     );
682   } else {
683     return '';
684   }
685 }
686
687
688   // This decode function isn't taking into consideration the above
689   // modifications to the encoding process. However, this method doesn't
690   // seem to be used anywhere so leaving it as is.
691   public static function urldecode_rfc3986($string) {
692     return urldecode($string);
693   }
694
695   // Utility function for turning the Authorization: header into
696   // parameters, has to do some unescaping
697   // Can filter out any non-oauth parameters if needed (default behaviour)
698   public static function split_header($header, $only_allow_oauth_parameters = true) {
699     $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
700     $offset = 0;
701     $params = array();
702     while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
703       $match = $matches[0];
704       $header_name = $matches[2][0];
705       $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
706       if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
707         $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
708       }
709       $offset = $match[1] + strlen($match[0]);
710     }
711
712     if (isset($params['realm'])) {
713       unset($params['realm']);
714     }
715
716     return $params;
717   }
718
719   // helper to try to sort out headers for people who aren't running apache
720   public static function get_headers() {
721     if (function_exists('apache_request_headers')) {
722       // we need this to get the actual Authorization: header
723       // because apache tends to tell us it doesn't exist
724       return apache_request_headers();
725     }
726     // otherwise we don't have apache and are just going to have to hope
727     // that $_SERVER actually contains what we need
728     $out = array();
729     foreach ($_SERVER as $key => $value) {
730       if (substr($key, 0, 5) == "HTTP_") {
731         // this is chaos, basically it is just there to capitalize the first
732         // letter of every word that is not an initial HTTP and strip HTTP
733         // code from przemek
734         $key = str_replace(
735           " ",
736           "-",
737           ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
738         );
739         $out[$key] = $value;
740       }
741     }
742     return $out;
743   }
744
745   // This function takes a input like a=b&a=c&d=e and returns the parsed
746   // parameters like this
747   // array('a' => array('b','c'), 'd' => 'e')
748   public static function parse_parameters( $input ) {
749     if (!isset($input) || !$input) return array();
750
751     $pairs = explode('&', $input);
752
753     $parsed_parameters = array();
754     foreach ($pairs as $pair) {
755       $split = explode('=', $pair, 2);
756       $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
757       $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
758
759       if (isset($parsed_parameters[$parameter])) {
760         // We have already recieved parameter(s) with this name, so add to the list
761         // of parameters with this name
762
763         if (is_scalar($parsed_parameters[$parameter])) {
764           // This is the first duplicate, so transform scalar (string) into an array
765           // so we can add the duplicates
766           $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
767         }
768
769         $parsed_parameters[$parameter][] = $value;
770       } else {
771         $parsed_parameters[$parameter] = $value;
772       }
773     }
774     return $parsed_parameters;
775   }
776
777   public static function build_http_query($params) {
778     if (!$params) return '';
779
780     // Urlencode both keys and values
781     $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
782     $values = OAuthUtil::urlencode_rfc3986(array_values($params));
783     $params = array_combine($keys, $values);
784
785     // Parameters are sorted by name, using lexicographical byte value ordering.
786     // Ref: Spec: 9.1.1 (1)
787     uksort($params, 'strcmp');
788
789     $pairs = array();
790     foreach ($params as $parameter => $value) {
791       if (is_array($value)) {
792         // If two or more parameters share the same name, they are sorted by their value
793         // Ref: Spec: 9.1.1 (1)
794         natsort($value);
795         foreach ($value as $duplicate_value) {
796           $pairs[] = $parameter . '=' . $duplicate_value;
797         }
798       } else {
799         $pairs[] = $parameter . '=' . $value;
800       }
801     }
802     // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
803     // Each name-value pair is separated by an '&' character (ASCII code 38)
804     return implode('&', $pairs);
805   }
806 }
807
808 ?>