Passed
Push — master ( e2f802...d5face )
by Terrence
11:55
created

DBService::getLastArchivedUser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 6
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace CILogon\Service;
4
5
use CILogon\Service\Util;
6
7
/**
8
 * DBService
9
 *
10
 * This class is a wrapper for the dbService servlet.  The dbService
11
 * servlet acts as a frontend to the database that stores info on users,
12
 * portal parameters, and IdPs. This was created to allow for fast
13
 * access to the database by keeping a connection open.  This class is a
14
 * rework of the old store.php class.
15
 *
16
 * Example usage:
17
 *     // For authentication, we have a bunch of attributes from an
18
 *     // identity provider. Thus get the database uid for the user
19
 *     // by using the multi-parameter version of getUser().
20
 *     $uid = '';
21
 *     $dbservice = new DBService();
22
 *     $dbservice->getUser('[email protected]',
23
 *                         'urn:mace:incommon:uiuc.edu',
24
 *                         'University of Illinois at Urbana-Champaign',
25
 *                         'John','Smith','John Smith,
26
 *                          '[email protected]');
27
 *     if (!($dbservice->status & 1)) { // OK status codes are even
28
 *         $uid = $dbservice->user_uid;
29
 *     }
30
 *
31
 *     // Later in the code, re-fetch the user using this uid
32
 *     // and print out the stored attributes.
33
 *     if (strlen($uid) > 0) {
34
 *         $dbservice->getUser($uid);
35
 *         echo 'Name = ' . $dbservice->first_name . ' ' .
36
 *                          $dbservice->last_name  . "\n";
37
 *         echo 'DN = '   . $dbservice->distinguished_name . "\n";
38
 *     }
39
 *
40
 *     // For getting/setting the Shibboleth-based IdPs, use the
41
 *     // getIdps()/setIdps() methods.  These methods utilize the
42
 *     // class member array $idp_uids for reading/writing. Two
43
 *     // convenience methods (setIdpsFromKeys($array) and
44
 *     // setIdpsFromValues($array)) are provided to populate the
45
 *     // $idp_uids array from the passed-in $array.
46
 *     $dbservice->getIdps();
47
 *     foreach($dbservice->idp_uids as $value) {
48
 *         echo "$value\n";
49
 *     }
50
 *
51
 *     $idps = array('urn:mace:incommon:ucsd.edu',
52
 *                   'urn:mace:incommon:uiuc.edu');
53
 *     $dbservice->setIdpsFromValues($idps);
54
 *     //   --- OR ---
55
 *     $idps = array('urn:mace:incommon:ucsd.edu' => 1,
56
 *                   'urn:mace:incommon:uiuc.edu' => 1);
57
 *     $dbservice->setIdpsFromKeys($idps);
58
 */
59
60
class DBService
61
{
62
    /**
63
     * @var array $STATUS The various STATUS_* constants, originally from
64
     *      Store.pm. The keys of the array are strings corresponding to the
65
     *      constant names. The values of the array are the integer (hex)
66
     *      values. For example, DBService::$STATUS['STATUS_OK'] = 0;
67
     *      Use 'array_search($this->status,DBService::$STATUS)' to look
68
     *      up the STATUS_* name given the status integer value.
69
     */
70
    public static $STATUS = array(
71
        'STATUS_OK'                        => 0x0,
72
        'STATUS_ACTION_NOT_FOUND'          => 0x1,
73
        'STATUS_NEW_USER'                  => 0x2,
74
        'STATUS_USER_UPDATED'              => 0x4,
75
        'STATUS_USER_NOT_FOUND'            => 0x6,
76
        'STATUS_USER_EXISTS'               => 0x8,
77
        'STATUS_USER_EXISTS_ERROR'         => 0xFFFA1, // 1048481
78
        'STATUS_USER_NOT_FOUND_ERROR'      => 0xFFFA3, // 1048483
79
        'STATUS_TRANSACTION_NOT_FOUND'     => 0xFFFA5, // 1048485
80
        'STATUS_IDP_SAVE_FAILED'           => 0xFFFA7, // 1048487
81
        'STATUS_DUPLICATE_PARAMETER_FOUND' => 0xFFFF1, // 1048561
82
        'STATUS_INTERNAL_ERROR'            => 0xFFFF3, // 1048563
83
        'STATUS_SAVE_IDP_FAILED'           => 0xFFFF5, // 1048565
84
        'STATUS_MALFORMED_INPUT_ERROR'     => 0xFFFF7, // 1048567
85
        'STATUS_MISSING_PARAMETER_ERROR'   => 0xFFFF9, // 1048569
86
        'STATUS_NO_REMOTE_USER'            => 0xFFFFB, // 1048571
87
        'STATUS_NO_IDENTITY_PROVIDER'      => 0xFFFFD, // 1048573
88
        'STATUS_CLIENT_NOT_FOUND'          => 0xFFFFF, // 1048575
89
        'STATUS_TRANSACTION_NOT_FOUND'     => 0x10001, //   65537
90
        'STATUS_EPTID_MISMATCH'            => 0x100001,// 1048577
91
        'STATUS_PAIRWISE_ID_MISMATCH'      => 0x100003,// 1048579
92
        'STATUS_SUBJECT_ID_MISMATCH'       => 0x100005,// 1048581
93
        'STATUS_EXPIRED_TOKEN'             => 0x10003, //   65539
94
        'STATUS_CREATE_TRANSACTION_FAILED' => 0x10005, //   65541
95
        'STATUS_UNKNOWN_CALLBACK'          => 0x10007, //   65543
96
        'STATUS_MISSING_CLIENT_ID'         => 0x10009, //   65545
97
        'STATUS_NO_REGISTERED_CALLBACKS'   => 0x1000B, //   65547
98
        'STATUS_UNKNOWN_CLIENT'            => 0x1000D, //   65549
99
        'STATUS_UNAPPROVED_CLIENT'         => 0x1000F  //   65551
100
    );
101
102
    public static $STATUS_TEXT = array(
103
        'STATUS_OK'                        => 'Status OK.',
104
        'STATUS_ACTION_NOT_FOUND'          => 'Action not found.',
105
        'STATUS_NEW_USER'                  => 'New user created.',
106
        'STATUS_USER_UPDATED'              => 'User data updated.',
107
        'STATUS_USER_NOT_FOUND'            => 'User not found.',
108
        'STATUS_USER_EXISTS'               => 'User exists.',
109
        'STATUS_USER_EXISTS_ERROR'         => 'User already exists.',
110
        'STATUS_USER_NOT_FOUND_ERROR'      => 'User not found.',
111
        'STATUS_TRANSACTION_NOT_FOUND'     => 'Transaction not found.',
112
        'STATUS_IDP_SAVE_FAILED'           => 'Could not save IdPs.',
113
        'STATUS_DUPLICATE_PARAMETER_FOUND' => 'Duplicate parameter.',
114
        'STATUS_INTERNAL_ERROR'            => 'Internal error.',
115
        'STATUS_SAVE_IDP_FAILED'           => 'Could not save IdP.',
116
        'STATUS_MALFORMED_INPUT_ERROR'     => 'Malformed input.',
117
        'STATUS_MISSING_PARAMETER_ERROR'   => 'Missing parameter.',
118
        'STATUS_NO_REMOTE_USER'            => 'Missing Remote User.',
119
        'STATUS_NO_IDENTITY_PROVIDER'      => 'Missing IdP.',
120
        'STATUS_CLIENT_NOT_FOUND'          => 'Missing client.',
121
        'STATUS_TRANSACTION_NOT_FOUND'     => 'Transaction not found.',
122
        'STATUS_EPTID_MISMATCH'            => 'EPTID mismatch.',
123
        'STATUS_PAIRWISE_ID_MISMATCH'      => 'Pairwise ID mismatch.',
124
        'STATUS_SUBJECT_ID_MISMATCH'       => 'Subject ID mismatch.',
125
        'STATUS_EXPIRED_TOKEN'             => 'Expired token.',
126
        'STATUS_CREATE_TRANSACTION_FAILED' => 'Failed to initialize OIDC flow.',
127
        'STATUS_UNKNOWN_CALLBACK'          => 'The redirect_uri does not match a registered callback URI.',
128
        'STATUS_MISSING_CLIENT_ID'         => 'Missing client_id parameter.',
129
        'STATUS_NO_REGISTERED_CALLBACKS'   => 'No registered callback URIs.',
130
        'STATUS_UNKNOWN_CLIENT'            => 'Unknown client_id.',
131
        'STATUS_UNAPPROVED_CLIENT'         => 'Client has not been approved.'
132
    );
133
134
    /**
135
     * @var array $user_attrs An array of all the user attributes that
136
     *      get passed to the getUser function. This is available to other
137
     *      function since these user attributes are set frequently
138
     *      throughout the code.
139
     */
140
    public static $user_attrs = [
141
        'remote_user',
142
        'idp',
143
        'idp_display_name',
144
        'first_name',
145
        'last_name',
146
        'display_name',
147
        'email',
148
        'loa',
149
        'eppn',
150
        'eptid',
151
        'open_id',
152
        'oidc',
153
        'subject_id',
154
        'pairwise_id',
155
        'affiliation',
156
        'ou',
157
        'member_of',
158
        'acr',
159
        'entitlement',
160
        'itrustuin',
161
    ];
162
163
    /**
164
     * @var int|null $status The returned status code from dbService calls
165
     */
166
    public $status;
167
168
    /**
169
     * @var string|null $user_uid The CILogon UID
170
     */
171
    public $user_uid;
172
173
    /**
174
     * @var string|null $remote_user The HTTP session REMOTE_USER
175
     */
176
    public $remote_user;
177
178
    /**
179
     * @var string|null $idp The Identity Provider's entityId
180
     */
181
    public $idp;
182
183
    /**
184
     * @var string|null $idp_display_name The Identity Provider's name
185
     */
186
    public $idp_display_name;
187
188
    /**
189
     * @var string|null $first_name User's given name
190
     */
191
    public $first_name;
192
193
    /**
194
     * @var string|null $last_name User's family name
195
     */
196
    public $last_name;
197
198
    /**
199
     * @var string|null $display_name User's full name
200
     */
201
    public $display_name;
202
203
    /**
204
     * @var string|null $email User's email address
205
     */
206
    public $email;
207
208
    /**
209
     * @var string|null $loa Level of Assurance (Note: not saved in database)
210
     */
211
    public $loa;
212
213
    /**
214
     * @var string|null $distinguished_name X.509 DN + email address
215
     */
216
    public $distinguished_name;
217
218
    /**
219
     * @var string|null $eppn eduPersonPrincipalName
220
     */
221
    public $eppn;
222
223
    /**
224
     * @var string|null $eptid eduPersonTargetedID
225
     */
226
    public $eptid;
227
228
    /**
229
     * @var string|null $open_id Old Google OpenID 2.0 identifier
230
     */
231
    public $open_id;
232
233
    /**
234
     * @var string|null $oidc OpenID Connect identifier
235
     */
236
    public $oidc;
237
238
    /**
239
     * @var string|null $affiliation eduPersonScopedAffiliation
240
     */
241
    public $affiliation;
242
243
    /**
244
     * @var string|null $ou Organizational Unit
245
     */
246
    public $ou;
247
248
    /**
249
     * @var string|null $member_of isMemberOf group information
250
     */
251
    public $member_of;
252
253
    /**
254
     * @var string|null $acr Authentication Context Class Ref
255
     */
256
    public $acr;
257
258
    /**
259
     * @var string|null $entitlement eduPersonEntitlement
260
     */
261
    public $entitlement;
262
263
    /**
264
     * @var string|null $itrustuin Person's univeristy ID number
265
     */
266
    public $itrustuin;
267
268
    /**
269
     * @var string|null $subject_id Person's univeristy subject identifier
270
     */
271
    public $subject_id;
272
273
    /**
274
     * @var string|null $pairwise_id Person's univeristy pairwise identifier
275
     */
276
    public $pairwise_id;
277
278
    /**
279
     * @var string|null $serial_string CILogon serial string (e.g., A34201)
280
     */
281
    public $serial_string;
282
283
    /**
284
     * @var string|null $create_time Time user entry was created
285
     */
286
    public $create_time;
287
288
    /**
289
     * @var string|null $oauth_token OAuth 2.0 token
290
     */
291
    public $oauth_token;
292
293
    /**
294
     * @var string|null $cilogon_callback OAuth 1.0a callback URL
295
     */
296
    public $cilogon_callback;
297
298
    /**
299
     * @var string|null $cilogon_success OAuth 1.0a success URL
300
     */
301
    public $cilogon_success;
302
303
    /**
304
     * @var string|null $cilogon_failure OAuth 1.0a failure URL
305
     */
306
    public $cilogon_failure;
307
308
    /**
309
     * @var string|null $cilogon_portal_name OAuth client name
310
     */
311
    public $cilogon_portal_name;
312
313
    /**
314
     * @var array $idp_uids IdPs stored in the 'values' of the array
315
     */
316
    public $idp_uids;
317
318
    /**
319
     * @var string|null $client_name OAuth 2.0 client name
320
     */
321
    public $client_name;
322
323
    /**
324
     * @var string|null $client_id OAuth 2.0 client identifier
325
     */
326
    public $client_id;
327
328
    /**
329
     * @var string|null $client_home_uri OAuth 2.0 client home URL
330
     */
331
    public $client_home_uri;
332
333
    /**
334
     * @var array $client_callback_uris An array of OAuth 2.0 callback URLs
335
     */
336
    public $client_callback_uris;
337
338
    /**
339
     * @var string|null $dbservice URL The URL to use for the dbService
340
     */
341
    private $dbserviceurl;
342
343
    /**
344
     * __construct
345
     *
346
     * Default constructor.  All of the various class members are
347
     * initialized to 'null' or empty arrays.
348
     *
349
     * @param string $serviceurl (Optional) The URL of the database service
350
     *        servlet
351
     */
352
    public function __construct($serviceurl = DEFAULT_DBSERVICE_URL)
0 ignored issues
show
Bug introduced by
The constant CILogon\Service\DEFAULT_DBSERVICE_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
353
    {
354
        $this->clear();
355
        $this->setDBServiceURL($serviceurl);
356
    }
357
358
    /**
359
     * getDBServiceURL
360
     *
361
     * Returns the full URL of the database servlet used by the call()
362
     * function.
363
     *
364
     * @return string The URL of the database service servlet
365
     */
366
    public function getDBServiceURL()
367
    {
368
        return $this->dbserviceurl;
369
    }
370
371
    /**
372
     * setDBServiceURL
373
     *
374
     * Set the private variable $dbserviceurl to the full URL of the
375
     * database servlet, which is used by the call() function.
376
     *
377
     * @param string $serviceurl The URL of the database service servlet.
378
     */
379
    public function setDBServiceURL($serviceurl)
380
    {
381
        $this->dbserviceurl = $serviceurl;
382
    }
383
384
    /**
385
     * clear
386
     *
387
     * Set all of the class members to 'null' or empty arrays.
388
     */
389
    public function clear()
390
    {
391
        $this->clearUser();
392
        $this->clearPortal();
393
        $this->clearIdps();
394
        $this->clearClient();
395
    }
396
397
    /**
398
     * clearUser
399
     *
400
     * Set all of the class member variables associated with getUser()
401
     * to 'null'.
402
     */
403
    public function clearUser()
404
    {
405
        foreach (static::$user_attrs as $value) {
406
            $this->$value = null;
407
        }
408
        $this->status = null;
409
        $this->user_uid = null;
410
        $this->distinguished_name = null;
411
        $this->serial_string = null;
412
        $this->create_time = null;
413
    }
414
415
    /**
416
     * clearPortal
417
     *
418
     * Set all of the class member variables associated with
419
     * getPortalParameters() to 'null'.
420
     */
421
    public function clearPortal()
422
    {
423
        $this->status = null;
424
        $this->oauth_token = null;
425
        $this->cilogon_callback = null;
426
        $this->cilogon_success = null;
427
        $this->cilogon_failure = null;
428
        $this->cilogon_portal_name = null;
429
    }
430
431
    /**
432
     * clearIdps
433
     *
434
     * Set the class member variable $idp_uids to an empty array.
435
     */
436
    public function clearIdps()
437
    {
438
        $this->status = null;
439
        $this->idp_uids = array();
440
    }
441
442
    /**
443
     * clearClient
444
     *
445
     * Set all of the class member variables associated with
446
     * getClient() to 'null'.
447
     */
448
    public function clearClient()
449
    {
450
        $this->status = null;
451
        $this->client_name = null;
452
        $this->client_id = null;
453
        $this->client_home_uri = null;
454
        $this->client_callback_uris = array();
455
    }
456
457
    /**
458
     * getUser
459
     *
460
     * This method calls the 'getUser' action of the servlet and sets
461
     * the class member variables associated with user info
462
     * appropriately.  If the servlet returns correctly (i.e. an HTTP
463
     * status code of 200), this method returns true.
464
     *
465
     * @param mixed $args Variable number of parameters: 1, or more.
466
     *        For 1 parameter : $uid (database user identifier)
467
     *        For more than 1 parameter, parameters can include:
468
     *            $remote_user, $idp, $idp_display_name,
469
     *            $first_name, $last_name, $display_name, $email,
470
     *            $eppn, $eptid, $openid, $oidc,
471
     *            $subject_id, $pairwise_id, $affiliation,
472
     *            $ou, $member_of, $acr, $entitlement, $itrustuin
473
     *
474
     * @return bool True if the servlet returned correctly. Else false.
475
     */
476
    public function getUser(...$args)
477
    {
478
        $retval = false;
479
        $this->clearUser();
480
        $this->setDBServiceURL(DEFAULT_DBSERVICE_URL);
0 ignored issues
show
Bug introduced by
The constant CILogon\Service\DEFAULT_DBSERVICE_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
481
        $numargs = count($args);
482
        if ($numargs == 1) {
483
            $retval = $this->call('action=getUser&user_uid=' .
484
                urlencode($args[0]));
485
        } elseif ($numargs > 1) {
486
            $cmd = 'action=getUser';
487
            $attr_arr = array();
488
            $ou_pos = array_search('ou', static::$user_attrs);
489
            for ($i = 0; $i < $numargs; $i++) {
490
                $arg = $args[$i];
491
                if (strlen($arg) > 0) {
492
                    if ($i > $ou_pos) {
493
                        // Put params after $ou into JSON object
494
                        $attr_arr[static::$user_attrs[$i]] = $arg;
495
                    } else {
496
                        $cmd .= '&' . static::$user_attrs[$i] . '=' . urlencode($arg);
497
                    }
498
                }
499
            }
500
            // If any elements in $attr_arr, append converted JSON object
501
            if (count($attr_arr) > 0) {
502
                if (
503
                    ($attr_json = json_encode(
504
                        $attr_arr,
505
                        JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES
506
                    )
507
                    ) !== false
508
                ) {
509
                    $cmd .= '&attr_json=' . urlencode($attr_json);
510
                }
511
            }
512
            // Add 'us_idp' parameter for InCommon/Google (1) or eduGAIN (0)
513
            $us_idp = 0;
514
            $idp = $args[1];
515
            $idp_display_name = $args[2];
516
            if (
517
                (Util::getIdpList()->isRegisteredByInCommon($idp)) ||
518
                (in_array($idp_display_name, Util::$oauth2idps))
519
            ) {
520
                $us_idp = 1;
521
            }
522
            $cmd .= "&us_idp=$us_idp";
523
524
            $retval = $this->call($cmd);
525
        }
526
        return $retval;
527
    }
528
529
    /**
530
     * removeUser
531
     *
532
     * This method calls the 'removeUser' action of the servlet and
533
     * sets the class member variable $status appropriately.  If the
534
     * servlet returns correctly (i.e. an HTTP status code of 200),
535
     * this method returns true.
536
     *
537
     * @param string $uid The database user identifier
538
     * @return bool True if the servlet returned correctly. Else false.
539
     */
540
    public function removeUser($uid)
541
    {
542
        $this->clearUser();
543
        $this->setDBServiceURL(DEFAULT_DBSERVICE_URL);
0 ignored issues
show
Bug introduced by
The constant CILogon\Service\DEFAULT_DBSERVICE_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
544
        return $this->call('action=removeUser&user_uid=' .
545
            urlencode($uid));
546
    }
547
548
    /**
549
     * getPortalParameters
550
     *
551
     * This method calls the 'getPortalParameter' action of the servlet
552
     * and sets the class member variables associated with the portal
553
     * parameters appropriately. If the servlet returns correctly (i.e.
554
     * an HTTP status code of 200), this method returns true.
555
     *
556
     * @param string $oauth_token The database OAuth identifier token
557
     * @return bool True if the servlet returned correctly. Else false.
558
     */
559
    public function getPortalParameters($oauth_token)
560
    {
561
        $this->clearPortal();
562
        $this->setDBServiceURL(OAUTH1_DBSERVICE_URL);
0 ignored issues
show
Bug introduced by
The constant CILogon\Service\OAUTH1_DBSERVICE_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
563
        return $this->call('action=getPortalParameter&oauth_token=' .
564
            urlencode($oauth_token));
565
    }
566
567
    /**
568
     * getIdps
569
     *
570
     * This method calls the 'getAllIdps' action of the servlet and
571
     * sets the class member array $idp_uris to contain all of the
572
     * Idps in the database, stored in the 'values' of the array.  If
573
     * the servlet returns correctly (i.e. an HTTP status code of 200),
574
     * this method returns true.
575
     *
576
     * @return bool True if the servlet returned correctly. Else false.
577
     */
578
    public function getIdps()
579
    {
580
        $this->clearIdps();
581
        $this->setDBServiceURL(DEFAULT_DBSERVICE_URL);
0 ignored issues
show
Bug introduced by
The constant CILogon\Service\DEFAULT_DBSERVICE_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
582
        return $this->call('action=getAllIdps');
583
    }
584
585
    /**
586
     * setIdps
587
     *
588
     * This method calls the 'setAllIdps' action of the servlet using
589
     * the class memeber array $idp_uris as the source for the Idps to
590
     * be stored to the database.  Note that if this array is empty,
591
     * an error code will be returned in the status since at least one
592
     * IdP should be saved to the database.  If you want to pass an
593
     * array of Idps to be saved, see the setIdpsFromKeys($array) and
594
     * setIdpsFromValues($array) methods.  If the servlet returns
595
     * correctly (i.e. an HTTP status code of 200), this method
596
     * returns true.
597
     *
598
     * @return bool True if the servlet returned correctly. Else false.
599
     */
600
    public function setIdps()
601
    {
602
        $retval = false;
603
        $this->setDBServiceURL(DEFAULT_DBSERVICE_URL);
0 ignored issues
show
Bug introduced by
The constant CILogon\Service\DEFAULT_DBSERVICE_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
604
        $idpcount = count($this->idp_uids);
605
        $idpidx = 0;
606
        if ($idpcount > 0) {
607
            // Loop through the idp_uids in chunks of 50 to deal
608
            // with query parameter limit of http browsers/servers.
609
            while ($idpidx < $idpcount) { // Loop through all IdPs
610
                $fiftyidx = 0;
611
                $idplist = '';
612
                while (
613
                    ($fiftyidx < 50) && // Send 50 IdPs at a time
614
                       ($idpidx < $idpcount)
615
                ) {
616
                    $idplist .=  '&idp_uid=' .
617
                                 urlencode($this->idp_uids[$idpidx]);
618
                    $fiftyidx++;
619
                    $idpidx++;
620
                }
621
                $cmd = 'action=setAllIdps' . $idplist;
622
                $retval = $this->call($cmd);
623
            }
624
        }
625
        return $retval;
626
    }
627
628
    /**
629
     * setIdpsFromKeys
630
     *
631
     * This is a convenience method which calls setIdps using a
632
     * passed-in array of IdPs stored as the keys of the array.  It
633
     * first sets the class member array $idp_uids appropriately and
634
     * then calls the setIdps() method. If the servlet returns
635
     * correctly (i.e. an HTTP status code of 200), this method
636
     * returns true.  See also setIdpsFromValues().
637
     *
638
     * @param array $idps An array of IdPs to be saved, stored in the
639
     *       'keys' of the array.
640
     * @return bool True if the servlet returned correctly. Else false.
641
     */
642
    public function setIdpsFromKeys($idps)
643
    {
644
        $this->clearIdps();
645
        foreach ($idps as $key => $value) {
646
            $this->idp_uids[] = $key;
647
        }
648
        return $this->setIdps();
649
    }
650
651
    /**
652
     * setIdpsFromValues
653
     *
654
     * This is a convenience method which calls setIdps using a
655
     * passed-in array of IdPs stored as the values of the array.  It
656
     * first sets the class member array $idp_uids appropriately and
657
     * then calls the setIdps() method. If the servlet returns
658
     * correctly (i.e. an HTTP status code of 200), this method
659
     * returns true.  See also setIdpsFromKeys().
660
     *
661
     * @param array $idps An array of IdPs to be saved, stored in the
662
     *        'values' of the array.
663
     * @return bool True if the servlet returned correctly. Else false.
664
     */
665
    public function setIdpsFromValues($idps)
666
    {
667
        $this->clearIdps();
668
        foreach ($idps as $value) {
669
            $this->idp_uids[] = $value;
670
        }
671
        return $this->setIdps();
672
    }
673
674
    /**
675
     * getClient
676
     *
677
     * This method calls the 'getClient' action of the Oauth 2.0
678
     * servlet and sets the class member variables associated with
679
     * client info appropriately.  If the servlet returns correctly
680
     * (i.e. an HTTP status code of 200), this method returns true.
681
     *
682
     * @param string $cid The Oauth 2.0 Client ID (client_id).
683
     * @return bool True if the servlet returned correctly. Else false.
684
     */
685
    public function getClient($cid)
686
    {
687
        $this->clearClient();
688
        $this->setDBServiceURL(OAUTH2_DBSERVICE_URL);
0 ignored issues
show
Bug introduced by
The constant CILogon\Service\OAUTH2_DBSERVICE_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
689
        return $this->call('action=getClient&client_id=' .
690
            urlencode($cid));
691
    }
692
693
    /**
694
     * setTransactionState
695
     *
696
     * This method calls the 'setTransactionState' action of the Oauth
697
     * 2.0 servlet to associate the Oauth 2.0 'code' with the database
698
     * user UID. This is necessary for the Oauth 2.0 server to be able
699
     * to return information about the user (name, email address) as
700
     * well as return a certificate for the user. If the servlet
701
     * returns correctly (i.e. an HTTP status code of 200), this method
702
     * returns true. Check the 'status' return value to verify that
703
     * the transaction state was set successfully.
704
     *
705
     * @param string $code The 'code' as returned by the OAuth 2.0 server.
706
     * @param string $uid The database user UID.
707
     * @param int $authntime The Unix timestamp of the user authentication.
708
     * @param string $loa (Optional) The Level of Assurance: '' = basic,
709
     *        'openid' =  OpenID Connect (e.g., Google),
710
     *        'http://incommonfederation.org/assurance/silver' = silver
711
     * @param string $myproxyinfo (Optional) the 'info:...' string to be
712
     *        passed to MyProxy.
713
     * @return bool True if the servlet returned correctly. Else false.
714
     */
715
    public function setTransactionState(
716
        $code,
717
        $uid,
718
        $authntime,
719
        $loa = '',
720
        $myproxyinfo = ''
721
    ) {
722
        $this->setDBServiceURL(OAUTH2_DBSERVICE_URL);
0 ignored issues
show
Bug introduced by
The constant CILogon\Service\OAUTH2_DBSERVICE_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
723
        return $this->call(
724
            'action=setTransactionState' .
725
            '&code=' . urlencode($code) .
726
            '&user_uid=' . urlencode($uid) .
727
            '&auth_time=' . urlencode($authntime) .
728
            '&loa=' . urlencode($loa) .
729
            ((strlen($myproxyinfo) > 0) ?
730
                ('&cilogon_info=' . urlencode($myproxyinfo)) : '')
731
        );
732
    }
733
734
    /**
735
     * call
736
     *
737
     * This method does the brunt of the work for calling the
738
     * dbService servlet.  The single parameter is a string of
739
     * 'key1=value1&key2=value2&...' containing all of the parameters
740
     * for the dbService.  If the servlet returns an HTTP status code
741
     * of 200, then this method will return true.  It parses the return
742
     * output for various 'key=value' lines and stores then in the
743
     * appropriate member variables, urldecoded of course.
744
     *
745
     * @param string $params A string containing 'key=value' pairs,
746
     *        separated by ampersands ('&') as appropriate for passing to a
747
     *        URL for a GET query.
748
     * @return bool True if the servlet returned correctly. Else false.
749
     */
750
    public function call($params)
751
    {
752
        $success = false;
753
754
        $attr_json = '';
755
        $ch = curl_init();
756
        if ($ch !== false) {
757
            $url = $this->getDBServiceURL() . '?' . $params;
758
            curl_setopt($ch, CURLOPT_URL, $url);
759
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
760
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
761
            $output = curl_exec($ch);
762
            if (curl_errno($ch)) { // Send alert on curl errors
763
                Util::sendErrorAlert(
764
                    'cUrl Error',
765
                    'cUrl Error    = ' . curl_error($ch) . "\n" .
766
                    "URL Accessed  = $url"
767
                );
768
            }
769
            if (!empty($output)) {
770
                $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
771
                if ($httpcode == 200) {
772
                    $success = true;
773
                    if (preg_match('/status=([^\r\n]+)/', $output, $match)) {
774
                        $this->status = (int)(urldecode($match[1]));
775
                    }
776
                    if (preg_match('/user_uid=([^\r\n]+)/', $output, $match)) {
777
                        $this->user_uid = urldecode($match[1]);
778
                    }
779
                    if (preg_match('/remote_user=([^\r\n]+)/', $output, $match)) {
780
                        $this->remote_user = urldecode($match[1]);
781
                    }
782
                    if (preg_match('/idp=([^\r\n]+)/', $output, $match)) {
783
                        $this->idp = urldecode($match[1]);
784
                    }
785
                    if (preg_match('/idp_display_name=([^\r\n]+)/', $output, $match)) {
786
                        $this->idp_display_name = urldecode($match[1]);
787
                    }
788
                    if (preg_match('/first_name=([^\r\n]+)/', $output, $match)) {
789
                        $this->first_name = urldecode($match[1]);
790
                    }
791
                    if (preg_match('/last_name=([^\r\n]+)/', $output, $match)) {
792
                        $this->last_name = urldecode($match[1]);
793
                    }
794
                    if (preg_match('/[^_]display_name=([^\r\n]+)/', $output, $match)) {
795
                        $this->display_name = urldecode($match[1]);
796
                    }
797
                    if (preg_match('/email=([^\r\n]+)/', $output, $match)) {
798
                        $this->email = urldecode($match[1]);
799
                    }
800
                    if (preg_match('/distinguished_name=([^\r\n]+)/', $output, $match)) {
801
                        $this->distinguished_name = urldecode($match[1]);
802
                    }
803
                    if (preg_match('/eppn=([^\r\n]+)/', $output, $match)) {
804
                        $this->eppn = urldecode($match[1]);
805
                    }
806
                    if (preg_match('/eptid=([^\r\n]+)/', $output, $match)) {
807
                        $this->eptid = urldecode($match[1]);
808
                    }
809
                    if (preg_match('/open_id=([^\r\n]+)/', $output, $match)) {
810
                        $this->open_id = urldecode($match[1]);
811
                    }
812
                    if (preg_match('/oidc=([^\r\n]+)/', $output, $match)) {
813
                        $this->oidc = urldecode($match[1]);
814
                    }
815
                    if (preg_match('/subject_id=([^\r\n]+)/', $output, $match)) {
816
                        $this->subject_id = urldecode($match[1]);
817
                    }
818
                    if (preg_match('/pairwise_id=([^\r\n]+)/', $output, $match)) {
819
                        $this->pairwise_id = urldecode($match[1]);
820
                    }
821
                    if (preg_match('/affiliation=([^\r\n]+)/', $output, $match)) {
822
                        $this->affiliation = urldecode($match[1]);
823
                    }
824
                    if (preg_match('/ou=([^\r\n]+)/', $output, $match)) {
825
                        $this->ou = urldecode($match[1]);
826
                    }
827
                    if (preg_match('/attr_json=([^\r\n]+)/', $output, $match)) {
828
                        // Decode $attr_json into class members later
829
                        $attr_json = urldecode($match[1]);
830
                    }
831
                    if (preg_match('/serial_string=([^\r\n]+)/', $output, $match)) {
832
                        $this->serial_string = urldecode($match[1]);
833
                    }
834
                    if (preg_match('/create_time=([^\r\n]+)/', $output, $match)) {
835
                        $this->create_time = urldecode($match[1]);
836
                    }
837
                    if (preg_match('/oauth_token=([^\r\n]+)/', $output, $match)) {
838
                        $this->oauth_token = urldecode($match[1]);
839
                    }
840
                    if (preg_match('/cilogon_callback=([^\r\n]+)/', $output, $match)) {
841
                        $this->cilogon_callback = urldecode($match[1]);
842
                    }
843
                    if (preg_match('/cilogon_success=([^\r\n]+)/', $output, $match)) {
844
                        $this->cilogon_success = urldecode($match[1]);
845
                    }
846
                    if (preg_match('/cilogon_failure=([^\r\n]+)/', $output, $match)) {
847
                        $this->cilogon_failure = urldecode($match[1]);
848
                    }
849
                    if (preg_match('/cilogon_portal_name=([^\r\n]+)/', $output, $match)) {
850
                        $this->cilogon_portal_name = urldecode($match[1]);
851
                    }
852
                    if (preg_match_all('/idp_uid=([^\r\n]+)/', $output, $match)) {
853
                        foreach ($match[1] as $value) {
854
                            $this->idp_uids[] = urldecode($value);
855
                        }
856
                    }
857
                    if (preg_match('/client_name=([^\r\n]+)/', $output, $match)) {
858
                        $this->client_name = urldecode($match[1]);
859
                    }
860
                    if (preg_match('/client_id=([^\r\n]+)/', $output, $match)) {
861
                        $this->client_id = urldecode($match[1]);
862
                    }
863
                    if (preg_match('/client_home_uri=([^\r\n]+)/', $output, $match)) {
864
                        $this->client_home_uri = urldecode($match[1]);
865
                    }
866
                    if (preg_match('/client_callback_uris=([^\r\n]+)/', $output, $match)) {
867
                        $this->client_callback_uris = explode(urldecode($match[1]), ',');
868
                    }
869
                }
870
            }
871
            curl_close($ch);
872
        }
873
874
        // Convert $attr_json into array and extract elements into class members
875
        if (strlen($attr_json) > 0) {
876
            $attr_arr = json_decode($attr_json, true);
877
            if (!is_null($attr_arr)) {
878
                if (isset($attr_arr['member_of'])) {
879
                    $this->member_of = $attr_arr['member_of'];
880
                }
881
                if (isset($attr_arr['acr'])) {
882
                    $this->acr = $attr_arr['acr'];
883
                }
884
                if (isset($attr_arr['entitlement'])) {
885
                    $this->entitlement = $attr_arr['entitlement'];
886
                }
887
                if (isset($attr_arr['itrustuin'])) {
888
                    $this->itrustuin = $attr_arr['itrustuin'];
889
                }
890
            }
891
        }
892
893
        return $success;
894
    }
895
896
    /**
897
     * dump
898
     *
899
     * This is a convenience method which prints out all of the
900
     * non-null / non-empty member variables to stdout.
901
     */
902
    public function dump()
903
    {
904
        if (!is_null($this->status)) {
905
            echo "status=$this->status (" .
906
            (string)(array_search($this->status, static::$STATUS)) . ")\n";
907
        }
908
        if (!is_null($this->user_uid)) {
909
            echo "user_uid=$this->user_uid\n";
910
        }
911
        if (!is_null($this->remote_user)) {
912
            echo "remote_user=$this->remote_user\n";
913
        }
914
        if (!is_null($this->idp)) {
915
            echo "idp=$this->idp\n";
916
        }
917
        if (!is_null($this->idp_display_name)) {
918
            echo "idp_display_name=$this->idp_display_name\n";
919
        }
920
        if (!is_null($this->first_name)) {
921
            echo "first_name=$this->first_name\n";
922
        }
923
        if (!is_null($this->last_name)) {
924
            echo "last_name=$this->last_name\n";
925
        }
926
        if (!is_null($this->display_name)) {
927
            echo "display_name=$this->display_name\n";
928
        }
929
        if (!is_null($this->email)) {
930
            echo "email=$this->email\n";
931
        }
932
        if (!is_null($this->distinguished_name)) {
933
            echo "distinguished_name=$this->distinguished_name\n";
934
        }
935
        if (!is_null($this->eppn)) {
936
            echo "eppn=$this->eppn\n";
937
        }
938
        if (!is_null($this->eptid)) {
939
            echo "eptid=$this->eptid\n";
940
        }
941
        if (!is_null($this->open_id)) {
942
            echo "open_id=$this->open_id\n";
943
        }
944
        if (!is_null($this->oidc)) {
945
            echo "oidc=$this->oidc\n";
946
        }
947
        if (!is_null($this->affiliation)) {
948
            echo "affiliation=$this->affiliation\n";
949
        }
950
        if (!is_null($this->ou)) {
951
            echo "ou=$this->ou\n";
952
        }
953
        if (!is_null($this->member_of)) {
954
            echo "member_of=$this->member_of\n";
955
        }
956
        if (!is_null($this->acr)) {
957
            echo "acr=$this->acr\n";
958
        }
959
        if (!is_null($this->entitlement)) {
960
            echo "entitlement=$this->entitlement\n";
961
        }
962
        if (!is_null($this->itrustuin)) {
963
            echo "itrustuin=$this->itrustuin\n";
964
        }
965
        if (!is_null($this->subject_id)) {
966
            echo "subject_id=$this->subject_id\n";
967
        }
968
        if (!is_null($this->pairwise_id)) {
969
            echo "pairwise_id=$this->pairwise_id\n";
970
        }
971
        if (!is_null($this->serial_string)) {
972
            echo "serial_string=$this->serial_string\n";
973
        }
974
        if (!is_null($this->create_time)) {
975
            echo "create_time=$this->create_time\n";
976
        }
977
        if (!is_null($this->oauth_token)) {
978
            echo "oauth_token=$this->oauth_token\n";
979
        }
980
        if (!is_null($this->cilogon_callback)) {
981
            echo "cilogon_callback=$this->cilogon_callback\n";
982
        }
983
        if (!is_null($this->cilogon_success)) {
984
            echo "cilogon_success=$this->cilogon_success\n";
985
        }
986
        if (!is_null($this->cilogon_failure)) {
987
            echo "cilogon_failure=$this->cilogon_failure\n";
988
        }
989
        if (!is_null($this->cilogon_portal_name)) {
990
            echo "cilogon_portal_name=$this->cilogon_portal_name\n";
991
        }
992
        if (count($this->idp_uids) > 0) {
993
            uasort($this->idp_uids, 'strcasecmp');
994
            echo "idp_uids={\n";
995
            foreach ($this->idp_uids as $value) {
996
                echo "    $value\n";
997
            }
998
            echo "}\n";
999
        }
1000
        if (!is_null($this->client_name)) {
1001
            echo "client_name=$this->client_name\n";
1002
        }
1003
        if (!is_null($this->client_id)) {
1004
            echo "client_id=$this->client_id\n";
1005
        }
1006
        if (!is_null($this->client_home_uri)) {
1007
            echo "client_home_uri=$this->client_home_uri\n";
1008
        }
1009
        if (count($this->client_callback_uris) > 0) {
1010
            uasort($this->client_callback_uris, 'strcasecmp');
1011
            echo "client_callback_uris={\n";
1012
            foreach ($this->client_callback_uris as $value) {
1013
                echo "    $value\n";
1014
            }
1015
            echo "}\n";
1016
        }
1017
    }
1018
}
1019