Passed
Push — master ( ab7cdd...870b1e )
by Terrence
10:49
created

Util::setUserAttributeSessionVars()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 10
Bugs 0 Features 0
Metric Value
cc 3
eloc 11
c 10
b 0
f 0
nc 3
nop 1
dl 0
loc 18
ccs 0
cts 16
cp 0
crap 12
rs 9.9
1
<?php
2
3
namespace CILogon\Service;
4
5
use CILogon\Service\CSRF;
6
use CILogon\Service\Loggit;
7
use CILogon\Service\IdpList;
8
use CILogon\Service\DBService;
9
use CILogon\Service\SessionMgr;
10
use CILogon\Service\Skin;
11
use CILogon\Service\TimeIt;
12
use CILogon\Service\PortalCookie;
13
use PEAR;
14
use DB;
15
16
/**
17
 * Util
18
 *
19
 * This class contains a bunch of static (class) utility
20
 * methods, for example getting and setting server environment
21
 * variables and handling cookies. See the header for each function for
22
 * detailed description.
23
 */
24
class Util
25
{
26
    /**
27
     * @var array $ini_array Read the cilogon.ini file into an array
28
     */
29
    public static $ini_array = null;
30
31
    /**
32
     * @var TimeIt $timeit Initialize by calling static::startTiming() in
33
     * init().
34
     */
35
    public static $timeit;
36
37
    /**
38
     * @var IdPList $idplist A 'global' IdpList object since dplist.xml is
39
     *      large and expensive to create multiple times.
40
     */
41
    public static $idplist = null;
42
43
    /**
44
     * @var CSRF $csrf A 'global' CSRF token object to set the CSRF cookie
45
     * and print the hidden CSRF form element. Needs to be set only once
46
     * to keep the same CSRF value through the session.
47
     */
48
    public static $csrf = null;
49
50
    /**
51
     * @var Skin $skin A 'global' Skin object for skin configuration.
52
     */
53
    public static $skin = null;
54
55
    /**
56
     * @var array $oauth2idps An array of OAuth2 Identity Providers.
57
     */
58
    public static $oauth2idps = ['Google', 'GitHub', 'ORCID'];
59
60
61
    /**
62
     * getIdPList
63
     *
64
     * This function initializes the class $idplist object (if not yet
65
     * created) and returns it. This allows for a single 'global'
66
     * $idplist to be used by other classes (since creating an IdPList
67
     * object is expensive).
68
     *
69
     * @return IdPList|null The class instantiated IdPList object.
70
     **/
71
    public static function getIdpList()
72
    {
73
        if (is_null(static::$idplist)) {
74
            static::$idplist = new IdpList();
75
        }
76
        return static::$idplist;
77
    }
78
79
    /**
80
     * getCsrf
81
     *
82
     * This function initializes the class $csrf object (if not yet
83
     * created) and returns it. This allows for a single 'global'
84
     * $csrf to be used by other classes (since we want the CSRV value
85
     * to be consistent for the current page load).
86
     *
87
     * @return CSRF|null The class instantiated CSRF object.
88
     */
89
    public static function getCsrf()
90
    {
91
        if (is_null(static::$csrf)) {
92
            static::$csrf = new CSRF();
93
        }
94
        return static::$csrf;
95
    }
96
97
    /**
98
     * getSkin
99
     *
100
     * This function initializes the class $skin object (if not yet
101
     * created) and returns it. This allows for a single 'global'
102
     * $skin to be used by other classes (since loading the skin is
103
     * potentially expensive).
104
     *
105
     * @return Skin|null The class instantiated Skin object.
106
     */
107
    public static function getSkin()
108
    {
109
        if (is_null(static::$skin)) {
110
            static::$skin = new Skin();
111
        }
112
        return static::$skin;
113
    }
114
115
    /**
116
     * startTiming
117
     *
118
     * This function initializes the class variable $timeit which is
119
     * used for timing/benchmarking purposes.
120
     */
121
    public static function startTiming()
122
    {
123
        static::$timeit = new TimeIt(TimeIt::DEFAULTFILENAME, true);
124
    }
125
126
    /**
127
     * getServerVar
128
     *
129
     * This function queries a given $_SERVER variable (which is set
130
     * by the Apache server) and returns the value.
131
     *
132
     * @param string $serv The $_SERVER variable to query.
133
     * @return string The value of the $_SERVER variable or empty string
134
     *         if that variable is not set.
135
     */
136
    public static function getServerVar($serv)
137
    {
138
        $retval = '';
139
        if (isset($_SERVER[$serv])) {
140
            $retval = $_SERVER[$serv];
141
        }
142
        return $retval;
143
    }
144
145
    /**
146
     * getGetVar
147
     *
148
     * This function queries a given $_GET parameter (which is set in
149
     * the URL via a '?parameter=value' parameter) and returns the
150
     * value.
151
     *
152
     * @param string $get The $_GET variable to query.
153
     * @return string The value of the $_GET variable or empty string if
154
     *         that variable is not set.
155
     */
156
    public static function getGetVar($get)
157
    {
158
        $retval = '';
159
        if (isset($_GET[$get])) {
160
            $retval = $_GET[$get];
161
        }
162
        return $retval;
163
    }
164
165
    /**
166
     * getPostVar
167
     *
168
     * This function queries a given $_POST variable (which is set when
169
     * the user submits a form, for example) and returns the value.
170
     *
171
     * @param string $post The $_POST variable to query.
172
     * @return string The value of the $_POST variable or empty string if
173
     *         that variable is not set.
174
     */
175
    public static function getPostVar($post)
176
    {
177
        $retval = '';
178
        if (isset($_POST[$post])) {
179
            $retval = $_POST[$post];
180
        }
181
        return $retval;
182
    }
183
184
    /**
185
     * getGetOrPostVar
186
     *
187
     * This function looks for a $_GET or $_POST variable, with
188
     * preference given to $_GET if both are present.
189
     *
190
     * @param string $var The $_GET or $_POST variable to query.
191
     * @return string The value of the $_GET or $_POST variable
192
     *         if present. Empty string if variable is not set.
193
     */
194
    public static function getGetOrPostVar($var)
195
    {
196
        $retval = static::getGetVar($var);
197
        if (empty($retval)) {
198
            $retval = static::getPostVar($var);
199
        }
200
        return $retval;
201
    }
202
203
    /**
204
     * getCookieVar
205
     *
206
     * This function returns the value of a given cookie.
207
     *
208
     * @param string $cookie he $_COOKIE variable to query.
209
     * @return string The value of the $_COOKIE variable or empty string
210
     *         if that variable is not set.
211
     */
212
    public static function getCookieVar($cookie)
213
    {
214
        $retval = '';
215
        if (isset($_COOKIE[$cookie])) {
216
            $retval = $_COOKIE[$cookie];
217
        }
218
        return $retval;
219
    }
220
221
    /**
222
     * setCookieVar
223
     *
224
     * This function sets a cookie.
225
     *
226
     * @param string $cookie The name of the cookie to set.
227
     * @param string $value (Optional) The value to set for the cookie.
228
     *        Defaults to empty string.
229
     * @param int $exp The future expiration time (in seconds) of the
230
     *        cookie. Defaults to 1 year from now. If set to 0,
231
     *        the cookie expires at the end of the session.
232
     */
233
    public static function setCookieVar($cookie, $value = '', $exp = 31536000)
234
    {
235
        if ($exp > 0) {
236
            $exp += time();
237
        }
238
        setcookie($cookie, $value, $exp, '/', '.' . static::getDN(), true);
239
        $_COOKIE[$cookie] = $value;
240
    }
241
242
    /**
243
     * unsetCookieVar
244
     *
245
     * This function unsets a cookie. Strictly speaking, the cookie is
246
     * not removed, rather it is set to an empty value with an expired
247
     * time.
248
     *
249
     * @param string $cookie The name of the cookie to unset (delete).
250
     */
251
    public static function unsetCookieVar($cookie)
252
    {
253
        setcookie($cookie, '', 1, '/', '.' . static::getDN(), true);
254
        unset($_COOKIE[$cookie]);
255
    }
256
257
    /**
258
     * getPortalOrCookieVar
259
     *
260
     * This is a convenience function which first checks if there is a
261
     * OAuth 1.0a ('delegate') or OIDC ('authorize') session active.
262
     * If so, it attempts to get the requested cookie from the
263
     * associated portalcookie. If there is not an OAuth/OIDC session
264
     * active, it looks for a 'normal' cookie. If you need a
265
     * portalcookie object to do multiple get/set method calls from
266
     * one function, it is probably better NOT to use this method since
267
     * creating the portalcookie object is potentially expensive.
268
     *
269
     * @param string $cookie The name of the cookie to get.
270
     * @return string The cookie value from either the portalcookie
271
     *         (in the case of an active OAuth session) or the
272
     *         'normal' cookie. Return empty string if no matching
273
     *         cookie in either place.
274
     */
275
    public static function getPortalOrCookieVar($cookie)
276
    {
277
        $retval = '';
278
        $pc = new PortalCookie();
279
        $pn = $pc->getPortalName();
280
        if (strlen($pn) > 0) {
281
            $retval = $pc->get($cookie);
282
        } else {
283
            $retval = static::getCookieVar($cookie);
284
        }
285
        return $retval;
286
    }
287
288
    /**
289
     * getSessionVar
290
     *
291
     * This function returns the value of a given PHP Session variable.
292
     *
293
     * @param string $sess The $_SESSION variable to query.
294
     * @return string The value of the $_SESSION variable or empty string
295
     *         if that variable is not set.
296
     */
297
    public static function getSessionVar($sess)
298
    {
299
        $retval = '';
300
        if (isset($_SESSION[$sess])) {
301
            $retval = $_SESSION[$sess];
302
        }
303
        return $retval;
304
    }
305
306
    /**
307
     * setSessionVar
308
     *
309
     * This function can set or unset a given PHP session variable.
310
     * The first parameter is the PHP session variable to set/unset.
311
     * If the second parameter is the empty string, then the session
312
     * variable is unset.  Otherwise, the session variable is set to
313
     * the second parameter.  The function returns true if the session
314
     * variable was set to a non-empty value, false otherwise.
315
     * Normally, the return value can be ignored.
316
     *
317
     * @param string $key The name of the PHP session variable to set
318
     *        (or unset).
319
     * @param string $value (Optional) The value of the PHP session variable
320
     *        (to set), or empty string (to unset). Defaults to empty
321
     *        string (implies unset the session variable).
322
     * @return bool True if the PHP session variable was set to a
323
     *         non-empty string, false if variable was unset or if
324
     *         the specified session variable was not previously set.
325
     */
326
    public static function setSessionVar($key, $value = '')
327
    {
328
        $retval = false;  // Assume we want to unset the session variable
329
        if (strlen($key) > 0) {  // Make sure session var name was passed in
330
            if (strlen($value) > 0) {
331
                $_SESSION[$key] = $value;
332
                $retval = true;
333
            } else {
334
                static::unsetSessionVar($key);
335
            }
336
        }
337
        return $retval;
338
    }
339
340
    /**
341
     * unsetSessionVar
342
     *
343
     * This function clears the given PHP session variable by first
344
     * setting it to null and then unsetting it entirely.
345
     *
346
     * @param string $sess The $_SESSION variable to erase.
347
     */
348
    public static function unsetSessionVar($sess)
349
    {
350
        if (isset($_SESSION[$sess])) {
351
            $_SESSION[$sess] = null;
352
            unset($_SESSION[$sess]);
353
        }
354
    }
355
356
    /**
357
     * removeShibCookies
358
     *
359
     * This function removes all '_shib*' cookies currently in the
360
     * user's browser session. In effect, this logs the user out of
361
     * any IdP. Note that you must call this before you output any
362
     * HTML. Strictly speaking, the cookies are not removed, rather
363
     * they are set to empty values with expired times.
364
     */
365
    public static function removeShibCookies()
366
    {
367
        foreach ($_COOKIE as $key => $value) {
368
            if (strncmp($key, '_shib', strlen('_shib')) == 0) {
369
                static::unsetCookieVar($key);
370
            }
371
        }
372
    }
373
374
    /**
375
     * startPHPSession
376
     *
377
     * This function starts a secure PHP session and should be called
378
     * at the beginning of each script before any HTML is output.  It
379
     * does a trick of setting a 'lastaccess' time so that the
380
     * $_SESSION variable does not expire without warning.
381
     *
382
     * @param string $storetype (Optional) Storage location of the PHP
383
     *        session data, one of 'file' or 'mysql'. Defaults to null,
384
     *        which means use the value of STORAGE_PHPSESSIONS from the
385
     *        config.php file, or 'file' if no such parameter configured.
386
     */
387
    public static function startPHPSession($storetype = null)
0 ignored issues
show
Unused Code introduced by
The parameter $storetype is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

387
    public static function startPHPSession(/** @scrutinizer ignore-unused */ $storetype = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
388
    {
389
        // No parameter given? Use the value read in from cilogon.ini file.
390
        // If STORAGE_PHPSESSIONS == 'mysqli', create a sessionmgr().
391
        $storetype = STORAGE_PHPSESSIONS;
0 ignored issues
show
Bug introduced by
The constant CILogon\Service\STORAGE_PHPSESSIONS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
392
393
        if (preg_match('/^mysql/', $storetype)) {
394
            $sessionmgr = new SessionMgr();
0 ignored issues
show
Unused Code introduced by
The assignment to $sessionmgr is dead and can be removed.
Loading history...
395
        }
396
397
        ini_set('session.cookie_secure', true);
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type string expected by parameter $newvalue of ini_set(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

397
        ini_set('session.cookie_secure', /** @scrutinizer ignore-type */ true);
Loading history...
398
        ini_set('session.cookie_domain', '.' . static::getDN());
399
        session_start();
400
        if (
401
            (!isset($_SESSION['lastaccess']) ||
402
            (time() - $_SESSION['lastaccess']) > 60)
403
        ) {
404
            $_SESSION['lastaccess'] = time();
405
        }
406
    }
407
408
    /**
409
     * getScriptDir
410
     *
411
     * This function returns the directory (or full url) of the script
412
     * that is currently running.  The returned directory/url is
413
     * terminated by a '/' character (unless the second parameter is
414
     * set to true). This function is useful for those scripts named
415
     * index.php where we don't want to actually see 'index.php' in the
416
     * address bar (again, unless the second parameter is set to true).
417
     *
418
     * @param bool $prependhttp (Optional) Boolean to prepend 'http(s)://' to
419
     *        the script name. Defaults to false.
420
     * @param bool $stripfile (Optional) Boolean to strip off the trailing
421
     *        filename (e.g. index.php) from the path.
422
     *        Defaults to true (i.e., defaults to directory
423
     *        only without the trailing filename).
424
     * @return string The directory or url of the current script, with or
425
     *         without the trailing .php filename.
426
     */
427
    public static function getScriptDir($prependhttp = false, $stripfile = true)
428
    {
429
        $retval = static::getServerVar('SCRIPT_NAME');
430
        if ($stripfile) {
431
            $retval = dirname($retval);
432
        }
433
        if ($retval == '.') {
434
            $retval = '';
435
        }
436
        if (
437
            (strlen($retval) == 0) ||
438
            ($stripfile && ($retval[strlen($retval) - 1] != '/'))
439
        ) {
440
            $retval .= '/';  // Append a slash if necessary
441
        }
442
        if ($prependhttp) {  // Prepend http(s)://hostname
443
            $retval = 'http' .
444
                      ((strtolower(static::getServerVar('HTTPS')) == 'on') ? 's' : '') .
445
                      '://' . static::getServerVar('HTTP_HOST') . $retval;
446
        }
447
        return $retval;
448
    }
449
450
    /**
451
     * tempDir
452
     *
453
     * This function creates a temporary subdirectory within the
454
     * specified subdirectory. The new directory name is composed of
455
     * 16 hexadecimal letters, plus any prefix if you specify one. The
456
     * full path of the the newly created directory is returned.
457
     *
458
     * @param string $dir The full path to the containing directory.
459
     * @param string $prefix (Optional) A prefix for the new temporary
460
     *        directory. Defaults to empty string.
461
     * @param int $mode (Optional) Access permissions for the new
462
     *        temporary directory. Defaults to 0775.
463
     * @return string Full path to the newly created temporary directory.
464
     */
465
    public static function tempDir($dir, $prefix = '', $mode = 0775)
466
    {
467
        if (substr($dir, -1) != '/') {
468
            $dir .= '/';
469
        }
470
471
        $path = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $path is dead and can be removed.
Loading history...
472
        do {
473
            $path = $dir . $prefix . sprintf("%08X%08X", mt_rand(), mt_rand());
474
        } while (!mkdir($path, $mode, true));
475
476
        return $path;
477
    }
478
479
    /**
480
     * deleteDir
481
     *
482
     * This function deletes a directory and all of its contents.
483
     *
484
     * @param string $dir The (possibly non-empty) directory to delete.
485
     * @param bool $shred (Optional) Shred the file before deleting?
486
     *        Defaults to false.
487
     */
488
    public static function deleteDir($dir, $shred = false)
489
    {
490
        if (is_dir($dir)) {
491
            $objects = scandir($dir);
492
            foreach ($objects as $object) {
493
                if ($object != "." && $object != "..") {
494
                    if (filetype($dir . "/" . $object) == "dir") {
495
                        static::deleteDir($dir . "/" . $object);
496
                    } else {
497
                        if ($shred) {
498
                            @exec('/bin/env /usr/bin/shred -u -z ' . $dir . "/" . $object);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for exec(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

498
                            /** @scrutinizer ignore-unhandled */ @exec('/bin/env /usr/bin/shred -u -z ' . $dir . "/" . $object);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
499
                        } else {
500
                            @unlink($dir . "/" . $object);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

500
                            /** @scrutinizer ignore-unhandled */ @unlink($dir . "/" . $object);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
501
                        }
502
                    }
503
                }
504
            }
505
            reset($objects);
0 ignored issues
show
Bug introduced by
It seems like $objects can also be of type false; however, parameter $array of reset() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

505
            reset(/** @scrutinizer ignore-type */ $objects);
Loading history...
506
            @rmdir($dir);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for rmdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

506
            /** @scrutinizer ignore-unhandled */ @rmdir($dir);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
507
        }
508
    }
509
510
    /**
511
     * htmlent
512
     *
513
     * This method is necessary since htmlentities() does not seem to
514
     * obey the default arguments as documented in the PHP manual, and
515
     * instead encodes accented characters incorrectly. By specifying
516
     * the flags and encoding, the problem is solved.
517
     *
518
     * @param string $str : A string to process with htmlentities().
519
     * @return string The input string processed by htmlentities with
520
     *         specific options.
521
     */
522
    public static function htmlent($str)
523
    {
524
        return htmlentities($str, ENT_COMPAT | ENT_HTML401, 'UTF-8');
525
    }
526
527
    /**
528
     * sendErrorAlert
529
     *
530
     * Use this function to send an error message. The $summary should
531
     * be a short description of the error since it is placed in the
532
     * subject of the email. Put a more verbose description of the
533
     * error in the $detail parameter. Any session variables available
534
     * are appended to the body of the message.
535
     *
536
     * @param string $summary A brief summary of the error (in email subject)
537
     * @param string $detail A detailed description of the error (in the
538
     *        email body)
539
     * @param string $mailto (Optional) The destination email address.
540
     *        Defaults to EMAIL_ALERTS (defined in the top-level
541
     *        config.php file as 'alerts@' . DEFAULT_HOSTNAME).
542
     */
543
    public static function sendErrorAlert(
544
        $summary,
545
        $detail,
546
        $mailto = EMAIL_ALERTS
0 ignored issues
show
Bug introduced by
The constant CILogon\Service\EMAIL_ALERTS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
547
    ) {
548
        $sessionvars = array(
549
            'idp'                => 'IdP ID',
550
            'idp_display_name'   => 'IdP Name',
551
            'user_uid'           => 'User UID',
552
            'distinguished_name' => 'Cert DN',
553
            'first_name'         => 'First Name',
554
            'last_name'          => 'Last Name',
555
            'display_name'       => 'Display Name',
556
            'eppn'               => 'ePPN',
557
            'eptid'              => 'ePTID',
558
            'open_id'            => 'OpenID ID',
559
            'oidc'               => 'OIDC ID',
560
            'subject_id'         => 'Subject ID',
561
            'pairwise_id'        => 'Pairwise ID',
562
            'loa'                => 'LOA',
563
            'affiliation'        => 'Affiliation',
564
            'ou'                 => 'OU',
565
            'member_of'          => 'MemberOf',
566
            'acr'                => 'AuthnContextClassRef',
567
            'entitlement'        => 'Entitlement',
568
            'itrustuin'          => 'iTrustUIN',
569
            'cilogon_skin'       => 'Skin Name',
570
            'authntime'          => 'Authn Time'
571
        );
572
573
        $remoteaddr = static::getServerVar('REMOTE_ADDR');
574
        $remotehost = gethostbyaddr($remoteaddr);
575
        $mailfrom = 'From: ' . EMAIL_ALERTS . "\r\n" .
576
                    'X-Mailer: PHP/' . phpversion();
577
        $mailsubj = 'CILogon Service on ' . php_uname('n') .
578
                    ' - ' . $summary;
579
        $mailmsg  = '
580
CILogon Service - ' . $summary . '
581
-----------------------------------------------------------
582
' . $detail . '
583
584
Session Variables
585
-----------------
586
Timestamp     = ' . date(DATE_ATOM) . '
587
Server Host   = ' . static::getHN() . '
588
Remote Address= ' . $remoteaddr . '
589
' . (($remotehost !== false) ? "Remote Host   = $remotehost" : '') . '
590
';
591
592
        foreach ($sessionvars as $svar => $sname) {
593
            if (strlen($val = static::getSessionVar($svar)) > 0) {
594
                $mailmsg .= sprintf("%-14s= %s\n", $sname, $val);
595
            }
596
        }
597
598
        mail($mailto, $mailsubj, $mailmsg, $mailfrom);
599
    }
600
601
    /**
602
     * getHN
603
     *
604
     * This function calculates and returns the 'hostname' for the
605
     * server. It first checks HTTP_HOST. If not set, it returns
606
     * DEFAULT_HOSTNAME. This is needed by command line scripts.
607
     *
608
     * @return string The 'Hostname' for the web server.
609
     */
610
    public static function getHN()
611
    {
612
        $thehostname = static::getServerVar('HTTP_HOST');
613
        if (strlen($thehostname) == 0) {
614
            $thehostname = DEFAULT_HOSTNAME;
0 ignored issues
show
Bug introduced by
The constant CILogon\Service\DEFAULT_HOSTNAME was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
615
        }
616
        return $thehostname;
617
    }
618
619
    /**
620
     * getDN
621
     *
622
     * This function calculates and returns the 'domainname' for the
623
     * server. It uses the hostname value calculated by getHN() and
624
     * uses the last two segments.
625
     *
626
     * @return string The 'Domainname' for the web server.
627
     */
628
    public static function getDN()
629
    {
630
        $thedomainname = static::getHN();
631
        if (preg_match('/[^\.]+\.[^\.]+$/', $thedomainname, $matches)) {
632
            $thedomainname = $matches[0];
633
        }
634
        return $thedomainname;
635
    }
636
637
    /**
638
     * getAuthzUrl
639
     *
640
     * This funtion takes in the name of an IdP (e.g., 'Google') and
641
     * returns the assoicated OAuth2 authorization URL.
642
     *
643
     * @param string $idp The name of an OAuth2 Identity Provider.
644
     * @return string The authorization URL for the given IdP.
645
     */
646
    public static function getAuthzUrl($idp)
647
    {
648
        $url = null;
649
        $idptourl = array(
650
            'Google' => 'https://accounts.google.com/o/oauth2/auth',
651
            'GitHub' => 'https://github.com/login/oauth/authorize',
652
            'ORCID'  => 'https://orcid.org/oauth/authorize',
653
        );
654
        if (array_key_exists($idp, $idptourl)) {
655
            $url = $idptourl[$idp];
656
        }
657
        return $url;
658
    }
659
660
    /**
661
     * getAuthzIdP
662
     *
663
     * This function takes in the OAuth2 authorization URL and returns
664
     * the associated pretty-print name of the IdP.
665
     *
666
     * @param string $url The authorization URL of an OAuth2 Identity Provider.
667
     * @return string The name of the IdP.
668
     */
669
    public static function getAuthzIdP($url)
670
    {
671
        $idp = null;
672
        $urltoidp = array(
673
            'https://accounts.google.com/o/oauth2/auth' => 'Google',
674
            'https://github.com/login/oauth/authorize'  => 'GitHub',
675
            'https://orcid.org/oauth/authorize'         => 'ORCID',
676
        );
677
        if (array_key_exists($url, $urltoidp)) {
678
            $idp = $urltoidp[$url];
679
        }
680
        return $idp;
681
    }
682
683
    /**
684
     * saveUserToDataStore
685
     *
686
     * This function is called when a user logs on to save identity
687
     * information to the datastore. As it is used by both Shibboleth
688
     * and OpenID Identity Providers, some parameters passed in may
689
     * be blank (empty string). If the function verifies that the minimal
690
     * sets of parameters are valid, the dbservice servlet is called
691
     * to save the user info. Then various session variables are set
692
     * for use by the program later on. In case of error, an email
693
     * alert is sent showing the missing parameters.
694
     *
695
     * @param mixed $args Variable number of parameters, the same as those
696
     *        in DBService::$user_attrs
697
     */
698
    public static function saveUserToDataStore(...$args)
699
    {
700
        $dbs = new DBService();
701
702
        // Save the passed-in variables to the session for later use
703
        // (e.g., by the error handler in handleGotUser). Then get these
704
        // session variables into local vars for ease of use.
705
        static::setUserAttributeSessionVars(...$args);
706
707
        // This bit of trickery sets local variables from the PHP session
708
        // that was just populated, using the names in the $user_attrs array.
709
        foreach (DBService::$user_attrs as $value) {
710
            $$value = static::getSessionVar($value);
711
        }
712
713
        // For the new Google OAuth 2.0 endpoint, we want to keep the
714
        // old Google OpenID endpoint URL in the database (so user does
715
        // not get a new certificate subject DN). Change the idp
716
        // and idp_display_name to the old Google OpenID values.
717
        if (
718
            ($idp_display_name == 'Google+') ||
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $idp_display_name seems to be never defined.
Loading history...
719
            ($idp == static::getAuthzUrl('Google'))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $idp seems to be never defined.
Loading history...
720
        ) {
721
            $idp_display_name = 'Google';
722
            $idp = 'https://www.google.com/accounts/o8/id';
723
        }
724
725
        // In the database, keep a consistent ProviderId format: only
726
        // allow 'http' (not 'https') and remove any 'www.' prefix.
727
        if ($loa == 'openid') {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $loa seems to be never defined.
Loading history...
728
            $idp = preg_replace('%^https://(www\.)?%', 'http://', $idp);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $idp does not seem to be defined for all execution paths leading up to this point.
Loading history...
729
        }
730
731
        // Call the dbService to get the user using IdP attributes.
732
        $result = $dbs->getUser(
733
            $remote_user,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $remote_user seems to be never defined.
Loading history...
734
            $idp,
735
            $idp_display_name,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $idp_display_name does not seem to be defined for all execution paths leading up to this point.
Loading history...
736
            $first_name,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $first_name seems to be never defined.
Loading history...
737
            $last_name,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $last_name seems to be never defined.
Loading history...
738
            $display_name,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $display_name does not exist. Did you maybe mean $idp_display_name?
Loading history...
739
            $email,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $email seems to be never defined.
Loading history...
740
            $loa,
741
            $eppn,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $eppn seems to be never defined.
Loading history...
742
            $eptid,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $eptid seems to be never defined.
Loading history...
743
            $open_id,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $open_id seems to be never defined.
Loading history...
744
            $oidc,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $oidc seems to be never defined.
Loading history...
745
            $subject_id,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $subject_id seems to be never defined.
Loading history...
746
            $pairwise_id,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $pairwise_id seems to be never defined.
Loading history...
747
            $affiliation,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $affiliation seems to be never defined.
Loading history...
748
            $ou,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ou seems to be never defined.
Loading history...
749
            $member_of,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $member_of seems to be never defined.
Loading history...
750
            $acr,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $acr seems to be never defined.
Loading history...
751
            $entitlement,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $entitlement seems to be never defined.
Loading history...
752
            $itrustuin
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $itrustuin seems to be never defined.
Loading history...
753
        );
754
        if ($result) {
755
            static::setSessionVar('user_uid', $dbs->user_uid);
756
            static::setSessionVar('distinguished_name', $dbs->distinguished_name);
757
            static::setSessionVar('status', $dbs->status);
758
        } else {
759
            static::sendErrorAlert(
760
                'dbService Error',
761
                'Error calling dbservice action "getUser" in ' .
762
                'saveUserToDatastore() method.'
763
            );
764
            static::unsetSessionVar('user_uid');
765
            static::unsetSessionVar('distinguished_name');
766
            static::setSessionVar('status', DBService::$STATUS['STATUS_INTERNAL_ERROR']);
767
        }
768
769
        // If 'status' is not STATUS_OK*, then send an error email
770
        $status = static::getSessionVar('status');
771
        if ($status & 1) { // Bad status codes are odd
772
            // For missing parameter errors, log an error message
773
            if (
774
                $status ==
775
                DBService::$STATUS['STATUS_MISSING_PARAMETER_ERROR']
776
            ) {
777
                $log = new Loggit();
778
                $log->error('STATUS_MISSING_PARAMETER_ERROR', true);
779
            }
780
781
            // For other dbservice errors OR for any error involving
782
            // LIGO (e.g., missing parameter error), send email alert.
783
            if (
784
                ($status !=
785
                    DBService::$STATUS['STATUS_MISSING_PARAMETER_ERROR']) ||
786
                (preg_match('/ligo\.org/', $idp))
787
            ) {
788
                $mailto = EMAIL_ALERTS;
0 ignored issues
show
Bug introduced by
The constant CILogon\Service\EMAIL_ALERTS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
789
790
                // CIL-205 - Notify LIGO about IdP login errors.
791
                // Set DISABLE_LIGO_ALERTS to true in the top-level
792
                // config.php file to stop LIGO failures
793
                // from being sent to EMAIL_ALERTS, but still
794
                // sent to '[email protected]'.
795
                if (preg_match('/ligo\.org/', $idp)) {
796
                    if (DISABLE_LIGO_ALERTS) {
0 ignored issues
show
Bug introduced by
The constant CILogon\Service\DISABLE_LIGO_ALERTS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
797
                        $mailto = '';
798
                    }
799
                    $mailto .= ((strlen($mailto) > 0) ? ',' : '') .
800
                        '[email protected]';
801
                }
802
803
                static::sendErrorAlert(
804
                    'Failure in ' .
805
                        (($loa == 'openid') ? '' : '/secure') . '/getuser/',
806
                    'Remote_User   = ' . ((strlen($remote_user) > 0) ?
807
                        $remote_user : '<MISSING>') . "\n" .
808
                    'IdP ID        = ' . ((strlen($idp) > 0) ?
809
                        $idp : '<MISSING>') . "\n" .
810
                    'IdP Name      = ' . ((strlen($idp_display_name) > 0) ?
811
                        $idp_display_name : '<MISSING>') . "\n" .
812
                    'First Name    = ' . ((strlen($first_name) > 0) ?
813
                        $first_name : '<MISSING>') . "\n" .
814
                    'Last Name     = ' . ((strlen($last_name) > 0) ?
815
                        $last_name : '<MISSING>') . "\n" .
816
                    'Display Name  = ' . ((strlen($display_name) > 0) ?
817
                        $display_name : '<MISSING>') . "\n" .
818
                    'Email Address = ' . ((strlen($email) > 0) ?
819
                        $email : '<MISSING>') . "\n" .
820
                    'LOA           = ' . ((strlen($loa) > 0) ?
821
                        $loa : '<MISSING>') . "\n" .
822
                    'ePPN          = ' . ((strlen($eppn) > 0) ?
823
                        $eppn : '<MISSING>') . "\n" .
824
                    'ePTID         = ' . ((strlen($eptid) > 0) ?
825
                        $eptid : '<MISSING>') . "\n" .
826
                    'OpenID ID     = ' . ((strlen($open_id) > 0) ?
827
                        $open_id : '<MISSING>') . "\n" .
828
                    'OIDC ID       = ' . ((strlen($oidc) > 0) ?
829
                        $oidc : '<MISSING>') . "\n" .
830
                    'Subject ID    = ' . ((strlen($subject_id) > 0) ?
831
                        $subject_id : '<MISSING>') . "\n" .
832
                    'Pairwise ID   = ' . ((strlen($pairwise_id) > 0) ?
833
                        $pairwise_id : '<MISSING>') . "\n" .
834
                    'Affiliation   = ' . ((strlen($affiliation) > 0) ?
835
                        $affiliation : '<MISSING>') . "\n" .
836
                    'OU            = ' . ((strlen($ou) > 0) ?
837
                        $ou : '<MISSING>') . "\n" .
838
                    'MemberOf      = ' . ((strlen($member_of) > 0) ?
839
                        $member_of : '<MISSING>') . "\n" .
840
                    'ACR           = ' . ((strlen($acr) > 0) ?
841
                        $acr : '<MISSING>') . "\n" .
842
                    'Entitlement   = ' . ((strlen($entitlement) > 0) ?
843
                        $entitlement : '<MISSING>') . "\n" .
844
                    'iTrustUIN     = ' . ((strlen($itrustuin) > 0) ?
845
                        $itrustuin : '<MISSING>') . "\n" .
846
                    'User UID      = ' . ((strlen(
847
                        $i = static::getSessionVar('user_uid')
848
                    ) > 0) ?  $i : '<MISSING>') . "\n" .
849
                    'Status Code   = ' . ((strlen(
0 ignored issues
show
Bug introduced by
Are you sure strlen($i = array_search... > 0 ? $i : '<MISSING>' of type false|integer|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

849
                    'Status Code   = ' . (/** @scrutinizer ignore-type */ (strlen(
Loading history...
850
                        $i = array_search(
0 ignored issues
show
Bug introduced by
It seems like $i = array_search($statu...vice\DBService::STATUS) can also be of type false; however, parameter $string of strlen() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

850
                        /** @scrutinizer ignore-type */ $i = array_search(
Loading history...
851
                            $status,
852
                            DBService::$STATUS
853
                        )
854
                    ) > 0) ?  $i : '<MISSING>'),
855
                    $mailto
856
                );
857
            }
858
            static::unsetSessionVar('authntime');
859
        } else {
860
            // Success! We need to overwrite current session vars with values
861
            // returned by the DBService, e.g., in case attributes were set
862
            // previously but not this time. Skip 'idp' since the PHP code
863
            // transforms 'https://' to 'http://' for database consistency.
864
            // Also skip 'loa' since that is not saved in the database.
865
            foreach (DBService::$user_attrs as $value) {
866
                if (($value != 'idp') && ($value != 'loa')) {
867
                    static::setSessionVar($value, $dbs->$value);
868
                }
869
            }
870
        }
871
    }
872
873
    /**
874
     * setUserAttributeSessionVars
875
     *
876
     * This method is called by saveUserToDatastore to put the passsed-in
877
     * variables into the PHP session for later use.
878
     *
879
     * @param mixed $args Variable number of user attribute paramters
880
     *        ordered as shown in the DBService::$user_attrs array.
881
     */
882
    public static function setUserAttributeSessionVars(...$args)
883
    {
884
        // Loop through the list of user_attrs. First, unset any previous
885
        // value for the attribute, then set the passed-in attribute value.
886
        $numattrs = count(DBService::$user_attrs);
887
        $numargs = count($args);
888
        for ($i = 0; $i < $numattrs; $i++) {
889
            static::unsetSessionVar(DBService::$user_attrs[$i]);
890
            if ($i < $numargs) {
891
                static::setSessionVar(DBService::$user_attrs[$i], $args[$i]);
892
            }
893
        }
894
895
        static::setSessionVar('status', '0');
896
        static::setSessionVar('submit', static::getSessionVar('responsesubmit'));
897
        static::setSessionVar('authntime', time());
898
        static::unsetSessionVar('responsesubmit');
899
        static::getCsrf()->setCookieAndSession();
900
    }
901
902
    /**
903
     * unsetClientSessionVars
904
     *
905
     * This function removes all of the PHP session variables related to
906
     * the client session.
907
     */
908
    public static function unsetClientSessionVars()
909
    {
910
        static::unsetSessionVar('submit');
911
912
        // Specific to 'Download Certificate' page
913
        static::unsetSessionVar('p12');
914
        static::unsetSessionVar('p12lifetime');
915
        static::unsetSessionVar('p12multiplier');
916
917
        // Specific to OAuth 1.0a flow
918
        static::unsetSessionVar('portalstatus');
919
        static::unsetSessionVar('callbackuri');
920
        static::unsetSessionVar('successuri');
921
        static::unsetSessionVar('failureuri');
922
        static::unsetSessionVar('portalname');
923
        static::unsetSessionVar('tempcred');
924
925
        // Specific to OIDC flow
926
        static::unsetSessionVar('clientparams');
927
    }
928
929
    /**
930
     * unsetUserSessionVars
931
     *
932
     * This function removes all of the PHP session variables related to
933
     * the user's session.  This will force the user to log on (again)
934
     * with their IdP and call the 'getuser' script to repopulate the PHP
935
     * session.
936
     */
937
    public static function unsetUserSessionVars()
938
    {
939
        foreach (DBService::$user_attrs as $value) {
940
            static::unsetSessionVar($value);
941
        }
942
        static::unsetSessionVar('status');
943
        static::unsetSessionVar('user_uid');
944
        static::unsetSessionVar('distinguished_name');
945
        static::unsetSessionVar('authntime');
946
        static::unsetSessionVar('cilogon_skin');
947
    }
948
949
    /**
950
     * unsetAllUserSessionVars
951
     *
952
     * This is a convenience method to clear all session variables related
953
     * to the client and the user.
954
     */
955
    public static function unsetAllUserSessionVars()
956
    {
957
        static::unsetClientSessionVars();
958
        static::unsetUserSessionVars();
959
    }
960
961
    /**
962
     * verifySessionAndCall
963
     *
964
     * This function is a convenience method called by several cases in the
965
     * main 'switch' call at the top of the index.php file. I noticed
966
     * a pattern where verifyCurrentUserSession() was called to verify the
967
     * current user session. Upon success, one or two functions were called
968
     * to continue program, flow. Upon failure, cookies and session
969
     * variables were cleared, and the main Logon page was printed. This
970
     * function encapsulates that pattern. If the user's session is valid,
971
     * the passed-in $func is called, possibly with parameters passed in as
972
     * an array. The function returns true if the session is verified, so
973
     * that other functions may be called upon return.
974
     *
975
     * @param callable $func The function to call if the current session is
976
     *        successfully verified.
977
     * @param array $params (Optional) An array of parameters to pass to the
978
     *        function. Defaults to empty array, meaning zero parameters.
979
     */
980
    public static function verifySessionAndCall($func, $params = array())
981
    {
982
        $retval = false;
983
        if (Content::verifyCurrentUserSession()) { // Verify PHP session is valid
984
            $retval = true;
985
            call_user_func_array($func, $params);
986
        } else {
987
            printLogonPage(true); // Clear cookies and session vars too
0 ignored issues
show
Bug introduced by
The function printLogonPage was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

987
            /** @scrutinizer ignore-call */ 
988
            printLogonPage(true); // Clear cookies and session vars too
Loading history...
988
        }
989
        return $retval;
990
    }
991
992
    /**
993
     * isEduGAINAndGetCert
994
     *
995
     * This function checks to see if the current session IdP is an
996
     * eduGAIN IdP (i.e., not Registered By InCommon) and the IdP does not
997
     * have both the REFEDS R&S and SIRTFI extensions in metadata. If so,
998
     * check to see if the transaction could be used to fetch a
999
     * certificate. (The only time the transaction is not used to fetch
1000
     * a cert is during OIDC without the 'getcert' scope.) If all that is
1001
     * true, then return true. Otherwise return false.
1002
     *
1003
     * @param string $idp (optional) The IdP entityID. If empty, read value
1004
     *        from PHP session.
1005
     * @param string $idp_display_name (optional) The IdP display name. If empty,
1006
     *        read value from PHP session.
1007
     * @return bool True if the current IdP is an eduGAIN IdP without
1008
     *         both REFEDS R&S and SIRTFI, AND the session could be
1009
     *         used to get a certificate.
1010
     */
1011
    public static function isEduGAINAndGetCert($idp = '', $idp_display_name = '')
1012
    {
1013
        $retval = false; // Assume not eduGAIN IdP and getcert
1014
1015
        // If $idp or $idp_display_name not passed in, get from current session.
1016
        if (strlen($idp) == 0) {
1017
            $idp = static::getSessionVar('idp');
1018
        }
1019
        if (strlen($idp_display_name) == 0) {
1020
            $idp_display_name = static::getSessionVar('idp_display_name');
1021
        }
1022
1023
        // Check if this was an OIDC transaction, and if the
1024
        // 'getcert' scope was requested.
1025
        $oidcscopegetcert = false;
1026
        $oidctrans = false;
1027
        $clientparams = json_decode(static::getSessionVar('clientparams'), true);
1028
        if (isset($clientparams['scope'])) {
1029
            $oidctrans = true;
1030
            if (
1031
                preg_match(
1032
                    '/edu.uiuc.ncsa.myproxy.getcert/',
1033
                    $clientparams['scope']
1034
                )
1035
            ) {
1036
                $oidcscopegetcert = true;
1037
            }
1038
        }
1039
1040
        // First, make sure $idp was set and is not an OAuth2 IdP.
1041
        $idplist = static::getIdpList();
1042
        if (
1043
            ((strlen($idp) > 0) &&
1044
            (strlen($idp_display_name) > 0) &&
1045
            (!in_array($idp_display_name, static::$oauth2idps))) &&
1046
                (
1047
                // Next, check for eduGAIN without REFEDS R&S and SIRTFI
1048
                ((!$idplist->isRegisteredByInCommon($idp)) &&
1049
                       ((!$idplist->isREFEDSRandS($idp)) ||
1050
                        (!$idplist->isSIRTFI($idp))
1051
                       )
1052
                ) &&
1053
                // Next, check if user could get X509 cert,
1054
                // i.e., OIDC getcert scope, or a non-OIDC
1055
                // transaction such as PKCS12, JWS, or OAuth 1.0a
1056
                ($oidcscopegetcert || !$oidctrans)
1057
                )
1058
        ) {
1059
            $retval = true;
1060
        }
1061
        return $retval;
1062
    }
1063
1064
    /**
1065
     * setPortalOrCookieVar
1066
     *
1067
     * This is a convenience function for a set of operations that is done
1068
     * a few times in Content.php. It first checks if the name of the portal
1069
     * in the PortalCookie is empty. If not, then it sets the PortalCookie
1070
     * key/value pair. Otherwise, it sets the 'normal' cookie key/value
1071
     * pair.
1072
     *
1073
     * @param PortalCookie $pc The PortalCookie to read/write. If the portal
1074
     *        name is empty, then use the 'normal' cookie instead.
1075
     * @param string $key The key of the PortalCookie or 'normal' cookie to
1076
     *        set.
1077
     * @param string $value The value to set for the $key.
1078
     * @param bool $save (optional) If set to true, attempt to write the
1079
     *        PortalCookie. Defaults to false.
1080
     */
1081
    public static function setPortalOrCookieVar($pc, $key, $value, $save = false)
1082
    {
1083
        $pn = $pc->getPortalName();
1084
        // If the portal name is valid, then set the PortalCookie key/value
1085
        if (strlen($pn) > 0) {
1086
            $pc->set($key, $value);
1087
            if ($save) {
1088
                $pc->write();
1089
            }
1090
        } else { // If portal name is not valid, then use the 'normal' cookie
1091
            if (strlen($value) > 0) {
1092
                Util::setCookieVar($key, $value);
1093
            } else { // If $value is empty, then UNset the 'normal' cookie
1094
                Util::unsetCookieVar($key);
1095
            }
1096
        }
1097
    }
1098
1099
    /**
1100
     * getOIDCClientParams
1101
     *
1102
     * This function addresses CIL-618 and reads OIDC client information
1103
     * directly from the database. It is a replacement for
1104
     * $dbs->getClient($clientparams['client_id']) which calls
1105
     * '/dbService?action=getClient&client_id=...'. This gives the PHP
1106
     * '/authorize' endpoint access to additional OIDC client parameters
1107
     * without having to rewrite the '/dbService?action=getClient' endpoint.
1108
     *
1109
     * @param array $clientparams An array of client parameters which gets
1110
     *              stored in the PHP session. The keys of the array are
1111
     *              the column names of the 'client' table in the 'ciloa2'
1112
     *              database, prefixed by 'client_'.
1113
     */
1114
    public static function getOIDCClientParams(&$clientparams)
1115
    {
1116
        $retval = false;
1117
        if (strlen(@$clientparams['client_id']) > 0) {
1118
            $dsn = array(
1119
                'phptype'  => 'mysqli',
1120
                'username' => MYSQLI_USERNAME,
0 ignored issues
show
Bug introduced by
The constant CILogon\Service\MYSQLI_USERNAME was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1121
                'password' => MYSQLI_PASSWORD,
0 ignored issues
show
Bug introduced by
The constant CILogon\Service\MYSQLI_PASSWORD was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1122
                'database' => 'ciloa2',
1123
                'hostspec' => 'localhost'
1124
            );
1125
1126
            $opts = array(
1127
                'persistent'  => true,
1128
                'portability' => DB_PORTABILITY_ALL
1129
            );
1130
1131
            $db = DB::connect($dsn, $opts);
1132
            if (!PEAR::isError($db)) {
1133
                $data = $db->getRow(
1134
                    'SELECT name,home_url,callback_uri,scopes from clients WHERE client_id = ?',
1135
                    array($clientparams['client_id']),
1136
                    DB_FETCHMODE_ASSOC
1137
                );
1138
                if (!DB::isError($data)) {
1139
                    if (!empty($data)) {
1140
                        foreach ($data as $key => $value) {
1141
                            $clientparams['client_' . $key] = $value;
1142
                        }
1143
                        $clientparams['clientstatus'] = DBService::$STATUS['STATUS_OK'];
1144
                        $retval = true;
1145
                    }
1146
                }
1147
                $db->disconnect();
1148
            }
1149
        }
1150
        return $retval;
1151
    }
1152
1153
    /**
1154
     * getMinMaxLifetimes
1155
     *
1156
     * This function checks the skin's configuration to see if either or
1157
     * both of minlifetime and maxlifetime in the specified config.xml
1158
     * block have been set. If not, default to minlifetime of 1 (hour) and
1159
     * the specified defaultmaxlifetime.
1160
     *
1161
     * @param string $section The XML section block from which to read the
1162
     *        minlifetime and maxlifetime values. Can be one of the
1163
     *        following: 'pkcs12' or 'delegate'.
1164
     * @param int $defaultmaxlifetime Default maxlifetime (in hours) for the
1165
     *        credential.
1166
     * @return array An array consisting of two entries: the minimum and
1167
     *         maximum lifetimes (in hours) for a credential.
1168
     */
1169
    public static function getMinMaxLifetimes($section, $defaultmaxlifetime)
1170
    {
1171
        $minlifetime = 1;    // Default minimum lifetime is 1 hour
1172
        $maxlifetime = $defaultmaxlifetime;
1173
        $skin = Util::getSkin();
1174
        $skinminlifetime = $skin->getConfigOption($section, 'minlifetime');
1175
        // Read the skin's minlifetime value from the specified section
1176
        if ((!is_null($skinminlifetime)) && ((int)$skinminlifetime > 0)) {
1177
            $minlifetime = max($minlifetime, (int)$skinminlifetime);
1178
            // Make sure $minlifetime is less than $maxlifetime;
1179
            $minlifetime = min($minlifetime, $maxlifetime);
1180
        }
1181
        // Read the skin's maxlifetime value from the specified section
1182
        $skinmaxlifetime = $skin->getConfigOption($section, 'maxlifetime');
1183
        if ((!is_null($skinmaxlifetime)) && ((int)$skinmaxlifetime) > 0) {
1184
            $maxlifetime = min($maxlifetime, (int)$skinmaxlifetime);
1185
            // Make sure $maxlifetime is greater than $minlifetime
1186
            $maxlifetime = max($minlifetime, $maxlifetime);
1187
        }
1188
1189
        return array($minlifetime, $maxlifetime);
1190
    }
1191
1192
    /**
1193
     * isLOASilver
1194
     *
1195
     * This function returns true if the 'loa' (level of assurance)
1196
     * should be http://incommonfederation.org/assurance/silver .
1197
     * As specified in CACC-238, this is when both of the following are true:
1198
     * (1) loa contains  https://refeds.org/assurance/profile/cappuccino
1199
     * (2) acr is either https://refeds.org/profile/sfa or
1200
     *                   https://refeds.org/profile/mfa
1201
     *
1202
     * @return bool True if level of assurance is 'silver'.
1203
     */
1204
    public static function isLOASilver()
1205
    {
1206
        $retval = false;
1207
        if (
1208
            (preg_match('%https://refeds.org/assurance/profile/cappuccino%', static::getSessionVar('loa'))) &&
1209
            (preg_match('%https://refeds.org/profile/[ms]fa%', static::getSessionVar('acr')))
1210
        ) {
1211
            $retval = true;
1212
        }
1213
        return $retval;
1214
    }
1215
1216
    /**
1217
     * getLOA
1218
     *
1219
     * This function is a bit of a hack. Once upon a time, the level of
1220
     * assurance (loa) was one of empty string (which implied 'basic
1221
     * CA'), 'openid' (which implied 'openid CA'), or
1222
     * 'http://incommonfederation.org/assurance/silver' (which implied
1223
     * 'silver CA'). Then things got more complex when the silver
1224
     * assurance was replaced by cappuccino (see CACC-238). But parts of the
1225
     * PHP code still depeneded on the InCommon silver string.
1226
     *
1227
     * This function transforms the assurance attribute asserted by an IdP
1228
     * (which is stored in the 'loa' session variable) into one of
1229
     * empty string (for 'basic CA'), 'openid', or
1230
     * 'http://incommonfederation.org/assurance/silver' for use by those
1231
     * PHP functions which expect the 'loa' in this format.
1232
     *
1233
     * @return string One of empty string, 'openid', or
1234
     *         'http://incommonfederation.org/assurance/silver'
1235
     */
1236
    public static function getLOA()
1237
    {
1238
        $retval = '';
1239
        if (static::isLOASilver()) {
1240
            $retval = 'http://incommonfederation.org/assurance/silver';
1241
        } else {
1242
            $retval = static::getSessionVar('loa');
1243
        }
1244
        return $retval;
1245
    }
1246
1247
    /**
1248
     * getLOAPort
1249
     *
1250
     * This function returns the port to be used for MyProxy based on the
1251
     * level of assurance.
1252
     *     Basic  CA = 7512
1253
     *     Silver CA = 7514
1254
     *     OpenID CA = 7516
1255
     *
1256
     * @return int The MyProxy port number to be used based on the 'level
1257
     *         of assurance' (basic, silver, openid).
1258
     */
1259
    public static function getLOAPort()
1260
    {
1261
        $port = 7512; // Basic
1262
        if (Util::isLOASilver()) {
1263
            $port = 7514;
1264
        } elseif (Util::getSessionVar('loa') == 'openid') {
1265
            $port = 7516;
1266
        }
1267
        return $port;
1268
    }
1269
1270
    /**
1271
     * getFirstAndLastName
1272
     *
1273
     * This function attempts to get the first and last name of a user
1274
     * extracted from the 'full name' (displayName) of the user.
1275
     * Simply pass in all name info (full, first, and last) and the
1276
     * function first tries to break up the full name into first/last.
1277
     * If this is not sufficient, the function checks first and last
1278
     * name. Finally, if either first or last is blank, the function
1279
     * duplicates first <=> last so both names have the same value.
1280
     * Note that even with all this, you still need to check if the
1281
     * returned (first,last) names are blank.
1282
     *
1283
     * @param string $full The 'full name' of the user
1284
     * @param string $first (Optional) The 'first name' of the user
1285
     * @param string $last (Optional) The 'last name' of the user
1286
     * @return array An array 'list(firstname,lastname)'
1287
     */
1288
    public static function getFirstAndLastName($full, $first = '', $last = '')
1289
    {
1290
        $firstname = '';
1291
        $lastname = '';
1292
1293
        # Try to split the incoming $full name into first and last names
1294
        if (strlen($full) > 0) {
1295
            $names = preg_split('/\s+/', $full, 2);
1296
            $firstname = @$names[0];
1297
            $lastname =  @$names[1];
1298
        }
1299
1300
        # If either first or last name blank, then use incoming $first and $last
1301
        if (strlen($firstname) == 0) {
1302
            $firstname = $first;
1303
        }
1304
        if (strlen($lastname) == 0) {
1305
            $lastname = $last;
1306
        }
1307
1308
        # Finally, if only a single name, copy first name <=> last name
1309
        if (strlen($lastname) == 0) {
1310
            $lastname = $firstname;
1311
        }
1312
        if (strlen($firstname) == 0) {
1313
            $firstname = $lastname;
1314
        }
1315
1316
        # Return both names as an array (i.e., use list($first,last)=...)
1317
        return array($firstname,$lastname);
1318
    }
1319
}
1320