Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

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