move code up one directory
[atutor.git] / mods / _standard / social / lib / OAuth / OAuth.php
1 <?php
2
3 /**
4  * Licensed to the Apache Software Foundation (ASF) under one
5  * or more contributor license agreements.  See the NOTICE file
6  * distributed with this work for additional information
7  * regarding copyright ownership.  The ASF licenses this file
8  * to you under the Apache License, Version 2.0 (the
9  * "License"); you may not use this file except in compliance
10  * with the License.  You may obtain a copy of the License at
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17  * KIND, either express or implied.  See the License for the
18  * specific language governing permissions and limitations
19  * under the License.
20  */
21 // $Id$
22
23 /* Generic exception class
24  */
25 class OAuthException extends Exception { // pass
26 }
27
28 class OAuthConsumer {
29   public $key;
30   public $secret;
31
32   function __construct($key, $secret, $callback_url = NULL) {
33     $this->key = $key;
34     $this->secret = $secret;
35     $this->callback_url = $callback_url;
36   }
37
38   function __toString() {
39     return "OAuthConsumer[key=$this->key,secret=$this->secret]";
40   }
41 }
42
43 class OAuthToken {
44   // access tokens and request tokens
45   public $key;
46   public $secret;
47
48   /**
49    * key = the token
50    * secret = the token secret
51    */
52   function __construct($key, $secret) {
53     $this->key = $key;
54     $this->secret = $secret;
55   }
56
57   /**
58    * generates the basic string serialization of a token that a server
59    * would respond to request_token and access_token calls with
60    */
61   function to_string() {
62     return "oauth_token=" . OAuthUtil::urlencodeRFC3986($this->key) . "&oauth_token_secret=" . OAuthUtil::urlencodeRFC3986($this->secret);
63   }
64
65   function __toString() {
66     return $this->to_string();
67   }
68 }
69
70 class OAuthSignatureMethod {
71
72   public function check_signature(&$request, $consumer, $token, $signature) {
73     $built = $this->build_signature($request, $consumer, $token);
74     return $built == $signature;
75   }
76 }
77
78 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
79
80   function get_name() {
81     return "HMAC-SHA1";
82   }
83
84   public function build_signature($request, $consumer, $token) {
85     $base_string = $request->get_signature_base_string();
86     $request->base_string = $base_string;
87
88     $key_parts = array($consumer->secret, ($token) ? $token->secret : "");
89
90     $key_parts = array_map(array('OAuthUtil', 'urlencodeRFC3986'), $key_parts);
91     $key = implode('&', $key_parts);
92     return base64_encode(hash_hmac('sha1', $base_string, $key, true));
93   }
94 }
95
96 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
97
98   public function get_name() {
99     return "PLAINTEXT";
100   }
101
102   public function build_signature($request, $consumer, $token) {
103     $sig = array(OAuthUtil::urlencodeRFC3986($consumer->secret));
104
105     if ($token) {
106       array_push($sig, OAuthUtil::urlencodeRFC3986($token->secret));
107     } else {
108       array_push($sig, '');
109     }
110
111     $raw = implode("&", $sig);
112     // for debug purposes
113     $request->base_string = $raw;
114
115     return OAuthUtil::urlencodeRFC3986($raw);
116   }
117 }
118
119 class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
120
121   public function get_name() {
122     return "RSA-SHA1";
123   }
124
125   protected function fetch_public_cert(&$request) {
126     // not implemented yet, ideas are:
127     // (1) do a lookup in a table of trusted certs keyed off of consumer
128     // (2) fetch via http using a url provided by the requester
129     // (3) some sort of specific discovery code based on request
130     //
131     // either way should return a string representation of the certificate
132     throw Exception("fetch_public_cert not implemented");
133   }
134
135   protected function fetch_private_cert(&$request) {
136     // not implemented yet, ideas are:
137     // (1) do a lookup in a table of trusted certs keyed off of consumer
138     //
139     // either way should return a string representation of the certificate
140     throw Exception("fetch_private_cert not implemented");
141   }
142
143   public function build_signature(&$request, $consumer, $token) {
144     $base_string = $request->get_signature_base_string();
145     $request->base_string = $base_string;
146
147     // Fetch the private key cert based on the request
148     $cert = $this->fetch_private_cert($request);
149
150     // Pull the private key ID from the certificate
151     $privatekeyid = openssl_get_privatekey($cert);
152
153     // Sign using the key
154     $ok = openssl_sign($base_string, $signature, $privatekeyid);
155
156     // Release the key resource
157     openssl_free_key($privatekeyid);
158
159     return base64_encode($signature);
160   }
161
162   public function check_signature(&$request, $consumer, $token, $signature) {
163     $decoded_sig = base64_decode($signature);
164
165     $base_string = $request->get_signature_base_string();
166
167     // Fetch the public key cert based on the request
168     $cert = $this->fetch_public_cert($request);
169
170     // Pull the public key ID from the certificate
171     $publickeyid = openssl_get_publickey($cert);
172
173     // Check the computed signature against the one passed in the query
174     $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
175
176     // Release the key resource
177     openssl_free_key($publickeyid);
178
179     return $ok == 1;
180   }
181 }
182
183 class OAuthRequest {
184   public $parameters;
185   private $http_method;
186   private $http_url;
187   // for debug purposes
188   public $base_string;
189   public static $version = '1.0';
190
191   function __construct($http_method, $http_url, $parameters = NULL) {
192     @$parameters or $parameters = array();
193     $this->parameters = $parameters;
194     $this->http_method = $http_method;
195     $this->http_url = $http_url;
196   }
197
198   /**
199    * attempt to build up a request from what was passed to the server
200    */
201   public static function from_request($http_method = NULL, $http_url = NULL, $parameters = NULL) {
202     $scheme = (! isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https';
203     @$http_url or $http_url = $scheme . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
204     @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
205     $request_headers = OAuthRequest::get_headers();
206     // let the library user override things however they'd like, if they know
207     // which parameters to use then go for it, for example XMLRPC might want to
208     // do this
209     if ($parameters) {
210       $req = new OAuthRequest($http_method, $http_url, $parameters);
211     } elseif (isset($request_headers['Authorization']) && substr($request_headers['Authorization'], 0, 5) == "OAuth") {
212       // next check for the auth header, we need to do some extra stuff
213       // if that is the case, namely suck in the parameters from GET or POST
214       // so that we can include them in the signature
215       $header_parameters = OAuthRequest::split_header($request_headers['Authorization']);
216       if ($http_method == "GET") {
217         $req_parameters = $_GET;
218       } else if ($http_method = "POST") {
219         $req_parameters = $_POST;
220       }
221       $parameters = array_merge($header_parameters, $req_parameters);
222       $req = new OAuthRequest($http_method, $http_url, $parameters);
223     } elseif ($http_method == "GET") {
224       $req = new OAuthRequest($http_method, $http_url, $_GET);
225     } elseif ($http_method == "POST") {
226       $req = new OAuthRequest($http_method, $http_url, $_POST);
227     }
228     return $req;
229   }
230
231   /**
232    * pretty much a helper function to set up the request
233    */
234   public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters = NULL) {
235     @$parameters or $parameters = array();
236     $defaults = array("oauth_version" => OAuthRequest::$version,
237         "oauth_nonce" => OAuthRequest::generate_nonce(),
238         "oauth_timestamp" => OAuthRequest::generate_timestamp(),
239         "oauth_consumer_key" => $consumer->key);
240     $parameters = array_merge($defaults, $parameters);
241
242     if ($token) {
243       $parameters['oauth_token'] = $token->key;
244     }
245     return new OAuthRequest($http_method, $http_url, $parameters);
246   }
247
248   public function set_parameter($name, $value) {
249     $this->parameters[$name] = $value;
250   }
251
252   public function get_parameter($name) {
253     return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
254   }
255
256   public function get_parameters() {
257     return $this->parameters;
258   }
259
260   /**
261    * Returns the normalized parameters of the request
262    *
263    * This will be all (except oauth_signature) parameters,
264    * sorted first by key, and if duplicate keys, then by
265    * value.
266    *
267    * The returned string will be all the key=value pairs
268    * concated by &.
269    *
270    * @return string
271    */
272   public function get_signable_parameters() {
273     // Grab all parameters
274     $params = $this->parameters;
275
276     // Remove oauth_signature if present
277     if (isset($params['oauth_signature'])) {
278       unset($params['oauth_signature']);
279     }
280
281     // Urlencode both keys and values
282     $keys = array_map(array('OAuthUtil', 'urlencodeRFC3986'), array_keys($params));
283     $values = array_map(array('OAuthUtil', 'urlencodeRFC3986'), array_values($params));
284     $params = array_combine($keys, $values);
285
286     // Sort by keys (natsort)
287     uksort($params, 'strnatcmp');
288
289     // Generate key=value pairs
290     $pairs = array();
291     foreach ($params as $key => $value) {
292       if (is_array($value)) {
293         // If the value is an array, it's because there are multiple
294         // with the same key, sort them, then add all the pairs
295         natsort($value);
296         foreach ($value as $v2) {
297           $pairs[] = $key . '=' . $v2;
298         }
299       } else {
300         $pairs[] = $key . '=' . $value;
301       }
302     }
303
304     // Return the pairs, concated with &
305     return implode('&', $pairs);
306   }
307
308   /**
309    * Returns the base string of this request
310    *
311    * The base string defined as the method, the url
312    * and the parameters (normalized), each urlencoded
313    * and the concated with &.
314    */
315   public function get_signature_base_string() {
316     $parts = array($this->get_normalized_http_method(), $this->get_normalized_http_url(),
317         $this->get_signable_parameters());
318
319     $parts = array_map(array('OAuthUtil', 'urlencodeRFC3986'), $parts);
320
321     return implode('&', $parts);
322   }
323
324   /**
325    * just uppercases the http method
326    */
327   public function get_normalized_http_method() {
328     return strtoupper($this->http_method);
329   }
330
331   /**
332    * parses the url and rebuilds it to be
333    * scheme://host/path
334    */
335   public function get_normalized_http_url() {
336     $parts = parse_url($this->http_url);
337
338     $port = @$parts['port'];
339     $scheme = $parts['scheme'];
340     $host = $parts['host'];
341     $path = @$parts['path'];
342
343     $port or $port = ($scheme == 'https') ? '443' : '80';
344
345     if (($scheme == 'https' && $port != '443') || ($scheme == 'http' && $port != '80')) {
346       $host = "$host:$port";
347     }
348     return "$scheme://$host$path";
349   }
350
351   /**
352    * builds a url usable for a GET request
353    */
354   public function to_url() {
355     $out = $this->get_normalized_http_url() . "?";
356     $out .= $this->to_postdata();
357     return $out;
358   }
359
360   /**
361    * builds the data one would send in a POST request
362    */
363   public function to_postdata() {
364     $total = array();
365     foreach ($this->parameters as $k => $v) {
366       $total[] = OAuthUtil::urlencodeRFC3986($k) . "=" . OAuthUtil::urlencodeRFC3986($v);
367     }
368     $out = implode("&", $total);
369     return $out;
370   }
371
372   /**
373    * builds the Authorization: header
374    */
375   public function to_header($realm = "") {
376     $out = 'Authorization: OAuth realm="' . $realm . '"';
377     $total = array();
378     foreach ($this->parameters as $k => $v) {
379       if (substr($k, 0, 5) != "oauth") continue;
380       $out .= ',' . OAuthUtil::urlencodeRFC3986($k) . '="' . OAuthUtil::urlencodeRFC3986($v) . '"';
381     }
382     return $out;
383   }
384
385   public function __toString() {
386     return $this->to_url();
387   }
388
389   public function sign_request($signature_method, $consumer, $token) {
390     $this->set_parameter("oauth_signature_method", $signature_method->get_name());
391     $signature = $this->build_signature($signature_method, $consumer, $token);
392     $this->set_parameter("oauth_signature", $signature);
393   }
394
395   public function build_signature($signature_method, $consumer, $token) {
396     $signature = $signature_method->build_signature($this, $consumer, $token);
397     return $signature;
398   }
399
400   /**
401    * util function: current timestamp
402    */
403   private static function generate_timestamp() {
404     return time();
405   }
406
407   /**
408    * util function: current nonce
409    */
410   private static function generate_nonce() {
411     $mt = microtime();
412     $rand = mt_rand();
413
414     return md5($mt . $rand); // md5s look nicer than numbers
415   }
416
417   /**
418    * util function for turning the Authorization: header into
419    * parameters, has to do some unescaping
420    */
421   private static function split_header($header) {
422     // remove 'OAuth ' at the start of a header
423     $header = substr($header, 6);
424
425     // error cases: commas in parameter values?
426     $parts = explode(",", $header);
427     $out = array();
428     foreach ($parts as $param) {
429       $param = ltrim($param);
430       // skip the "realm" param, nobody ever uses it anyway
431       if (substr($param, 0, 5) != "oauth") continue;
432
433       $param_parts = explode("=", $param);
434
435       // rawurldecode() used because urldecode() will turn a "+" in the
436       // value into a space
437       $out[$param_parts[0]] = rawurldecode(substr($param_parts[1], 1, - 1));
438     }
439     return $out;
440   }
441
442   /**
443    * helper to try to sort out headers for people who aren't running apache
444    */
445   private static function get_headers() {
446     if (function_exists('apache_request_headers')) {
447       // we need this to get the actual Authorization: header
448       // because apache tends to tell us it doesn't exist
449       return apache_request_headers();
450     }
451     // otherwise we don't have apache and are just going to have to hope
452     // that $_SERVER actually contains what we need
453     $out = array();
454     foreach ($_SERVER as $key => $value) {
455       if (substr($key, 0, 5) == "HTTP_") {
456         // this is chaos, basically it is just there to capitalize the first
457         // letter of every word that is not an initial HTTP and strip HTTP
458         // code from przemek
459         $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
460         $out[$key] = $value;
461       }
462     }
463     return $out;
464   }
465 }
466
467 class OAuthServer {
468   protected $timestamp_threshold = 300; // in seconds, five minutes
469   protected $version = 1.0; // hi blaine
470   protected $signature_methods = array();
471
472   protected $data_store;
473
474   function __construct($data_store) {
475     $this->data_store = $data_store;
476   }
477
478   public function add_signature_method($signature_method) {
479     $this->signature_methods[$signature_method->get_name()] = $signature_method;
480   }
481
482   // high level functions
483
484
485   /**
486    * process a request_token request
487    * returns the request token on success
488    */
489   public function fetch_request_token(&$request) {
490     $this->get_version($request);
491 //@harris
492 //open up firebug, check RemoteContentRequest Object
493 //the parameter has only oauth_signature but nothing else.all the keys are missing.
494 //failing the get_consumer request.
495 //print_r($request);exit;
496     $consumer = $this->get_consumer($request);
497
498         // no token required for the initial token request
499     $token = NULL;
500
501     $this->check_signature($request, $consumer, $token);
502
503     $new_token = $this->data_store->new_request_token($consumer);
504
505     return $new_token;
506   }
507
508   /**
509    * process an access_token request
510    * returns the access token on success
511    */
512   public function fetch_access_token(&$request) {
513     $this->get_version($request);
514
515     $consumer = $this->get_consumer($request);
516
517     // requires authorized request token
518     $token = $this->get_token($request, $consumer, "request");
519
520     $this->check_signature($request, $consumer, $token);
521
522     $new_token = $this->data_store->new_access_token($token, $consumer);
523
524     return $new_token;
525   }
526
527   /**
528    * verify an api call, checks all the parameters
529    */
530   public function verify_request(&$request) {
531     $this->get_version($request);
532     $consumer = $this->get_consumer($request);
533     $token = $this->get_token($request, $consumer, "access");
534     $this->check_signature($request, $consumer, $token);
535     return array($consumer, $token);
536   }
537
538   // Internals from here
539   /**
540    * version 1
541    */
542   private function get_version(&$request) {
543     $version = $request->get_parameter("oauth_version");
544     if (! $version) {
545       $version = 1.0;
546     }
547     if ($version && $version != $this->version) {
548       throw new OAuthException("OAuth version '$version' not supported");
549     }
550     return $version;
551   }
552
553   /**
554    * figure out the signature with some defaults
555    */
556   private function get_signature_method(&$request) {
557     $signature_method = @$request->get_parameter("oauth_signature_method");
558     if (! $signature_method) {
559       $signature_method = "PLAINTEXT";
560     }
561     if (! in_array($signature_method, array_keys($this->signature_methods))) {
562       throw new OAuthException("Signature method '$signature_method' not supported try one of the following: " . implode(", ", array_keys($this->signature_methods)));
563     }
564     return $this->signature_methods[$signature_method];
565   }
566
567   /**
568    * try to find the consumer for the provided request's consumer key
569    */
570   private function get_consumer(&$request) {
571     $consumer_key = @$request->get_parameter("oauth_consumer_key");
572     if (! $consumer_key) {
573       throw new OAuthException("Invalid consumer key");
574     }
575
576     $consumer = $this->data_store->lookup_consumer($consumer_key);
577     if (! $consumer) {
578       throw new OAuthException("Invalid consumer");
579     }
580
581     return $consumer;
582   }
583
584   /**
585    * try to find the token for the provided request's token key
586    */
587   private function get_token(&$request, $consumer, $token_type = "access") {
588     $token_field = @$request->get_parameter('oauth_token');
589     $token = $this->data_store->lookup_token($consumer, $token_type, $token_field);
590     if (! $token) {
591       throw new OAuthException("Invalid $token_type token: $token_field");
592     }
593     return $token;
594   }
595
596   /**
597    * all-in-one function to check the signature on a request
598    * should guess the signature method appropriately
599    */
600   private function check_signature(&$request, $consumer, $token) {
601     // this should probably be in a different method
602     $timestamp = @$request->get_parameter('oauth_timestamp');
603     $nonce = @$request->get_parameter('oauth_nonce');
604     $this->check_timestamp($timestamp);
605     $this->check_nonce($consumer, $token, $nonce, $timestamp);
606     $signature_method = $this->get_signature_method($request);
607     $signature = $request->get_parameter('oauth_signature');
608     $valid_sig = $signature_method->check_signature($request, $consumer, $token, $signature);
609     if (! $valid_sig) {
610       throw new OAuthException("Invalid signature");
611     }
612   }
613
614   /**
615    * check that the timestamp is new enough
616    */
617   private function check_timestamp($timestamp) {
618     // verify that timestamp is recentish
619     $now = time();
620     if ($now - $timestamp > $this->timestamp_threshold) {
621       throw new OAuthException("Expired timestamp, yours $timestamp, ours $now");
622     }
623   }
624
625   /**
626    * check that the nonce is not repeated
627    */
628   private function check_nonce($consumer, $token, $nonce, $timestamp) {
629     // verify that the nonce is uniqueish
630     $found = $this->data_store->lookup_nonce($consumer, $token, $nonce, $timestamp);
631     if ($found) {
632       throw new OAuthException("Nonce already used: $nonce");
633     }
634   }
635
636 }
637
638 class OAuthDataStore {
639
640   function lookup_consumer($consumer_key) {
641     // implement me
642   }
643
644   function lookup_token($consumer, $token_type, $token) {
645     // implement me
646   }
647
648   function lookup_nonce($consumer, $token, $nonce, $timestamp) {
649     // implement me
650   }
651
652   function fetch_request_token($consumer, $token_secret) {
653     // return a new token attached to this consumer
654   }
655
656   function fetch_access_token($token, $consumer) {
657     // return a new access token attached to this consumer for the user
658     // associated with this token if the request token is authorized
659     // should also invalidate the request token
660   }
661
662 }
663
664 /*  A very naive dbm-based oauth storage
665  */
666 /* @harris, not needed, use AT_
667 class SimpleOAuthDataStore extends OAuthDataStore {
668   private $dbh;
669
670   function __construct($path = "oauth.gdbm") {
671     $this->dbh = dba_popen($path, 'c', 'gdbm');
672   }
673
674   function __destruct() {
675     dba_close($this->dbh);
676   }
677
678   function lookup_consumer($consumer_key) {
679     $rv = dba_fetch("consumer_$consumer_key", $this->dbh);
680     if ($rv === FALSE) {
681       return NULL;
682     }
683     $obj = unserialize($rv);
684     if (! ($obj instanceof OAuthConsumer)) {
685       return NULL;
686     }
687     return $obj;
688   }
689
690   function lookup_token($consumer, $token_type, $token) {
691     $rv = dba_fetch("${token_type}_${token}", $this->dbh);
692     if ($rv === FALSE) {
693       return NULL;
694     }
695     $obj = unserialize($rv);
696     if (! ($obj instanceof OAuthToken)) {
697       return NULL;
698     }
699     return $obj;
700   }
701
702   function lookup_nonce($consumer, $token, $nonce, $timestamp) {
703     if (dba_exists("nonce_$nonce", $this->dbh)) {
704       return TRUE;
705     } else {
706       dba_insert("nonce_$nonce", "1", $this->dbh);
707       return FALSE;
708     }
709   }
710
711   function new_token($consumer, $type = "request") {
712     $key = md5(time());
713     $secret = time() + time();
714     $token = new OAuthToken($key, md5(md5($secret)));
715     if (! dba_insert("${type}_$key", serialize($token), $this->dbh)) {
716       throw new OAuthException("doooom!");
717     }
718     return $token;
719   }
720
721   function new_request_token($consumer, $token_secret = null) {
722     return $this->new_token($consumer, "request");
723   }
724
725   function new_access_token($token, $consumer) {
726     $token = $this->new_token($consumer, 'access');
727     dba_delete("request_" . $token->key, $this->dbh);
728     return $token;
729   }
730 }
731 */
732
733 class OAuthUtil {
734
735   public static function urlencodeRFC3986($string) {
736     return str_replace('+', ' ', str_replace('%7E', '~', rawurlencode($string)));
737
738   }
739
740   // This decode function isn't taking into consideration the above
741   // modifications to the encoding process. However, this method doesn't
742   // seem to be used anywhere so leaving it as is.
743   public static function urldecodeRFC3986($string) {
744     return rawurldecode($string);
745   }
746 }
747