Proyectos de Subversion Moodle

Rev

| 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
        // TODO: Remove this block once PHP 8.0 becomes required.
274
        if (PHP_MAJOR_VERSION < 8) {
275
            // Release the key resource
276
            openssl_free_key($privatekeyid);
277
        }
278
 
279
        return base64_encode($signature);
280
    }
281
 
282
    public function check_signature(&$request, $consumer, $token, $signature) {
283
        $decoded_sig = base64_decode($signature);
284
 
285
        $base_string = $request->get_signature_base_string();
286
 
287
        // Fetch the public key cert based on the request
288
        $cert = $this->fetch_public_cert($request);
289
 
290
        // Pull the public key ID from the certificate
291
        $publickeyid = openssl_get_publickey($cert);
292
 
293
        // Check the computed signature against the one passed in the query
294
        $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
295
 
296
        // TODO: Remove this block once PHP 8.0 becomes required.
297
        if (PHP_MAJOR_VERSION < 8) {
298
            // Release the key resource
299
            openssl_free_key($publickeyid);
300
        }
301
 
302
        return $ok == 1;
303
    }
304
}
305
 
306
class OAuthRequest {
307
    private $parameters;
308
    private $http_method;
309
    private $http_url;
310
    // for debug purposes
311
    public $base_string;
312
    public static $version = '1.0';
313
    public static $POST_INPUT = 'php://input';
314
 
315
    function __construct($http_method, $http_url, $parameters = null) {
316
        @$parameters or $parameters = array();
317
        $this->parameters = $parameters;
318
        $this->http_method = $http_method;
319
        $this->http_url = $http_url;
320
    }
321
 
322
    /**
323
     * attempt to build up a request from what was passed to the server
324
     */
325
    public static function from_request($http_method = null, $http_url = null, $parameters = null) {
326
        $scheme = (!is_https()) ? 'http' : 'https';
327
        $port = "";
328
        if ($_SERVER['SERVER_PORT'] != "80" && $_SERVER['SERVER_PORT'] != "443" && strpos(':', $_SERVER['HTTP_HOST']) < 0) {
329
            $port = ':' . $_SERVER['SERVER_PORT'];
330
        }
331
        @$http_url or $http_url = $scheme .
332
        '://' . $_SERVER['HTTP_HOST'] .
333
        $port .
334
        $_SERVER['REQUEST_URI'];
335
        @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
336
 
337
        // We weren't handed any parameters, so let's find the ones relevant to
338
        // this request.
339
        // If you run XML-RPC or similar you should use this to provide your own
340
        // parsed parameter-list
341
        if (!$parameters) {
342
            // Find request headers
343
            $request_headers = OAuthUtil::get_headers();
344
 
345
            // Parse the query-string to find GET parameters
346
            $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
347
 
348
            $ourpost = $_POST;
349
            // Add POST Parameters if they exist
350
            $parameters = array_merge($parameters, $ourpost);
351
 
352
            // We have a Authorization-header with OAuth data. Parse the header
353
            // and add those overriding any duplicates from GET or POST
354
            if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
355
                $header_parameters = OAuthUtil::split_header($request_headers['Authorization']);
356
                $parameters = array_merge($parameters, $header_parameters);
357
            }
358
 
359
        }
360
 
361
        return new OAuthRequest($http_method, $http_url, $parameters);
362
    }
363
 
364
    /**
365
     * pretty much a helper function to set up the request
366
     */
367
    public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters = null) {
368
        @$parameters or $parameters = array();
369
        $defaults = array(
370
            "oauth_version" => self::$version,
371
            "oauth_nonce" => self::generate_nonce(),
372
            "oauth_timestamp" => self::generate_timestamp(),
373
            "oauth_consumer_key" => $consumer->key
374
        );
375
        if ($token) {
376
            $defaults['oauth_token'] = $token->key;
377
        }
378
 
379
        $parameters = array_merge($defaults, $parameters);
380
 
381
        // Parse the query-string to find and add GET parameters
382
        $parts = parse_url($http_url);
383
        if (isset($parts['query'])) {
384
            $qparms = OAuthUtil::parse_parameters($parts['query']);
385
            $parameters = array_merge($qparms, $parameters);
386
        }
387
 
388
        return new OAuthRequest($http_method, $http_url, $parameters);
389
    }
390
 
391
    public function set_parameter($name, $value, $allow_duplicates = true) {
392
        if ($allow_duplicates && isset($this->parameters[$name])) {
393
            // We have already added parameter(s) with this name, so add to the list
394
            if (is_scalar($this->parameters[$name])) {
395
                // This is the first duplicate, so transform scalar (string)
396
                // into an array so we can add the duplicates
397
                $this->parameters[$name] = array($this->parameters[$name]);
398
            }
399
 
400
            $this->parameters[$name][] = $value;
401
        } else {
402
            $this->parameters[$name] = $value;
403
        }
404
    }
405
 
406
    public function get_parameter($name) {
407
        return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
408
    }
409
 
410
    public function get_parameters() {
411
        return $this->parameters;
412
    }
413
 
414
    public function unset_parameter($name) {
415
        unset($this->parameters[$name]);
416
    }
417
 
418
    /**
419
     * The request parameters, sorted and concatenated into a normalized string.
420
     * @return string
421
     */
422
    public function get_signable_parameters() {
423
        // Grab all parameters
424
        $params = $this->parameters;
425
 
426
        // Remove oauth_signature if present
427
        // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
428
        if (isset($params['oauth_signature'])) {
429
            unset($params['oauth_signature']);
430
        }
431
 
432
        return OAuthUtil::build_http_query($params);
433
    }
434
 
435
    /**
436
     * Returns the base string of this request
437
     *
438
     * The base string defined as the method, the url
439
     * and the parameters (normalized), each urlencoded
440
     * and the concated with &.
441
     */
442
    public function get_signature_base_string() {
443
        $parts = array(
444
            $this->get_normalized_http_method(),
445
            $this->get_normalized_http_url(),
446
            $this->get_signable_parameters()
447
        );
448
 
449
        $parts = OAuthUtil::urlencode_rfc3986($parts);
450
 
451
        return implode('&', $parts);
452
    }
453
 
454
    /**
455
     * just uppercases the http method
456
     */
457
    public function get_normalized_http_method() {
458
        return strtoupper($this->http_method);
459
    }
460
 
461
    /**
462
     * Parses {@see http_url} and returns normalized scheme://host/path if non-empty, otherwise return empty string
463
     *
464
     * @return string
465
     */
466
    public function get_normalized_http_url() {
467
        if ($this->http_url === '') {
468
            return '';
469
        }
470
 
471
        $parts = parse_url($this->http_url);
472
 
473
        $port = @$parts['port'];
474
        $scheme = $parts['scheme'];
475
        $host = $parts['host'];
476
        $path = @$parts['path'];
477
 
478
        $port or $port = ($scheme == 'https') ? '443' : '80';
479
 
480
        if (($scheme == 'https' && $port != '443') || ($scheme == 'http' && $port != '80')) {
481
            $host = "$host:$port";
482
        }
483
        return "$scheme://$host$path";
484
    }
485
 
486
    /**
487
     * builds a url usable for a GET request
488
     */
489
    public function to_url() {
490
        $post_data = $this->to_postdata();
491
        $out = $this->get_normalized_http_url();
492
        if ($post_data) {
493
            $out .= '?'.$post_data;
494
        }
495
        return $out;
496
    }
497
 
498
    /**
499
     * builds the data one would send in a POST request
500
     */
501
    public function to_postdata() {
502
        return OAuthUtil::build_http_query($this->parameters);
503
    }
504
 
505
    /**
506
     * builds the Authorization: header
507
     */
508
    public function to_header() {
509
        $out = 'Authorization: OAuth realm=""';
510
        $total = array();
511
        foreach ($this->parameters as $k => $v) {
512
            if (substr($k, 0, 5) != "oauth") {
513
                continue;
514
            }
515
            if (is_array($v)) {
516
                throw new OAuthException('Arrays not supported in headers');
517
            }
518
            $out .= ',' .
519
            OAuthUtil::urlencode_rfc3986($k) .
520
            '="' .
521
            OAuthUtil::urlencode_rfc3986($v) .
522
            '"';
523
        }
524
        return $out;
525
    }
526
 
527
    public function __toString() {
528
        return $this->to_url();
529
    }
530
 
531
    public function sign_request($signature_method, $consumer, $token) {
532
        $this->set_parameter("oauth_signature_method", $signature_method->get_name(), false);
533
        $signature = $this->build_signature($signature_method, $consumer, $token);
534
        $this->set_parameter("oauth_signature", $signature, false);
535
    }
536
 
537
    public function build_signature($signature_method, $consumer, $token) {
538
        $signature = $signature_method->build_signature($this, $consumer, $token);
539
        return $signature;
540
    }
541
 
542
    /**
543
     * util function: current timestamp
544
     */
545
    private static function generate_timestamp() {
546
        return time();
547
    }
548
 
549
    /**
550
     * util function: current nonce
551
     */
552
    private static function generate_nonce() {
553
        $mt = microtime();
554
        $rand = mt_rand();
555
 
556
        return md5($mt.$rand); // md5s look nicer than numbers
557
    }
558
}
559
 
560
class OAuthServer {
561
    protected $timestamp_threshold = 300; // in seconds, five minutes
562
    protected $version = 1.0; // hi blaine
563
    protected $signature_methods = array();
564
    protected $data_store;
565
 
566
    function __construct($data_store) {
567
        $this->data_store = $data_store;
568
    }
569
 
570
    public function add_signature_method($signature_method) {
571
        $this->signature_methods[$signature_method->get_name()] = $signature_method;
572
    }
573
 
574
    // high level functions
575
 
576
    /**
577
     * process a request_token request
578
     * returns the request token on success
579
     */
580
    public function fetch_request_token(&$request) {
581
        $this->get_version($request);
582
 
583
        $consumer = $this->get_consumer($request);
584
 
585
        // no token required for the initial token request
586
        $token = null;
587
 
588
        $this->check_signature($request, $consumer, $token);
589
 
590
        $new_token = $this->data_store->new_request_token($consumer);
591
 
592
        return $new_token;
593
    }
594
 
595
    /**
596
     * process an access_token request
597
     * returns the access token on success
598
     */
599
    public function fetch_access_token(&$request) {
600
        $this->get_version($request);
601
 
602
        $consumer = $this->get_consumer($request);
603
 
604
        // requires authorized request token
605
        $token = $this->get_token($request, $consumer, "request");
606
 
607
        $this->check_signature($request, $consumer, $token);
608
 
609
        $new_token = $this->data_store->new_access_token($token, $consumer);
610
 
611
        return $new_token;
612
    }
613
 
614
    /**
615
     * verify an api call, checks all the parameters
616
     */
617
    public function verify_request(&$request) {
618
        global $lastcomputedsignature;
619
        $lastcomputedsignature = false;
620
        $this->get_version($request);
621
        $consumer = $this->get_consumer($request);
622
        $token = $this->get_token($request, $consumer, "access");
623
        $this->check_signature($request, $consumer, $token);
624
        return array(
625
            $consumer,
626
            $token
627
        );
628
    }
629
 
630
    // Internals from here
631
    /**
632
     * version 1
633
     */
634
    private function get_version(&$request) {
635
        $version = $request->get_parameter("oauth_version");
636
        if (!$version) {
637
            $version = 1.0;
638
        }
639
        if ($version && $version != $this->version) {
640
            throw new OAuthException("OAuth version '$version' not supported");
641
        }
642
        return $version;
643
    }
644
 
645
    /**
646
     * figure out the signature with some defaults
647
     */
648
    private function get_signature_method(&$request) {
649
        $signature_method = @ $request->get_parameter("oauth_signature_method");
650
        if (!$signature_method) {
651
            $signature_method = "PLAINTEXT";
652
        }
653
        if (!in_array($signature_method, array_keys($this->signature_methods))) {
654
            throw new OAuthException("Signature method '$signature_method' not supported " .
655
            "try one of the following: " .
656
            implode(", ", array_keys($this->signature_methods)));
657
        }
658
        return $this->signature_methods[$signature_method];
659
    }
660
 
661
    /**
662
     * try to find the consumer for the provided request's consumer key
663
     */
664
    private function get_consumer(&$request) {
665
        $consumer_key = @ $request->get_parameter("oauth_consumer_key");
666
        if (!$consumer_key) {
667
            throw new OAuthException("Invalid consumer key");
668
        }
669
 
670
        $consumer = $this->data_store->lookup_consumer($consumer_key);
671
        if (!$consumer) {
672
            throw new OAuthException("Invalid consumer");
673
        }
674
 
675
        return $consumer;
676
    }
677
 
678
    /**
679
     * try to find the token for the provided request's token key
680
     */
681
    private function get_token(&$request, $consumer, $token_type = "access") {
682
        $token_field = @ $request->get_parameter('oauth_token');
683
        if (!$token_field) {
684
            return false;
685
        }
686
        $token = $this->data_store->lookup_token($consumer, $token_type, $token_field);
687
        if (!$token) {
688
            throw new OAuthException("Invalid $token_type token: $token_field");
689
        }
690
        return $token;
691
    }
692
 
693
    /**
694
     * all-in-one function to check the signature on a request
695
     * should guess the signature method appropriately
696
     */
697
    private function check_signature(&$request, $consumer, $token) {
698
        // this should probably be in a different method
699
        global $lastcomputedsignature;
700
        $lastcomputedsignature = false;
701
 
702
        $timestamp = @ $request->get_parameter('oauth_timestamp');
703
        $nonce = @ $request->get_parameter('oauth_nonce');
704
 
705
        $this->check_timestamp($timestamp);
706
        $this->check_nonce($consumer, $token, $nonce, $timestamp);
707
 
708
        $signature_method = $this->get_signature_method($request);
709
 
710
        $signature = $request->get_parameter('oauth_signature');
711
        $valid_sig = $signature_method->check_signature($request, $consumer, $token, $signature);
712
 
713
        if (!$valid_sig) {
714
            $ex_text = "Invalid signature";
715
            if ($lastcomputedsignature) {
716
                $ex_text = $ex_text . " ours= $lastcomputedsignature yours=$signature";
717
            }
718
            throw new OAuthException($ex_text);
719
        }
720
    }
721
 
722
    /**
723
     * check that the timestamp is new enough
724
     */
725
    private function check_timestamp($timestamp) {
726
        // verify that timestamp is recentish
727
        $now = time();
728
        if ($now - $timestamp > $this->timestamp_threshold) {
729
            throw new OAuthException("Expired timestamp, yours $timestamp, ours $now");
730
        }
731
    }
732
 
733
    /**
734
     * check that the nonce is not repeated
735
     */
736
    private function check_nonce($consumer, $token, $nonce, $timestamp) {
737
        // verify that the nonce is uniqueish
738
        $found = $this->data_store->lookup_nonce($consumer, $token, $nonce, $timestamp);
739
        if ($found) {
740
            throw new OAuthException("Nonce already used: $nonce");
741
        }
742
    }
743
 
744
}
745
 
746
class OAuthDataStore {
747
    function lookup_consumer($consumer_key) {
748
        // implement me
749
    }
750
 
751
    function lookup_token($consumer, $token_type, $token) {
752
        // implement me
753
    }
754
 
755
    function lookup_nonce($consumer, $token, $nonce, $timestamp) {
756
        // implement me
757
    }
758
 
759
    function new_request_token($consumer) {
760
        // return a new token attached to this consumer
761
    }
762
 
763
    function new_access_token($token, $consumer) {
764
        // return a new access token attached to this consumer
765
        // for the user associated with this token if the request token
766
        // is authorized
767
        // should also invalidate the request token
768
    }
769
 
770
}
771
 
772
class OAuthUtil {
773
    public static function urlencode_rfc3986($input) {
774
        if (is_array($input)) {
775
            return array_map(array(
776
                'moodle\mod\lti\OAuthUtil',
777
                'urlencode_rfc3986'
778
            ), $input);
779
        } else {
780
            if (is_scalar($input)) {
781
                return str_replace('+', ' ', str_replace('%7E', '~', rawurlencode($input)));
782
            } else {
783
                return '';
784
            }
785
        }
786
    }
787
 
788
    // This decode function isn't taking into consideration the above
789
    // modifications to the encoding process. However, this method doesn't
790
    // seem to be used anywhere so leaving it as is.
791
    public static function urldecode_rfc3986($string) {
792
        return urldecode($string);
793
    }
794
 
795
    // Utility function for turning the Authorization: header into
796
    // parameters, has to do some unescaping
797
    // Can filter out any non-oauth parameters if needed (default behaviour)
798
    public static function split_header($header, $only_allow_oauth_parameters = true) {
799
        $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
800
        $offset = 0;
801
        $params = array();
802
        while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
803
            $match = $matches[0];
804
            $header_name = $matches[2][0];
805
            $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
806
            if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
807
                $params[$header_name] = self::urldecode_rfc3986($header_content);
808
            }
809
            $offset = $match[1] + strlen($match[0]);
810
        }
811
 
812
        if (isset($params['realm'])) {
813
            unset($params['realm']);
814
        }
815
 
816
        return $params;
817
    }
818
 
819
    // helper to try to sort out headers for people who aren't running apache
820
    public static function get_headers() {
821
        if (function_exists('apache_request_headers')) {
822
            // we need this to get the actual Authorization: header
823
            // because apache tends to tell us it doesn't exist
824
            $in = apache_request_headers();
825
            $out = array();
826
            foreach ($in as $key => $value) {
827
                $key = str_replace(" ", "-", ucwords(strtolower(str_replace("-", " ", $key))));
828
                $out[$key] = $value;
829
            }
830
            return $out;
831
        }
832
        // otherwise we don't have apache and are just going to have to hope
833
        // that $_SERVER actually contains what we need
834
        $out = array();
835
        foreach ($_SERVER as $key => $value) {
836
            if (substr($key, 0, 5) == "HTTP_") {
837
                // this is chaos, basically it is just there to capitalize the first
838
                // letter of every word that is not an initial HTTP and strip HTTP
839
                // code from przemek
840
                $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
841
                $out[$key] = $value;
842
            }
843
        }
844
        return $out;
845
    }
846
 
847
    // This function takes a input like a=b&a=c&d=e and returns the parsed
848
    // parameters like this
849
    // array('a' => array('b','c'), 'd' => 'e')
850
    public static function parse_parameters($input) {
851
        if (!isset($input) || !$input) {
852
            return array();
853
        }
854
 
855
        $pairs = explode('&', $input);
856
 
857
        $parsed_parameters = array();
858
        foreach ($pairs as $pair) {
859
            $split = explode('=', $pair, 2);
860
            $parameter = self::urldecode_rfc3986($split[0]);
861
            $value = isset($split[1]) ? self::urldecode_rfc3986($split[1]) : '';
862
 
863
            if (isset($parsed_parameters[$parameter])) {
864
                // We have already recieved parameter(s) with this name, so add to the list
865
                // of parameters with this name
866
 
867
                if (is_scalar($parsed_parameters[$parameter])) {
868
                    // This is the first duplicate, so transform scalar (string) into an array
869
                    // so we can add the duplicates
870
                    $parsed_parameters[$parameter] = array(
871
                        $parsed_parameters[$parameter]
872
                    );
873
                }
874
 
875
                $parsed_parameters[$parameter][] = $value;
876
            } else {
877
                $parsed_parameters[$parameter] = $value;
878
            }
879
        }
880
        return $parsed_parameters;
881
    }
882
 
883
    public static function build_http_query($params) {
884
        if (!$params) {
885
            return '';
886
        }
887
 
888
        // Urlencode both keys and values
889
        $keys = self::urlencode_rfc3986(array_keys($params));
890
        $values = self::urlencode_rfc3986(array_values($params));
891
        $params = array_combine($keys, $values);
892
 
893
        // Parameters are sorted by name, using lexicographical byte value ordering.
894
        // Ref: Spec: 9.1.1 (1)
895
        uksort($params, 'strcmp');
896
 
897
        $pairs = array();
898
        foreach ($params as $parameter => $value) {
899
            if (is_array($value)) {
900
                // If two or more parameters share the same name, they are sorted by their value
901
                // Ref: Spec: 9.1.1 (1)
902
                natsort($value);
903
                foreach ($value as $duplicate_value) {
904
                    $pairs[] = $parameter . '=' . $duplicate_value;
905
                }
906
            } else {
907
                $pairs[] = $parameter . '=' . $value;
908
            }
909
        }
910
        // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
911
        // Each name-value pair is separated by an '&' character (ASCII code 38)
912
        return implode('&', $pairs);
913
    }
914
}