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
// This file is part of BasicLTI4Moodle
3
//
4
// BasicLTI4Moodle is an IMS BasicLTI (Basic Learning Tools for Interoperability)
5
// consumer for Moodle 1.9 and Moodle 2.0. BasicLTI is a IMS Standard that allows web
6
// based learning tools to be easily integrated in LMS as native ones. The IMS BasicLTI
7
// specification is part of the IMS standard Common Cartridge 1.1 Sakai and other main LMS
8
// are already supporting or going to support BasicLTI. This project Implements the consumer
9
// for Moodle. Moodle is a Free Open source Learning Management System by Martin Dougiamas.
10
// BasicLTI4Moodle is a project iniciated and leaded by Ludo(Marc Alier) and Jordi Piguillem
11
// at the GESSI research group at UPC.
12
// SimpleLTI consumer for Moodle is an implementation of the early specification of LTI
13
// by Charles Severance (Dr Chuck) htp://dr-chuck.com , developed by Jordi Piguillem in a
14
// Google Summer of Code 2008 project co-mentored by Charles Severance and Marc Alier.
15
//
16
// BasicLTI4Moodle is copyright 2009 by Marc Alier Forment, Jordi Piguillem and Nikolas Galanis
17
// of the Universitat Politecnica de Catalunya http://www.upc.edu
18
// Contact info: Marc Alier Forment granludo @ gmail.com or marc.alier @ upc.edu
19
//
20
// OAuth.php is distributed under the MIT License
21
//
22
// The MIT License
23
//
24
// Copyright (c) 2007 Andy Smith
25
//
26
// Permission is hereby granted, free of charge, to any person obtaining a copy
27
// of this software and associated documentation files (the "Software"), to deal
28
// in the Software without restriction, including without limitation the rights
29
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
30
// copies of the Software, and to permit persons to whom the Software is
31
// furnished to do so, subject to the following conditions:
32
//
33
// The above copyright notice and this permission notice shall be included in
34
// all copies or substantial portions of the Software.
35
//
36
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
37
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
38
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
39
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
40
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
41
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
42
// THE SOFTWARE.
43
//
44
// Moodle is free software: you can redistribute it and/or modify
45
// it under the terms of the GNU General Public License as published by
46
// the Free Software Foundation, either version 3 of the License, or
47
// (at your option) any later version.
48
//
49
// Moodle is distributed in the hope that it will be useful,
50
// but WITHOUT ANY WARRANTY; without even the implied warranty of
51
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
52
// GNU General Public License for more details.
53
//
54
// You should have received a copy of the GNU General Public License
55
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
56
 
57
/**
58
 * This file contains the OAuth 1.0a implementation used for support for LTI 1.1.
59
 *
60
 * @package    mod_lti
61
 * @copyright moodle
62
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
63
 */
64
namespace moodle\mod\lti;//Using a namespace as the basicLTI module imports classes with the same names
65
 
66
defined('MOODLE_INTERNAL') || die;
67
 
68
$lastcomputedsignature = false;
69
 
70
/**
71
 * Generic exception class
72
 */
73
class OAuthException extends \Exception {
74
    // pass
75
}
76
 
77
/**
78
 * OAuth 1.0 Consumer class
79
 */
80
class OAuthConsumer {
81
    public $key;
82
    public $secret;
83
 
84
    /** @var string|null callback URL. */
85
    public ?string $callback_url;
86
 
87
    function __construct($key, $secret, $callback_url = null) {
88
        $this->key = $key;
89
        $this->secret = $secret;
90
        $this->callback_url = $callback_url;
91
    }
92
 
93
    function __toString() {
94
        return "OAuthConsumer[key=$this->key,secret=$this->secret]";
95
    }
96
}
97
 
98
class OAuthToken {
99
    // access tokens and request tokens
100
    public $key;
101
    public $secret;
102
 
103
    /**
104
     * key = the token
105
     * secret = the token secret
106
     */
107
    function __construct($key, $secret) {
108
        $this->key = $key;
109
        $this->secret = $secret;
110
    }
111
 
112
    /**
113
     * generates the basic string serialization of a token that a server
114
     * would respond to request_token and access_token calls with
115
     */
116
    function to_string() {
117
        return "oauth_token=" .
118
        OAuthUtil::urlencode_rfc3986($this->key) .
119
        "&oauth_token_secret=" .
120
        OAuthUtil::urlencode_rfc3986($this->secret);
121
    }
122
 
123
    function __toString() {
124
        return $this->to_string();
125
    }
126
}
127
 
128
class OAuthSignatureMethod {
129
    public function check_signature(&$request, $consumer, $token, $signature) {
130
        $built = $this->build_signature($request, $consumer, $token);
131
        return $built == $signature;
132
    }
133
}
134
 
135
 
136
/**
137
 * Base class for the HMac based signature methods.
138
 */
139
abstract class OAuthSignatureMethod_HMAC extends OAuthSignatureMethod {
140
 
141
    /**
142
     * Name of the Algorithm used.
143
     *
144
     * @return string algorithm name.
145
     */
146
    abstract public function get_name(): string;
147
 
148
    public function build_signature($request, $consumer, $token) {
149
        global $lastcomputedsignature;
150
        $lastcomputedsignature = false;
151
 
152
        $basestring = $request->get_signature_base_string();
153
        $request->base_string = $basestring;
154
 
155
        $key_parts = array(
156
            $consumer->secret,
157
             ($token) ? $token->secret : ""
158
        );
159
 
160
        $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
161
        $key = implode('&', $key_parts);
162
 
163
        $computedsignature = base64_encode(hash_hmac(strtolower(substr($this->get_name(), 5)), $basestring, $key, true));
164
        $lastcomputedsignature = $computedsignature;
165
        return $computedsignature;
166
    }
167
 
168
}
169
 
170
/**
171
 * Implementation for SHA 1.
172
 */
173
class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod_HMAC {
174
    /**
175
     * Name of the Algorithm used.
176
     *
177
     * @return string algorithm name.
178
     */
179
    public function get_name(): string {
180
        return "HMAC-SHA1";
181
    }
182
}
183
 
184
/**
185
 * Implementation for SHA 256.
186
 */
187
class OAuthSignatureMethod_HMAC_SHA256 extends OAuthSignatureMethod_HMAC {
188
    /**
189
     * Name of the Algorithm used.
190
     *
191
     * @return string algorithm name.
192
     */
193
    public function get_name(): string {
194
        return "HMAC-SHA256";
195
    }
196
}
197
 
198
class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
199
    /**
200
     * Name of the Algorithm used.
201
     *
202
     * @return string algorithm name.
203
     */
204
    public function get_name(): string {
205
        return "PLAINTEXT";
206
    }
207
 
208
    public function build_signature($request, $consumer, $token) {
209
        $sig = array(
210
            OAuthUtil::urlencode_rfc3986($consumer->secret)
211
        );
212
 
213
        if ($token) {
214
            array_push($sig, OAuthUtil::urlencode_rfc3986($token->secret));
215
        } else {
216
            array_push($sig, '');
217
        }
218
 
219
        $raw = implode("&", $sig);
220
        // for debug purposes
221
        $request->base_string = $raw;
222
 
223
        return OAuthUtil::urlencode_rfc3986($raw);
224
    }
225
}
226
 
227
class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
228
    /**
229
     * Name of the Algorithm used.
230
     *
231
     * @return string algorithm name.
232
     */
233
    public function get_name(): string {
234
        return "RSA-SHA1";
235
    }
236
 
237
    protected function fetch_public_cert(&$request) {
238
        // not implemented yet, ideas are:
239
        // (1) do a lookup in a table of trusted certs keyed off of consumer
240
        // (2) fetch via http using a url provided by the requester
241
        // (3) some sort of specific discovery code based on request
242
        //
243
        // either way should return a string representation of the certificate
244
        throw new OAuthException("fetch_public_cert not implemented");
245
    }
246
 
247
    protected function fetch_private_cert(&$request) {
248
        // not implemented yet, ideas are:
249
        // (1) do a lookup in a table of trusted certs keyed off of consumer
250
        //
251
        // either way should return a string representation of the certificate
252
        throw new OAuthException("fetch_private_cert not implemented");
253
    }
254
 
255
    public function build_signature(&$request, $consumer, $token) {
256
        $base_string = $request->get_signature_base_string();
257
        $request->base_string = $base_string;
258
 
259
        // Fetch the private key cert based on the request
260
        $cert = $this->fetch_private_cert($request);
261
 
262
        // Pull the private key ID from the certificate
263
        $privatekeyid = openssl_get_privatekey($cert);
264
 
265
        // Sign using the key
266
        $ok = openssl_sign($base_string, $signature, $privatekeyid);
267
 
268
        // Avoid passing null values to base64_encode.
269
        if (!$ok) {
270
            throw new OAuthException("OpenSSL unable to sign data");
271
        }
272
 
273
        return base64_encode($signature);
274
    }
275
 
276
    public function check_signature(&$request, $consumer, $token, $signature) {
277
        $decoded_sig = base64_decode($signature);
278
 
279
        $base_string = $request->get_signature_base_string();
280
 
281
        // Fetch the public key cert based on the request
282
        $cert = $this->fetch_public_cert($request);
283
 
284
        // Pull the public key ID from the certificate
285
        $publickeyid = openssl_get_publickey($cert);
286
 
287
        // Check the computed signature against the one passed in the query
288
        $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
289
 
290
        return $ok == 1;
291
    }
292
}
293
 
294
class OAuthRequest {
295
    private $parameters;
296
    private $http_method;
297
    private $http_url;
298
    // for debug purposes
299
    public $base_string;
300
    public static $version = '1.0';
301
    public static $POST_INPUT = 'php://input';
302
 
303
    function __construct($http_method, $http_url, $parameters = null) {
304
        @$parameters or $parameters = array();
305
        $this->parameters = $parameters;
306
        $this->http_method = $http_method;
307
        $this->http_url = $http_url;
308
    }
309
 
310
    /**
311
     * attempt to build up a request from what was passed to the server
312
     */
313
    public static function from_request($http_method = null, $http_url = null, $parameters = null) {
314
        $scheme = (!is_https()) ? 'http' : 'https';
315
        $port = "";
316
        if ($_SERVER['SERVER_PORT'] != "80" && $_SERVER['SERVER_PORT'] != "443" && strpos(':', $_SERVER['HTTP_HOST']) < 0) {
317
            $port = ':' . $_SERVER['SERVER_PORT'];
318
        }
319
        @$http_url or $http_url = $scheme .
320
        '://' . $_SERVER['HTTP_HOST'] .
321
        $port .
322
        $_SERVER['REQUEST_URI'];
323
        @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
324
 
325
        // We weren't handed any parameters, so let's find the ones relevant to
326
        // this request.
327
        // If you run XML-RPC or similar you should use this to provide your own
328
        // parsed parameter-list
329
        if (!$parameters) {
330
            // Find request headers
331
            $request_headers = OAuthUtil::get_headers();
332
 
333
            // Parse the query-string to find GET parameters
334
            $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
335
 
336
            $ourpost = $_POST;
337
            // Add POST Parameters if they exist
338
            $parameters = array_merge($parameters, $ourpost);
339
 
340
            // We have a Authorization-header with OAuth data. Parse the header
341
            // and add those overriding any duplicates from GET or POST
342
            if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
343
                $header_parameters = OAuthUtil::split_header($request_headers['Authorization']);
344
                $parameters = array_merge($parameters, $header_parameters);
345
            }
346
 
347
        }
348
 
349
        return new OAuthRequest($http_method, $http_url, $parameters);
350
    }
351
 
352
    /**
353
     * pretty much a helper function to set up the request
354
     */
355
    public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters = null) {
356
        @$parameters or $parameters = array();
357
        $defaults = array(
358
            "oauth_version" => self::$version,
359
            "oauth_nonce" => self::generate_nonce(),
360
            "oauth_timestamp" => self::generate_timestamp(),
361
            "oauth_consumer_key" => $consumer->key
362
        );
363
        if ($token) {
364
            $defaults['oauth_token'] = $token->key;
365
        }
366
 
367
        $parameters = array_merge($defaults, $parameters);
368
 
369
        // Parse the query-string to find and add GET parameters
370
        $parts = parse_url($http_url);
371
        if (isset($parts['query'])) {
372
            $qparms = OAuthUtil::parse_parameters($parts['query']);
373
            $parameters = array_merge($qparms, $parameters);
374
        }
375
 
376
        return new OAuthRequest($http_method, $http_url, $parameters);
377
    }
378
 
379
    public function set_parameter($name, $value, $allow_duplicates = true) {
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
        return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
396
    }
397
 
398
    public function get_parameters() {
399
        return $this->parameters;
400
    }
401
 
402
    public function unset_parameter($name) {
403
        unset($this->parameters[$name]);
404
    }
405
 
406
    /**
407
     * The request parameters, sorted and concatenated into a normalized string.
408
     * @return string
409
     */
410
    public function get_signable_parameters() {
411
        // Grab all parameters
412
        $params = $this->parameters;
413
 
414
        // Remove oauth_signature if present
415
        // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
416
        if (isset($params['oauth_signature'])) {
417
            unset($params['oauth_signature']);
418
        }
419
 
420
        return OAuthUtil::build_http_query($params);
421
    }
422
 
423
    /**
424
     * Returns the base string of this request
425
     *
426
     * The base string defined as the method, the url
427
     * and the parameters (normalized), each urlencoded
428
     * and the concated with &.
429
     */
430
    public function get_signature_base_string() {
431
        $parts = array(
432
            $this->get_normalized_http_method(),
433
            $this->get_normalized_http_url(),
434
            $this->get_signable_parameters()
435
        );
436
 
437
        $parts = OAuthUtil::urlencode_rfc3986($parts);
438
 
439
        return implode('&', $parts);
440
    }
441
 
442
    /**
443
     * just uppercases the http method
444
     */
445
    public function get_normalized_http_method() {
446
        return strtoupper($this->http_method);
447
    }
448
 
449
    /**
450
     * Parses {@see http_url} and returns normalized scheme://host/path if non-empty, otherwise return empty string
451
     *
452
     * @return string
453
     */
454
    public function get_normalized_http_url() {
455
        if ($this->http_url === '') {
456
            return '';
457
        }
458
 
459
        $parts = parse_url($this->http_url);
460
 
461
        $port = @$parts['port'];
462
        $scheme = $parts['scheme'];
463
        $host = $parts['host'];
464
        $path = @$parts['path'];
465
 
466
        $port or $port = ($scheme == 'https') ? '443' : '80';
467
 
468
        if (($scheme == 'https' && $port != '443') || ($scheme == 'http' && $port != '80')) {
469
            $host = "$host:$port";
470
        }
471
        return "$scheme://$host$path";
472
    }
473
 
474
    /**
475
     * builds a url usable for a GET request
476
     */
477
    public function to_url() {
478
        $post_data = $this->to_postdata();
479
        $out = $this->get_normalized_http_url();
480
        if ($post_data) {
481
            $out .= '?'.$post_data;
482
        }
483
        return $out;
484
    }
485
 
486
    /**
487
     * builds the data one would send in a POST request
488
     */
489
    public function to_postdata() {
490
        return OAuthUtil::build_http_query($this->parameters);
491
    }
492
 
493
    /**
494
     * builds the Authorization: header
495
     */
496
    public function to_header() {
497
        $out = 'Authorization: OAuth realm=""';
498
        $total = array();
499
        foreach ($this->parameters as $k => $v) {
500
            if (substr($k, 0, 5) != "oauth") {
501
                continue;
502
            }
503
            if (is_array($v)) {
504
                throw new OAuthException('Arrays not supported in headers');
505
            }
506
            $out .= ',' .
507
            OAuthUtil::urlencode_rfc3986($k) .
508
            '="' .
509
            OAuthUtil::urlencode_rfc3986($v) .
510
            '"';
511
        }
512
        return $out;
513
    }
514
 
515
    public function __toString() {
516
        return $this->to_url();
517
    }
518
 
519
    public function sign_request($signature_method, $consumer, $token) {
520
        $this->set_parameter("oauth_signature_method", $signature_method->get_name(), false);
521
        $signature = $this->build_signature($signature_method, $consumer, $token);
522
        $this->set_parameter("oauth_signature", $signature, false);
523
    }
524
 
525
    public function build_signature($signature_method, $consumer, $token) {
526
        $signature = $signature_method->build_signature($this, $consumer, $token);
527
        return $signature;
528
    }
529
 
530
    /**
531
     * util function: current timestamp
532
     */
533
    private static function generate_timestamp() {
534
        return time();
535
    }
536
 
537
    /**
538
     * util function: current nonce
539
     */
540
    private static function generate_nonce() {
541
        $mt = microtime();
542
        $rand = mt_rand();
543
 
544
        return md5($mt.$rand); // md5s look nicer than numbers
545
    }
546
}
547
 
548
class OAuthServer {
549
    protected $timestamp_threshold = 300; // in seconds, five minutes
550
    protected $version = 1.0; // hi blaine
551
    protected $signature_methods = array();
552
    protected $data_store;
553
 
554
    function __construct($data_store) {
555
        $this->data_store = $data_store;
556
    }
557
 
558
    public function add_signature_method($signature_method) {
559
        $this->signature_methods[$signature_method->get_name()] = $signature_method;
560
    }
561
 
562
    // high level functions
563
 
564
    /**
565
     * process a request_token request
566
     * returns the request token on success
567
     */
568
    public function fetch_request_token(&$request) {
569
        $this->get_version($request);
570
 
571
        $consumer = $this->get_consumer($request);
572
 
573
        // no token required for the initial token request
574
        $token = null;
575
 
576
        $this->check_signature($request, $consumer, $token);
577
 
578
        $new_token = $this->data_store->new_request_token($consumer);
579
 
580
        return $new_token;
581
    }
582
 
583
    /**
584
     * process an access_token request
585
     * returns the access token on success
586
     */
587
    public function fetch_access_token(&$request) {
588
        $this->get_version($request);
589
 
590
        $consumer = $this->get_consumer($request);
591
 
592
        // requires authorized request token
593
        $token = $this->get_token($request, $consumer, "request");
594
 
595
        $this->check_signature($request, $consumer, $token);
596
 
597
        $new_token = $this->data_store->new_access_token($token, $consumer);
598
 
599
        return $new_token;
600
    }
601
 
602
    /**
603
     * verify an api call, checks all the parameters
604
     */
605
    public function verify_request(&$request) {
606
        global $lastcomputedsignature;
607
        $lastcomputedsignature = false;
608
        $this->get_version($request);
609
        $consumer = $this->get_consumer($request);
610
        $token = $this->get_token($request, $consumer, "access");
611
        $this->check_signature($request, $consumer, $token);
612
        return array(
613
            $consumer,
614
            $token
615
        );
616
    }
617
 
618
    // Internals from here
619
    /**
620
     * version 1
621
     */
622
    private function get_version(&$request) {
623
        $version = $request->get_parameter("oauth_version");
624
        if (!$version) {
625
            $version = 1.0;
626
        }
627
        if ($version && $version != $this->version) {
628
            throw new OAuthException("OAuth version '$version' not supported");
629
        }
630
        return $version;
631
    }
632
 
633
    /**
634
     * figure out the signature with some defaults
635
     */
636
    private function get_signature_method(&$request) {
637
        $signature_method = @ $request->get_parameter("oauth_signature_method");
638
        if (!$signature_method) {
639
            $signature_method = "PLAINTEXT";
640
        }
641
        if (!in_array($signature_method, array_keys($this->signature_methods))) {
642
            throw new OAuthException("Signature method '$signature_method' not supported " .
643
            "try one of the following: " .
644
            implode(", ", array_keys($this->signature_methods)));
645
        }
646
        return $this->signature_methods[$signature_method];
647
    }
648
 
649
    /**
650
     * try to find the consumer for the provided request's consumer key
651
     */
652
    private function get_consumer(&$request) {
653
        $consumer_key = @ $request->get_parameter("oauth_consumer_key");
654
        if (!$consumer_key) {
655
            throw new OAuthException("Invalid consumer key");
656
        }
657
 
658
        $consumer = $this->data_store->lookup_consumer($consumer_key);
659
        if (!$consumer) {
660
            throw new OAuthException("Invalid consumer");
661
        }
662
 
663
        return $consumer;
664
    }
665
 
666
    /**
667
     * try to find the token for the provided request's token key
668
     */
669
    private function get_token(&$request, $consumer, $token_type = "access") {
670
        $token_field = @ $request->get_parameter('oauth_token');
671
        if (!$token_field) {
672
            return false;
673
        }
674
        $token = $this->data_store->lookup_token($consumer, $token_type, $token_field);
675
        if (!$token) {
676
            throw new OAuthException("Invalid $token_type token: $token_field");
677
        }
678
        return $token;
679
    }
680
 
681
    /**
682
     * all-in-one function to check the signature on a request
683
     * should guess the signature method appropriately
684
     */
685
    private function check_signature(&$request, $consumer, $token) {
686
        // this should probably be in a different method
687
        global $lastcomputedsignature;
688
        $lastcomputedsignature = false;
689
 
690
        $timestamp = @ $request->get_parameter('oauth_timestamp');
691
        $nonce = @ $request->get_parameter('oauth_nonce');
692
 
693
        $this->check_timestamp($timestamp);
694
        $this->check_nonce($consumer, $token, $nonce, $timestamp);
695
 
696
        $signature_method = $this->get_signature_method($request);
697
 
698
        $signature = $request->get_parameter('oauth_signature');
699
        $valid_sig = $signature_method->check_signature($request, $consumer, $token, $signature);
700
 
701
        if (!$valid_sig) {
702
            $ex_text = "Invalid signature";
703
            if ($lastcomputedsignature) {
704
                $ex_text = $ex_text . " ours= $lastcomputedsignature yours=$signature";
705
            }
706
            throw new OAuthException($ex_text);
707
        }
708
    }
709
 
710
    /**
711
     * check that the timestamp is new enough
712
     */
713
    private function check_timestamp($timestamp) {
714
        // verify that timestamp is recentish
715
        $now = time();
716
        if ($now - $timestamp > $this->timestamp_threshold) {
717
            throw new OAuthException("Expired timestamp, yours $timestamp, ours $now");
718
        }
719
    }
720
 
721
    /**
722
     * check that the nonce is not repeated
723
     */
724
    private function check_nonce($consumer, $token, $nonce, $timestamp) {
725
        // verify that the nonce is uniqueish
726
        $found = $this->data_store->lookup_nonce($consumer, $token, $nonce, $timestamp);
727
        if ($found) {
728
            throw new OAuthException("Nonce already used: $nonce");
729
        }
730
    }
731
 
732
}
733
 
734
class OAuthDataStore {
735
    function lookup_consumer($consumer_key) {
736
        // implement me
737
    }
738
 
739
    function lookup_token($consumer, $token_type, $token) {
740
        // implement me
741
    }
742
 
743
    function lookup_nonce($consumer, $token, $nonce, $timestamp) {
744
        // implement me
745
    }
746
 
747
    function new_request_token($consumer) {
748
        // return a new token attached to this consumer
749
    }
750
 
751
    function new_access_token($token, $consumer) {
752
        // return a new access token attached to this consumer
753
        // for the user associated with this token if the request token
754
        // is authorized
755
        // should also invalidate the request token
756
    }
757
 
758
}
759
 
760
class OAuthUtil {
761
    public static function urlencode_rfc3986($input) {
762
        if (is_array($input)) {
763
            return array_map(array(
764
                'moodle\mod\lti\OAuthUtil',
765
                'urlencode_rfc3986'
766
            ), $input);
767
        } else {
768
            if (is_scalar($input)) {
769
                return str_replace('+', ' ', str_replace('%7E', '~', rawurlencode($input)));
770
            } else {
771
                return '';
772
            }
773
        }
774
    }
775
 
776
    // This decode function isn't taking into consideration the above
777
    // modifications to the encoding process. However, this method doesn't
778
    // seem to be used anywhere so leaving it as is.
779
    public static function urldecode_rfc3986($string) {
780
        return urldecode($string);
781
    }
782
 
783
    // Utility function for turning the Authorization: header into
784
    // parameters, has to do some unescaping
785
    // Can filter out any non-oauth parameters if needed (default behaviour)
786
    public static function split_header($header, $only_allow_oauth_parameters = true) {
787
        $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
788
        $offset = 0;
789
        $params = array();
790
        while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
791
            $match = $matches[0];
792
            $header_name = $matches[2][0];
793
            $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
794
            if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
795
                $params[$header_name] = self::urldecode_rfc3986($header_content);
796
            }
797
            $offset = $match[1] + strlen($match[0]);
798
        }
799
 
800
        if (isset($params['realm'])) {
801
            unset($params['realm']);
802
        }
803
 
804
        return $params;
805
    }
806
 
807
    // helper to try to sort out headers for people who aren't running apache
808
    public static function get_headers() {
809
        if (function_exists('apache_request_headers')) {
810
            // we need this to get the actual Authorization: header
811
            // because apache tends to tell us it doesn't exist
812
            $in = apache_request_headers();
813
            $out = array();
814
            foreach ($in as $key => $value) {
815
                $key = str_replace(" ", "-", ucwords(strtolower(str_replace("-", " ", $key))));
816
                $out[$key] = $value;
817
            }
818
            return $out;
819
        }
820
        // otherwise we don't have apache and are just going to have to hope
821
        // that $_SERVER actually contains what we need
822
        $out = array();
823
        foreach ($_SERVER as $key => $value) {
824
            if (substr($key, 0, 5) == "HTTP_") {
825
                // this is chaos, basically it is just there to capitalize the first
826
                // letter of every word that is not an initial HTTP and strip HTTP
827
                // code from przemek
828
                $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
829
                $out[$key] = $value;
830
            }
831
        }
832
        return $out;
833
    }
834
 
835
    // This function takes a input like a=b&a=c&d=e and returns the parsed
836
    // parameters like this
837
    // array('a' => array('b','c'), 'd' => 'e')
838
    public static function parse_parameters($input) {
839
        if (!isset($input) || !$input) {
840
            return array();
841
        }
842
 
843
        $pairs = explode('&', $input);
844
 
845
        $parsed_parameters = array();
846
        foreach ($pairs as $pair) {
847
            $split = explode('=', $pair, 2);
848
            $parameter = self::urldecode_rfc3986($split[0]);
849
            $value = isset($split[1]) ? self::urldecode_rfc3986($split[1]) : '';
850
 
851
            if (isset($parsed_parameters[$parameter])) {
852
                // We have already recieved parameter(s) with this name, so add to the list
853
                // of parameters with this name
854
 
855
                if (is_scalar($parsed_parameters[$parameter])) {
856
                    // This is the first duplicate, so transform scalar (string) into an array
857
                    // so we can add the duplicates
858
                    $parsed_parameters[$parameter] = array(
859
                        $parsed_parameters[$parameter]
860
                    );
861
                }
862
 
863
                $parsed_parameters[$parameter][] = $value;
864
            } else {
865
                $parsed_parameters[$parameter] = $value;
866
            }
867
        }
868
        return $parsed_parameters;
869
    }
870
 
871
    public static function build_http_query($params) {
872
        if (!$params) {
873
            return '';
874
        }
875
 
876
        // Urlencode both keys and values
877
        $keys = self::urlencode_rfc3986(array_keys($params));
878
        $values = self::urlencode_rfc3986(array_values($params));
879
        $params = array_combine($keys, $values);
880
 
881
        // Parameters are sorted by name, using lexicographical byte value ordering.
882
        // Ref: Spec: 9.1.1 (1)
883
        uksort($params, 'strcmp');
884
 
885
        $pairs = array();
886
        foreach ($params as $parameter => $value) {
887
            if (is_array($value)) {
888
                // If two or more parameters share the same name, they are sorted by their value
889
                // Ref: Spec: 9.1.1 (1)
890
                natsort($value);
891
                foreach ($value as $duplicate_value) {
892
                    $pairs[] = $parameter . '=' . $duplicate_value;
893
                }
894
            } else {
895
                $pairs[] = $parameter . '=' . $value;
896
            }
897
        }
898
        // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
899
        // Each name-value pair is separated by an '&' character (ASCII code 38)
900
        return implode('&', $pairs);
901
    }
902
}