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

Util::getFirstAndLastName()   A

Complexity

Conditions 6
Paths 32

Size

Total Lines 30
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
eloc 15
c 2
b 0
f 0
nc 32
nop 3
dl 0
loc 30
ccs 0
cts 4
cp 0
crap 42
rs 9.2222

1 Method

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

388
    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...
389
    {
390
        // No parameter given? Use the value read in from cilogon.ini file.
391
        // If STORAGE_PHPSESSIONS == 'mysqli', create a sessionmgr().
392
        $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...
393
394
        if (preg_match('/^mysql/', $storetype)) {
395
            $sessionmgr = new SessionMgr();
0 ignored issues
show
Unused Code introduced by
The assignment to $sessionmgr is dead and can be removed.
Loading history...
396
        }
397
398
        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

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

499
                            /** @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...
500
                        } else {
501
                            @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

501
                            /** @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...
502
                        }
503
                    }
504
                }
505
            }
506
            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

506
            reset(/** @scrutinizer ignore-type */ $objects);
Loading history...
507
            @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

507
            /** @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...
508
        }
509
    }
510
511
    /**
512
     * htmlent
513
     *
514
     * This method is necessary since htmlentities() does not seem to
515
     * obey the default arguments as documented in the PHP manual, and
516
     * instead encodes accented characters incorrectly. By specifying
517
     * the flags and encoding, the problem is solved.
518
     *
519
     * @param string $str : A string to process with htmlentities().
520
     * @return string The input string processed by htmlentities with
521
     *         specific options.
522
     */
523
    public static function htmlent($str)
524
    {
525
        return htmlentities($str, ENT_COMPAT | ENT_HTML401, 'UTF-8');
526
    }
527
528
    /**
529
     * sendErrorAlert
530
     *
531
     * Use this function to send an error message. The $summary should
532
     * be a short description of the error since it is placed in the
533
     * subject of the email. Put a more verbose description of the
534
     * error in the $detail parameter. Any session variables available
535
     * are appended to the body of the message.
536
     *
537
     * @param string $summary A brief summary of the error (in email subject)
538
     * @param string $detail A detailed description of the error (in the
539
     *        email body)
540
     * @param string $mailto (Optional) The destination email address.
541
     *        Defaults to EMAIL_ALERTS (defined in the top-level
542
     *        config.php file as 'alerts@' . DEFAULT_HOSTNAME).
543
     */
544
    public static function sendErrorAlert(
545
        $summary,
546
        $detail,
547
        $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...
548
    ) {
549
        $sessionvars = array(
550
            'idp'                => 'IdP ID',
551
            'idp_display_name'   => 'IdP Name',
552
            'user_uid'           => 'User UID',
553
            'distinguished_name' => 'Cert DN',
554
            'first_name'         => 'First Name',
555
            'last_name'          => 'Last Name',
556
            'display_name'       => 'Display Name',
557
            'eppn'               => 'ePPN',
558
            'eptid'              => 'ePTID',
559
            'open_id'            => 'OpenID ID',
560
            'oidc'               => 'OIDC ID',
561
            'subject_id'         => 'Subject ID',
562
            'pairwise_id'        => 'Pairwise ID',
563
            'loa'                => 'LOA',
564
            'affiliation'        => 'Affiliation',
565
            'ou'                 => 'OU',
566
            'member_of'          => 'MemberOf',
567
            'acr'                => 'AuthnContextClassRef',
568
            'entitlement'        => 'Entitlement',
569
            'itrustuin'          => 'iTrustUIN',
570
            'cilogon_skin'       => 'Skin Name',
571
            'authntime'          => 'Authn Time'
572
        );
573
574
        $remoteaddr = static::getServerVar('REMOTE_ADDR');
575
        $remotehost = gethostbyaddr($remoteaddr);
576
        $mailfrom = 'From: ' . EMAIL_ALERTS . "\r\n" .
577
                    'X-Mailer: PHP/' . phpversion();
578
        $mailsubj = 'CILogon Service on ' . php_uname('n') .
579
                    ' - ' . $summary;
580
        $mailmsg  = '
581
CILogon Service - ' . $summary . '
582
-----------------------------------------------------------
583
' . $detail . '
584
585
Session Variables
586
-----------------
587
Timestamp     = ' . date(DATE_ATOM) . '
588
Server Host   = ' . static::getHN() . '
589
Remote Address= ' . $remoteaddr . '
590
' . (($remotehost !== false) ? "Remote Host   = $remotehost" : '') . '
591
';
592
593
        foreach ($sessionvars as $svar => $sname) {
594
            if (strlen($val = static::getSessionVar($svar)) > 0) {
595
                $mailmsg .= sprintf("%-14s= %s\n", $sname, $val);
596
            }
597
        }
598
599
        mail($mailto, $mailsubj, $mailmsg, $mailfrom);
600
    }
601
602
    /**
603
     * getHN
604
     *
605
     * This function calculates and returns the 'hostname' for the
606
     * server. It first checks HTTP_HOST. If not set, it returns
607
     * DEFAULT_HOSTNAME. This is needed by command line scripts.
608
     *
609
     * @return string The 'Hostname' for the web server.
610
     */
611
    public static function getHN()
612
    {
613
        $thehostname = static::getServerVar('HTTP_HOST');
614
        if (strlen($thehostname) == 0) {
615
            $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...
616
        }
617
        return $thehostname;
618
    }
619
620
    /**
621
     * getDN
622
     *
623
     * This function calculates and returns the 'domainname' for the
624
     * server. It uses the hostname value calculated by getHN() and
625
     * uses the last two segments.
626
     *
627
     * @return string The 'Domainname' for the web server.
628
     */
629
    public static function getDN()
630
    {
631
        $thedomainname = static::getHN();
632
        if (preg_match('/[^\.]+\.[^\.]+$/', $thedomainname, $matches)) {
633
            $thedomainname = $matches[0];
634
        }
635
        return $thedomainname;
636
    }
637
638
    /**
639
     * getAuthzUrl
640
     *
641
     * This funtion takes in the name of an IdP (e.g., 'Google') and
642
     * returns the assoicated OAuth2 authorization URL.
643
     *
644
     * @param string $idp The name of an OAuth2 Identity Provider.
645
     * @return string The authorization URL for the given IdP.
646
     */
647
    public static function getAuthzUrl($idp)
648
    {
649
        $url = null;
650
        $idptourl = array(
651
            'Google' => 'https://accounts.google.com/o/oauth2/auth',
652
            'GitHub' => 'https://github.com/login/oauth/authorize',
653
            'ORCID'  => 'https://orcid.org/oauth/authorize',
654
        );
655
        if (array_key_exists($idp, $idptourl)) {
656
            $url = $idptourl[$idp];
657
        }
658
        return $url;
659
    }
660
661
    /**
662
     * getAuthzIdP
663
     *
664
     * This function takes in the OAuth2 authorization URL and returns
665
     * the associated pretty-print name of the IdP.
666
     *
667
     * @param string $url The authorization URL of an OAuth2 Identity Provider.
668
     * @return string The name of the IdP.
669
     */
670
    public static function getAuthzIdP($url)
671
    {
672
        $idp = null;
673
        $urltoidp = array(
674
            'https://accounts.google.com/o/oauth2/auth' => 'Google',
675
            'https://github.com/login/oauth/authorize'  => 'GitHub',
676
            'https://orcid.org/oauth/authorize'         => 'ORCID',
677
        );
678
        if (array_key_exists($url, $urltoidp)) {
679
            $idp = $urltoidp[$url];
680
        }
681
        return $idp;
682
    }
683
684
    /**
685
     * saveUserToDataStore
686
     *
687
     * This function is called when a user logs on to save identity
688
     * information to the datastore. As it is used by both Shibboleth
689
     * and OpenID Identity Providers, some parameters passed in may
690
     * be blank (empty string). If the function verifies that the minimal
691
     * sets of parameters are valid, the dbservice servlet is called
692
     * to save the user info. Then various session variables are set
693
     * for use by the program later on. In case of error, an email
694
     * alert is sent showing the missing parameters.
695
     *
696
     * @param mixed $args Variable number of parameters, the same as those
697
     *        in DBService::$user_attrs
698
     */
699
    public static function saveUserToDataStore(...$args)
700
    {
701
        $dbs = new DBService();
702
703
        // Save the passed-in variables to the session for later use
704
        // (e.g., by the error handler in handleGotUser). Then get these
705
        // session variables into local vars for ease of use.
706
        static::setUserAttributeSessionVars(...$args);
707
708
        // Set local variables from the PHP session that was just populated
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
        $numargs = count($args);
885
        for ($i = 0; $i < $numargs; $i++) {
886
            static::setSessionVar(DBService::$user_attrs[$i], $args[$i]);
887
        }
888
889
        static::setSessionVar('status', '0');
890
        static::setSessionVar('submit', static::getSessionVar('responsesubmit'));
891
        static::setSessionVar('authntime', time());
892
        static::unsetSessionVar('responsesubmit');
893
        static::getCsrf()->setCookieAndSession();
894
    }
895
896
    /**
897
     * unsetClientSessionVars
898
     *
899
     * This function removes all of the PHP session variables related to
900
     * the client session.
901
     */
902
    public static function unsetClientSessionVars()
903
    {
904
        static::unsetSessionVar('submit');
905
906
        // Specific to 'Download Certificate' page
907
        static::unsetSessionVar('p12');
908
        static::unsetSessionVar('p12lifetime');
909
        static::unsetSessionVar('p12multiplier');
910
911
        // Specific to OAuth 1.0a flow
912
        static::unsetSessionVar('portalstatus');
913
        static::unsetSessionVar('callbackuri');
914
        static::unsetSessionVar('successuri');
915
        static::unsetSessionVar('failureuri');
916
        static::unsetSessionVar('portalname');
917
        static::unsetSessionVar('tempcred');
918
919
        // Specific to OIDC flow
920
        static::unsetSessionVar('clientparams');
921
    }
922
923
    /**
924
     * unsetUserSessionVars
925
     *
926
     * This function removes all of the PHP session variables related to
927
     * the user's session.  This will force the user to log on (again)
928
     * with their IdP and call the 'getuser' script to repopulate the PHP
929
     * session.
930
     */
931
    public static function unsetUserSessionVars()
932
    {
933
        foreach (DBService::$user_attrs as $value) {
934
            static::unsetSessionVar($value);
935
        }
936
        static::unsetSessionVar('status');
937
        static::unsetSessionVar('user_uid');
938
        static::unsetSessionVar('distinguished_name');
939
        static::unsetSessionVar('authntime');
940
        static::unsetSessionVar('cilogon_skin');
941
    }
942
943
    /**
944
     * unsetAllUserSessionVars
945
     *
946
     * This is a convenience method to clear all session variables related
947
     * to the client and the user.
948
     */
949
    public static function unsetAllUserSessionVars()
950
    {
951
        static::unsetClientSessionVars();
952
        static::unsetUserSessionVars();
953
    }
954
955
    /**
956
     * verifySessionAndCall
957
     *
958
     * This function is a convenience method called by several cases in the
959
     * main 'switch' call at the top of the index.php file. I noticed
960
     * a pattern where verifyCurrentUserSession() was called to verify the
961
     * current user session. Upon success, one or two functions were called
962
     * to continue program, flow. Upon failure, cookies and session
963
     * variables were cleared, and the main Logon page was printed. This
964
     * function encapsulates that pattern. If the user's session is valid,
965
     * the passed-in $func is called, possibly with parameters passed in as
966
     * an array. The function returns true if the session is verified, so
967
     * that other functions may be called upon return.
968
     *
969
     * @param callable $func The function to call if the current session is
970
     *        successfully verified.
971
     * @param array $params (Optional) An array of parameters to pass to the
972
     *        function. Defaults to empty array, meaning zero parameters.
973
     */
974
    public static function verifySessionAndCall($func, $params = array())
975
    {
976
        $retval = false;
977
        if (Content::verifyCurrentUserSession()) { // Verify PHP session is valid
978
            $retval = true;
979
            call_user_func_array($func, $params);
980
        } else {
981
            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

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