Passed
Push — master ( f06884...36b9e7 )
by Terrence
12:52
created

DBService::clearClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 7
ccs 0
cts 7
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 $dbservice URL The URL to use for the dbService
320
     */
321
    private $dbserviceurl;
322
323
    /**
324
     * __construct
325
     *
326
     * Default constructor.  All of the various class members are
327
     * initialized to 'null' or empty arrays.
328
     *
329
     * @param string $serviceurl (Optional) The URL of the database service
330
     *        servlet
331
     */
332
    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...
333
    {
334
        $this->clear();
335
        $this->setDBServiceURL($serviceurl);
336
    }
337
338
    /**
339
     * getDBServiceURL
340
     *
341
     * Returns the full URL of the database servlet used by the call()
342
     * function.
343
     *
344
     * @return string The URL of the database service servlet
345
     */
346
    public function getDBServiceURL()
347
    {
348
        return $this->dbserviceurl;
349
    }
350
351
    /**
352
     * setDBServiceURL
353
     *
354
     * Set the private variable $dbserviceurl to the full URL of the
355
     * database servlet, which is used by the call() function.
356
     *
357
     * @param string $serviceurl The URL of the database service servlet.
358
     */
359
    public function setDBServiceURL($serviceurl)
360
    {
361
        $this->dbserviceurl = $serviceurl;
362
    }
363
364
    /**
365
     * clear
366
     *
367
     * Set all of the class members to 'null' or empty arrays.
368
     */
369
    public function clear()
370
    {
371
        $this->clearUser();
372
        $this->clearPortal();
373
        $this->clearIdps();
374
    }
375
376
    /**
377
     * clearUser
378
     *
379
     * Set all of the class member variables associated with getUser()
380
     * to 'null'.
381
     */
382
    public function clearUser()
383
    {
384
        foreach (static::$user_attrs as $value) {
385
            $this->$value = null;
386
        }
387
        $this->status = null;
388
        $this->user_uid = null;
389
        $this->distinguished_name = null;
390
        $this->serial_string = null;
391
        $this->create_time = null;
392
    }
393
394
    /**
395
     * clearPortal
396
     *
397
     * Set all of the class member variables associated with
398
     * getPortalParameters() to 'null'.
399
     */
400
    public function clearPortal()
401
    {
402
        $this->status = null;
403
        $this->oauth_token = null;
404
        $this->cilogon_callback = null;
405
        $this->cilogon_success = null;
406
        $this->cilogon_failure = null;
407
        $this->cilogon_portal_name = null;
408
    }
409
410
    /**
411
     * clearIdps
412
     *
413
     * Set the class member variable $idp_uids to an empty array.
414
     */
415
    public function clearIdps()
416
    {
417
        $this->status = null;
418
        $this->idp_uids = array();
419
    }
420
421
    /**
422
     * getUser
423
     *
424
     * This method calls the 'getUser' action of the servlet and sets
425
     * the class member variables associated with user info
426
     * appropriately.  If the servlet returns correctly (i.e. an HTTP
427
     * status code of 200), this method returns true.
428
     *
429
     * @param mixed $args Variable number of parameters: 1, or more.
430
     *        For 1 parameter : $uid (database user identifier)
431
     *        For more than 1 parameter, parameters can include:
432
     *            $remote_user, $idp, $idp_display_name,
433
     *            $first_name, $last_name, $display_name, $email,
434
     *            $eppn, $eptid, $openid, $oidc,
435
     *            $subject_id, $pairwise_id, $affiliation,
436
     *            $ou, $member_of, $acr, $entitlement, $itrustuin
437
     *
438
     * @return bool True if the servlet returned correctly. Else false.
439
     */
440
    public function getUser(...$args)
441
    {
442
        $retval = false;
443
        $this->clearUser();
444
        $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...
445
        $numargs = count($args);
446
        if ($numargs == 1) {
447
            $retval = $this->call('action=getUser&user_uid=' .
448
                urlencode($args[0]));
449
        } elseif ($numargs > 1) {
450
            $cmd = 'action=getUser';
451
            $attr_arr = array();
452
            $ou_pos = array_search('ou', static::$user_attrs);
453
            for ($i = 0; $i < $numargs; $i++) {
454
                $arg = $args[$i];
455
                if (strlen($arg) > 0) {
456
                    if ($i > $ou_pos) {
457
                        // Put params after $ou into JSON object
458
                        $attr_arr[static::$user_attrs[$i]] = $arg;
459
                    } else {
460
                        $cmd .= '&' . static::$user_attrs[$i] . '=' . urlencode($arg);
461
                    }
462
                }
463
            }
464
            // If any elements in $attr_arr, append converted JSON object
465
            if (count($attr_arr) > 0) {
466
                if (
467
                    ($attr_json = json_encode(
468
                        $attr_arr,
469
                        JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES
470
                    )
471
                    ) !== false
472
                ) {
473
                    $cmd .= '&attr_json=' . urlencode($attr_json);
474
                }
475
            }
476
            // Add 'us_idp' parameter for InCommon/Google (1) or eduGAIN (0)
477
            $us_idp = 0;
478
            $idp = $args[1];
479
            $idp_display_name = $args[2];
480
            if (
481
                (Util::getIdpList()->isRegisteredByInCommon($idp)) ||
482
                (in_array($idp_display_name, Util::$oauth2idps))
483
            ) {
484
                $us_idp = 1;
485
            }
486
            $cmd .= "&us_idp=$us_idp";
487
488
            $retval = $this->call($cmd);
489
        }
490
        return $retval;
491
    }
492
493
    /**
494
     * removeUser
495
     *
496
     * This method calls the 'removeUser' action of the servlet and
497
     * sets the class member variable $status appropriately.  If the
498
     * servlet returns correctly (i.e. an HTTP status code of 200),
499
     * this method returns true.
500
     *
501
     * @param string $uid The database user identifier
502
     * @return bool True if the servlet returned correctly. Else false.
503
     */
504
    public function removeUser($uid)
505
    {
506
        $this->clearUser();
507
        $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...
508
        return $this->call('action=removeUser&user_uid=' .
509
            urlencode($uid));
510
    }
511
512
    /**
513
     * getPortalParameters
514
     *
515
     * This method calls the 'getPortalParameter' action of the servlet
516
     * and sets the class member variables associated with the portal
517
     * parameters appropriately. If the servlet returns correctly (i.e.
518
     * an HTTP status code of 200), this method returns true.
519
     *
520
     * @param string $oauth_token The database OAuth identifier token
521
     * @return bool True if the servlet returned correctly. Else false.
522
     */
523
    public function getPortalParameters($oauth_token)
524
    {
525
        $this->clearPortal();
526
        $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...
527
        return $this->call('action=getPortalParameter&oauth_token=' .
528
            urlencode($oauth_token));
529
    }
530
531
    /**
532
     * getIdps
533
     *
534
     * This method calls the 'getAllIdps' action of the servlet and
535
     * sets the class member array $idp_uris to contain all of the
536
     * Idps in the database, stored in the 'values' of the array.  If
537
     * the servlet returns correctly (i.e. an HTTP status code of 200),
538
     * this method returns true.
539
     *
540
     * @return bool True if the servlet returned correctly. Else false.
541
     */
542
    public function getIdps()
543
    {
544
        $this->clearIdps();
545
        $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...
546
        return $this->call('action=getAllIdps');
547
    }
548
549
    /**
550
     * setIdps
551
     *
552
     * This method calls the 'setAllIdps' action of the servlet using
553
     * the class memeber array $idp_uris as the source for the Idps to
554
     * be stored to the database.  Note that if this array is empty,
555
     * an error code will be returned in the status since at least one
556
     * IdP should be saved to the database.  If you want to pass an
557
     * array of Idps to be saved, see the setIdpsFromKeys($array) and
558
     * setIdpsFromValues($array) methods.  If the servlet returns
559
     * correctly (i.e. an HTTP status code of 200), this method
560
     * returns true.
561
     *
562
     * @return bool True if the servlet returned correctly. Else false.
563
     */
564
    public function setIdps()
565
    {
566
        $retval = false;
567
        $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...
568
        $idpcount = count($this->idp_uids);
569
        $idpidx = 0;
570
        if ($idpcount > 0) {
571
            // Loop through the idp_uids in chunks of 50 to deal
572
            // with query parameter limit of http browsers/servers.
573
            while ($idpidx < $idpcount) { // Loop through all IdPs
574
                $fiftyidx = 0;
575
                $idplist = '';
576
                while (
577
                    ($fiftyidx < 50) && // Send 50 IdPs at a time
578
                       ($idpidx < $idpcount)
579
                ) {
580
                    $idplist .=  '&idp_uid=' .
581
                                 urlencode($this->idp_uids[$idpidx]);
582
                    $fiftyidx++;
583
                    $idpidx++;
584
                }
585
                $cmd = 'action=setAllIdps' . $idplist;
586
                $retval = $this->call($cmd);
587
            }
588
        }
589
        return $retval;
590
    }
591
592
    /**
593
     * setIdpsFromKeys
594
     *
595
     * This is a convenience method which calls setIdps using a
596
     * passed-in array of IdPs stored as the keys of the array.  It
597
     * first sets the class member array $idp_uids appropriately and
598
     * then calls the setIdps() method. If the servlet returns
599
     * correctly (i.e. an HTTP status code of 200), this method
600
     * returns true.  See also setIdpsFromValues().
601
     *
602
     * @param array $idps An array of IdPs to be saved, stored in the
603
     *       'keys' of the array.
604
     * @return bool True if the servlet returned correctly. Else false.
605
     */
606
    public function setIdpsFromKeys($idps)
607
    {
608
        $this->clearIdps();
609
        foreach ($idps as $key => $value) {
610
            $this->idp_uids[] = $key;
611
        }
612
        return $this->setIdps();
613
    }
614
615
    /**
616
     * setIdpsFromValues
617
     *
618
     * This is a convenience method which calls setIdps using a
619
     * passed-in array of IdPs stored as the values of the array.  It
620
     * first sets the class member array $idp_uids appropriately and
621
     * then calls the setIdps() method. If the servlet returns
622
     * correctly (i.e. an HTTP status code of 200), this method
623
     * returns true.  See also setIdpsFromKeys().
624
     *
625
     * @param array $idps An array of IdPs to be saved, stored in the
626
     *        'values' of the array.
627
     * @return bool True if the servlet returned correctly. Else false.
628
     */
629
    public function setIdpsFromValues($idps)
630
    {
631
        $this->clearIdps();
632
        foreach ($idps as $value) {
633
            $this->idp_uids[] = $value;
634
        }
635
        return $this->setIdps();
636
    }
637
638
    /**
639
     * setTransactionState
640
     *
641
     * This method calls the 'setTransactionState' action of the Oauth
642
     * 2.0 servlet to associate the Oauth 2.0 'code' with the database
643
     * user UID. This is necessary for the Oauth 2.0 server to be able
644
     * to return information about the user (name, email address) as
645
     * well as return a certificate for the user. If the servlet
646
     * returns correctly (i.e. an HTTP status code of 200), this method
647
     * returns true. Check the 'status' return value to verify that
648
     * the transaction state was set successfully.
649
     *
650
     * @param string $code The 'code' as returned by the OAuth 2.0 server.
651
     * @param string $uid The database user UID.
652
     * @param int $authntime The Unix timestamp of the user authentication.
653
     * @param string $loa (Optional) The Level of Assurance: '' = basic,
654
     *        'openid' =  OpenID Connect (e.g., Google),
655
     *        'http://incommonfederation.org/assurance/silver' = silver
656
     * @param string $myproxyinfo (Optional) the 'info:...' string to be
657
     *        passed to MyProxy.
658
     * @return bool True if the servlet returned correctly. Else false.
659
     */
660
    public function setTransactionState(
661
        $code,
662
        $uid,
663
        $authntime,
664
        $loa = '',
665
        $myproxyinfo = ''
666
    ) {
667
        $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...
668
        return $this->call(
669
            'action=setTransactionState' .
670
            '&code=' . urlencode($code) .
671
            '&user_uid=' . urlencode($uid) .
672
            '&auth_time=' . urlencode($authntime) .
673
            '&loa=' . urlencode($loa) .
674
            ((strlen($myproxyinfo) > 0) ?
675
                ('&cilogon_info=' . urlencode($myproxyinfo)) : '')
676
        );
677
    }
678
679
    /**
680
     * call
681
     *
682
     * This method does the brunt of the work for calling the
683
     * dbService servlet.  The single parameter is a string of
684
     * 'key1=value1&key2=value2&...' containing all of the parameters
685
     * for the dbService.  If the servlet returns an HTTP status code
686
     * of 200, then this method will return true.  It parses the return
687
     * output for various 'key=value' lines and stores then in the
688
     * appropriate member variables, urldecoded of course.
689
     *
690
     * @param string $params A string containing 'key=value' pairs,
691
     *        separated by ampersands ('&') as appropriate for passing to a
692
     *        URL for a GET query.
693
     * @return bool True if the servlet returned correctly. Else false.
694
     */
695
    public function call($params)
696
    {
697
        $success = false;
698
699
        $attr_json = '';
700
        $ch = curl_init();
701
        if ($ch !== false) {
702
            $url = $this->getDBServiceURL() . '?' . $params;
703
            curl_setopt($ch, CURLOPT_URL, $url);
704
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
705
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
706
            $output = curl_exec($ch);
707
            if (curl_errno($ch)) { // Send alert on curl errors
708
                Util::sendErrorAlert(
709
                    'cUrl Error',
710
                    'cUrl Error    = ' . curl_error($ch) . "\n" .
711
                    "URL Accessed  = $url"
712
                );
713
            }
714
            if (!empty($output)) {
715
                $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
716
                if ($httpcode == 200) {
717
                    $success = true;
718
                    if (preg_match('/status=([^\r\n]+)/', $output, $match)) {
719
                        $this->status = (int)(urldecode($match[1]));
720
                    }
721
                    if (preg_match('/user_uid=([^\r\n]+)/', $output, $match)) {
722
                        $this->user_uid = urldecode($match[1]);
723
                    }
724
                    if (preg_match('/remote_user=([^\r\n]+)/', $output, $match)) {
725
                        $this->remote_user = urldecode($match[1]);
726
                    }
727
                    if (preg_match('/idp=([^\r\n]+)/', $output, $match)) {
728
                        $this->idp = urldecode($match[1]);
729
                    }
730
                    if (preg_match('/idp_display_name=([^\r\n]+)/', $output, $match)) {
731
                        $this->idp_display_name = urldecode($match[1]);
732
                    }
733
                    if (preg_match('/first_name=([^\r\n]+)/', $output, $match)) {
734
                        $this->first_name = urldecode($match[1]);
735
                    }
736
                    if (preg_match('/last_name=([^\r\n]+)/', $output, $match)) {
737
                        $this->last_name = urldecode($match[1]);
738
                    }
739
                    if (preg_match('/[^_]display_name=([^\r\n]+)/', $output, $match)) {
740
                        $this->display_name = urldecode($match[1]);
741
                    }
742
                    if (preg_match('/email=([^\r\n]+)/', $output, $match)) {
743
                        $this->email = urldecode($match[1]);
744
                    }
745
                    if (preg_match('/distinguished_name=([^\r\n]+)/', $output, $match)) {
746
                        $this->distinguished_name = urldecode($match[1]);
747
                    }
748
                    if (preg_match('/eppn=([^\r\n]+)/', $output, $match)) {
749
                        $this->eppn = urldecode($match[1]);
750
                    }
751
                    if (preg_match('/eptid=([^\r\n]+)/', $output, $match)) {
752
                        $this->eptid = urldecode($match[1]);
753
                    }
754
                    if (preg_match('/open_id=([^\r\n]+)/', $output, $match)) {
755
                        $this->open_id = urldecode($match[1]);
756
                    }
757
                    if (preg_match('/oidc=([^\r\n]+)/', $output, $match)) {
758
                        $this->oidc = urldecode($match[1]);
759
                    }
760
                    if (preg_match('/subject_id=([^\r\n]+)/', $output, $match)) {
761
                        $this->subject_id = urldecode($match[1]);
762
                    }
763
                    if (preg_match('/pairwise_id=([^\r\n]+)/', $output, $match)) {
764
                        $this->pairwise_id = urldecode($match[1]);
765
                    }
766
                    if (preg_match('/affiliation=([^\r\n]+)/', $output, $match)) {
767
                        $this->affiliation = urldecode($match[1]);
768
                    }
769
                    if (preg_match('/ou=([^\r\n]+)/', $output, $match)) {
770
                        $this->ou = urldecode($match[1]);
771
                    }
772
                    if (preg_match('/attr_json=([^\r\n]+)/', $output, $match)) {
773
                        // Decode $attr_json into class members later
774
                        $attr_json = urldecode($match[1]);
775
                    }
776
                    if (preg_match('/serial_string=([^\r\n]+)/', $output, $match)) {
777
                        $this->serial_string = urldecode($match[1]);
778
                    }
779
                    if (preg_match('/create_time=([^\r\n]+)/', $output, $match)) {
780
                        $this->create_time = urldecode($match[1]);
781
                    }
782
                    if (preg_match('/oauth_token=([^\r\n]+)/', $output, $match)) {
783
                        $this->oauth_token = urldecode($match[1]);
784
                    }
785
                    if (preg_match('/cilogon_callback=([^\r\n]+)/', $output, $match)) {
786
                        $this->cilogon_callback = urldecode($match[1]);
787
                    }
788
                    if (preg_match('/cilogon_success=([^\r\n]+)/', $output, $match)) {
789
                        $this->cilogon_success = urldecode($match[1]);
790
                    }
791
                    if (preg_match('/cilogon_failure=([^\r\n]+)/', $output, $match)) {
792
                        $this->cilogon_failure = urldecode($match[1]);
793
                    }
794
                    if (preg_match('/cilogon_portal_name=([^\r\n]+)/', $output, $match)) {
795
                        $this->cilogon_portal_name = urldecode($match[1]);
796
                    }
797
                    if (preg_match_all('/idp_uid=([^\r\n]+)/', $output, $match)) {
798
                        foreach ($match[1] as $value) {
799
                            $this->idp_uids[] = urldecode($value);
800
                        }
801
                    }
802
                }
803
            }
804
            curl_close($ch);
805
        }
806
807
        // Convert $attr_json into array and extract elements into class members
808
        if (strlen($attr_json) > 0) {
809
            $attr_arr = json_decode($attr_json, true);
810
            if (!is_null($attr_arr)) {
811
                if (isset($attr_arr['member_of'])) {
812
                    $this->member_of = $attr_arr['member_of'];
813
                }
814
                if (isset($attr_arr['acr'])) {
815
                    $this->acr = $attr_arr['acr'];
816
                }
817
                if (isset($attr_arr['entitlement'])) {
818
                    $this->entitlement = $attr_arr['entitlement'];
819
                }
820
                if (isset($attr_arr['itrustuin'])) {
821
                    $this->itrustuin = $attr_arr['itrustuin'];
822
                }
823
            }
824
        }
825
826
        return $success;
827
    }
828
829
    /**
830
     * dump
831
     *
832
     * This is a convenience method which prints out all of the
833
     * non-null / non-empty member variables to stdout.
834
     */
835
    public function dump()
836
    {
837
        if (!is_null($this->status)) {
838
            echo "status=$this->status (" .
839
            (string)(array_search($this->status, static::$STATUS)) . ")\n";
840
        }
841
        if (!is_null($this->user_uid)) {
842
            echo "user_uid=$this->user_uid\n";
843
        }
844
        if (!is_null($this->remote_user)) {
845
            echo "remote_user=$this->remote_user\n";
846
        }
847
        if (!is_null($this->idp)) {
848
            echo "idp=$this->idp\n";
849
        }
850
        if (!is_null($this->idp_display_name)) {
851
            echo "idp_display_name=$this->idp_display_name\n";
852
        }
853
        if (!is_null($this->first_name)) {
854
            echo "first_name=$this->first_name\n";
855
        }
856
        if (!is_null($this->last_name)) {
857
            echo "last_name=$this->last_name\n";
858
        }
859
        if (!is_null($this->display_name)) {
860
            echo "display_name=$this->display_name\n";
861
        }
862
        if (!is_null($this->email)) {
863
            echo "email=$this->email\n";
864
        }
865
        if (!is_null($this->distinguished_name)) {
866
            echo "distinguished_name=$this->distinguished_name\n";
867
        }
868
        if (!is_null($this->eppn)) {
869
            echo "eppn=$this->eppn\n";
870
        }
871
        if (!is_null($this->eptid)) {
872
            echo "eptid=$this->eptid\n";
873
        }
874
        if (!is_null($this->open_id)) {
875
            echo "open_id=$this->open_id\n";
876
        }
877
        if (!is_null($this->oidc)) {
878
            echo "oidc=$this->oidc\n";
879
        }
880
        if (!is_null($this->affiliation)) {
881
            echo "affiliation=$this->affiliation\n";
882
        }
883
        if (!is_null($this->ou)) {
884
            echo "ou=$this->ou\n";
885
        }
886
        if (!is_null($this->member_of)) {
887
            echo "member_of=$this->member_of\n";
888
        }
889
        if (!is_null($this->acr)) {
890
            echo "acr=$this->acr\n";
891
        }
892
        if (!is_null($this->entitlement)) {
893
            echo "entitlement=$this->entitlement\n";
894
        }
895
        if (!is_null($this->itrustuin)) {
896
            echo "itrustuin=$this->itrustuin\n";
897
        }
898
        if (!is_null($this->subject_id)) {
899
            echo "subject_id=$this->subject_id\n";
900
        }
901
        if (!is_null($this->pairwise_id)) {
902
            echo "pairwise_id=$this->pairwise_id\n";
903
        }
904
        if (!is_null($this->serial_string)) {
905
            echo "serial_string=$this->serial_string\n";
906
        }
907
        if (!is_null($this->create_time)) {
908
            echo "create_time=$this->create_time\n";
909
        }
910
        if (!is_null($this->oauth_token)) {
911
            echo "oauth_token=$this->oauth_token\n";
912
        }
913
        if (!is_null($this->cilogon_callback)) {
914
            echo "cilogon_callback=$this->cilogon_callback\n";
915
        }
916
        if (!is_null($this->cilogon_success)) {
917
            echo "cilogon_success=$this->cilogon_success\n";
918
        }
919
        if (!is_null($this->cilogon_failure)) {
920
            echo "cilogon_failure=$this->cilogon_failure\n";
921
        }
922
        if (!is_null($this->cilogon_portal_name)) {
923
            echo "cilogon_portal_name=$this->cilogon_portal_name\n";
924
        }
925
        if (count($this->idp_uids) > 0) {
926
            uasort($this->idp_uids, 'strcasecmp');
927
            echo "idp_uids={\n";
928
            foreach ($this->idp_uids as $value) {
929
                echo "    $value\n";
930
            }
931
            echo "}\n";
932
        }
933
    }
934
}
935