Passed
Push — master ( 82b957...099118 )
by Terrence
13:54
created

src/Service/Util.php (2 issues)

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)
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;
392
393
        if (preg_match('/^mysql/', $storetype)) {
394
            $sessionmgr = new SessionMgr();
395
        }
396
397
        ini_set('session.cookie_secure', true);
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 = '';
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);
499
                        } else {
500
                            @unlink($dir . "/" . $object);
501
                        }
502
                    }
503
                }
504
            }
505
            reset($objects);
506
            @rmdir($dir);
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
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
            'amr'                => 'AuthnMethodRef',
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;
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
        // This bit of trickery sets local variables from the PHP session
709
        // that was just populated, using the names in the $user_attrs array.
710
        foreach (DBService::$user_attrs as $value) {
711
            $$value = static::getSessionVar($value);
712
        }
713
714
        // For the new Google OAuth 2.0 endpoint, we want to keep the
715
        // old Google OpenID endpoint URL in the database (so user does
716
        // not get a new certificate subject DN). Change the idp
717
        // and idp_display_name to the old Google OpenID values.
718
        if (
719
            ($idp_display_name == 'Google+') ||
720
            ($idp == static::getAuthzUrl('Google'))
721
        ) {
722
            $idp_display_name = 'Google';
723
            $idp = 'https://www.google.com/accounts/o8/id';
724
        }
725
726
        // In the database, keep a consistent ProviderId format: only
727
        // allow 'http' (not 'https') and remove any 'www.' prefix.
728
        if ($loa == 'openid') {
729
            $idp = preg_replace('%^https://(www\.)?%', 'http://', $idp);
730
        }
731
732
        // Call the dbService to get the user using IdP attributes.
733
        $result = $dbs->getUser(
734
            $remote_user,
735
            $idp,
736
            $idp_display_name,
737
            $first_name,
738
            $last_name,
739
            $display_name,
740
            $email,
741
            $loa,
742
            $eppn,
743
            $eptid,
744
            $open_id,
745
            $oidc,
746
            $subject_id,
747
            $pairwise_id,
748
            $affiliation,
749
            $ou,
750
            $member_of,
751
            $acr,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $acr seems to be never defined.
Loading history...
752
            $amr,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $amr seems to be never defined.
Loading history...
753
            $entitlement,
754
            $itrustuin
755
        );
756
        if ($result) {
757
            static::setSessionVar('user_uid', $dbs->user_uid);
758
            static::setSessionVar('distinguished_name', $dbs->distinguished_name);
759
            static::setSessionVar('status', $dbs->status);
760
        } else {
761
            static::sendErrorAlert(
762
                'dbService Error',
763
                'Error calling dbservice action "getUser" in ' .
764
                'saveUserToDatastore() method.'
765
            );
766
            static::unsetSessionVar('user_uid');
767
            static::unsetSessionVar('distinguished_name');
768
            static::setSessionVar('status', DBService::$STATUS['STATUS_INTERNAL_ERROR']);
769
        }
770
771
        // If 'status' is not STATUS_OK*, then send an error email
772
        $status = static::getSessionVar('status');
773
        if ($status & 1) { // Bad status codes are odd
774
            // For missing parameter errors, log an error message
775
            if (
776
                $status ==
777
                DBService::$STATUS['STATUS_MISSING_PARAMETER_ERROR']
778
            ) {
779
                $log = new Loggit();
780
                $log->error('STATUS_MISSING_PARAMETER_ERROR', true);
781
            }
782
783
            // For other dbservice errors OR for any error involving
784
            // LIGO (e.g., missing parameter error), send email alert.
785
            if (
786
                ($status !=
787
                    DBService::$STATUS['STATUS_MISSING_PARAMETER_ERROR']) ||
788
                (preg_match('/ligo\.org/', $idp))
789
            ) {
790
                $mailto = EMAIL_ALERTS;
791
792
                // CIL-205 - Notify LIGO about IdP login errors.
793
                // Set DISABLE_LIGO_ALERTS to true in the top-level
794
                // config.php file to stop LIGO failures
795
                // from being sent to EMAIL_ALERTS, but still
796
                // sent to '[email protected]'.
797
                if (preg_match('/ligo\.org/', $idp)) {
798
                    if (DISABLE_LIGO_ALERTS) {
799
                        $mailto = '';
800
                    }
801
                    $mailto .= ((strlen($mailto) > 0) ? ',' : '') .
802
                        '[email protected]';
803
                }
804
805
                static::sendErrorAlert(
806
                    'Failure in ' .
807
                        (($loa == 'openid') ? '' : '/secure') . '/getuser/',
808
                    'Remote_User   = ' . ((strlen($remote_user) > 0) ?
809
                        $remote_user : '<MISSING>') . "\n" .
810
                    'IdP ID        = ' . ((strlen($idp) > 0) ?
811
                        $idp : '<MISSING>') . "\n" .
812
                    'IdP Name      = ' . ((strlen($idp_display_name) > 0) ?
813
                        $idp_display_name : '<MISSING>') . "\n" .
814
                    'First Name    = ' . ((strlen($first_name) > 0) ?
815
                        $first_name : '<MISSING>') . "\n" .
816
                    'Last Name     = ' . ((strlen($last_name) > 0) ?
817
                        $last_name : '<MISSING>') . "\n" .
818
                    'Display Name  = ' . ((strlen($display_name) > 0) ?
819
                        $display_name : '<MISSING>') . "\n" .
820
                    'Email Address = ' . ((strlen($email) > 0) ?
821
                        $email : '<MISSING>') . "\n" .
822
                    'LOA           = ' . ((strlen($loa) > 0) ?
823
                        $loa : '<MISSING>') . "\n" .
824
                    'ePPN          = ' . ((strlen($eppn) > 0) ?
825
                        $eppn : '<MISSING>') . "\n" .
826
                    'ePTID         = ' . ((strlen($eptid) > 0) ?
827
                        $eptid : '<MISSING>') . "\n" .
828
                    'OpenID ID     = ' . ((strlen($open_id) > 0) ?
829
                        $open_id : '<MISSING>') . "\n" .
830
                    'OIDC ID       = ' . ((strlen($oidc) > 0) ?
831
                        $oidc : '<MISSING>') . "\n" .
832
                    'Subject ID    = ' . ((strlen($subject_id) > 0) ?
833
                        $subject_id : '<MISSING>') . "\n" .
834
                    'Pairwise ID   = ' . ((strlen($pairwise_id) > 0) ?
835
                        $pairwise_id : '<MISSING>') . "\n" .
836
                    'Affiliation   = ' . ((strlen($affiliation) > 0) ?
837
                        $affiliation : '<MISSING>') . "\n" .
838
                    'OU            = ' . ((strlen($ou) > 0) ?
839
                        $ou : '<MISSING>') . "\n" .
840
                    'MemberOf      = ' . ((strlen($member_of) > 0) ?
841
                        $member_of : '<MISSING>') . "\n" .
842
                    'ACR           = ' . ((strlen($acr) > 0) ?
843
                        $acr : '<MISSING>') . "\n" .
844
                    'AMR           = ' . ((strlen($amr) > 0) ?
845
                        $amr : '<MISSING>') . "\n" .
846
                    'Entitlement   = ' . ((strlen($entitlement) > 0) ?
847
                        $entitlement : '<MISSING>') . "\n" .
848
                    'iTrustUIN     = ' . ((strlen($itrustuin) > 0) ?
849
                        $itrustuin : '<MISSING>') . "\n" .
850
                    'User UID      = ' . ((strlen(
851
                        $i = static::getSessionVar('user_uid')
852
                    ) > 0) ?  $i : '<MISSING>') . "\n" .
853
                    'Status Code   = ' . ((strlen(
854
                        $i = array_search(
855
                            $status,
856
                            DBService::$STATUS
857
                        )
858
                    ) > 0) ?  $i : '<MISSING>'),
859
                    $mailto
860
                );
861
            }
862
            static::unsetSessionVar('authntime');
863
        } else {
864
            // Success! We need to overwrite current session vars with values
865
            // returned by the DBService, e.g., in case attributes were set
866
            // previously but not this time. Skip 'idp' since the PHP code
867
            // transforms 'https://' to 'http://' for database consistency.
868
            // Also skip 'loa' since that is not saved in the database.
869
            foreach (DBService::$user_attrs as $value) {
870
                if (($value != 'idp') && ($value != 'loa')) {
871
                    static::setSessionVar($value, $dbs->$value);
872
                }
873
            }
874
        }
875
    }
876
877
    /**
878
     * setUserAttributeSessionVars
879
     *
880
     * This method is called by saveUserToDatastore to put the passsed-in
881
     * variables into the PHP session for later use.
882
     *
883
     * @param mixed $args Variable number of user attribute paramters
884
     *        ordered as shown in the DBService::$user_attrs array.
885
     */
886
    public static function setUserAttributeSessionVars(...$args)
887
    {
888
        // Loop through the list of user_attrs. First, unset any previous
889
        // value for the attribute, then set the passed-in attribute value.
890
        $numattrs = count(DBService::$user_attrs);
891
        $numargs = count($args);
892
        for ($i = 0; $i < $numattrs; $i++) {
893
            static::unsetSessionVar(DBService::$user_attrs[$i]);
894
            if ($i < $numargs) {
895
                static::setSessionVar(DBService::$user_attrs[$i], $args[$i]);
896
            }
897
        }
898
899
        static::setSessionVar('status', '0');
900
        static::setSessionVar('submit', static::getSessionVar('responsesubmit'));
901
        static::setSessionVar('authntime', time());
902
        static::unsetSessionVar('responsesubmit');
903
        static::getCsrf()->setCookieAndSession();
904
    }
905
906
    /**
907
     * unsetClientSessionVars
908
     *
909
     * This function removes all of the PHP session variables related to
910
     * the client session.
911
     */
912
    public static function unsetClientSessionVars()
913
    {
914
        static::unsetSessionVar('submit');
915
916
        // Specific to 'Download Certificate' page
917
        static::unsetSessionVar('p12');
918
        static::unsetSessionVar('p12lifetime');
919
        static::unsetSessionVar('p12multiplier');
920
921
        // Specific to OAuth 1.0a flow
922
        static::unsetSessionVar('portalstatus');
923
        static::unsetSessionVar('callbackuri');
924
        static::unsetSessionVar('successuri');
925
        static::unsetSessionVar('failureuri');
926
        static::unsetSessionVar('portalname');
927
        static::unsetSessionVar('tempcred');
928
929
        // Specific to OIDC flow
930
        static::unsetSessionVar('clientparams');
931
    }
932
933
    /**
934
     * unsetUserSessionVars
935
     *
936
     * This function removes all of the PHP session variables related to
937
     * the user's session.  This will force the user to log on (again)
938
     * with their IdP and call the 'getuser' script to repopulate the PHP
939
     * session.
940
     */
941
    public static function unsetUserSessionVars()
942
    {
943
        foreach (DBService::$user_attrs as $value) {
944
            static::unsetSessionVar($value);
945
        }
946
        static::unsetSessionVar('status');
947
        static::unsetSessionVar('user_uid');
948
        static::unsetSessionVar('distinguished_name');
949
        static::unsetSessionVar('authntime');
950
        static::unsetSessionVar('cilogon_skin');
951
    }
952
953
    /**
954
     * unsetAllUserSessionVars
955
     *
956
     * This is a convenience method to clear all session variables related
957
     * to the client and the user.
958
     */
959
    public static function unsetAllUserSessionVars()
960
    {
961
        static::unsetClientSessionVars();
962
        static::unsetUserSessionVars();
963
    }
964
965
    /**
966
     * verifySessionAndCall
967
     *
968
     * This function is a convenience method called by several cases in the
969
     * main 'switch' call at the top of the index.php file. I noticed
970
     * a pattern where verifyCurrentUserSession() was called to verify the
971
     * current user session. Upon success, one or two functions were called
972
     * to continue program, flow. Upon failure, cookies and session
973
     * variables were cleared, and the main Logon page was printed. This
974
     * function encapsulates that pattern. If the user's session is valid,
975
     * the passed-in $func is called, possibly with parameters passed in as
976
     * an array. The function returns true if the session is verified, so
977
     * that other functions may be called upon return.
978
     *
979
     * @param callable $func The function to call if the current session is
980
     *        successfully verified.
981
     * @param array $params (Optional) An array of parameters to pass to the
982
     *        function. Defaults to empty array, meaning zero parameters.
983
     */
984
    public static function verifySessionAndCall($func, $params = array())
985
    {
986
        $retval = false;
987
        if (Content::verifyCurrentUserSession()) { // Verify PHP session is valid
988
            $retval = true;
989
            call_user_func_array($func, $params);
990
        } else {
991
            printLogonPage(true); // Clear cookies and session vars too
992
        }
993
        return $retval;
994
    }
995
996
    /**
997
     * isEduGAINAndGetCert
998
     *
999
     * This function checks to see if the current session IdP is an
1000
     * eduGAIN IdP (i.e., not Registered By InCommon) and the IdP does not
1001
     * have both the REFEDS R&S and SIRTFI extensions in metadata. If so,
1002
     * check to see if the transaction could be used to fetch a
1003
     * certificate. (The only time the transaction is not used to fetch
1004
     * a cert is during OIDC without the 'getcert' scope.) If all that is
1005
     * true, then return true. Otherwise return false.
1006
     *
1007
     * @param string $idp (optional) The IdP entityID. If empty, read value
1008
     *        from PHP session.
1009
     * @param string $idp_display_name (optional) The IdP display name. If empty,
1010
     *        read value from PHP session.
1011
     * @return bool True if the current IdP is an eduGAIN IdP without
1012
     *         both REFEDS R&S and SIRTFI, AND the session could be
1013
     *         used to get a certificate.
1014
     */
1015
    public static function isEduGAINAndGetCert($idp = '', $idp_display_name = '')
1016
    {
1017
        $retval = false; // Assume not eduGAIN IdP and getcert
1018
1019
        // If $idp or $idp_display_name not passed in, get from current session.
1020
        if (strlen($idp) == 0) {
1021
            $idp = static::getSessionVar('idp');
1022
        }
1023
        if (strlen($idp_display_name) == 0) {
1024
            $idp_display_name = static::getSessionVar('idp_display_name');
1025
        }
1026
1027
        // Check if this was an OIDC transaction, and if the
1028
        // 'getcert' scope was requested.
1029
        $oidcscopegetcert = false;
1030
        $oidctrans = false;
1031
        $clientparams = json_decode(static::getSessionVar('clientparams'), true);
1032
        if (isset($clientparams['scope'])) {
1033
            $oidctrans = true;
1034
            if (
1035
                preg_match(
1036
                    '/edu.uiuc.ncsa.myproxy.getcert/',
1037
                    $clientparams['scope']
1038
                )
1039
            ) {
1040
                $oidcscopegetcert = true;
1041
            }
1042
        }
1043
1044
        // First, make sure $idp was set and is not an OAuth2 IdP.
1045
        $idplist = static::getIdpList();
1046
        if (
1047
            ((strlen($idp) > 0) &&
1048
            (strlen($idp_display_name) > 0) &&
1049
            (!in_array($idp_display_name, static::$oauth2idps))) &&
1050
                (
1051
                // Next, check for eduGAIN without REFEDS R&S and SIRTFI
1052
                ((!$idplist->isRegisteredByInCommon($idp)) &&
1053
                       ((!$idplist->isREFEDSRandS($idp)) ||
1054
                        (!$idplist->isSIRTFI($idp))
1055
                       )
1056
                ) &&
1057
                // Next, check if user could get X509 cert,
1058
                // i.e., OIDC getcert scope, or a non-OIDC
1059
                // transaction such as PKCS12, JWS, or OAuth 1.0a
1060
                ($oidcscopegetcert || !$oidctrans)
1061
                )
1062
        ) {
1063
            $retval = true;
1064
        }
1065
        return $retval;
1066
    }
1067
1068
    /**
1069
     * setPortalOrCookieVar
1070
     *
1071
     * This is a convenience function for a set of operations that is done
1072
     * a few times in Content.php. It first checks if the name of the portal
1073
     * in the PortalCookie is empty. If not, then it sets the PortalCookie
1074
     * key/value pair. Otherwise, it sets the 'normal' cookie key/value
1075
     * pair.
1076
     *
1077
     * @param PortalCookie $pc The PortalCookie to read/write. If the portal
1078
     *        name is empty, then use the 'normal' cookie instead.
1079
     * @param string $key The key of the PortalCookie or 'normal' cookie to
1080
     *        set.
1081
     * @param string $value The value to set for the $key.
1082
     * @param bool $save (optional) If set to true, attempt to write the
1083
     *        PortalCookie. Defaults to false.
1084
     */
1085
    public static function setPortalOrCookieVar($pc, $key, $value, $save = false)
1086
    {
1087
        $pn = $pc->getPortalName();
1088
        // If the portal name is valid, then set the PortalCookie key/value
1089
        if (strlen($pn) > 0) {
1090
            $pc->set($key, $value);
1091
            if ($save) {
1092
                $pc->write();
1093
            }
1094
        } else { // If portal name is not valid, then use the 'normal' cookie
1095
            if (strlen($value) > 0) {
1096
                Util::setCookieVar($key, $value);
1097
            } else { // If $value is empty, then UNset the 'normal' cookie
1098
                Util::unsetCookieVar($key);
1099
            }
1100
        }
1101
    }
1102
1103
    /**
1104
     * getOIDCClientParams
1105
     *
1106
     * This function addresses CIL-618 and reads OIDC client information
1107
     * directly from the database. It is a replacement for
1108
     * $dbs->getClient($clientparams['client_id']) which calls
1109
     * '/dbService?action=getClient&client_id=...'. This gives the PHP
1110
     * '/authorize' endpoint access to additional OIDC client parameters
1111
     * without having to rewrite the '/dbService?action=getClient' endpoint.
1112
     *
1113
     * @param array $clientparams An array of client parameters which gets
1114
     *              stored in the PHP session. The keys of the array are
1115
     *              the column names of the 'client' table in the 'ciloa2'
1116
     *              database, prefixed by 'client_'.
1117
     */
1118
    public static function getOIDCClientParams(&$clientparams)
1119
    {
1120
        $retval = false;
1121
        if (strlen(@$clientparams['client_id']) > 0) {
1122
            $dsn = array(
1123
                'phptype'  => 'mysqli',
1124
                'username' => MYSQLI_USERNAME,
1125
                'password' => MYSQLI_PASSWORD,
1126
                'database' => 'ciloa2',
1127
                'hostspec' => 'localhost'
1128
            );
1129
1130
            $opts = array(
1131
                'persistent'  => true,
1132
                'portability' => DB_PORTABILITY_ALL
1133
            );
1134
1135
            $db = DB::connect($dsn, $opts);
1136
            if (!PEAR::isError($db)) {
1137
                $data = $db->getRow(
1138
                    'SELECT name,home_url,callback_uri,scopes from clients WHERE client_id = ?',
1139
                    array($clientparams['client_id']),
1140
                    DB_FETCHMODE_ASSOC
1141
                );
1142
                if (!DB::isError($data)) {
1143
                    if (!empty($data)) {
1144
                        foreach ($data as $key => $value) {
1145
                            $clientparams['client_' . $key] = $value;
1146
                        }
1147
                        $clientparams['clientstatus'] = DBService::$STATUS['STATUS_OK'];
1148
                        $retval = true;
1149
                    }
1150
                }
1151
                $db->disconnect();
1152
            }
1153
        }
1154
        return $retval;
1155
    }
1156
1157
    /**
1158
     * getMinMaxLifetimes
1159
     *
1160
     * This function checks the skin's configuration to see if either or
1161
     * both of minlifetime and maxlifetime in the specified config.xml
1162
     * block have been set. If not, default to minlifetime of 1 (hour) and
1163
     * the specified defaultmaxlifetime.
1164
     *
1165
     * @param string $section The XML section block from which to read the
1166
     *        minlifetime and maxlifetime values. Can be one of the
1167
     *        following: 'pkcs12' or 'delegate'.
1168
     * @param int $defaultmaxlifetime Default maxlifetime (in hours) for the
1169
     *        credential.
1170
     * @return array An array consisting of two entries: the minimum and
1171
     *         maximum lifetimes (in hours) for a credential.
1172
     */
1173
    public static function getMinMaxLifetimes($section, $defaultmaxlifetime)
1174
    {
1175
        $minlifetime = 1;    // Default minimum lifetime is 1 hour
1176
        $maxlifetime = $defaultmaxlifetime;
1177
        $skin = Util::getSkin();
1178
        $skinminlifetime = $skin->getConfigOption($section, 'minlifetime');
1179
        // Read the skin's minlifetime value from the specified section
1180
        if ((!is_null($skinminlifetime)) && ((int)$skinminlifetime > 0)) {
1181
            $minlifetime = max($minlifetime, (int)$skinminlifetime);
1182
            // Make sure $minlifetime is less than $maxlifetime;
1183
            $minlifetime = min($minlifetime, $maxlifetime);
1184
        }
1185
        // Read the skin's maxlifetime value from the specified section
1186
        $skinmaxlifetime = $skin->getConfigOption($section, 'maxlifetime');
1187
        if ((!is_null($skinmaxlifetime)) && ((int)$skinmaxlifetime) > 0) {
1188
            $maxlifetime = min($maxlifetime, (int)$skinmaxlifetime);
1189
            // Make sure $maxlifetime is greater than $minlifetime
1190
            $maxlifetime = max($minlifetime, $maxlifetime);
1191
        }
1192
1193
        return array($minlifetime, $maxlifetime);
1194
    }
1195
1196
    /**
1197
     * isLOASilver
1198
     *
1199
     * This function returns true if the 'loa' (level of assurance)
1200
     * should be http://incommonfederation.org/assurance/silver .
1201
     * As specified in CACC-238, this is when both of the following are true:
1202
     * (1) loa contains  https://refeds.org/assurance/profile/cappuccino
1203
     * (2) acr is either https://refeds.org/profile/sfa or
1204
     *                   https://refeds.org/profile/mfa
1205
     *
1206
     * @return bool True if level of assurance is 'silver'.
1207
     */
1208
    public static function isLOASilver()
1209
    {
1210
        $retval = false;
1211
        if (
1212
            (preg_match('%https://refeds.org/assurance/profile/cappuccino%', static::getSessionVar('loa'))) &&
1213
            (preg_match('%https://refeds.org/profile/[ms]fa%', static::getSessionVar('acr')))
1214
        ) {
1215
            $retval = true;
1216
        }
1217
        return $retval;
1218
    }
1219
1220
    /**
1221
     * getLOA
1222
     *
1223
     * This function is a bit of a hack. Once upon a time, the level of
1224
     * assurance (loa) was one of empty string (which implied 'basic
1225
     * CA'), 'openid' (which implied 'openid CA'), or
1226
     * 'http://incommonfederation.org/assurance/silver' (which implied
1227
     * 'silver CA'). Then things got more complex when the silver
1228
     * assurance was replaced by cappuccino (see CACC-238). But parts of the
1229
     * PHP code still depeneded on the InCommon silver string.
1230
     *
1231
     * This function transforms the assurance attribute asserted by an IdP
1232
     * (which is stored in the 'loa' session variable) into one of
1233
     * empty string (for 'basic CA'), 'openid', or
1234
     * 'http://incommonfederation.org/assurance/silver' for use by those
1235
     * PHP functions which expect the 'loa' in this format.
1236
     *
1237
     * @return string One of empty string, 'openid', or
1238
     *         'http://incommonfederation.org/assurance/silver'
1239
     */
1240
    public static function getLOA()
1241
    {
1242
        $retval = '';
1243
        if (static::isLOASilver()) {
1244
            $retval = 'http://incommonfederation.org/assurance/silver';
1245
        } else {
1246
            $retval = static::getSessionVar('loa');
1247
        }
1248
        return $retval;
1249
    }
1250
1251
    /**
1252
     * getLOAPort
1253
     *
1254
     * This function returns the port to be used for MyProxy based on the
1255
     * level of assurance.
1256
     *     Basic  CA = 7512
1257
     *     Silver CA = 7514
1258
     *     OpenID CA = 7516
1259
     *
1260
     * @return int The MyProxy port number to be used based on the 'level
1261
     *         of assurance' (basic, silver, openid).
1262
     */
1263
    public static function getLOAPort()
1264
    {
1265
        $port = 7512; // Basic
1266
        if (Util::isLOASilver()) {
1267
            $port = 7514;
1268
        } elseif (Util::getSessionVar('loa') == 'openid') {
1269
            $port = 7516;
1270
        }
1271
        return $port;
1272
    }
1273
1274
    /**
1275
     * getFirstAndLastName
1276
     *
1277
     * This function attempts to get the first and last name of a user
1278
     * extracted from the 'full name' (displayName) of the user.
1279
     * Simply pass in all name info (full, first, and last) and the
1280
     * function first tries to break up the full name into first/last.
1281
     * If this is not sufficient, the function checks first and last
1282
     * name. Finally, if either first or last is blank, the function
1283
     * duplicates first <=> last so both names have the same value.
1284
     * Note that even with all this, you still need to check if the
1285
     * returned (first,last) names are blank.
1286
     *
1287
     * @param string $full The 'full name' of the user
1288
     * @param string $first (Optional) The 'first name' of the user
1289
     * @param string $last (Optional) The 'last name' of the user
1290
     * @return array An array 'list(firstname,lastname)'
1291
     */
1292
    public static function getFirstAndLastName($full, $first = '', $last = '')
1293
    {
1294
        $firstname = '';
1295
        $lastname = '';
1296
1297
        # Try to split the incoming $full name into first and last names
1298
        if (strlen($full) > 0) {
1299
            if (preg_match('/,/', $full)) { // Split on comma if present
1300
                $names = preg_split('/,/', $full, 2);
1301
                $lastname =  trim(@$names[0]);
1302
                $firstname = trim(@$names[1]);
1303
            } else {
1304
                $names = preg_split('/\s+/', $full, 2);
1305
                $firstname = trim(@$names[0]);
1306
                $lastname =  trim(@$names[1]);
1307
            }
1308
        }
1309
1310
        # If either first or last name blank, then use incoming $first and $last
1311
        if (strlen($firstname) == 0) {
1312
            $firstname = $first;
1313
        }
1314
        if (strlen($lastname) == 0) {
1315
            $lastname = $last;
1316
        }
1317
1318
        # Finally, if only a single name, copy first name <=> last name
1319
        if (strlen($lastname) == 0) {
1320
            $lastname = $firstname;
1321
        }
1322
        if (strlen($firstname) == 0) {
1323
            $firstname = $lastname;
1324
        }
1325
1326
        # Return both names as an array (i.e., use list($first,last)=...)
1327
        return array($firstname,$lastname);
1328
    }
1329
}
1330