Move ExAuth, FKOAuth1 & FKOAuthDataStore to own namespace `Friendica\Security`
[friendica.git/.git] / library / OAuth1.php
1 <?php
2 // vim: foldmethod=marker
3
4 /* Generic exception class
5  */
6
7 use Friendica\Security\FKOAuthDataStore;
8
9 if (!class_exists('OAuthException', false)) {
10         class OAuthException extends Exception
11         {
12         }
13 }
14
15 class OAuthConsumer
16 {
17         public $key;
18         public $secret;
19         public $callback_url;
20
21         function __construct($key, $secret, $callback_url = NULL)
22         {
23                 $this->key = $key;
24                 $this->secret = $secret;
25                 $this->callback_url = $callback_url;
26         }
27
28         function __toString()
29         {
30                 return "OAuthConsumer[key=$this->key,secret=$this->secret]";
31         }
32 }
33
34 class OAuthToken
35 {
36         // access tokens and request tokens
37         public $key;
38         public $secret;
39
40         public $expires;
41         public $scope;
42         public $uid;
43
44         /**
45          * key = the token
46          * secret = the token secret
47          *
48          * @param $key
49          * @param $secret
50          */
51         function __construct($key, $secret)
52         {
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         {
63                 return "oauth_token=" .
64                         OAuthUtil::urlencode_rfc3986($this->key) .
65                         "&oauth_token_secret=" .
66                         OAuthUtil::urlencode_rfc3986($this->secret);
67         }
68
69         function __toString()
70         {
71                 return $this->to_string();
72         }
73 }
74
75 /**
76  * A class for implementing a Signature Method
77  * See section 9 ("Signing Requests") in the spec
78  */
79 abstract class OAuthSignatureMethod
80 {
81         /**
82          * Needs to return the name of the Signature Method (ie HMAC-SHA1)
83          *
84          * @return string
85          */
86         abstract public function get_name();
87
88         /**
89          * Build up the signature
90          * NOTE: The output of this function MUST NOT be urlencoded.
91          * the encoding is handled in OAuthRequest when the final
92          * request is serialized
93          *
94          * @param OAuthRequest  $request
95          * @param OAuthConsumer $consumer
96          * @param OAuthToken    $token
97          * @return string
98          */
99         abstract public function build_signature(OAuthRequest $request, OAuthConsumer $consumer, OAuthToken $token = null);
100
101         /**
102          * Verifies that a given signature is correct
103          *
104          * @param OAuthRequest  $request
105          * @param OAuthConsumer $consumer
106          * @param OAuthToken    $token
107          * @param string        $signature
108          * @return bool
109          */
110         public function check_signature(OAuthRequest $request, OAuthConsumer $consumer, $signature, OAuthToken $token = null)
111         {
112                 $built = $this->build_signature($request, $consumer, $token);
113                 return ($built == $signature);
114         }
115 }
116
117 /**
118  * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
119  * where the Signature Base String is the text and the key is the concatenated values (each first
120  * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
121  * character (ASCII code 38) even if empty.
122  *   - Chapter 9.2 ("HMAC-SHA1")
123  */
124 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod
125 {
126         function get_name()
127         {
128                 return "HMAC-SHA1";
129         }
130
131         /**
132          * @param OAuthRequest  $request
133          * @param OAuthConsumer $consumer
134          * @param OAuthToken    $token
135          * @return string
136          */
137         public function build_signature(OAuthRequest $request, OAuthConsumer $consumer, OAuthToken $token = null)
138         {
139                 $base_string = $request->get_signature_base_string();
140                 $request->base_string = $base_string;
141
142                 $key_parts = array(
143                         $consumer->secret,
144                         ($token) ? $token->secret : ""
145                 );
146
147                 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
148                 $key = implode('&', $key_parts);
149
150
151                 $r = base64_encode(hash_hmac('sha1', $base_string, $key, true));
152                 return $r;
153         }
154 }
155
156 /**
157  * The PLAINTEXT method does not provide any security protection and SHOULD only be used
158  * over a secure channel such as HTTPS. It does not use the Signature Base String.
159  *   - Chapter 9.4 ("PLAINTEXT")
160  */
161 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod
162 {
163         public function get_name()
164         {
165                 return "PLAINTEXT";
166         }
167
168         /**
169          * oauth_signature is set to the concatenated encoded values of the Consumer Secret and
170          * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
171          * empty. The result MUST be encoded again.
172          *   - Chapter 9.4.1 ("Generating Signatures")
173          *
174          * Please note that the second encoding MUST NOT happen in the SignatureMethod, as
175          * OAuthRequest handles this!
176          *
177          * @param $request
178          * @param $consumer
179          * @param $token
180          * @return string
181          */
182         public function build_signature(OAuthRequest $request, OAuthConsumer $consumer, OAuthToken $token = null)
183         {
184                 $key_parts = array(
185                         $consumer->secret,
186                         ($token) ? $token->secret : ""
187                 );
188
189                 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
190                 $key = implode('&', $key_parts);
191                 $request->base_string = $key;
192
193                 return $key;
194         }
195 }
196
197 /**
198  * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
199  * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
200  * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
201  * verified way to the Service Provider, in a manner which is beyond the scope of this
202  * specification.
203  *   - Chapter 9.3 ("RSA-SHA1")
204  */
205 abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod
206 {
207         public function get_name()
208         {
209                 return "RSA-SHA1";
210         }
211
212         // Up to the SP to implement this lookup of keys. Possible ideas are:
213         // (1) do a lookup in a table of trusted certs keyed off of consumer
214         // (2) fetch via http using a url provided by the requester
215         // (3) some sort of specific discovery code based on request
216         //
217         // Either way should return a string representation of the certificate
218         protected abstract function fetch_public_cert(&$request);
219
220         // Up to the SP to implement this lookup of keys. Possible ideas are:
221         // (1) do a lookup in a table of trusted certs keyed off of consumer
222         //
223         // Either way should return a string representation of the certificate
224         protected abstract function fetch_private_cert(&$request);
225
226         public function build_signature(OAuthRequest $request, OAuthConsumer $consumer, OAuthToken $token = null)
227         {
228                 $base_string = $request->get_signature_base_string();
229                 $request->base_string = $base_string;
230
231                 // Fetch the private key cert based on the request
232                 $cert = $this->fetch_private_cert($request);
233
234                 // Pull the private key ID from the certificate
235                 $privatekeyid = openssl_get_privatekey($cert);
236
237                 // Sign using the key
238                 openssl_sign($base_string, $signature, $privatekeyid);
239
240                 // Release the key resource
241                 openssl_free_key($privatekeyid);
242
243                 return base64_encode($signature);
244         }
245
246         public function check_signature(OAuthRequest $request, OAuthConsumer $consumer, $signature, OAuthToken $token = null)
247         {
248                 $decoded_sig = base64_decode($signature);
249
250                 $base_string = $request->get_signature_base_string();
251
252                 // Fetch the public key cert based on the request
253                 $cert = $this->fetch_public_cert($request);
254
255                 // Pull the public key ID from the certificate
256                 $publickeyid = openssl_get_publickey($cert);
257
258                 // Check the computed signature against the one passed in the query
259                 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
260
261                 // Release the key resource
262                 openssl_free_key($publickeyid);
263
264                 return $ok == 1;
265         }
266 }
267
268 class OAuthRequest
269 {
270         private $parameters;
271         private $http_method;
272         private $http_url;
273         // for debug purposes
274         public $base_string;
275         public static $version = '1.0';
276         public static $POST_INPUT = 'php://input';
277
278         function __construct($http_method, $http_url, $parameters = NULL)
279         {
280                 @$parameters or $parameters = array();
281                 $parameters = array_merge(OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
282                 $this->parameters = $parameters;
283                 $this->http_method = $http_method;
284                 $this->http_url = $http_url;
285         }
286
287
288         /**
289          * attempt to build up a request from what was passed to the server
290          *
291          * @param string|null $http_method
292          * @param string|null $http_url
293          * @param string|null $parameters
294          * @return OAuthRequest
295          */
296         public static function from_request($http_method = NULL, $http_url = NULL, $parameters = NULL)
297         {
298                 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
299                         ? 'http'
300                         : 'https';
301                 @$http_url or $http_url = $scheme .
302                         '://' . $_SERVER['HTTP_HOST'] .
303                         ':' .
304                         $_SERVER['SERVER_PORT'] .
305                         $_SERVER['REQUEST_URI'];
306                 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
307
308                 // We weren't handed any parameters, so let's find the ones relevant to
309                 // this request.
310                 // If you run XML-RPC or similar you should use this to provide your own
311                 // parsed parameter-list
312                 if (!$parameters) {
313                         // Find request headers
314                         $request_headers = OAuthUtil::get_headers();
315
316                         // Parse the query-string to find GET parameters
317                         $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
318
319                         // It's a POST request of the proper content-type, so parse POST
320                         // parameters and add those overriding any duplicates from GET
321                         if (
322                                 $http_method == "POST"
323                                 && @strstr(
324                                         $request_headers["Content-Type"],
325                                         "application/x-www-form-urlencoded"
326                                 )
327                         ) {
328                                 $post_data = OAuthUtil::parse_parameters(
329                                         file_get_contents(self::$POST_INPUT)
330                                 );
331                                 $parameters = array_merge($parameters, $post_data);
332                         }
333
334                         // We have a Authorization-header with OAuth data. Parse the header
335                         // and add those overriding any duplicates from GET or POST
336                         if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
337                                 $header_parameters = OAuthUtil::split_header(
338                                         $request_headers['Authorization']
339                                 );
340                                 $parameters = array_merge($parameters, $header_parameters);
341                         }
342                 }
343                 // fix for friendica redirect system
344
345                 $http_url = substr($http_url, 0, strpos($http_url, $parameters['pagename']) + strlen($parameters['pagename']));
346                 unset($parameters['pagename']);
347
348                 return new OAuthRequest($http_method, $http_url, $parameters);
349         }
350
351         /**
352          * pretty much a helper function to set up the request
353          *
354          * @param OAuthConsumer $consumer
355          * @param OAuthToken    $token
356          * @param string        $http_method
357          * @param string        $http_url
358          * @param array|null    $parameters
359          * @return OAuthRequest
360          */
361         public static function from_consumer_and_token(OAuthConsumer $consumer, $http_method, $http_url, array $parameters = null, OAuthToken $token = null)
362         {
363                 @$parameters or $parameters = array();
364                 $defaults = array(
365                         "oauth_version" => OAuthRequest::$version,
366                         "oauth_nonce" => OAuthRequest::generate_nonce(),
367                         "oauth_timestamp" => OAuthRequest::generate_timestamp(),
368                         "oauth_consumer_key" => $consumer->key
369                 );
370                 if ($token)
371                         $defaults['oauth_token'] = $token->key;
372
373                 $parameters = array_merge($defaults, $parameters);
374
375                 return new OAuthRequest($http_method, $http_url, $parameters);
376         }
377
378         public function set_parameter($name, $value, $allow_duplicates = true)
379         {
380                 if ($allow_duplicates && isset($this->parameters[$name])) {
381                         // We have already added parameter(s) with this name, so add to the list
382                         if (is_scalar($this->parameters[$name])) {
383                                 // This is the first duplicate, so transform scalar (string)
384                                 // into an array so we can add the duplicates
385                                 $this->parameters[$name] = array($this->parameters[$name]);
386                         }
387
388                         $this->parameters[$name][] = $value;
389                 } else {
390                         $this->parameters[$name] = $value;
391                 }
392         }
393
394         public function get_parameter($name)
395         {
396                 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
397         }
398
399         public function get_parameters()
400         {
401                 return $this->parameters;
402         }
403
404         public function unset_parameter($name)
405         {
406                 unset($this->parameters[$name]);
407         }
408
409         /**
410          * The request parameters, sorted and concatenated into a normalized string.
411          *
412          * @return string
413          */
414         public function get_signable_parameters()
415         {
416                 // Grab all parameters
417                 $params = $this->parameters;
418
419                 // Remove oauth_signature if present
420                 // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
421                 if (isset($params['oauth_signature'])) {
422                         unset($params['oauth_signature']);
423                 }
424
425                 return OAuthUtil::build_http_query($params);
426         }
427
428         /**
429          * Returns the base string of this request
430          *
431          * The base string defined as the method, the url
432          * and the parameters (normalized), each urlencoded
433          * and the concated with &.
434          */
435         public function get_signature_base_string()
436         {
437                 $parts = array(
438                         $this->get_normalized_http_method(),
439                         $this->get_normalized_http_url(),
440                         $this->get_signable_parameters()
441                 );
442
443                 $parts = OAuthUtil::urlencode_rfc3986($parts);
444
445                 return implode('&', $parts);
446         }
447
448         /**
449          * just uppercases the http method
450          */
451         public function get_normalized_http_method()
452         {
453                 return strtoupper($this->http_method);
454         }
455
456         /**
457          * parses the url and rebuilds it to be
458          * scheme://host/path
459          */
460         public function get_normalized_http_url()
461         {
462                 $parts = parse_url($this->http_url);
463
464                 $port = @$parts['port'];
465                 $scheme = $parts['scheme'];
466                 $host = $parts['host'];
467                 $path = @$parts['path'];
468
469                 $port or $port = ($scheme == 'https') ? '443' : '80';
470
471                 if (($scheme == 'https' && $port != '443')
472                         || ($scheme == 'http' && $port != '80')
473                 ) {
474                         $host = "$host:$port";
475                 }
476                 return "$scheme://$host$path";
477         }
478
479         /**
480          * builds a url usable for a GET request
481          */
482         public function to_url()
483         {
484                 $post_data = $this->to_postdata();
485                 $out = $this->get_normalized_http_url();
486                 if ($post_data) {
487                         $out .= '?' . $post_data;
488                 }
489                 return $out;
490         }
491
492         /**
493          * builds the data one would send in a POST request
494          *
495          * @param bool $raw
496          * @return array|string
497          */
498         public function to_postdata(bool $raw = false)
499         {
500                 if ($raw)
501                         return $this->parameters;
502                 else
503                         return OAuthUtil::build_http_query($this->parameters);
504         }
505
506         /**
507          * builds the Authorization: header
508          *
509          * @param string|null $realm
510          * @return string
511          * @throws OAuthException
512          */
513         public function to_header($realm = null)
514         {
515                 $first = true;
516                 if ($realm) {
517                         $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
518                         $first = false;
519                 } else
520                         $out = 'Authorization: OAuth';
521
522                 foreach ($this->parameters as $k => $v) {
523                         if (substr($k, 0, 5) != "oauth") continue;
524                         if (is_array($v)) {
525                                 throw new OAuthException('Arrays not supported in headers');
526                         }
527                         $out .= ($first) ? ' ' : ',';
528                         $out .= OAuthUtil::urlencode_rfc3986($k) .
529                                 '="' .
530                                 OAuthUtil::urlencode_rfc3986($v) .
531                                 '"';
532                         $first = false;
533                 }
534                 return $out;
535         }
536
537         public function __toString()
538         {
539                 return $this->to_url();
540         }
541
542
543         public function sign_request(OAuthSignatureMethod $signature_method, $consumer, $token)
544         {
545                 $this->set_parameter(
546                         "oauth_signature_method",
547                         $signature_method->get_name(),
548                         false
549                 );
550                 $signature = $this->build_signature($signature_method, $consumer, $token);
551                 $this->set_parameter("oauth_signature", $signature, false);
552         }
553
554         public function build_signature(OAuthSignatureMethod $signature_method, $consumer, $token)
555         {
556                 $signature = $signature_method->build_signature($this, $consumer, $token);
557                 return $signature;
558         }
559
560         /**
561          * util function: current timestamp
562          */
563         private static function generate_timestamp()
564         {
565                 return time();
566         }
567
568         /**
569          * util function: current nonce
570          */
571         private static function generate_nonce()
572         {
573                 return Friendica\Util\Strings::getRandomHex(32);
574         }
575 }
576
577 class OAuthServer
578 {
579         protected $timestamp_threshold = 300; // in seconds, five minutes
580         protected $version = '1.0';             // hi blaine
581         /** @var OAuthSignatureMethod[] */
582         protected $signature_methods = array();
583
584         /** @var FKOAuthDataStore */
585         protected $data_store;
586
587         function __construct(FKOAuthDataStore $data_store)
588         {
589                 $this->data_store = $data_store;
590         }
591
592         public function add_signature_method(OAuthSignatureMethod $signature_method)
593         {
594                 $this->signature_methods[$signature_method->get_name()] =
595                         $signature_method;
596         }
597
598         // high level functions
599
600         /**
601          * process a request_token request
602          * returns the request token on success
603          *
604          * @param OAuthRequest $request
605          * @return OAuthToken|null
606          * @throws OAuthException
607          */
608         public function fetch_request_token(OAuthRequest $request)
609         {
610                 $this->get_version($request);
611
612                 $consumer = $this->get_consumer($request);
613
614                 // no token required for the initial token request
615                 $token = NULL;
616
617                 $this->check_signature($request, $consumer, $token);
618
619                 // Rev A change
620                 $callback = $request->get_parameter('oauth_callback');
621                 $new_token = $this->data_store->new_request_token($consumer, $callback);
622
623                 return $new_token;
624         }
625
626         /**
627          * process an access_token request
628          * returns the access token on success
629          *
630          * @param OAuthRequest $request
631          * @return object
632          * @throws OAuthException
633          */
634         public function fetch_access_token(OAuthRequest $request)
635         {
636                 $this->get_version($request);
637
638                 $consumer = $this->get_consumer($request);
639
640                 // requires authorized request token
641                 $token = $this->get_token($request, $consumer, "request");
642
643                 $this->check_signature($request, $consumer, $token);
644
645                 // Rev A change
646                 $verifier = $request->get_parameter('oauth_verifier');
647                 $new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
648
649                 return $new_token;
650         }
651
652         /**
653          * verify an api call, checks all the parameters
654          *
655          * @param OAuthRequest $request
656          * @return array
657          * @throws OAuthException
658          */
659         public function verify_request(OAuthRequest $request)
660         {
661                 $this->get_version($request);
662                 $consumer = $this->get_consumer($request);
663                 $token = $this->get_token($request, $consumer, "access");
664                 $this->check_signature($request, $consumer, $token);
665                 return [$consumer, $token];
666         }
667
668         // Internals from here
669
670         /**
671          * version 1
672          *
673          * @param OAuthRequest $request
674          * @return string
675          * @throws OAuthException
676          */
677         private function get_version(OAuthRequest $request)
678         {
679                 $version = $request->get_parameter("oauth_version");
680                 if (!$version) {
681                         // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
682                         // Chapter 7.0 ("Accessing Protected Ressources")
683                         $version = '1.0';
684                 }
685                 if ($version !== $this->version) {
686                         throw new OAuthException("OAuth version '$version' not supported");
687                 }
688                 return $version;
689         }
690
691         /**
692          * figure out the signature with some defaults
693          *
694          * @param OAuthRequest $request
695          * @return OAuthSignatureMethod
696          * @throws OAuthException
697          */
698         private function get_signature_method(OAuthRequest $request)
699         {
700                 $signature_method =
701                         @$request->get_parameter("oauth_signature_method");
702
703                 if (!$signature_method) {
704                         // According to chapter 7 ("Accessing Protected Ressources") the signature-method
705                         // parameter is required, and we can't just fallback to PLAINTEXT
706                         throw new OAuthException('No signature method parameter. This parameter is required');
707                 }
708
709                 if (!in_array(
710                         $signature_method,
711                         array_keys($this->signature_methods)
712                 )) {
713                         throw new OAuthException(
714                                 "Signature method '$signature_method' not supported " .
715                                 "try one of the following: " .
716                                 implode(", ", array_keys($this->signature_methods))
717                         );
718                 }
719                 return $this->signature_methods[$signature_method];
720         }
721
722         /**
723          * try to find the consumer for the provided request's consumer key
724          *
725          * @param OAuthRequest $request
726          * @return OAuthConsumer
727          * @throws OAuthException
728          */
729         private function get_consumer(OAuthRequest $request)
730         {
731                 $consumer_key = @$request->get_parameter("oauth_consumer_key");
732                 if (!$consumer_key) {
733                         throw new OAuthException("Invalid consumer key");
734                 }
735
736                 $consumer = $this->data_store->lookup_consumer($consumer_key);
737                 if (!$consumer) {
738                         throw new OAuthException("Invalid consumer");
739                 }
740
741                 return $consumer;
742         }
743
744         /**
745          * try to find the token for the provided request's token key
746          *
747          * @param OAuthRequest $request
748          * @param              $consumer
749          * @param string       $token_type
750          * @return OAuthToken|null
751          * @throws OAuthException
752          */
753         private function get_token(OAuthRequest &$request, $consumer, $token_type = "access")
754         {
755                 $token_field = @$request->get_parameter('oauth_token');
756                 $token = $this->data_store->lookup_token(
757                         $consumer,
758                         $token_type,
759                         $token_field
760                 );
761                 if (!$token) {
762                         throw new OAuthException("Invalid $token_type token: $token_field");
763                 }
764                 return $token;
765         }
766
767         /**
768          * all-in-one function to check the signature on a request
769          * should guess the signature method appropriately
770          *
771          * @param OAuthRequest    $request
772          * @param OAuthConsumer   $consumer
773          * @param OAuthToken|null $token
774          * @throws OAuthException
775          */
776         private function check_signature(OAuthRequest $request, OAuthConsumer $consumer, OAuthToken $token = null)
777         {
778                 // this should probably be in a different method
779                 $timestamp = @$request->get_parameter('oauth_timestamp');
780                 $nonce = @$request->get_parameter('oauth_nonce');
781
782                 $this->check_timestamp($timestamp);
783                 $this->check_nonce($consumer, $token, $nonce, $timestamp);
784
785                 $signature_method = $this->get_signature_method($request);
786
787                 $signature = $request->get_parameter('oauth_signature');
788                 $valid_sig = $signature_method->check_signature(
789                         $request,
790                         $consumer,
791                         $signature,
792                         $token
793                 );
794
795                 if (!$valid_sig) {
796                         throw new OAuthException("Invalid signature");
797                 }
798         }
799
800         /**
801          * check that the timestamp is new enough
802          *
803          * @param int $timestamp
804          * @throws OAuthException
805          */
806         private function check_timestamp($timestamp)
807         {
808                 if (!$timestamp)
809                         throw new OAuthException(
810                                 'Missing timestamp parameter. The parameter is required'
811                         );
812
813                 // verify that timestamp is recentish
814                 $now = time();
815                 if (abs($now - $timestamp) > $this->timestamp_threshold) {
816                         throw new OAuthException(
817                                 "Expired timestamp, yours $timestamp, ours $now"
818                         );
819                 }
820         }
821
822         /**
823          * check that the nonce is not repeated
824          *
825          * @param OAuthConsumer $consumer
826          * @param OAuthToken    $token
827          * @param string        $nonce
828          * @param int           $timestamp
829          * @throws OAuthException
830          */
831         private function check_nonce(OAuthConsumer $consumer, OAuthToken $token, $nonce, int $timestamp)
832         {
833                 if (!$nonce)
834                         throw new OAuthException(
835                                 'Missing nonce parameter. The parameter is required'
836                         );
837
838                 // verify that the nonce is uniqueish
839                 $found = $this->data_store->lookup_nonce(
840                         $consumer,
841                         $token,
842                         $nonce,
843                         $timestamp
844                 );
845                 if ($found) {
846                         throw new OAuthException("Nonce already used: $nonce");
847                 }
848         }
849 }
850
851 class OAuthDataStore
852 {
853         function lookup_consumer($consumer_key)
854         {
855                 // implement me
856         }
857
858         function lookup_token(OAuthConsumer $consumer, $token_type, $token_id)
859         {
860                 // implement me
861         }
862
863         function lookup_nonce(OAuthConsumer $consumer, OAuthToken $token, $nonce, int $timestamp)
864         {
865                 // implement me
866         }
867
868         function new_request_token(OAuthConsumer $consumer, $callback = null)
869         {
870                 // return a new token attached to this consumer
871         }
872
873         function new_access_token(OAuthToken $token, OAuthConsumer $consumer, $verifier = null)
874         {
875                 // return a new access token attached to this consumer
876                 // for the user associated with this token if the request token
877                 // is authorized
878                 // should also invalidate the request token
879         }
880 }
881
882 class OAuthUtil
883 {
884         public static function urlencode_rfc3986($input)
885         {
886                 if (is_array($input)) {
887                         return array_map(['OAuthUtil', 'urlencode_rfc3986'], $input);
888                 } else if (is_scalar($input)) {
889                         return str_replace(
890                                 '+',
891                                 ' ',
892                                 str_replace('%7E', '~', rawurlencode($input))
893                         );
894                 } else {
895                         return '';
896                 }
897         }
898
899
900         // This decode function isn't taking into consideration the above
901         // modifications to the encoding process. However, this method doesn't
902         // seem to be used anywhere so leaving it as is.
903         public static function urldecode_rfc3986($string)
904         {
905                 return urldecode($string);
906         }
907
908         // Utility function for turning the Authorization: header into
909         // parameters, has to do some unescaping
910         // Can filter out any non-oauth parameters if needed (default behaviour)
911         public static function split_header($header, $only_allow_oauth_parameters = true)
912         {
913                 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
914                 $offset = 0;
915                 $params = [];
916                 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
917                         $match = $matches[0];
918                         $header_name = $matches[2][0];
919                         $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
920                         if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
921                                 $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
922                         }
923                         $offset = $match[1] + strlen($match[0]);
924                 }
925
926                 if (isset($params['realm'])) {
927                         unset($params['realm']);
928                 }
929
930                 return $params;
931         }
932
933         // helper to try to sort out headers for people who aren't running apache
934         public static function get_headers()
935         {
936                 if (function_exists('apache_request_headers')) {
937                         // we need this to get the actual Authorization: header
938                         // because apache tends to tell us it doesn't exist
939                         $headers = apache_request_headers();
940
941                         // sanitize the output of apache_request_headers because
942                         // we always want the keys to be Cased-Like-This and arh()
943                         // returns the headers in the same case as they are in the
944                         // request
945                         $out = [];
946                         foreach ($headers as $key => $value) {
947                                 $key = str_replace(
948                                         " ",
949                                         "-",
950                                         ucwords(strtolower(str_replace("-", " ", $key)))
951                                 );
952                                 $out[$key] = $value;
953                         }
954                 } else {
955                         // otherwise we don't have apache and are just going to have to hope
956                         // that $_SERVER actually contains what we need
957                         $out = [];
958                         if (isset($_SERVER['CONTENT_TYPE']))
959                                 $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
960                         if (isset($_ENV['CONTENT_TYPE']))
961                                 $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
962
963                         foreach ($_SERVER as $key => $value) {
964                                 if (substr($key, 0, 5) == "HTTP_") {
965                                         // this is chaos, basically it is just there to capitalize the first
966                                         // letter of every word that is not an initial HTTP and strip HTTP
967                                         // code from przemek
968                                         $key = str_replace(
969                                                 " ",
970                                                 "-",
971                                                 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
972                                         );
973                                         $out[$key] = $value;
974                                 }
975                         }
976                 }
977                 return $out;
978         }
979
980         // This function takes a input like a=b&a=c&d=e and returns the parsed
981         // parameters like this
982         // array('a' => array('b','c'), 'd' => 'e')
983         public static function parse_parameters($input)
984         {
985                 if (!isset($input) || !$input) return array();
986
987                 $pairs = explode('&', $input);
988
989                 $parsed_parameters = [];
990                 foreach ($pairs as $pair) {
991                         $split = explode('=', $pair, 2);
992                         $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
993                         $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
994
995                         if (isset($parsed_parameters[$parameter])) {
996                                 // We have already recieved parameter(s) with this name, so add to the list
997                                 // of parameters with this name
998
999                                 if (is_scalar($parsed_parameters[$parameter])) {
1000                                         // This is the first duplicate, so transform scalar (string) into an array
1001                                         // so we can add the duplicates
1002                                         $parsed_parameters[$parameter] = [$parsed_parameters[$parameter]];
1003                                 }
1004
1005                                 $parsed_parameters[$parameter][] = $value;
1006                         } else {
1007                                 $parsed_parameters[$parameter] = $value;
1008                         }
1009                 }
1010                 return $parsed_parameters;
1011         }
1012
1013         public static function build_http_query($params)
1014         {
1015                 if (!$params) return '';
1016
1017                 // Urlencode both keys and values
1018                 $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
1019                 $values = OAuthUtil::urlencode_rfc3986(array_values($params));
1020                 $params = array_combine($keys, $values);
1021
1022                 // Parameters are sorted by name, using lexicographical byte value ordering.
1023                 // Ref: Spec: 9.1.1 (1)
1024                 uksort($params, 'strcmp');
1025
1026                 $pairs = [];
1027                 foreach ($params as $parameter => $value) {
1028                         if (is_array($value)) {
1029                                 // If two or more parameters share the same name, they are sorted by their value
1030                                 // Ref: Spec: 9.1.1 (1)
1031                                 natsort($value);
1032                                 foreach ($value as $duplicate_value) {
1033                                         $pairs[] = $parameter . '=' . $duplicate_value;
1034                                 }
1035                         } else {
1036                                 $pairs[] = $parameter . '=' . $value;
1037                         }
1038                 }
1039                 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
1040                 // Each name-value pair is separated by an '&' character (ASCII code 38)
1041                 return implode('&', $pairs);
1042         }
1043 }