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