Completed
Push — master ( 5a053e...8eeafe )
by Terrence
10:16
created

index-functions.php ➔ handleAllowDelegation()   F

Complexity

Conditions 32
Paths > 20000

Size

Total Lines 239

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 32
nc 23520
nop 1
dl 0
loc 239
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This file contains functions called by index-site.php. The index-site.php
5
 * file should include this file with the following statement at the top:
6
 *
7
 * require_once __DIR__ . '/index-functions.php';
8
 */
9
10
use CILogon\Service\Util;
11
use CILogon\Service\Content;
12
use CILogon\Service\PortalCookie;
13
use CILogon\Service\DBService;
14
use CILogon\Service\Loggit;
15
16
// The full URL of the 'oauth/authorized' OAuth script
17
define('AUTHORIZED_URL', 'http://localhost:8080/oauth/authorized');
18
19
/**
20
 * printLogonPage
21
 *
22
 * This function prints out the HTML for the main cilogon.org page.
23
 * Explanatory text is shown as well as a button to log in to an IdP
24
 * and get rerouted to the Shibboleth protected getuser script.
25
 */
26
function printLogonPage()
0 ignored issues
show
Best Practice introduced by
The function printLogonPage() has been defined more than once; this definition is ignored, only the first definition in authorize/index-functions.php (L25-121) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
27
{
28
    $log = new Loggit();
29
    $log->info('Welcome page hit.');
30
31
    Util::setSessionVar('stage', 'logon'); // For Show/Hide Help button clicks
32
33
    // Check if this is the first time the user has visited the site from
34
    // the current portal.  We do this by checking the portal cookie's
35
    // lifetime for a positive value.  If the portal cookie has NOT YET been
36
    // set, then check the skin config to see if either initialremember or
37
    // initiallifetime has been set.  We do this here because these two
38
    // values set the portal cookie, which needs to be done before we go
39
    // to the next page (where the cookie is actually read).
40
    $skin = Util::getSkin();
41
    $pc = new PortalCookie();
42
    $portallifetime = $pc->get('lifetime');
43
44
    if ((strlen($portallifetime) == 0) || ($portallifetime == 0)) {
45
        $needtosetcookie = 0;
46
47
        // Try to read the skin's initiallifetime
48
        $initiallifetime = $skin->getConfigOption(
49
            'delegate',
50
            'initiallifetime'
51
        );
52
        if ((!is_null($initiallifetime)) && ((int)$initiallifetime > 0)) {
53
            $needtosetcookie = 1;
54
            $initiallifetime = (int)$initiallifetime;
55
        } else { // Set a default lifetime value in case initialremember is set
56
            $initiallifetime = 12;
57
        }
58
59
        // Make sure initiallifetime is within [minlifetime..maxlifetime]
60
        list($minlifetime, $maxlifetime) =
61
            Content::getMinMaxLifetimes('delegate', 240);
62
        if ($initiallifetime < $minlifetime) {
63
            $needtosetcookie = 1;
64
            $initiallifetime = $minlifetime;
65
        } elseif ($initiallifetime > $maxlifetime) {
66
            $needtosetcookie = 1;
67
            $initiallifetime = $maxlifetime;
68
        }
69
70
        // Next, try to read the skin's initialremember
71
        $initialremember = $skin->getConfigOption(
72
            'delegate',
73
            'initialremember'
74
        );
75
        if ((!is_null($initialremember)) && ((int)$initialremember > 0)) {
76
            $needtosetcookie = 1;
77
            $initialremember = (int)$initialremember;
78
        } else { // Set a default remember value in case initiallifetime is set
79
            $initialremember = 0;
80
        }
81
82
        if ($needtosetcookie) {
83
            $pc->set('remember', $initialremember);
84
            $pc->set('lifetime', $initiallifetime);
85
            $pc->write();
86
        }
87
    }
88
89
    Content::printHeader('Welcome To The CILogon Delegation Service');
90
91
    echo '
92
    <div class="boxed">
93
    ';
94
95
    Content::printHelpButton();
96
97
    echo '
98
      <br />
99
    ';
100
101
    // If the <hideportalinfo> option is set, do not show the portal info if
102
    // the callback uri is in the portal list.
103
    $showportalinfo = true;
104
    if (
105
        ((int)$skin->getConfigOption(
106
            'portallistaction',
107
            'hideportalinfo'
108
        ) == 1) &&
109
        ($skin->inPortalList(Util::getSessionVar('callbackuri')))
110
    ) {
111
        $showportalinfo = false;
112
    }
113
114
    if ($showportalinfo) {
115
        echo '
116
          <br/>
117
          <p>"' ,
118
          htmlspecialchars(Util::getSessionVar('portalname')) ,
119
          '" requests that you select an Identity Provider and click "' ,
120
          Content::getLogOnButtonText() ,
121
          '". If you do not approve this request, do not proceed.
122
          </p>
123
          <p><em>By proceeding you agree to share your name and
124
          email address with "' ,
125
          htmlspecialchars(Util::getSessionVar('portalname')) ,
126
          '"</em>.</p>
127
        ';
128
129
        printPortalInfo('1');
130
    }
131
132
    Content::printWAYF();
133
134
    echo '
135
    </div> <!-- End boxed -->
136
    ';
137
138
    Content::printFooter();
139
}
140
141
/**
142
 * printBadOAuthTokenPage
143
 *
144
 * This function prints out the HTML for the page when the oauth_token
145
 * (tempcred) or associated OAuth information is missing, bad, or expired.
146
 */
147
function printBadOAuthTokenPage()
148
{
149
    $log = new Loggit();
150
    $log->warn('Missing or invalid oauth_token.');
151
152
    Content::printHeader('CILogon Delegation Service');
153
154
    echo '
155
    <div class="boxed">
156
      <br class="clear"/>
157
      <p>
158
      You have reached the CILogon Delegation Service.  This service is for
159
      use by third parties to obtain certificates for their users.
160
      End users should not normally see this page.
161
      </p>
162
      <p>
163
      Possible reasons for seeing this page include:
164
      </p>
165
      <ul>
166
      <li>You navigated directly to this page.</li>
167
      <li>You clicked your browser\'s "Back" button.</li>
168
      <li>There was a problem with the delegation process.</li>
169
      </ul>
170
      <p>
171
      Please return to the previous site and try again.  If the error persists,
172
      please contact us at the email address at the bottom of the page.
173
      </p>
174
      <p>
175
      If you are an individual wishing to download a certificate to your
176
      local computer, please try the <a target="_blank"
177
      href="https://' , Util::getHN() , '/">CILogon Service</a>.
178
      </p>
179
      <p>
180
      <strong>Note:</strong> You must enable cookies in your web browser to
181
      use this site.
182
      </p>
183
    </div>
184
    ';
185
186
    Content::printFooter();
187
}
188
189
/**
190
 * printMainPage
191
 *
192
 * This function prints out the HTML for the main page where the user
193
 * is presented with the portal information and asked to either allow
194
 * or deny delegation of a certificate to the portal.  We first check
195
 * to see if the 'remember' cookie has been set for this portal. If
196
 * so, then we automatically always approve delegation.  Otherwise,
197
 * we print out the HTML for the <form> buttons.
198
 */
199
function printMainPage()
0 ignored issues
show
Best Practice introduced by
The function printMainPage() has been defined more than once; this definition is ignored, only the first definition in authorize/index-functions.php (L192-289) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
200
{
201
    $log = new Loggit();
202
    $log->info('Allow Or Deny Delegation page hit.');
203
204
    Util::setSessionVar('stage', 'main'); // For Show/Hide Help button clicks
205
206
    $remember = 0;   // Default value for remember checkbox is unchecked
207
    $lifetime = 12;  // Default value for lifetime is 12 hours
208
209
    // Check the skin for forceremember and forcelifetime
210
    $skin = Util::getSkin();
211
    $forceremember = $skin->getConfigOption(
212
        'delegate',
213
        'forceremember'
214
    );
215
    if ((!is_null($forceremember)) && ((int)$forceremember == 1)) {
216
        $forceremember = 1;
217
    } else {
218
        $forceremember = 0;
219
    }
220
    $forcelifetime = $skin->getConfigOption(
221
        'delegate',
222
        'forcelifetime'
223
    );
224
    if ((!is_null($forcelifetime)) && ((int)$forcelifetime > 0)) {
225
        $forcelifetime = (int)$forcelifetime;
226
    } else {
227
        $forcelifetime = 0;
228
    }
229
230
    // Try to read the portal coookie for the remember and lifetime values.
231
    $pc = new PortalCookie();
232
    $portalremember = $pc->get('remember');
233
    $portallifetime = $pc->get('lifetime');
234
235
    // If skin's forceremember or portal cookie's remember is set,
236
    // then we bypass the Allow/Deny delegate page.
237
    if (($forceremember == 1) || ($portalremember == 1)) {
238
        $remember = 1;
239
    }
240
241
    // If skin's forcelifetime or portal cookie's lifetime is set,
242
    // set lifetime accordingly and make sure value is between the
243
    // configured minlifetime and maxlifetime.
244
    if ($forcelifetime > 0) {
245
        $lifetime = $forcelifetime;
246
    } elseif ($portallifetime > 0) {
247
        $lifetime = $portallifetime;
248
    }
249
    list($minlifetime, $maxlifetime) =
250
        Content::getMinMaxLifetimes('delegate', 240);
251
    if ($lifetime < $minlifetime) {
252
        $lifetime = $minlifetime;
253
    } elseif ($lifetime > $maxlifetime) {
254
        $lifetime = $maxlifetime;
255
    }
256
257
    // If 'remember' is set, then auto-click the 'OK' button for the user.
258
    if ($remember == 1) {
259
        handleAllowDelegation(true);
260
    } else {
261
        // User did not check 'Remember OK' before, so show the
262
        // HTML to prompt user for OK or Cancel delegation.
263
264
        $lifetimetext = "Specify the lifetime of the certificate to " .
265
            "be issued. Acceptable range is between $minlifetime and " .
266
            "$maxlifetime hours.";
267
        $remembertext = "Check this box to automatically approve " .
268
            "certificate issuance to the site on future visits. " .
269
            "The certificate lifetime will be remembered. You will " .
270
            "need to clear your browser's cookies to return here.";
271
272
        Content::printHeader('Confirm Allow Delegation');
273
274
        echo '
275
        <div class="boxed">
276
        ';
277
278
        Content::printHelpButton();
279
280
        echo '
281
        <br />
282
        <p>"' ,
283
        htmlspecialchars(Util::getSessionVar('portalname')) ,
284
        '" is requesting a certificate for you.
285
        If you approve, then "OK" the request.
286
        Otherwise, "Cancel" the request or navigate away from this page.
287
        </p>
288
        ';
289
290
        printPortalInfo('2');
291
292
        echo '
293
        <div class="actionbox"';
294
295
        if (Util::getSessionVar('showhelp') == 'on') {
296
            echo ' style="width:92%;"';
297
        }
298
299
        echo '>
300
        <table class="helptable">
301
        <tr>
302
        <td class="actioncell">
303
        ';
304
305
        Content::printFormHead();
306
307
        echo '
308
        <fieldset>
309
        <p>
310
        <label for="lifetime" title="' , $lifetimetext , '"
311
        class="helpcursor">Certificate Lifetime (in hours):</label>
312
        <input type="text" name="lifetime" id="lifetime" title="' ,
313
        $lifetimetext , '" size="3" maxlength="3" value="' ,
314
        $lifetime , '" ' ,
315
        (($forcelifetime > 0) ? 'disabled="disabled" ' : 'class="helpcursor" ') ,
316
        '/>
317
<!--[if IE]><input type="text" style="display:none;" disabled="disabled" size="1"/><![endif]-->
318
        </p>
319
        <p>
320
        <label for="rememberok" title="', $remembertext , '"
321
        class="helpcursor">Remember my OK for the site:</label>
322
        <input type="checkbox" name="rememberok" id="rememberok"
323
        title="', $remembertext, '" class="helpcursor" />
324
        </p>
325
        <p>
326
        <input type="submit" name="submit" class="submit" value="OK" />
327
        &nbsp;
328
        <input type="submit" name="submit" class="submit" value="Cancel" />
329
        </p>
330
        </fieldset>
331
        </form>
332
        </td>
333
        ';
334
335
        if (Util::getSessionVar('showhelp') == 'on') {
336
            echo '
337
            <td class="helpcell">
338
            <div>
339
            <p>
340
            Please enter the lifetime of the certificate to be issued.
341
            Acceptable range is between ' , $minlifetime, ' and ' ,
342
            $maxlifetime , ' hours.
343
            </p>
344
            <p>
345
            If you check the "Remember my OK for the site" checkbox,
346
            certificates will be issued automatically to this site on future
347
            visits, using the lifetime you specify here.  You will need to
348
            clear your browser\'s cookies to return to see this page again.
349
            </p>
350
            </div>
351
            </td>
352
            ';
353
        }
354
355
356
357
        echo '
358
        </tr>
359
        </table>
360
        </div> <!-- actionbox -->
361
        ';
362
363
        Content::printTwoFactorBox();
364
365
        echo '
366
        </div> <!-- boxed -->
367
        ';
368
        Content::printFooter();
369
    }
370
}
371
372
/**
373
 * printPortalInfo
374
 *
375
 * This function prints out the portal information table at the top of
376
 * of the page.  The optional parameter $suffix allows you to append
377
 * a number (for example) to differentiate the portalinfo table on the
378
 * log in page from the one on the main page.
379
 *
380
 * @param string $suffix An optional suffix to append to the 'portalinfo'
381
 *        table class name.
382
 */
383
function printPortalInfo($suffix = '')
0 ignored issues
show
Best Practice introduced by
The function printPortalInfo() has been defined more than once; this definition is ignored, only the first definition in authorize/index-functions.php (L302-352) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
384
{
385
    $showhelp = Util::getSessionVar('showhelp');
386
    $helptext = "The Site Name is provided by the site to CILogon and has not been vetted.";
387
388
    echo '
389
    <table class="portalinfo' , $suffix , '">
390
    <tr class="inforow">
391
      <th title="' , $helptext ,'">Site&nbsp;Name:</th>
392
      <td title="' , $helptext ,'">' ,
393
      htmlspecialchars(Util::getSessionVar('portalname')) , '</td>
394
    ';
395
396
    if ($showhelp == 'on') {
397
        echo ' <td class="helpcell">' , $helptext , '</td>';
398
    }
399
400
    $helptext = "The Site URL is the location to which the site requests you to return upon completion.";
401
402
    echo '
403
    </tr>
404
    <tr class="inforow">
405
      <th title="' , $helptext , '">Site&nbsp;URL:</th>
406
      <td title="' , $helptext , '">' ,
407
          htmlspecialchars(Util::getSessionVar('successuri')) , '</td>
408
    ';
409
410
    if ($showhelp == 'on') {
411
        echo '<td class="helpcell">' , $helptext , '</td>';
412
    }
413
414
    $helptext = "The Service URL is the location to which CILogon " .
415
        "will send a certificate containing your identity information.";
416
417
    echo '
418
    </tr>
419
    <tr class="inforow">
420
      <th title="' , $helptext , '">Service&nbsp;URL:</th>
421
      <td title="' , $helptext , '">' ,
422
          htmlspecialchars(Util::getSessionVar('callbackuri')) , '</td>
423
      ';
424
425
    if ($showhelp == 'on') {
426
        echo '<td class="helpcell">' , $helptext , '</td>';
427
    }
428
429
    echo '
430
    </tr>
431
    </table>
432
    ';
433
}
434
435
/**
436
 * printCancelPage
437
 *
438
 * This function prints out the HTML for when the user clicked the
439
 * 'Cancel' button on the 'Allow Delegation' page.  It gives the user a
440
 * link back to the portal via the 'failure URL'.
441
 */
442
function printCancelPage()
443
{
444
    $portalname = Util::getSessionVar('portalname');
445
446
    Content::printHeader('Delegation Denied');
447
448
    echo '
449
    <div class="boxed">
450
    <br class="clear"/>
451
    <p>
452
    You have canceled delegation of a certificate to "' ,
453
    htmlspecialchars($portalname) , '".
454
    Below is a link to return to the
455
    portal.  This link has been provided by the portal to be used when
456
    delegation of a certificate fails.
457
    </p>
458
    <p>
459
    <strong>Note:</strong> If you do not trust the information provided by
460
    the portal, <strong>do not</strong> click on the link below.  Instead,
461
    please contact your portal administrators or contact us at the email
462
    address at the bottom of the page.
463
    </p>
464
465
    <div class="returnlink">
466
      <a href="' , Util::getSessionVar('failureuri') , '">Return to ' ,
467
      htmlspecialchars($portalname) , '</a>
468
    </div>
469
    </div>
470
    ';
471
    Content::printFooter();
472
}
473
474
/**
475
 * handleAllowDelegation
476
 *
477
 * This fuction is called when the user clicks the 'OK' button on the
478
 * main page, or when the user had previously checked the 'Remember
479
 * my OK for this portal' checkbox which saved the 'remember' cookie
480
 * for the current portal. It first reads the cookie for the portal and
481
 * updates the 'lifetime' and 'remember' parameters, then (re)saves
482
 * the cookie.  Then it calls out to the 'oauth/authorized' servlet
483
 * in order to do the back-end certificate delegation process. If the
484
 * $always parameter is true, then the user is automatically returned
485
 * to the portal's successuri or failureuri.  Otherwise, the user is
486
 * presented with a page showing the result of the attempted
487
 * certificate delegation as well as a link to 'return to your portal'.
488
 *
489
 * @param bool True if the user selected to always allow delegation.
490
 */
491
function handleAllowDelegation($always = false)
492
{
493
    // The 'authorized' servlet may return a response URL to be used
494
    // instead of the success / failure URLs.
495
    $responseurl = '';
496
497
    $log = new Loggit();
498
    $log->info('Attempting to delegate a certificate to a portal...');
499
500
    $lifetime = 0;
501
    // Check the skin's forcelifetime and use it if it is configured.
502
    $forcelifetime = Util::getSkin()->getConfigOption(
503
        'delegate',
504
        'forcelifetime'
505
    );
506
    if ((!is_null($forcelifetime)) && ((int)$forcelifetime > 0)) {
507
        $lifetime = (int)$forcelifetime;
508
    }
509
510
    // Next, try to get the certificate lifetime from a submitted <form>
511
    if ($lifetime == 0) {
512
        $lifetime = (int)(trim(Util::getPostVar('lifetime')));
513
    }
514
515
    // If we couldn't get lifetime from the <form>, try the cookie
516
    $pc = new PortalCookie();
517
    if ($lifetime == 0) {
518
        $lifetime = (int)($pc->get('lifetime'));
519
    }
520
521
    // Default lifetime to 12 hours. And then make sure lifetime is in
522
    // acceptable range.
523
    if ($lifetime == 0) {
524
        $lifetime = 12;
525
    }
526
    list($minlifetime, $maxlifetime) =
527
        Content::getMinMaxLifetimes('delegate', 240);
528
    if ($lifetime < $minlifetime) {
529
        $lifetime = $minlifetime;
530
    } elseif ($lifetime > $maxlifetime) {
531
        $lifetime = $maxlifetime;
532
    }
533
534
    $pc->set('remember', (int)$always);
535
    $pc->set('lifetime', $lifetime);
536
    $pc->write();
537
538
    $success = false;  // Assume delegation of certificate failed
539
    $certtext = '';    // Output of 'openssl x509 -noout -text -in cert.pem'
540
    $myproxyinfo = Util::getSessionVar('myproxyinfo');
541
542
    // Now call out to the 'oauth/authorized' servlet to execute
543
    // the delegation the credential to the portal.
544
    $ch = curl_init();
545
    if ($ch !== false) {
546
        $tempcred = Util::getSessionVar('tempcred');
547
        $url = AUTHORIZED_URL . '?' .
548
               'oauth_token=' . urlencode($tempcred) . '&' .
549
               'cilogon_lifetime=' . $lifetime . '&' .
550
               'cilogon_loa=' . urlencode(Util::getSessionVar('loa')) . '&' .
551
               'cilogon_uid=' . urlencode(Util::getSessionVar('uid')) .
552
               ((strlen($myproxyinfo) > 0) ?
553
                   ('&cilogon_info=' . urlencode($myproxyinfo)) : '');
554
        curl_setopt($ch, CURLOPT_URL, $url);
555
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
556
        curl_setopt($ch, CURLOPT_TIMEOUT, 35);
557
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
558
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
559
        $output = curl_exec($ch);
560
        if (curl_errno($ch)) { // Send alert on curl errors
561
            Util::sendErrorAlert(
562
                'cUrl Error',
563
                'cUrl Error    = ' . curl_error($ch) . "\n" .
564
                "URL Accessed  = $url"
565
            );
566
        }
567
        if (!empty($output)) {
568
            $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
569
            if ($httpcode == 200) {
570
                // Check body of curl query for cilogon_status=ok
571
                if (preg_match('/cilogon_status=ok/', $output)) {
572
                    $success = true;
573
                    // Also check if the cert was returned as base64
574
                    // encoded PEM certificate.  If so, get info about it.
575
                    if (
576
                        preg_match(
577
                            '/cilogon_cert=([^\s]+)/',
578
                            $output,
579
                            $matches
580
                        )
581
                    ) {
582
                        $b64cert = $matches[1];
583
                        $cert = base64_decode($b64cert);
584
                        if ($cert !== false) {
585
                            // Run 'openssl x509' command for cert info
586
                            exec(
587
                                '/bin/env RANDFILE=/tmp/.rnd ' .
588
                                '/usr/bin/openssl x509 -text ' .
589
                                '<<< ' . escapeshellarg($cert) . ' 2>&1',
590
                                $x509out,
591
                                $retcode
592
                            );
593
                            if ($retcode == 0) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $retcode of type integer|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
594
                                $certtext = implode("\n", $x509out);
595
                            } else {
596
                                $certtext = $cert;
597
                            }
598
                        }
599
                    }
600
                }
601
                // Check for an alternate response URL to be used
602
                // in place of success / failure URLs.
603
                if (
604
                    preg_match(
605
                        '/cilogon_response_url=([^\s]+)/',
606
                        $output,
607
                        $matches
608
                    )
609
                ) {
610
                    $responseurl = $matches[1];
611
                }
612
            }
613
        }
614
        curl_close($ch);
615
    }
616
617
    $log = new Loggit();
618
    $log->info('Delegation of certificate to portal ' .
619
               ($success ? 'succeeded.' : 'failed.'));
620
    //CIL-507 Special log message for XSEDE
621
    $log->info('USAGE email="' . Util::getSessionVar('emailaddr') .
622
               '" client="' . Util::getSessionVar('portalname') . '"');
623
624
625
    // Depending on the result (success or failure), output appropriate
626
    // HTML to allow the user to return to the portal, or if $always
627
    // was set, then automatically return the user to the successuri,
628
    // failureuri, or cilogon_reponse_url if supplied by authorized servlet.
629
    if ($always) {
630
        $log->info("Automatically returning to portal's " .
631
            ($success ? 'success' : 'failure') . ' url.');
632
        $location = 'Location: ' . ((strlen($responseurl) > 0) ? $responseurl :
633
            (Util::getSessionVar($success ? 'successuri' : 'failureuri')));
634
        if ($success) {
635
            Util::unsetClientSessionVars();
636
            /// Util::unsetAllUserSessionVars();
637
        } else {
638
            Util::unsetAllUserSessionVars();
639
        }
640
        header($location);
641
        exit; // No further processing necessary
642
    } else {
643
        Content::printHeader('Delegation ' .
644
            ($success ? 'Successful' : 'Failed'));
645
646
        echo '
647
        <div class="boxed">
648
        <div>
649
        <div class="icon">
650
        ';
651
        Content::printIcon(($success ? 'okay' : 'error'));
652
        echo '
653
        </div>
654
        <h2>' , ($success ? 'Success!' : 'Failure!') , '</h2>
655
        </div>
656
        ';
657
        if ($success) {
658
            echo '
659
            <p>
660
            The CILogon Service has issued a certificate to "' ,
661
            htmlspecialchars(Util::getSessionVar('portalname')) , '".
662
            Below is a link to return to
663
            the site to use the issued certificate.
664
            </p>
665
            ';
666
            // If we got the cert from the 'oauth/authorized' script,
667
            // output it in an expandable/scrollable <div> for user info.
668
            if (strlen($certtext) > 0) {
669
                echo '
670
                <noscript>
671
                <div class="nojs">
672
                Javascript is disabled. In order to expand the "Certificate
673
                Details" section below, please enable Javascript in your
674
                browser.
675
                </div>
676
                </noscript>
677
678
                <div class="summary">
679
                <div id="certtext1" style="display:inline"><span
680
                class="expander"><a
681
                href="javascript:showHideDiv(\'certtext\',-1)"><img
682
                src="/images/triright.gif" alt="&rArr;" width="14"
683
                height="14" />
684
                Certificate Details</a></span>
685
                </div>
686
                <div id="certtext2" style="display:none"><span
687
                class="expander"><a
688
                href="javascript:showHideDiv(\'certtext\',-1)"><img
689
                src="/images/tridown.gif" alt="&dArr;" width="14"
690
                height="14" />
691
                Certificate Details</a></span>
692
                </div>
693
                <br class="clear" />
694
                <div id="certtext3" style="display:none">
695
                  <div class="portalinfo">
696
                  <pre>' , htmlspecialchars($certtext) , '</pre>
697
                  </div>
698
                </div>
699
                </div>
700
                ';
701
            }
702
        } else {
703
            echo '
704
            <p>
705
            We were unable to issue a certificate to "' ,
706
            htmlspecialchars(Util::getSessionVar('portalname')) , '".
707
            Below is a link to return to the site.
708
            </p>
709
            ';
710
        }
711
        echo '
712
        <div class="returnlink">
713
          <a href="' ,
714
          ((strlen($responseurl) > 0) ? $responseurl :
715
           (Util::getSessionVar($success ? 'successuri' : 'failureuri'))) ,
716
          '">Return to ' ,
717
          htmlspecialchars(Util::getSessionVar('portalname')) , '</a>
718
        </div>
719
        </div>
720
        ';
721
        Content::printFooter();
722
        if ($success) {
723
            Util::unsetClientSessionVars();
724
            // Util::unsetAllUserSessionVars();
725
        } else {
726
            Util::unsetAllUserSessionVars();
727
        }
728
    }
729
}
730
731
/**
732
 * verifyOAuthToken
733
 *
734
 * This function verifies that all of the various PortalParameters
735
 * have been set in the PHP session.  If the first parameter is passed
736
 * in, it first attempts to call CILogon::getPortalParameters() and
737
 * populates the PHP session with the associated values.
738
 *
739
 * @param string $token (Optional) The temporary credential passed from a
740
 *        Community Portal to the 'delegate' script as 'oauth_token' in the
741
 *        URL (as a $_GET variable). Defaults to empty string.
742
 * @return bool True if the various parameters related to the OAuth
743
 *         token (callbackuri, failureuri, successuri, portalname,
744
 *         and tempcred) are in the PHP session, false otherwise.
745
 */
746
function verifyOAuthToken($token = '')
747
{
748
    $retval = false; // Assume OAuth session info is not valid
749
750
    // If passing in the OAuth $token, try to get the associated info
751
    // from the persistent store and put it into the PHP session.
752
    if (strlen($token) > 0) {
753
        $dbs = new DBService();
754
        $dbs->getPortalParameters($token);
755
        $status = $dbs->status;
756
        Util::setSessionVar('portalstatus', $status);
757
        if (!($status & 1)) {  // STATUS_OK* codes are even-numbered
758
            Util::setSessionVar('callbackuri', $dbs->cilogon_callback);
759
            Util::setSessionVar('failureuri', $dbs->cilogon_failure);
760
            Util::setSessionVar('successuri', $dbs->cilogon_success);
761
            Util::setSessionVar('portalname', $dbs->cilogon_portal_name);
762
            Util::setSessionVar('tempcred', $dbs->oauth_token);
763
        }
764
    }
765
766
    // Now check to verify all session variables have data
767
    if (
768
        (strlen(Util::getSessionVar('callbackuri')) > 0) &&
769
        (strlen(Util::getSessionVar('failureuri')) > 0) &&
770
        (strlen(Util::getSessionVar('successuri')) > 0) &&
771
        (strlen(Util::getSessionVar('portalname')) > 0) &&
772
        (strlen(Util::getSessionVar('tempcred')) > 0) &&
773
        (!(Util::getSessionVar('portalstatus') & 1))
774
    ) { // STATUS_OK* are even
775
        $retval = true;
776
    }
777
778
    // As a final check, see if this portal requires a forced skin
779
    if ($retval) {
780
        Util::getSkin()->init();
781
    }
782
783
    return $retval;
784
}
785