Completed
Push — master ( 277f1b...d142f4 )
by Terrence
13:18
created

index-site.php ➔ printGetCertificate()   F

Complexity

Conditions 32
Paths 13828

Size

Total Lines 221
Code Lines 110

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 32
eloc 110
nc 13828
nop 0
dl 0
loc 221
rs 2
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
// error_reporting(E_ALL); ini_set('display_errors',1);
4
5
require_once __DIR__ . '/vendor/autoload.php';
6
7
use CILogon\Service\Util;
8
use CILogon\Service\Content;
9
use CILogon\Service\ShibError;
10
use CILogon\Service\Loggit;
11
12
Util::startPHPSession();
13
14
// Util::startTiming();
15
// Util::$timeit->printTime('MAIN Program START...');
16
17
// Check for a Shibboleth error and handle it
18
$shiberror = new ShibError();
19
20
// Check the csrf cookie against either a hidden <form> element or a
21
// PHP session variable, and get the value of the 'submit' element.
22
// Note: replace CR/LF with space for 'Show/Hide Help' buttons.
23
$retchars = array("\r\n","\n","\r");
24
$submit = str_replace(
25
    $retchars,
26
    " ",
27
    Util::getCsrf()->verifyCookieAndGetSubmit()
28
);
29
Util::unsetSessionVar('submit');
30
31
$log = new Loggit();
32
$log->info('submit="' . $submit . '"');
33
34
// Depending on the value of the clicked 'submit' button or the
35
// equivalent PHP session variable, take action or print out HTML.
36
switch ($submit) {
37
    case 'Log On': // Check for OpenID or InCommon usage.
38
    case 'Continue': // For OOI
39
        Content::handleLogOnButtonClicked();
40
        break; // End case 'Log On'
41
42
    case 'Log Off':   // Click the 'Log Off' button
43
        printLogonPage(true);
0 ignored issues
show
Unused Code introduced by
The call to printLogonPage() has too many arguments starting with true.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
44
        break; // End case 'Log Off'
45
46
    case 'gotuser': // Return from the getuser script
47
        Content::handleGotUser();
48
        break; // End case 'gotuser'
49
50
    case 'Go Back': // Return to the Main page
51
    case 'Proceed': // Proceed after 'User Changed' or Error page
52
    case 'Done with Two-Factor':
53
        Util::verifySessionAndCall('printMainPage');
0 ignored issues
show
Documentation introduced by
'printMainPage' is of type string, but the function expects a object<CILogon\Service\function>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
54
        break; // End case 'Go Back' / 'Proceed'
55
56
    case 'Cancel': // Cancel button on WAYF page - go to Google
57
        header('Location: https://www.google.com/');
58
        exit; // No further processing necessary
59
        break;
60
61
    case 'Get New Certificate':
62
        if (Util::verifySessionAndCall(
63
            'CILogon\\Service\\Content::generateP12'
0 ignored issues
show
Documentation introduced by
'CILogon\\Service\\Content::generateP12' is of type string, but the function expects a object<CILogon\Service\function>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
64
        )) {
65
            printMainPage();
66
        }
67
        break; // End case 'Get New Certificate'
68
69
    case 'Get New Activation Code':
70
        if (Util::verifySessionAndCall('generateActivationCode')) {
0 ignored issues
show
Documentation introduced by
'generateActivationCode' is of type string, but the function expects a object<CILogon\Service\function>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
71
            printMainPage();
72
        }
73
        break; // End case 'Get New Activation Code'
74
75
    case 'Manage Two-Factor':
76
        Util::verifySessionAndCall(
77
            'CILogon\\Service\\Content::printTwoFactorPage'
0 ignored issues
show
Documentation introduced by
'CILogon\\Service\\Content::printTwoFactorPage' is of type string, but the function expects a object<CILogon\Service\function>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
78
        );
79
        break; // End case 'Manage Two-Factor'
80
81
    case 'Enable':   // Enable / Disable two-factor authentication
82
    case 'Disable':
83
    case 'Verify':   // Log in with Google Authenticator
84
    case 'Disable Two-Factor':
85
        $enable = !preg_match('/^Disable/', $submit);
86
        Util::verifySessionAndCall(
87
            'CILogon\\Service\\Content::handleEnableDisableTwoFactor',
0 ignored issues
show
Documentation introduced by
'CILogon\\Service\\Conte...EnableDisableTwoFactor' is of type string, but the function expects a object<CILogon\Service\function>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
88
            array($enable)
89
        );
90
        break; // End case 'Enable' / 'Disable'
91
92
    case 'I Lost My Phone':
93
        Util::verifySessionAndCall(
94
            'CILogon\\Service\\Content::handleILostMyPhone'
0 ignored issues
show
Documentation introduced by
'CILogon\\Service\\Content::handleILostMyPhone' is of type string, but the function expects a object<CILogon\Service\function>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
95
        );
96
        break; // End case 'I Lost My Phone'
97
98
    case 'Enter': // Verify Google Authenticator one time password
99
        Util::verifySessionAndCall(
100
            'CILogon\\Service\\Content::handleGoogleAuthenticatorLogin'
0 ignored issues
show
Documentation introduced by
'CILogon\\Service\\Conte...ogleAuthenticatorLogin' is of type string, but the function expects a object<CILogon\Service\function>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
101
        );
102
        break; // End case 'Enter'
103
104
    case 'EnterDuo': // Verify Duo Security login
105
        Util::verifySessionAndCall(
106
            'CILogon\\Service\\Content::handleDuoSecurityLogin'
0 ignored issues
show
Documentation introduced by
'CILogon\\Service\\Conte...handleDuoSecurityLogin' is of type string, but the function expects a object<CILogon\Service\function>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
107
        );
108
        break; // End case 'EnterDuo'
109
110
    case 'Show  Help ': // Toggle showing of help text on and off
111
    case 'Hide  Help ':
112
        Content::handleHelpButtonClicked();
113
        break; // End case 'Show Help' / 'Hide Help'
114
115
    default: // No submit button clicked nor PHP session submit variable set
116
        Content::handleNoSubmitButtonClicked();
117
        break; // End default case
118
} // End switch($submit)
119
120
121
/**
122
 * printLogonPage
123
 *
124
 * This function prints out the HTML for the main cilogon.org page.
125
 * Explanatory text is shown as well as a button to log in to an IdP
126
 * and get rerouted to the Shibboleth protected service script, or the
127
 * OpenID script.
128
 *
129
 * @param bool $clearcookies True if the Shibboleth cookies and session
130
 *        variables  should be cleared out before displaying the page.
131
 *        Defaults to false.
132
 */
133
function printLogonPage($clearcookies = false)
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-site.php (L143-234) 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...
134
{
135
    if ($clearcookies) {
136
        Util::removeShibCookies();
137
        Util::unsetAllUserSessionVars();
138
        Util::getSkin()->init(true);  // Clear cilogon_skin var; check for forced skin
139
    }
140
141
    $log = new Loggit();
142
    $log->info('Welcome page hit.');
143
144
    Util::setSessionVar('stage', 'logon'); // For Show/Hide Help button clicks
145
146
    Content::printHeader('Welcome To The CILogon Service');
147
148
    echo '
149
    <div class="boxed">
150
    ';
151
152
    Content::printHelpButton();
153
    Content::printWAYF();
154
155
    echo '
156
    </div> <!-- End boxed -->
157
    ';
158
    Content::printFooter();
159
}
160
161
/**
162
 * printMainPage
163
 *
164
 * This function prints out the HTML for the main page where the user
165
 * can download a certificate or generate an Activation Code.
166
 */
167
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-site.php (L305-397) 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...
168
{
169
    $log = new Loggit();
170
    $log->info('Get And Use Certificate page hit.');
171
172
    Util::setSessionVar('stage', 'main'); // For Show/Hide Help button clicks
173
174
    Content::printHeader('Get Your Certificate');
175
176
    echo '
177
    <div class="boxed">
178
    ';
179
180
    Content::printHelpButton();
181
    printCertInfo();
182
    printGetCertificate();
183
    printDownloadCertificate();
184
    printGetActivationCode();
185
    Content::printTwoFactorBox();
186
    printLogOff();
187
188
    echo '
189
    </div> <!-- boxed -->
190
    ';
191
    Content::printFooter();
192
}
193
194
/**
195
 * printCertInfo
196
 *
197
 * This function prints the certificate information table at the top
198
 * of the main page.
199
 */
200
function printCertInfo()
201
{
202
    $dn = Util::getSessionVar('dn');
203
    $dn = Content::reformatDN(preg_replace('/\s+email=.+$/', '', $dn));
204
205
    echo '
206
    <table class="certinfo">
207
      <tr>
208
        <th>Certificate&nbsp;Subject:</th>
209
        <td>' , Util::htmlent($dn) , '</td>
210
      </tr>
211
      <tr>
212
        <th>Identity&nbsp;Provider:</th>
213
        <td>' , Util::getSessionVar('idpname') , '</td>
214
      </tr>
215
      <tr>
216
        <th><a target="_blank"
217
        href="http://ca.cilogon.org/loa">Level&nbsp;of&nbsp;Assurance:</a></th>
218
        <td>
219
    ';
220
221
    $loa = Util::getSessionVar('loa');
222
    if ($loa == 'openid') {
223
        echo '<a href="http://ca.cilogon.org/policy/openid"
224
              target="_blank">OpenID</a>';
225
    } elseif ($loa == 'http://incommonfederation.org/assurance/silver') {
226
        echo '<a href="http://ca.cilogon.org/policy/silver"
227
              target="_blank">Silver</a>';
228
    } else {
229
        echo '<a href="http://ca.cilogon.org/policy/basic"
230
              target="_blank">Basic</a>';
231
    }
232
    echo '
233
        </td>
234
      </tr>
235
    </table>
236
    ';
237
}
238
239
/**
240
 * printGetCertificate
241
 *
242
 * This function prints the 'Get New Certificate' box on the main page.
243
 * If the 'p12' PHP session variable is valid, it is read and a ink for the
244
 * usercred.p12 file is presented to the user.
245
 */
246
function printGetCertificate()
247
{
248
    // Check if PKCS12 downloading is disabled. If so, print out message.
249
    $skin = Util::getSkin();
250
    $disabled = $skin->getConfigOption('pkcs12', 'disabled');
251
    if ((!is_null($disabled)) && ((int)$disabled == 1)) {
252
        $disabledmsg = $skin->getConfigOption(
253
            'pkcs12',
254
            'disabledmessage'
255
        );
256
        if (!is_null($disabledmsg)) {
257
            $disabledmsg = trim(html_entity_decode($disabledmsg));
258
        }
259
        if (strlen($disabledmsg) == 0) {
260
            $disabledmsg = "Downloading PKCS12 certificates is " .
261
                "restricted. Please try another method or log on " .
262
                "with a different Identity Provider.";
263
        }
264
265
        echo '<div class="p12actionbox"><p>
266
             ', $disabledmsg , '
267
             </p></div> <!-- p12actionbox -->';
268
    } else { // PKCS12 downloading is okay
269
270
        $downloadcerttext = "Clicking this button will generate a link " .
271
            "to a new certificate, which you can download to your local " .
272
            "computer. The certificate is valid for up to 13 months.";
273
        $p12linktext = "Left-click this link to import the certificate " .
274
            "into your broswer / operating system. (Firefox users see " .
275
            "the FAQ.) Right-click this link and select 'Save As...' to " .
276
            "save the certificate to your desktop.";
277
        $passwordtext1 = 'Enter a password of at least 12 characters to " .
278
            "protect your certificate.';
279
        $passwordtext2 = 'Re-enter your password to verify.';
280
281
        validateP12();
282
        $p12expire = '';
283
        $p12link = '';
284
        $p12 = Util::getSessionVar('p12');
285
        if (preg_match('/([^\s]*)\s(.*)/', $p12, $match)) {
286
            $p12expire = $match[1];
287
            $p12link = $match[2];
288
        }
289
290
        if ((strlen($p12link) > 0) && (strlen($p12expire) > 0)) {
291
            $p12link = '<a href="' . $p12link .
292
                '">&raquo; Click Here To Download Your Certificate &laquo;</a>';
293
        }
294
        if ((strlen($p12expire) > 0) && ($p12expire > 0)) {
295
            $expire = $p12expire - time();
296
            $minutes = floor($expire % 3600 / 60);
297
            $seconds = $expire % 60;
298
            $p12expire = 'Link Expires: ' .
299
                sprintf("%02dm:%02ds", $minutes, $seconds);
300
        } else {
301
            $p12expire = '';
302
        }
303
304
        $p12lifetime = Util::getSessionVar('p12lifetime');
305
        if ((strlen($p12lifetime) == 0) || ($p12lifetime == 0)) {
306
            $p12lifetime = Util::getCookieVar('p12lifetime');
307
        }
308
        $p12multiplier = Util::getSessionVar('p12multiplier');
309
        if ((strlen($p12multiplier) == 0) || ($p12multiplier == 0)) {
310
            $p12multiplier = Util::getCookieVar('p12multiplier');
311
        }
312
313
        // Try to read the skin's intiallifetime if not yet set
314
        if ((strlen($p12lifetime) == 0) || ($p12lifetime <= 0)) {
315
            // See if the skin specified an initial value
316
            $skinlife = $skin->getConfigOption('pkcs12', 'initiallifetime', 'number');
317
            $skinmult = $skin->getConfigOption('pkcs12', 'initiallifetime', 'multiplier');
318
            if ((!is_null($skinlife)) && (!is_null($skinmult)) &&
319
                ((int)$skinlife > 0) && ((int)$skinmult > 0)) {
320
                $p12lifetime = (int)$skinlife;
321
                $p12multiplier = (int)$skinmult;
322
            } else {
323
                $p12lifetime = 13;      // Default to 13 months
324
                $p12multiplier = 732;
325
            }
326
        }
327
        if ((strlen($p12multiplier) == 0) || ($p12multiplier <= 0)) {
328
            $p12multiplier = 732;   // Default to months
329
            if ($p12lifetime > 13) {
330
                $p12lifetime = 13;
331
            }
332
        }
333
334
        // Make sure lifetime is within [minlifetime,maxlifetime]
335
        list($minlifetime, $maxlifetime) =
336
            Content::getMinMaxLifetimes('pkcs12', 9516);
337
        if (($p12lifetime * $p12multiplier) < $minlifetime) {
338
            $p12lifetime = $minlifetime;
339
            $p12multiplier = 1; // In hours
340
        } elseif (($p12lifetime * $p12multiplier) > $maxlifetime) {
341
            $p12lifetime = $maxlifetime;
342
            $p12multiplier = 1; // In hours
343
        }
344
345
        $lifetimetext = "Specify the certificate lifetime. Acceptable range " .
346
                        "is between $minlifetime and $maxlifetime hours" .
347
                        (($maxlifetime > 732) ?
348
                            " ( = " . round(($maxlifetime/732), 2) . " months)." :
349
                            "."
350
                        );
351
352
        echo '
353
        <div class="p12actionbox"';
354
355
        if (Util::getSessionVar('showhelp') == 'on') {
356
            echo ' style="width:92%;"';
357
        }
358
359
        echo '>
360
        <table class="helptable">
361
        <tr>
362
        <td class="actioncell">
363
        ';
364
365
        Content::printFormHead();
366
367
        echo '
368
          <fieldset>
369
          ';
370
371
        $p12error = Util::getSessionVar('p12error');
372
        if (strlen($p12error) > 0) {
373
            echo "<p class=\"logonerror\">$p12error</p>";
374
            Util::unsetSessionVar('p12error');
375
        }
376
377
        echo '
378
          <p>
379
          Password Protect Your New Certificate:
380
          </p>
381
382
          <p>
383
          <label for="password1" class="helpcursor" title="' ,
384
          $passwordtext1 , '">Enter A Password:</label>
385
          <input type="password" name="password1" id="password1"
386
          size="22" title="' , $passwordtext1 , '" onkeyup="checkPassword()"/>
387
          <img src="/images/blankIcon.png" width="14" height="14" alt=""
388
          id="pw1icon"/>
389
          </p>
390
391
          <p>
392
          <label for="password2" class="helpcursor" title="' ,
393
          $passwordtext2 , '">Confirm Password:</label>
394
          <input type="password" name="password2" id="password2"
395
          size="22" title="' , $passwordtext2 , '" onkeyup="checkPassword()"/>
396
          <img src="/images/blankIcon.png" width="14" height="14" alt=""
397
          id="pw2icon"/>
398
          </p>
399
400
          <p class="p12certificatelifetime">
401
          <label for="p12lifetime" title="' , $lifetimetext ,
402
          '" class="helpcursor">Certificate Lifetime:</label>
403
          <input type="text" name="p12lifetime" id="p12lifetime"
404
          title="', $lifetimetext ,
405
          '" class="helpcursor" value="' , $p12lifetime ,
406
          '" size="8" maxlength="8"/>
407
          <select title="' , $lifetimetext ,
408
          '" class="helpcursor" id="p12multiplier" name="p12multiplier">
409
          <option value="1"' ,
410
              (($p12multiplier==1) ? ' selected="selected"' : '') ,
411
              '>hours</option>
412
          <option value="24"' ,
413
              (($p12multiplier==24) ? ' selected="selected"' : '') ,
414
              '>days</option>
415
          <option value="732"' ,
416
              (($p12multiplier==732) ? ' selected="selected"' : '') ,
417
              '>months</option>
418
          </select>
419
          <img src="/images/blankIcon.png" width="14" height="14" alt=""/>
420
          </p>
421
422
          <p>
423
          <input type="submit" name="submit" class="submit helpcursor"
424
          title="' , $downloadcerttext , '" value="Get New Certificate"
425
          onclick="showHourglass(\'p12\')"/>
426
          <img src="/images/hourglass.gif" width="32" height="32" alt=""
427
          class="hourglass" id="p12hourglass"/>
428
          </p>
429
430
          <p id="p12value" class="helpcursor" title="' ,
431
              $p12linktext , '">' , $p12link , '</p>
432
          <p id="p12expire">' , $p12expire , '</p>
433
434
          </fieldset>
435
          </form>
436
        </td>
437
        ';
438
439
        if (Util::getSessionVar('showhelp') == 'on') {
440
            echo '
441
            <td class="helpcell">
442
            <div>
443
            <p>
444
            In order to get a new certificate, please enter a password of at
445
            least 12 characters in length.  This password protects the private
446
            key of the certificate and is different from your identity provider
447
            password.  You must enter the password twice for verification.
448
            </p>
449
            <p>
450
            After entering a password, click the "Get New Certificate" button to
451
            generate a new link.  Right-click on this link to download the
452
            certificate to your computer.  The certificate is valid for up to 13
453
            months.
454
            </p>
455
            </div>
456
            </td>
457
            ';
458
        }
459
460
        echo '
461
        </tr>
462
        </table>
463
        </div> <!-- p12actionbox -->
464
        ';
465
    }
466
}
467
468
/**
469
 * printDownlaodCertificate
470
 *
471
 * This function prints the 'Download Certificate' box, which uses the
472
 * GridShib-CA JWS client to download a certificate for the user.
473
 */
474
function printDownloadCertificate()
475
{
476
    $gridshibconf = Util::parseGridShibConf();
477
    $idpname = Util::getSessionVar('idpname');
0 ignored issues
show
Unused Code introduced by
$idpname is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
478
479
    $downloadcerttext = "Download a certificate to your local computer. " .
480
        "Clicking this button should launch a Java Web Start (JWS) " .
481
        "application, which requires Java to be installed on your " .
482
        "computer and enabled in your web browser.";
483
484
    echo '
485
    <div class="certactionbox"';
486
487
    if (Util::getSessionVar('showhelp') == 'on') {
488
        echo ' style="width:92%;"';
489
    }
490
491
    echo '>
492
    <table class="helptable">
493
    <tr>
494
    <td class="actioncell">
495
    ';
496
497
    Content::printFormHead(
498
        preg_replace(
499
            '/^\s*=\s*/',
500
            '',
501
            $gridshibconf['root']['GridShibCAURL']
502
        ) . 'shibCILaunchGSCA.jnlp',
503
        'post',
504
        true
505
    );
506
507
    $certlifetime   = Util::getCookieVar('certlifetime');
508
    $certmultiplier = Util::getCookieVar('certmultiplier');
509
510
    // Try to read the skin's initiallifetime if not yet set
511
    if ((strlen($certlifetime) == 0) || ($certlifetime <= 0)) {
512
        $skin = Util::getSkin();
513
        $skinlife = $skin->getConfigOption('gsca', 'initiallifetime', 'number');
514
        $skinmult = $skin->getConfigOption('gsca', 'initiallifetime', 'multiplier');
515
        if ((!is_null($skinlife)) && (!is_null($skinmult)) &&
516
            ((int)$skinlife > 0) && ((int)$skinmult > 0)) {
517
            $certlifetime = (int)$skinlife;
518
            $certmultiplier = (int)$skinmult;
519
        } else { // Use gridshib-ca.conf default value
520
            $certlifetime = round(preg_replace(
521
                '/^\s*=\s*/',
522
                '',
523
                $gridshibconf['root']['CA']['DefaultCredLifetime']
524
            ) / 3600);
525
            $certmultiplier = 3600;
526
        }
527
    }
528
    if ((strlen($certmultiplier) == 0) || ($certmultiplier <= 0)) {
529
        $certmultiplier = 3600;   // Default to hours
530
    }
531
532
    // Make sure lifetime is within [minlifetime,maxlifetime]
533
    $defaultmaxlifetime = preg_replace(
534
        '/^\s*=\s*/',
535
        '',
536
        $gridshibconf['root']['CA']['MaximumCredLifetime']
537
    ) / 3600;
538
    list($minlifetime, $maxlifetime) =
539
        Content::getMinMaxLifetimes('gsca', $defaultmaxlifetime);
540
    if (($certlifetime * $certmultiplier / 3600) < $minlifetime) {
541
        $certlifetime = $minlifetime;
542
        $certmultiplier = 3600; // In hours
543
    } elseif (($certlifetime * $certmultiplier / 3600) > $maxlifetime) {
544
        $certlifetime = $maxlifetime;
545
        $certmultiplier = 3600; // In hours
546
    }
547
548
    $lifetimetext = "Specify the certificate lifetime. Acceptable range " .
549
                    "is between $minlifetime and $maxlifetime hours" .
550
                    (($maxlifetime > 732) ?
551
                        " ( = " . round(($maxlifetime/732), 2) . " months)." :
552
                        "."
553
                    );
554
555
    $maxcleartextlifetime = preg_replace(
556
        '/^\s*=\s*/',
557
        '',
558
        $gridshibconf['root']['LaunchClient']['MaxCleartextLifetime']
559
    ) / 3600;
560
    if (($maxcleartextlifetime > 0) &&
561
        ($maxlifetime >= $maxcleartextlifetime)) {
562
        $lifetimetext .= " Lifetimes greater than " .
563
            round(($maxcleartextlifetime/24), 2) .
564
            " days will require you to specify a passphrase.";
565
    }
566
567
    echo '
568
      <fieldset>
569
      <p class="jwscertificatelifetime">
570
      <label for="certlifetime" title="' , $lifetimetext ,
571
      '" class="helpcursor">Lifetime:</label>
572
      <input type="text" name="certlifetime" id="certlifetime"
573
      title="', $lifetimetext ,
574
      '" class="helpcursor" value="' , $certlifetime ,
575
      '" size="8" maxlength="8" disabled="disabled"/>
576
      <select title="' , $lifetimetext ,
577
      '" class="helpcursor" id="certmultiplier" name="certmultiplier"
578
      disabled="disabled">
579
      <option value="3600"' ,
580
          (($certmultiplier==3600) ? ' selected="selected"' : '') ,
581
          '>hours</option>
582
      <option value="86400"' ,
583
          (($certmultiplier==86400) ? ' selected="selected"' : '') ,
584
          '>days</option>
585
      <option value="2635200"' ,
586
          (($certmultiplier==2635200) ? ' selected="selected"' : '') ,
587
          '>months</option>
588
      </select>
589
      <input type="hidden" name="minlifetime" id="minlifetime" value="' ,
590
      $minlifetime*3600 , '" />
591
      <input type="hidden" name="maxlifetime" id="maxlifetime" value="' ,
592
      $maxlifetime*3600 , '" />
593
      <input type="hidden" name="RequestedLifetime" id="RequestedLifetime"
594
      value="' , ($certlifetime * $certmultiplier) , '" />
595
      </p>
596
      <p>
597
      <input type="submit" name="submit" class="submit helpcursor"
598
      title="' , $downloadcerttext ,
599
      '" value="Download Certificate" onclick="handleLifetime();" />
600
      </p>
601
      <p class="smaller zeroheight" id="mayneedjava">
602
      You may need to install <a target="_blank"
603
      href="http://www.javatester.org/version.html">Java</a>.
604
      </p>
605
      </fieldset>
606
607
      <noscript>
608
      <div class="nojs smaller">
609
      JavaScript must be enabled to specify Lifetime.
610
      </div>
611
      </noscript>
612
613
      </form>
614
    </td>
615
    ';
616
617
    if (Util::getSessionVar('showhelp') == 'on') {
618
        echo '
619
        <td class="helpcell">
620
        <div>
621
        <p>
622
        When you click on the "Download Certificate" button, a JNLP file is
623
        downloaded to your computer which will launch Java Web Start
624
        (assuming <a target="_blank"
625
        href="http://java.com/getjava/">Java</a> is correctly installed on
626
        your machine).  This will run the CILogon Certificate Retriever
627
        program to download a certificate.  The program may prompt you to
628
        enter a password of at least 12 characters to protect the private
629
        key of the certificate.  This password is different from your
630
        identity provider password.
631
        </p>
632
        </div>
633
        </td>
634
        ';
635
    }
636
637
    echo '
638
    </tr>
639
    </table>
640
    </div> <!-- certactionbox -->
641
    ';
642
}
643
644
/**
645
 * printGetActivationCode
646
 *
647
 * This function prints the 'Get New Activation Code' box on the main
648
 * page.  If the 'activation' PHP session variable is valid, it is
649
 * shown at the bottom of the box.  The Activation Code can be used by
650
 * the GridShib-CA python client to fetch a certificate.
651
 */
652
function printGetActivationCode()
653
{
654
    $generatecodetext = "Get a new one-time-use activation code for " .
655
        "CILogon-enabled applications.";
656
    $tokenhelptext = "Click the button below to display a one-time-use " .
657
        "activation code for CILogon-enabled applications. You can copy " .
658
        "and paste this code into the application to download a " .
659
        "certificate. See FAQ for more information.";
660
    $tokenvaluetext = 'Copy and paste the one-time-use activation code " .
661
        "into your CILogon-enabled application to download a certificate.';
662
663
    echo '
664
    <div class="tokenactionbox"';
665
666
    if (Util::getSessionVar('showhelp') == 'on') {
667
        echo ' style="width:92%;"';
668
    }
669
670
    echo '>
671
    <table class="helptable">
672
    <tr>
673
    <td class="actioncell">
674
    ';
675
676
    Content::printFormHead();
677
678
    validateActivationCode();
679
    $tokenvalue = '';
680
    $tokenexpire = '';
681
    $activation = Util::getSessionVar('activation');
682
    if (preg_match('/([^\s]*)\s(.*)/', $activation, $match)) {
683
        $tokenexpire = $match[1];
684
        $tokenvalue = $match[2];
685
    }
686
    if ((strlen($tokenvalue) > 0) && (strlen($tokenexpire) > 0)) {
687
        $tokenvalue = 'Activation&nbsp;Code: ' . $tokenvalue;
688
    }
689
    if ((strlen($tokenexpire) > 0) && ($tokenexpire > 0)) {
690
        $expire = $tokenexpire - time();
691
        $minutes = floor($expire % 3600 / 60);
692
        $seconds = $expire % 60;
693
        $tokenexpire = 'Code Expires: ' .
694
            sprintf("%02dm:%02ds", $minutes, $seconds);
695
    } else {
696
        $tokenexpire = '';
697
    }
698
699
    echo '
700
      <p class="helpcursor" title="' ,
701
          $tokenhelptext , '">For CILogon-enabled Applications:</p>
702
      <p>
703
704
      <input type="submit" name="submit" class="submit helpcursor"
705
      title="' , $generatecodetext , '" value="Get New Activation Code"
706
      onclick="showHourglass(\'token\')"/>
707
      <img src="/images/hourglass.gif" width="32" height="32" alt=""
708
      class="hourglass" id="tokenhourglass"/>
709
      </p>
710
      <p id="tokenvalue" class="helpcursor" title="' ,
711
          $tokenvaluetext , '">' , $tokenvalue , '</p>
712
      <p id="tokenexpire">' , $tokenexpire , '</p>
713
714
      </form>
715
    </td>
716
    ';
717
718
    if (Util::getSessionVar('showhelp') == 'on') {
719
        echo '
720
        <td class="helpcell">
721
        <div>
722
        <p>
723
        An Activation Code can be used by a <a target="_blank"
724
        href="http://www.cilogon.org/enabled">CILogon-enabled
725
        Application</a> to download a certificate. Click the "Get New
726
        Activation Code" button to generate a random sequence of letters and
727
        numbers.  Highlight the activation code (e.g. double-click it), copy
728
        the code from your browser, and paste it into the CILogon-enabled
729
        application.
730
        </p>
731
        </div>
732
        </td>
733
        ';
734
    }
735
736
    echo '
737
    </tr>
738
    </table>
739
    </div> <!-- tokenactionbox -->
740
    ';
741
}
742
743
/**
744
 * printLogOff
745
 *
746
 * This function prints the Log Off boxes at the bottom of the main page.
747
 */
748
function printLogOff()
749
{
750
    $logofftext = 'End your CILogon session and return to the welcome page. ' .
751
                  'Note that this will not log you out at ' .
752
                  Util::getSessionVar('idpname') . '.';
753
754
    $showhelp = Util::getSessionVar('showhelp');
755
756
    echo '
757
    <div class="logoffactionbox"';
758
759
    if ($showhelp == 'on') {
760
        echo ' style="width:92%;"';
761
    }
762
763
    echo '>
764
    <table class="helptable">
765
    <tr>
766
    <td class="actioncell">
767
    ';
768
769
    Content::printFormHead();
770
771
    echo '
772
      <p>
773
      <input type="submit" name="submit" class="submit helpcursor"
774
      title="' , $logofftext , '" value="Log Off" />
775
      </p>
776
    </form>
777
    </td>
778
    ';
779
780
    if ($showhelp == 'on') {
781
        echo '
782
        <td class="helpcell">
783
        <div>
784
        <p>
785
        This button will log you off of the CILogon Service. In order to log
786
        out from your identity provider, you must either quit your browser
787
        or manually clear your browser\'s cookies.
788
        </p>
789
        </div>
790
        </td>
791
        ';
792
    }
793
794
    echo '
795
    </tr>
796
    </table>
797
    </div> <!-- logoffactionbox -->
798
799
    <div class="logofftextbox"';
800
801
    if ($showhelp == 'on') {
802
        echo ' style="width:92%;"';
803
    }
804
805
    echo '>
806
    <table class="helptable">
807
    <tr>
808
    <td class="actioncell">
809
      <p>To log off, please quit your browser.<p>
810
    </td>
811
    ';
812
813
    if ($showhelp == 'on') {
814
        echo '
815
        <td class="helpcell">
816
        <div>
817
        <p>
818
        Quitting your browser clears all session cookies which logs you out
819
        from your identity provider.  Alternatively, you can manually clear
820
        your browser\'s cookies.
821
        </p>
822
        </div>
823
        </td>
824
        ';
825
    }
826
827
    echo '
828
    </tr>
829
    </table>
830
    </div> <!-- logofftextbox -->
831
    ';
832
}
833
834
/**
835
 * generateActivationCode
836
 *
837
 * This function is called when the user clicks the 'Get New Activation
838
 * Code' button.  It calls the GridShib CA functionality to create a
839
 * .jnlp file, uses 'curl' to slurp in the resulting .jnlp file, and
840
 * scans for the AuthenticationToken in the file.  This is stored in
841
 * the 'activation' PHP session value to be output to the user when
842
 * the Main Page is redrawn. The token can be used by the GridShib-CA
843
 * python client to fetch a certificate.
844
 */
845
function generateActivationCode()
846
{
847
    $tokenvalue = '';
848
    $gridshibconf = Util::parseGridShibConf();
849
850
    $ch = curl_init();
851
    if ($ch !== false) {
852
        $csrf = Util::getCsrf();
853
        $url = 'https://' . Util::getHN() . preg_replace(
854
            '/^\s*=\s*/',
855
            '',
856
            $gridshibconf['root']['GridShibCAURL']
857
        ) . 'shibCILaunchGSCA.jnlp';
858
        curl_setopt($ch, CURLOPT_URL, $url);
859
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
860
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
861
        curl_setopt($ch, CURLOPT_POST, true);
862
        curl_setopt($ch, CURLOPT_HEADER, false);
863
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
864
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
865
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
866
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'CSRFProtection=' .
867
            $csrf->getTokenValue());
868
        curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=' .
869
            Util::getCookieVar('PHPSESSID') . '; CSRFProtection=' .
870
            $csrf->getTokenValue() . ';');
871
872
        // Must close PHP session file so GridShib-CA can read it.
873
        session_write_close();
874
        $output = curl_exec($ch);
875
        if (curl_errno($ch)) { // Send alert on curl errors
876
            Util::sendErrorAlert(
877
                'cUrl Error',
878
                'cUrl Error    = ' . curl_error($ch) . "\n" .
879
                "URL Accessed  = $url"
880
            );
881
        }
882
        if (!empty($output)) {
883
            $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
884
            if ($httpcode == 200) {
885
                if (preg_match(
886
                    '/AuthenticationToken = ([^<]+)/',
887
                    $output,
888
                    $match
889
                )) {
890
                    $tokenvalue = $match[1];
891
                }
892
            }
893
        }
894
        curl_close($ch);
895
896
        // If we got a valid AuthenticationToken, store it in the session.
897
        Util::startPHPSession();
898
        if (strlen($tokenvalue) > 0) {
899
            $tokenlifetime = preg_replace(
900
                '/^\s*=\s*/',
901
                '',
902
                $gridshibconf['root']['Session']['CredentialRetrieverClientLifetime']
903
            );
904
            if ((strlen($tokenlifetime) == 0) || ($tokenlifetime == 0)) {
905
                $tokenlifetime = 300;
906
            }
907
            $activation = (time()+$tokenlifetime) . " " . $tokenvalue;
908
            Util::setSessionVar('activation', $activation);
909
            $log = new Loggit();
910
            $log->info('Generated New Activation Code="'.$tokenvalue.'"');
911
        }
912
    }
913
}
914
915
/**
916
 * validateP12
917
 *
918
 * This function is called just before the 'Download your certificate'
919
 * link is printed out to HTML. It checks to see if the p12 is still
920
 * valid time-wise. If not, then it unsets the PHP session variable
921
 * 'p12'.
922
 */
923
function validateP12()
924
{
925
    $p12link = '';
926
    $p12expire = '';
927
    $p12 = Util::getSessionVar('p12');
928
    if (preg_match('/([^\s]*)\s(.*)/', $p12, $match)) {
929
        $p12expire = $match[1];
930
        $p12link = $match[2];
931
    }
932
933
    // Verify that the p12expire and p12link values are valid.
934
    if ((strlen($p12expire) == 0) ||
935
        ($p12expire == 0) ||
936
        (time() > $p12expire) ||
937
        (strlen($p12link) == 0)) {
938
        Util::unsetSessionVar('p12');
939
    }
940
}
941
942
/**
943
 * validateActivationCode
944
 *
945
 * This function is called just before the certificate token is printed
946
 * out to HTML.  It checks to see if the activation token value is
947
 * expired. If so, it unsets the PHP session variable 'activation'.
948
 */
949
function validateActivationCode()
950
{
951
    $tokenvalue = '';
0 ignored issues
show
Unused Code introduced by
$tokenvalue is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
952
    $tokenexpire = '';
953
    $activation = Util::getSessionVar('activation');
954
    if (preg_match('/([^\s]*)\s(.*)/', $activation, $match)) {
955
        $tokenexpire = $match[1];
956
        $tokenvalue = $match[2];
0 ignored issues
show
Unused Code introduced by
$tokenvalue is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
957
    }
958
959
    // If there is a tokenexpire value, check against current time.
960
    if ((strlen($tokenexpire) == 0) ||
961
        ($tokenexpire == 0) ||
962
        (time() > $tokenexpire)) {
963
        Util::unsetSessionVar('activation');
964
    }
965
}
966
967
// Util::$timeit->printTime('MAIN Program END...  ');
968