Passed
Push — master ( 951518...df5075 )
by
unknown
09:13
created

xoPutLicenseKey()   B

Complexity

Conditions 11
Paths 26

Size

Total Lines 54
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 28
nc 26
nop 3
dl 0
loc 54
rs 7.3166
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
 * See the enclosed file license.txt for licensing information.
4
 * If you did not receive this file, get it at https://www.gnu.org/licenses/gpl-2.0.html
5
 *
6
 * @copyright    (c) 2000-2021 XOOPS Project (www.xoops.org)
7
 * @license          GNU GPL 2.0 or later (https://www.gnu.org/licenses/gpl-2.0.html)
8
 * @package          installer
9
 * @since            2.3.0
10
 * @author           Haruki Setoyama  <[email protected]>
11
 * @author           Kazumi Ono <[email protected]>
12
 * @author           Skalpa Keo <[email protected]>
13
 * @author           Taiwen Jiang <[email protected]>
14
 * @author           DuGris (aka L. JEN) <[email protected]>
15
 * @param string $hash
16
 * @return bool
17
 */
18
19
/**
20
 * call htmlspecialchars with standard arguments
21
 * @param string $value
22
 * @return string
23
 */
24
function installerHtmlSpecialChars($value = '')
25
{
26
    return htmlspecialchars($value, ENT_QUOTES, _INSTALL_CHARSET, true);
27
}
28
29
function install_acceptUser($hash = '')
0 ignored issues
show
Unused Code introduced by
The parameter $hash is not used and could be removed. ( Ignorable by Annotation )

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

29
function install_acceptUser(/** @scrutinizer ignore-unused */ $hash = '')

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

Loading history...
30
{
31
    $GLOBALS['xoopsUser'] = null;
32
    $assertClaims = [
33
        'sub' => 'xoopsinstall',
34
    ];
35
    $claims = \Xmf\Jwt\TokenReader::fromCookie('install', 'xo_install_user', $assertClaims);
36
    if (false === $claims || empty($claims->uname)) {
0 ignored issues
show
introduced by
The condition false === $claims is always true.
Loading history...
37
        return false;
38
    }
39
    $uname = $claims->uname;
40
    /** @var XoopsMemberHandler $memberHandler */
41
    $memberHandler = xoops_getHandler('member');
42
    $users = $memberHandler->getUsers(new Criteria('uname', $uname));
43
    $user = array_pop($users);
44
45
    if (is_object($GLOBALS['xoops']) && method_exists($GLOBALS['xoops'], 'acceptUser')) {
46
        $res = $GLOBALS['xoops']->acceptUser($uname, true, '');
47
48
        return $res;
49
    }
50
51
    $GLOBALS['xoopsUser']        = $user;
52
    $_SESSION['xoopsUserId']     = $GLOBALS['xoopsUser']->getVar('uid');
53
    $_SESSION['xoopsUserGroups'] = $GLOBALS['xoopsUser']->getGroups();
54
55
    return true;
56
}
57
58
/**
59
 * @param $installer_modified
60
 */
61
function install_finalize($installer_modified)
62
{
63
    // Set mainfile.php readonly
64
    @chmod(XOOPS_ROOT_PATH . '/mainfile.php', 0444);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

64
    /** @scrutinizer ignore-unhandled */ @chmod(XOOPS_ROOT_PATH . '/mainfile.php', 0444);

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
65
    // Set Secure file readonly
66
    @chmod(XOOPS_VAR_PATH . '/data/secure.php', 0444);
67
    // Rename installer folder
68
    @rename(XOOPS_ROOT_PATH . '/install', XOOPS_ROOT_PATH . '/' . $installer_modified);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for rename(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

68
    /** @scrutinizer ignore-unhandled */ @rename(XOOPS_ROOT_PATH . '/install', XOOPS_ROOT_PATH . '/' . $installer_modified);

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
69
}
70
71
/**
72
 * @param string $name
73
 * @param string $value
74
 * @param string $label
75
 * @param string $help
76
 */
77
function xoFormField($name, $value, $label, $help = '')
78
{
79
    $label = installerHtmlSpecialChars($label);
80
    $name  = installerHtmlSpecialChars($name);
81
    $value = installerHtmlSpecialChars($value);
82
    echo '<div class="form-group">';
83
    echo '<label class="xolabel" for="' . $name . '">' . $label . '</label>';
84
    if ($help) {
85
        echo '<div class="xoform-help alert alert-info">' . $help . '</div>';
86
    }
87
    echo '<input type="text" class="form-control" name="'.$name.'" id="'.$name.'" value="'.$value.'">';
88
    echo '</div>';
89
}
90
91
/**
92
 * @param        $name
93
 * @param        $value
94
 * @param        $label
95
 * @param string $help
96
 */
97
function xoPassField($name, $value, $label, $help = '')
98
{
99
    $label = installerHtmlSpecialChars($label);
100
    $name  = installerHtmlSpecialChars($name);
101
    $value = installerHtmlSpecialChars($value);
102
    echo '<div class="form-group">';
103
    echo '<label class="xolabel" for="' . $name . '">' . $label . '</label>';
104
    if ($help) {
105
        echo '<div class="xoform-help alert alert-info">' . $help . '</div>';
106
    }
107
    if ($name === 'adminpass') {
108
        echo '<input type="password" class="form-control" name="'.$name.'" id="'.$name.'" value="'.$value.'"  onkeyup="passwordStrength(this.value)">';
109
    } else {
110
        echo '<input type="password" class="form-control" name="'.$name.'" id="'.$name.'" value="'.$value.'">';
111
    }
112
    echo '</div>';
113
}
114
115
/**
116
 * @param        $name
117
 * @param        $value
118
 * @param        $label
119
 * @param array  $options
120
 * @param string $help
121
 * @param        $extra
122
 */
123
function xoFormSelect($name, $value, $label, $options, $help = '', $extra='')
124
{
125
    $label = installerHtmlSpecialChars($label);
126
    $name  = installerHtmlSpecialChars($name);
127
    $value = installerHtmlSpecialChars($value);
128
    echo '<div class="form-group">';
129
    echo '<label class="xolabel" for="' . $name . '">' . $label . '</label>';
130
    if ($help) {
131
        echo '<div class="xoform-help alert alert-info">' . $help . '</div>';
132
    }
133
    echo '<select class="form-control" name="'.$name.'" id="'.$name.'" value="'.$value.'" '.$extra.'>';
134
    foreach ($options as $optionValue => $optionReadable) {
135
        $selected = ($value === $optionValue) ? ' selected' : '';
136
        echo '<option value="'.$optionValue . '"' . $selected . '>' . $optionReadable . '</option>';
137
    }
138
    echo '</select>';
139
    echo '</div>';
140
}
141
142
/*
143
 * gets list of name of directories inside a directory
144
 */
145
/**
146
 * @param $dirname
147
 *
148
 * @return array
149
 */
150
function getDirList($dirname)
151
{
152
    $dirlist = [];
153
    if ($handle = opendir($dirname)) {
154
        while ($file = readdir($handle)) {
155
            if ($file[0] !== '.' && is_dir($dirname . $file)) {
156
                $dirlist[] = $file;
157
            }
158
        }
159
        closedir($handle);
160
        asort($dirlist);
161
        reset($dirlist);
162
    }
163
164
    return $dirlist;
165
}
166
167
/**
168
 * @param        $status
169
 * @param string $str
170
 *
171
 * @return string
172
 */
173
function xoDiag($status = -1, $str = '')
174
{
175
    if ($status == -1) {
176
        $GLOBALS['error'] = true;
177
    }
178
    $classes = [-1 => 'fa-solid fa-ban text-danger', 0 => 'fa-solid fa-square text-warning', 1 => 'fa-solid fa-check text-success'];
179
    $strings = [-1 => FAILED, 0 => WARNING, 1 => SUCCESS];
180
    if (empty($str)) {
181
        $str = $strings[$status];
182
    }
183
184
    return '<span class="' . $classes[$status] . '"></span>' . $str;
185
}
186
187
/**
188
 * @param      $name
189
 * @param bool $wanted
190
 * @param bool $severe
191
 *
192
 * @return string
193
 */
194
function xoDiagBoolSetting($name, $wanted = false, $severe = false)
195
{
196
    $setting = (bool) ini_get($name);
197
    if ($setting === (bool) $wanted) {
198
        return xoDiag(1, $setting ? 'ON' : 'OFF');
199
    } else {
200
        return xoDiag($severe ? -1 : 0, $setting ? 'ON' : 'OFF');
201
    }
202
}
203
204
/**
205
 * seems to only be used for license file?
206
 * @param string $path dir or file path
207
 *
208
 * @return string
209
 */
210
function xoDiagIfWritable($path)
211
{
212
    $path  = '../' . $path;
213
    $error = true;
214
    if (!is_dir($path)) {
215
        if (file_exists($path) && !is_writable($path)) {
216
            @chmod($path, 0664);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

216
            /** @scrutinizer ignore-unhandled */ @chmod($path, 0664);

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
217
            $error = !is_writable($path);
218
        }
219
    } else {
220
        if (!is_writable($path)) {
221
            @chmod($path, 0775);
222
            $error = !is_writable($path);
223
        }
224
    }
225
226
    return xoDiag($error ? -1 : 1, $error ? ' ' : ' ');
227
}
228
229
/**
230
 * @return string
231
 */
232
function xoPhpVersion()
233
{
234
    if (version_compare(phpversion(), '5.6.0', '>=')) {
235
        return xoDiag(1, phpversion());
236
    } else {
237
        return xoDiag(-1, phpversion());
238
    }
239
}
240
241
/**
242
 * @param $path
243
 * @param $valid
244
 *
245
 * @return string
246
 */
247
function genPathCheckHtml($path, $valid)
248
{
249
    if ($valid) {
250
        switch ($path) {
251
            case 'root':
252
                $msg = sprintf(XOOPS_FOUND, XOOPS_VERSION);
253
                break;
254
255
            case 'lib':
256
            case 'data':
257
            default:
258
                $msg = XOOPS_PATH_FOUND;
259
                break;
260
        }
261
262
        return '<span class="pathmessage"><span class="fa-solid fa-check text-success"></span> ' . $msg . '</span>';
263
    } else {
264
        switch ($path) {
265
            case 'root':
266
                $msg = ERR_NO_XOOPS_FOUND;
267
                break;
268
269
            case 'lib':
270
            case 'data':
271
            default:
272
                $msg = ERR_COULD_NOT_ACCESS;
273
                break;
274
        }
275
        $GLOBALS['error'] = true;
276
        return '<div class="alert alert-danger"><span class="fa-solid fa-ban text-danger"></span> ' . $msg . '</div>';
277
    }
278
}
279
280
/**
281
 * @param $link
282
 *
283
 * @return mixed
284
 */
285
function getDbCharsets($link)
286
{
287
    static $charsets = [];
288
    if ($charsets) {
289
        return $charsets;
290
    }
291
292
    if ($result = mysqli_query($link, 'SHOW CHARSET')) {
293
        while ($row = mysqli_fetch_assoc($result)) {
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type true; however, parameter $result of mysqli_fetch_assoc() does only seem to accept mysqli_result, maybe add an additional type check? ( Ignorable by Annotation )

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

293
        while ($row = mysqli_fetch_assoc(/** @scrutinizer ignore-type */ $result)) {
Loading history...
294
            $charsets[$row['Charset']] = $row['Description'];
295
        }
296
    }
297
298
    return $charsets;
299
}
300
301
/**
302
 * @param $link
303
 * @param $charset
304
 *
305
 * @return mixed
306
 */
307
function getDbCollations($link, $charset)
308
{
309
    static $collations = [];
310
    if (!empty($collations[$charset])) {
311
        return $collations[$charset];
312
    }
313
314
    if ($result = mysqli_query($link, "SHOW COLLATION WHERE CHARSET = '" . mysqli_real_escape_string($link, $charset) . "'")) {
315
        while ($row = mysqli_fetch_assoc($result)) {
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type true; however, parameter $result of mysqli_fetch_assoc() does only seem to accept mysqli_result, maybe add an additional type check? ( Ignorable by Annotation )

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

315
        while ($row = mysqli_fetch_assoc(/** @scrutinizer ignore-type */ $result)) {
Loading history...
316
            $collations[$charset][$row['Collation']] = $row['Default'] ? 1 : 0;
317
        }
318
    }
319
320
    return $collations[$charset];
321
}
322
323
/**
324
 * @param $link
325
 * @param $charset
326
 * @param $collation
327
 *
328
 * @return null|string
329
 */
330
function validateDbCharset($link, $charset, &$collation)
331
{
332
    $error = null;
333
334
    if (empty($charset)) {
335
        $collation = '';
336
    }
337
    if (empty($charset) && empty($collation)) {
338
        return $error;
339
    }
340
341
    $charsets = getDbCharsets($link);
342
    if (!isset($charsets[$charset])) {
343
        $error = sprintf(ERR_INVALID_DBCHARSET, $charset);
344
    } elseif (!empty($collation)) {
345
        $collations = getDbCollations($link, $charset);
346
        if (!isset($collations[$collation])) {
347
            $error = sprintf(ERR_INVALID_DBCOLLATION, $collation);
348
        }
349
    }
350
351
    return $error;
352
}
353
354
/**
355
 * @param $name
356
 * @param $value
357
 * @param $label
358
 * @param $help
359
 * @param $link
360
 * @param $charset
361
 *
362
 * @return string
363
 */
364
function xoFormFieldCollation($name, $value, $label, $help, $link, $charset)
365
{
366
    if (empty($charset) || !$collations = getDbCollations($link, $charset)) {
367
        return '';
368
    }
369
370
    $options           = [];
371
    foreach ($collations as $key => $isDefault) {
372
        if ($isDefault) {  // 'Yes' or ''
373
            $options = [$key => $key . ' (Default)'] + $options;
374
        } else {
375
            $options[$key] = $key;
376
        }
377
    }
378
379
    return xoFormSelect($name, $value, $label, $options, $help);
0 ignored issues
show
Bug introduced by
Are you sure the usage of xoFormSelect($name, $val...label, $options, $help) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
380
}
381
382
/**
383
 * @param $name
384
 * @param $value
385
 * @param $label
386
 * @param $help
387
 * @param $link
388
 * @param $charset
389
 *
390
 * @return string
391
 */
392
function xoFormBlockCollation($name, $value, $label, $help, $link, $charset)
393
{
394
    return xoFormFieldCollation($name, $value, $label, $help, $link, $charset);
395
}
396
397
/**
398
 * @param        $name
399
 * @param        $value
400
 * @param        $label
401
 * @param string $help
402
 * @param        $link
403
 *
404
 * @return string
405
 */
406
function xoFormFieldCharset($name, $value, $label, $help, $link)
407
{
408
    if (!$charsets = getDbCharsets($link)) {
409
        return '';
410
    }
411
    foreach ($charsets as $k => $v) {
412
        $charsets[$k] = $v . ' (' . $k . ')';
413
    }
414
    asort($charsets);
415
    $label = installerHtmlSpecialChars($label);
416
    $name  = installerHtmlSpecialChars($name);
417
    $value = installerHtmlSpecialChars($value);
418
    $extra = 'onchange="setFormFieldCollation(\'DB_COLLATION\', this.value)"';
419
    return xoFormSelect($name, $value, $label, $charsets, $help, $extra);
0 ignored issues
show
Bug introduced by
Are you sure the usage of xoFormSelect($name, $val...harsets, $help, $extra) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
420
}
421
422
/**
423
 * *#@+
424
 * Xoops Write Licence System Key
425
 * @param        $system_key
426
 * @param        $licensefile
427
 * @param string $license_file_dist
428
 * @return string
429
 */
430
function xoPutLicenseKey($system_key, $licensefile, $license_file_dist = 'license.dist.php')
431
{
432
    // If file exists, ensure it's writable first
433
    if (file_exists($licensefile)) {
434
        if (!is_writable($licensefile)) {
435
            // Try to make it writable
436
            if (!chmod($licensefile, 0666)) {
437
                return 'Error: Unable to make license file writable';
438
            }
439
        }
440
    } else {
441
        // Check if directory is writable
442
        $dir = dirname($licensefile);
443
        if (!is_writable($dir)) {
444
            return 'Error: Directory is not writable';
445
        }
446
    }
447
448
    // Open file with error checking
449
    $fver     = fopen($licensefile, 'w');
450
    if ($fver === false) {
451
        return 'Error: Unable to open license file for writing';
452
    }
453
454
    // Read distribution file with error checking
455
    if (!is_readable($license_file_dist)) {
456
        fclose($fver);
457
        return 'Error: Distribution license file is not readable';
458
    }
459
460
    $fver_buf = file($license_file_dist);
461
    if ($fver_buf === false) {
462
        fclose($fver);
463
        return 'Error: Unable to read distribution license file';
464
    }
465
466
467
    // Write the contents
468
    foreach ($fver_buf as $line => $value) {
469
        $ret = $value;
470
        if (strpos($value, 'XOOPS_LICENSE_KEY') > 0) {
471
            $ret = 'define(\'XOOPS_LICENSE_KEY\', \'' . $system_key . "');\n";
472
        }
473
        if (fwrite($fver, $ret) === false) {
474
            fclose($fver);
475
            return 'Error: Failed to write to license file';
476
        }
477
    }
478
    fclose($fver);
479
480
    // Set final permissions
481
    chmod($licensefile, 0444);
482
483
    return sprintf(WRITTEN_LICENSE, XOOPS_LICENSE_CODE, $system_key);
484
}
485
486
/**
487
 * *#@+
488
 * Xoops Build Licence System Key
489
 * @throws \Random\RandomException
490
 */
491
function xoBuildLicenceKey()
492
{
493
    $xoops_serdat = [];
494
    $checksums = [1 => 'md5', 2 => 'sha1'];
495
    $type      = random_int(1, 2);
496
    $func      = $checksums[$type];
497
498
    error_reporting(0);
499
500
    // Public Key
501
    if ($xoops_serdat['version'] = $func(XOOPS_VERSION)) {
502
        $xoops_serdat['version'] = substr($xoops_serdat['version'], 0, 6);
503
    }
504
    if ($xoops_serdat['licence'] = $func(XOOPS_LICENSE_CODE)) {
505
        $xoops_serdat['licence'] = substr($xoops_serdat['licence'], 0, 2);
506
    }
507
    if ($xoops_serdat['license_text'] = $func(XOOPS_LICENSE_TEXT)) {
508
        $xoops_serdat['license_text'] = substr($xoops_serdat['license_text'], 0, 2);
509
    }
510
511
    if ($xoops_serdat['domain_host'] = $func($_SERVER['HTTP_HOST'])) {
512
        $xoops_serdat['domain_host'] = substr($xoops_serdat['domain_host'], 0, 2);
513
    }
514
515
    // Private Key
516
    $xoops_serdat['file']     = $func(__FILE__);
517
    $xoops_serdat['basename'] = $func(basename(__FILE__));
518
    $xoops_serdat['path']     = $func(__DIR__);
519
520
    foreach ($_SERVER as $key => $data) {
521
        $xoops_serdat[$key] = substr($func(serialize($data)), 0, 4);
522
    }
523
524
    $xoops_key = '';
525
    foreach ($xoops_serdat as $key => $data) {
526
        $xoops_key .= $data;
527
    }
528
    while (strlen($xoops_key) > 40) {
529
        $lpos      = random_int(18, strlen($xoops_key));
530
        $xoops_key = substr($xoops_key, 0, $lpos) . substr($xoops_key, $lpos + 1, strlen($xoops_key) - ($lpos + 1));
531
    }
532
533
    return xoStripeKey($xoops_key);
534
}
535
536
/**
537
 * *#@+
538
 * Xoops Stripe Licence System Key
539
 * @param $xoops_key
540
 * @return mixed|string
541
 */
542
function xoStripeKey($xoops_key)
543
{
544
    $uu     = 0;
545
    $num    = 6;
0 ignored issues
show
Unused Code introduced by
The assignment to $num is dead and can be removed.
Loading history...
546
    $length = 30;
547
    $strip  = floor(strlen($xoops_key) / 6);
548
    $strlen = strlen($xoops_key);
549
    $ret = '';
550
    for ($i = 0; $i < $strlen; ++$i) {
551
        if ($i < $length) {
552
            ++$uu;
553
            if ($uu == $strip) {
554
                $ret .= substr($xoops_key, $i, 1) . '-';
555
                $uu = 0;
556
            } else {
557
                if (substr($xoops_key, $i, 1) != '-') {
558
                    $ret .= substr($xoops_key, $i, 1);
559
                } else {
560
                    $uu--;
561
                }
562
            }
563
        }
564
    }
565
    $ret = str_replace('--', '-', $ret);
566
    if (substr($ret, 0, 1) == '-') {
567
        $ret = substr($ret, 2, strlen($ret));
568
    }
569
    if (substr($ret, strlen($ret) - 1, 1) == '-') {
570
        $ret = substr($ret, 0, strlen($ret) - 1);
571
    }
572
573
    return $ret;
574
}
575
576
577
/**
578
 * @return string
579
 */
580
function writeLicenseKey()
581
{
582
    return xoPutLicenseKey(xoBuildLicenceKey(), XOOPS_VAR_PATH . '/data/license.php', __DIR__ . '/license.dist.php');
583
}
584