SanityTests   F
last analyzed

Complexity

Total Complexity 153

Size/Duplication

Total Lines 938
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 153
eloc 485
c 3
b 0
f 0
dl 0
loc 938
rs 2

29 Methods

Rating   Name   Duplication   Size   Complexity  
A runConstantsTest() 0 18 3
A testConfigConstants() 0 21 4
A __construct() 0 19 5
A getExecPath() 0 17 4
A testRADIUSProbes() 0 13 4
A getTestNames() 0 10 3
A runTest() 0 11 2
A storeTestResult() 0 5 1
A testCatBaseUrl() 0 9 4
A runTests() 0 15 5
A testPhp() 0 6 2
A testSecurity() 0 4 2
A testSsp() 0 12 4
A testLogdir() 0 6 2
B testPhpModules() 0 37 8
A testZip() 0 13 3
A testEapoltest() 0 12 3
C testGeoip() 0 60 13
A testOpenssl() 0 12 3
A testMailer() 0 28 4
B testMakensis() 0 29 9
A testDirectories() 0 30 4
A testUDPhosts() 0 2 1
C testDeviceCache() 0 36 13
F testDatabases() 0 49 14
B testSslscan() 0 25 9
A testLocales() 0 13 4
C testDefaults() 0 35 13
B testNSISmodules() 0 27 7

How to fix   Complexity   

Complex Class

Complex classes like SanityTests often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SanityTests, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/*
4
 * *****************************************************************************
5
 * Contributions to this work were made on behalf of the GÉANT project, a 
6
 * project that has received funding from the European Union’s Framework 
7
 * Programme 7 under Grant Agreements No. 238875 (GN3) and No. 605243 (GN3plus),
8
 * Horizon 2020 research and innovation programme under Grant Agreements No. 
9
 * 691567 (GN4-1) and No. 731122 (GN4-2).
10
 * On behalf of the aforementioned projects, GEANT Association is the sole owner
11
 * of the copyright in all material which was developed by a member of the GÉANT
12
 * project. GÉANT Vereniging (Association) is registered with the Chamber of 
13
 * Commerce in Amsterdam with registration number 40535155 and operates in the 
14
 * UK as a branch of GÉANT Vereniging.
15
 * 
16
 * Registered office: Hoekenrode 3, 1102BR Amsterdam, The Netherlands. 
17
 * UK branch address: City House, 126-130 Hills Road, Cambridge CB2 1PQ, UK
18
 *
19
 * License: see the web/copyright.inc.php file in the file structure or
20
 *          <base_url>/copyright.php after deploying the software
21
 */
22
23
/**
24
 * 
25
 * 
26
 * This is the definition of the CAT class implementing various configuration
27
 * tests. 
28
 * Each test is implemented as a private method which needs to be named "test_name_test".
29
 * The test returns the results by calling the testReturn method, this passing the return
30
 * code and the explanatory message. Multiple calls to testReturn are allowed.
31
 *
32
 * An individual test can be run by the "test" method which takes the test name as an argument
33
 * multiple tests should be run by the run_all_tests method which takes an array as an argument
34
 * see method descriptions for more information.
35
 * 
36
 * The results of the tests are passed within the $test_result array
37
 *
38
 * Some configuration of this class is required, see further down.
39
 * @author Stefan Winter <[email protected]>
40
 * @author Tomasz Wolniewicz <[email protected]>
41
 *
42
 * @license see LICENSE file in root directory
43
 *
44
 * @package Utilities
45
 */
46
47
namespace core;
48
49
use GeoIp2\Database\Reader;
50
use \Exception;
0 ignored issues
show
Bug introduced by
The type \Exception was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
51
52
class SanityTests extends CAT
53
{
54
    /* in this section set current CAT requirements */
55
56
    /**
57
     * the minimum required php version 
58
     * 
59
     * @var string
60
     */
61
    private $needversionPHP = '7.2.0';
62
63
    /**
64
     * the minimum required simpleSAMLphp version
65
     * 
66
     * @var array
67
     */
68
    private $needversionSSP = ['major' => 1, 'minor' => 15];
69
70
    /**
71
     * all required NSIS modules
72
     * 
73
     * @var array<string>
74
     */
75
    private $NSISModules = [
76
        "nsArray.nsh",
77
        "FileFunc.nsh",
78
        "LogicLib.nsh",
79
        "WordFunc.nsh",
80
        "FileFunc.nsh",
81
        "x64.nsh",
82
    ];
83
84
    /**
85
     * set $profile_option_ct to the number of rows returned by 
86
     * "SELECT * FROM profile_option_dict" 
87
     * to compare actual vs. expected database structure
88
     * 
89
     * @var integer
90
     */
91
    private $profileOptionCount;
92
93
    /**
94
     * set $view_admin_ct to the number of rows returned by "desc view_admin" 
95
     *
96
     * @var integer
97
     */
98
    private $viewAdminCount = 8;
99
100
    /* end of config */
101
102
    /**
103
     * array holding the output of all tests that were executed
104
     * 
105
     * @var array
106
     */
107
    public $out;
108
109
    /**
110
     * temporary storage for the name of the test as it is being run
111
     * 
112
     * @var string
113
     */
114
    public $name;
115
    
116
    /**
117
     * variable used to signal that no more tests are to be performed
118
     * 
119
     * @var boolean
120
     */
121
    public $fatalError = false;
122
123
    /**
124
     * initialise the tests. Includes counting the number of expected rows in the profile_option_dict table.
125
     */
126
    public function __construct()
127
    {
128
        parent::__construct();
129
        $this->test_result = [];
130
        $this->test_result['global'] = 0;
131
        // parse the schema file to find out the number of expected rows...
132
        $schema = file(dirname(dirname(__FILE__)) . "/schema/schema.sql");
133
        $this->profileOptionCount = 0;
134
        $passedTheWindmill = FALSE;
135
        foreach ($schema as $schemaLine) {
136
            if (preg_match("/^INSERT INTO \`profile_option_dict\` VALUES/", $schemaLine)) {
137
                $passedTheWindmill = TRUE;
138
                continue;
139
            }
140
            if ($passedTheWindmill) {
141
                if (substr($schemaLine, 0, 1) == '(') { // a relevant line in schema
142
                    $this->profileOptionCount = $this->profileOptionCount + 1;
143
                } else { // anything else, quit parsing
144
                    break;
145
                }
146
            }
147
        }
148
    }
149
150
    /**
151
     * The single test wrapper
152
     * @param string $test the test name
153
     * @return void
154
     */
155
    public function runTest($test)
156
    {
157
        $this->out[$test] = [];
158
        $this->name = $test;
159
        $m_name = 'test' . $test;
160
        $this->test_result[$test] = 0;
161
        if (!method_exists($this, $m_name)) {
162
            $this->storeTestResult(\core\common\Entity::L_ERROR, "Configuration error, no test configured for <strong>$test</strong>.");
163
            return;
164
        }
165
        $this->$m_name();
166
    }
167
168
    /**
169
     * The multiple tests wrapper
170
     * @param array $Tests the tests array is a simple string array, where each 
171
     *                     entry is a test name. The test names can also be 
172
     *                     given in the format "test=>subtest", which defines a
173
     *                     conditional execution of the "subtest" if the "test"
174
     *                     was run earlier and returned a success.
175
     * @return void
176
     */
177
    public function runTests($Tests)
178
    {
179
        foreach ($Tests as $testName) {
180
            $matchArray = [];
181
            if (preg_match('/(.+)=>(.+)/', $testName, $matchArray)) {
182
                $tst = $matchArray[1];
183
                $subtst = $matchArray[2];
184
                if ($this->test_result[$tst] < \core\common\Entity::L_ERROR) {
185
                    $this->runTest($subtst);
186
                }
187
            } else {
188
                $this->runTest($testName);
189
            }
190
            if ($this->fatalError) {
191
                return;
192
            }
193
        }
194
    }
195
196
    /**
197
     * enumerates the tests which are defined
198
     * 
199
     * @return array
200
     */
201
    public function getTestNames()
202
    {
203
        $T = get_class_methods($this);
204
        $out = [];
205
        foreach ($T as $t) {
206
            if (preg_match('/^test(.*)$/', $t, $m)) {
207
                $out[] = $m[1];
208
            }
209
        }
210
        return $out;
211
    }
212
213
    /**
214
     * This array is used to return the test results.
215
     * As the 'global' entry it returns the maximum return value
216
     * from all tests.
217
     * Individual tests results are teturned as separate entries
218
     * indexed by test names; each value is an array passing "level" and "message"
219
     * from each of the tests.
220
     * $test_result is set by the testReturn method
221
     *
222
     * @var array $test_result
223
     */
224
    public $test_result;
225
226
    /**
227
     * stores the result of a given test in standardised format
228
     * 
229
     * @param int    $level   severity level of the result
230
     * @param string $message verbal description of the result
231
     * @return void
232
     */
233
    private function storeTestResult($level, $message)
234
    {
235
        $this->out[$this->name][] = ['level' => $level, 'message' => $message];
236
        $this->test_result[$this->name] = max($this->test_result[$this->name], $level);
237
        $this->test_result['global'] = max($this->test_result['global'], $level);
238
    }
239
240
    /**
241
     * finds out if a path name is configured as an absolute path or only implicit (e.g. is in $PATH)
242
     * @param string $pathToCheck the path to check
243
     * @return array
244
     */
245
    private function getExecPath($pathToCheck)
246
    {
247
        $the_path = "";
248
        $exec_is = "UNDEFINED";
249
250
        foreach ([\config\Master::PATHS, \config\ConfAssistant::PATHS, \config\Diagnostics::PATHS] as $config) {
251
            if (!empty($config[$pathToCheck])) {
252
                $the_path = $config[$pathToCheck];
253
                if (substr($the_path, 0, 1) == "/") {
254
                    $exec_is = "EXPLICIT";
255
                } else {
256
                    $exec_is = "IMPLICIT";
257
                }
258
                return(['exec' => $the_path, 'exec_is' => $exec_is]);
259
            }
260
        }
261
        return(['exec' => $the_path, 'exec_is' => $exec_is]);
262
    }
263
264
    /**
265
     *  Test for php version
266
     * 
267
     * @return void
268
     */
269
    private function testPhp()
270
    {
271
        if (version_compare(phpversion(), $this->needversionPHP, '>=')) {
272
            $this->storeTestResult(\core\common\Entity::L_OK, "<strong>PHP</strong> is sufficiently recent. You are running " . phpversion() . ".");
273
        } else {
274
            $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>PHP</strong> is too old. We need at least $this->needversionPHP, but you only have " . phpversion() . ".");
275
        }
276
    }
277
    
278
    /**
279
     * Check if configuration constants from the template are set
280
     * in the corresponding config file
281
     * 
282
     * @param string $config file basename
283
     * @return array $failResults
284
     */
285
    private function runConstantsTest($config)
286
    {
287
        $templateConfig = file_get_contents(ROOT . "/config/$config-template.php");
288
        $newTemplateConfig = preg_replace("/class *$config/", "class $config" . "_template", $templateConfig);
289
        file_put_contents(ROOT . "/var/tmp/$config-template.php", $newTemplateConfig);
290
        include(ROOT . "/var/tmp/$config-template.php");
291
        unlink(ROOT . "/var/tmp/$config-template.php");
292
        $rft = new \ReflectionClass("\config\\$config" . "_template");
293
        $templateConstants = $rft->getConstants();
294
        $failResults = [];
295
        foreach ($templateConstants as $constant => $value) {
296
            try {
297
                $m = constant("\config\\$config::$constant");
0 ignored issues
show
Unused Code introduced by
The assignment to $m is dead and can be removed.
Loading history...
298
            } catch (Exception $e) {
299
                $failResults[] = "\config\\$config::$constant";
300
            }
301
        }
302
        return $failResults;
303
    }
304
305
    /**
306
     * Check if all required constants are set
307
     */
308
    private function testConfigConstants() {
309
        set_error_handler(function ($severity, $message, $file, $line) {
310
            throw new \ErrorException($message, $severity, $severity, $file, $line);
311
        });
312
        
313
        $failCount = 0;
314
        
315
        foreach (["Master", "ConfAssistant", "Diagnostics"] as $conf) {
316
            $failResults = $this->runConstantsTest($conf);
317
            $failCount = $failCount + count($failResults);
318
            if (count($failResults) > 0) {
319
            $this->storeTestResult(\core\common\Entity::L_ERROR, 
320
                    "<strong>The following constants are not set:</strong>" . implode(', ', $failResults));
321
            }
322
        }
323
        
324
        restore_error_handler();
325
        if ($failCount == 0) {
326
            $this->storeTestResult(\core\common\Entity::L_OK, "<strong>All config constants set</strong>");
327
        } else {
328
            $this->fatalError = true;
329
        }
330
    }
331
    /**
332
     * set for cat_base_url setting
333
     * 
334
     * @return void
335
     */
336
    private function testCatBaseUrl()
337
    {
338
        $rootUrl = substr(\config\Master::PATHS['cat_base_url'], -1) === '/' ? substr(\config\Master::PATHS['cat_base_url'], 0, -1) : \config\Master::PATHS['cat_base_url'];
339
        preg_match('/(^.*)\/admin\/112365365321.php/', $_SERVER['SCRIPT_NAME'], $m);
340
        if ($rootUrl === $m[1]) {
341
            $this->storeTestResult(\core\common\Entity::L_OK, "<strong>cat_base_url</strong> set correctly");
342
        } else {
343
            $rootFromScript = $m[1] === '' ? '/' : $m[1];
344
            $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>cat_base_url</strong> is set to <strong>" . \config\Master::PATHS['cat_base_url'] . "</strong> and should be <strong>$rootFromScript</strong>");
345
        }
346
    }
347
348
    /**
349
     * check whether the configured RADIUS hosts actually exist
350
     * 
351
     * @return void
352
     */
353
    private function testRADIUSProbes()
354
    {
355
        $probeReturns = [];
356
        foreach (\config\Diagnostics::RADIUSTESTS['UDP-hosts'] as $oneProbe) {
357
            $statusServer = new diag\RFC5997Tests($oneProbe['ip'], 1812, $oneProbe['secret']);
358
            if ($statusServer->statusServerCheck() !== diag\AbstractTest::RETVAL_OK) {
359
                $probeReturns[] = $oneProbe['display_name'];
360
            }
361
        }
362
        if (count($probeReturns) == 0) {
363
            $this->storeTestResult(common\Entity::L_OK, "All configured RADIUS/UDP probes are reachable.");
364
        } else {
365
            $this->storeTestResult(common\Entity::L_ERROR, "The following RADIUS probes are NOT reachable: " . implode(', ', $probeReturns));
366
        }
367
    }
368
369
    /**
370
     * test for simpleSAMLphp
371
     * 
372
     * @return void
373
     */
374
    private function testSsp()
375
    {
376
        if (!is_file(\config\Master::AUTHENTICATION['ssp-path-to-autoloader'])) {
377
            $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>simpleSAMLphp</strong> not found!");
378
        } else {
379
            include_once \config\Master::AUTHENTICATION['ssp-path-to-autoloader'];
380
            $SSPconfig = \SimpleSAML\Configuration::getInstance();
381
            $sspVersion = explode('.', $SSPconfig->getVersion());
382
            if ((int) $sspVersion[0] >= $this->needversionSSP['major'] && (int) $sspVersion[1] >= $this->needversionSSP['minor']) {
383
                $this->storeTestResult(\core\common\Entity::L_OK, "<strong>simpleSAMLphp</strong> is sufficiently recent. You are running " . implode('.', $sspVersion));
384
            } else {
385
                $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>simpleSAMLphp</strong> is too old. We need at least " . implode('.', $this->needversionSSP));
386
            }
387
        }
388
    }
389
390
    /**
391
     * test for security setting
392
     * 
393
     * @return void
394
     */
395
    private function testSecurity()
396
    {
397
        if (in_array("I do not care about security!", \config\Master::SUPERADMINS)) {
398
            $this->storeTestResult(\core\common\Entity::L_WARN, "You do not care about security. This page should be made accessible to the CAT admin only! See config/Master.php: 'SUPERADMINS'!");
399
        }
400
    }
401
402
    /**
403
     * test if zip is available
404
     * 
405
     * @return void
406
     */
407
    private function testZip()
408
    {
409
        $A = $this->getExecPath('zip');
410
        if ($A['exec'] != "") {
411
            $fullOutput = [];
412
            $t = exec($A['exec'] . ' --version', $fullOutput);
0 ignored issues
show
Unused Code introduced by
The assignment to $t is dead and can be removed.
Loading history...
413
            if ($A['exec_is'] == "EXPLICIT") {
414
                $this->storeTestResult(\core\common\Entity::L_OK, "<strong>".$fullOutput[1]."</strong> was found and is configured explicitly in your config.");
415
            } else {
416
                $this->storeTestResult(\core\common\Entity::L_WARN, "<strong>".$fullOutput[1]."</strong> was found, but is not configured with an absolute path in your config.");
417
            }
418
        } else {
419
            $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>zip</strong> was not found on your system!");
420
        }
421
    }
422
423
    /**
424
     * test if eapol_test is available and recent enough
425
     * 
426
     * @return void
427
     */
428
    private function testEapoltest()
429
    {
430
        exec(\config\Diagnostics::PATHS['eapol_test'], $out, $retval);
431
        if ($retval == 255) {
432
            $o = preg_grep('/-o<server cert/', $out);
433
            if (count($o) > 0) {
434
                $this->storeTestResult(\core\common\Entity::L_OK, "<strong>eapol_test</strong> script found.");
435
            } else {
436
                $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>eapol_test</strong> found, but is too old!");
437
            }
438
        } else {
439
            $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>eapol_test</strong> not found!");
440
        }
441
    }
442
443
    /**
444
     * test if logdir exists and is writable
445
     * 
446
     * @return void
447
     */
448
    private function testLogdir()
449
    {
450
        if (fopen(\config\Master::PATHS['logdir'] . "/debug.log", "a") == FALSE) {
451
            $this->storeTestResult(\core\common\Entity::L_WARN, "Log files in <strong>" . \config\Master::PATHS['logdir'] . "</strong> are not writable!");
452
        } else {
453
            $this->storeTestResult(\core\common\Entity::L_OK, "Log directory is writable.");
454
        }
455
    }
456
457
    /**
458
     * test for required PHP modules
459
     * 
460
     * @return void
461
     */
462
    private function testPhpModules()
463
    {
464
        if (function_exists('idn_to_ascii')) {
465
            $this->storeTestResult(\core\common\Entity::L_OK, "PHP can handle internationalisation.");
466
        } else {
467
            $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP can <strong>NOT</strong> handle internationalisation (idn_to_ascii() from php7.0-intl).");
468
        }
469
470
        if (function_exists('gettext')) {
471
            $this->storeTestResult(\core\common\Entity::L_OK, "PHP extension <strong>GNU Gettext</strong> is installed.");
472
        } else {
473
            $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GNU Gettext</strong> not found!");
474
        }
475
476
        if (function_exists('openssl_sign')) {
477
            $this->storeTestResult(\core\common\Entity::L_OK, "PHP extension <strong>OpenSSL</strong> is installed.");
478
        } else {
479
            $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>OpenSSL</strong> not found!");
480
        }
481
482
        if (class_exists('\\Gmagick')) {
483
            $this->storeTestResult(\core\common\Entity::L_OK, "PHP extension <strong>Gmagic</strong> is installed.");
484
        } elseif (class_exists('\\Imagick')) {
485
            $this->storeTestResult(\core\common\Entity::L_OK, "PHP extension <strong>Imagick</strong> is installed.");
486
        } else {
487
            $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>Gmagic</strong> nor <strong>Imagic</stromg> not found!");
488
        }
489
        if (function_exists('ImageCreate')) {
490
            $this->storeTestResult(\core\common\Entity::L_OK, "PHP extension <strong>GD</strong> is installed.");
491
        } else {
492
            $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GD</strong> not found!</a>.");
493
        }
494
495
        if (function_exists('mysqli_connect')) {
496
            $this->storeTestResult(\core\common\Entity::L_OK, "PHP extension <strong>MySQL</strong> is installed.");
497
        } else {
498
            $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>MySQL</strong> not found!");
499
        }
500
    }
501
502
    /**
503
     * test if GeoIP is installed correctly
504
     * 
505
     * @return void
506
     */
507
    private function testGeoip()
508
    {
509
        $host_4 = '145.0.2.50';
510
        $host_6 = '2001:610:188:444::50';
511
        switch (\config\Master::GEOIP['version']) {
512
            case 0:
513
                $this->storeTestResult(\core\common\Entity::L_REMARK, "As set in the config, no geolocation service will be used");
514
                break;
515
            case 1:
516
                if (!function_exists('geoip_record_by_name')) {
517
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GeoIP</strong> (legacy) not found! Get it from your distribution or <a href='http://pecl.php.net/package/geoip'>here</a> or better install GeoIP2 from <a href='https://github.com/maxmind/GeoIP2-php'>here</a>.");
518
                    return;
519
                }
520
                $record = geoip_record_by_name($host_4);
521
                if ($record === FALSE) {
522
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GeoIP</strong> (legacy) found but not working properly, perhaps you need to download the databases. See utils/GeoIP-update.sh in the CAT distribution and use it tu update the GeoIP database regularly.");
523
                    return;
524
                }
525
                if ($record['city'] != 'Utrecht') {
526
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GeoIP</strong> (legacy) found but not working properly, perhaps you need to download the databases. See utils/GeoIP-update.sh in the CAT distribution and use it tu update the GeoIP database regularly.");
527
                    return;
528
                }
529
                $this->storeTestResult(\core\common\Entity::L_REMARK, "PHP extension <strong>GeoIP</strong> (legacy) is installed and working. See utils/GeoIP-update.sh in the CAT distribution and use it tu update the GeoIP database regularly. We strongly advise to replace the legacy GeoIP with GeoIP2 from <a href='https://github.com/maxmind/GeoIP2-php'>here</a>.");
530
                break;
531
            case 2:
532
                if (!is_file(\config\Master::GEOIP['geoip2-path-to-autoloader'])) {
533
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GeoIP2</strong> not found! Get it from <a href='https://github.com/maxmind/GeoIP2-php'>here</a>.");
534
                    return;
535
                }
536
                if (!is_file(\config\Master::GEOIP['geoip2-path-to-db'])) {
537
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>GeoIP2 database</strong> not found! See utils/GeoIP-update.sh in the CAT distribution and use it tu update the GeoIP database regularly.");
538
                    return;
539
                }
540
                include_once \config\Master::GEOIP['geoip2-path-to-autoloader'];
541
                $reader = new Reader(\config\Master::GEOIP['geoip2-path-to-db']);
542
                try {
543
                    $record = $reader->city($host_4);
544
                } catch (Exception $e) {
545
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GeoIP2</strong> found but not working properly, perhaps you need to download the databases. See utils/GeoIP-update.sh in the CAT distribution and use it to update the GeoIP database regularly.");
546
                    return;
547
                }
548
                if ($record->city->name != 'Utrecht') {
549
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GeoIP2</strong> found but not working properly, perhaps you need to download the databases. See utils/GeoIP-update.sh in the CAT distribution and use it to update the GeoIP database regularly.");
550
                    return;
551
                }
552
                try {
553
                    $record = $reader->city($host_6);
554
                } catch (Exception $e) {
555
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GeoIP2</strong> found but not working properly with IPv6, perhaps you need to download the databases. See utils/GeoIP-update.sh in the CAT distribution and use it tu update the GeoIP database regularly.");
556
                    return;
557
                }
558
                if ($record->city->name != 'Utrecht') {
559
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GeoIP2</strong> found but not working properly with IPv6, perhaps you need to download the databases. See utils/GeoIP-update.sh in the CAT distribution and use it tu update the GeoIP database regularly.");
560
                    return;
561
                }
562
                $this->storeTestResult(\core\common\Entity::L_OK, "PHP extension <strong>GeoIP2</strong> is installed and working. See utils/GeoIP-update.sh in the CAT distribution and use it tu update the GeoIP database regularly.");
563
                break;
564
            default:
565
                $this->storeTestResult(\core\common\Entity::L_ERROR, 'Check \config\Master::GEOIP[\'version\'], it must be set to either 1 or 2');
566
                break;
567
        }
568
    }
569
570
    /**
571
     * test if openssl is available
572
     * 
573
     * @return void
574
     */
575
    private function testOpenssl()
576
    {
577
        $A = $this->getExecPath('openssl');
578
        if ($A['exec'] != "") {
579
            $t = exec($A['exec'] . ' version');
580
            if ($A['exec_is'] == "EXPLICIT") {
581
                $this->storeTestResult(\core\common\Entity::L_OK, "<strong>$t</strong> was found and is configured explicitly in your config.");
582
            } else {
583
                $this->storeTestResult(\core\common\Entity::L_WARN, "<strong>$t</strong> was found, but is not configured with an absolute path in your config.");
584
            }
585
        } else {
586
            $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>openssl</strong> was not found on your system!");
587
        }
588
    }
589
590
    /**
591
     * test if sslscan is available
592
     * 
593
     * @return void
594
     */
595
    private function testSslscan()
596
    {
597
        $A = $this->getExecPath('sslscan'); 
598
        if ($A['exec'] != "" && $A['exec_is'] == "EXPLICIT" && !file_exists($A['exec'])) { 
599
            $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>sslscan</strong> is configured explicitly and was not found on your system!");    
600
        } else {
601
            exec($A['exec'] . ' --version --xml=-', $output, $res);
602
            if ($res == 0) {
603
                $xml = simplexml_load_string(implode($output));
604
                $resarray = json_decode(json_encode((array)$xml),true);
605
                $t = 'sslscan';
606
                if (isset($resarray['@attributes']) and isset($resarray['@attributes']['version'])) {
607
                    $t = 'sslscan ' . $resarray['@attributes']['version'];
608
                }
609
            } else {
610
                $t = '';
611
            }
612
            if ($t != '') {
613
                if ($A['exec_is'] == "EXPLICIT") {
614
                    $this->storeTestResult(\core\common\Entity::L_OK, "<strong>$t</strong> was found and is configured explicitly in your config.");
615
                } else {
616
                    $this->storeTestResult(\core\common\Entity::L_WARN, "<strong>$t</strong> was found, but is not configured with an absolute path in your config.");
617
                }
618
            } else {
619
                $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>sslscan</strong> was not found on your system!");
620
            }
621
        }
622
    }
623
    /**
624
     * test if makensis is available
625
     * 
626
     * @return void
627
     */
628
    private function testMakensis()
629
    {
630
        if (!is_numeric(\config\ConfAssistant::NSIS_VERSION)) {
631
            $this->storeTestResult(\core\common\Entity::L_ERROR, "NSIS_VERSION needs to be numeric!");
632
            return;
633
        }
634
        if (\config\ConfAssistant::NSIS_VERSION < 2) {
635
            $this->storeTestResult(\core\common\Entity::L_ERROR, "NSIS_VERSION needs to be at least 2!");
636
            return;
637
        }
638
        $A = $this->getExecPath('makensis');
639
        if ($A['exec'] != "") {
640
            $t = exec($A['exec'] . ' -VERSION');
641
            if ($A['exec_is'] == "EXPLICIT") {
642
                $this->storeTestResult(\core\common\Entity::L_OK, "<strong>makensis $t</strong> was found and is configured explicitly in your config.");
643
            } else {
644
                $this->storeTestResult(\core\common\Entity::L_WARN, "<strong>makensis $t</strong> was found, but is not configured with an absolute path in your config.");
645
            }
646
            $outputArray = [];
647
            exec($A['exec'] . ' -HELP', $outputArray);
648
            $t1 = count(preg_grep('/INPUTCHARSET/', $outputArray));
649
            if ($t1 == 1 && \config\ConfAssistant::NSIS_VERSION == 2) {
650
                $this->storeTestResult(\core\common\Entity::L_ERROR, "Declared NSIS_VERSION does not seem to match the file pointed to by PATHS['makensis']!");
651
            }
652
            if ($t1 == 0 && \config\ConfAssistant::NSIS_VERSION >= 3) {
653
                $this->storeTestResult(\core\common\Entity::L_ERROR, "Declared NSIS_VERSION does not seem to match the file pointed to by PATHS['makensis']!");
654
            }
655
        } else {
656
            $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>makensis</strong> was not found on your system!");
657
        }
658
    }
659
660
    /**
661
     * test if all required NSIS modules are available
662
     * 
663
     * @return void
664
     */
665
    private function testNSISmodules()
666
    {
667
        $tmp_dir = \core\common\Entity::createTemporaryDirectory('installer', 0)['dir'];
668
        if (!chdir($tmp_dir)) {
669
            $this->loggerInstance->debug(2, "Cannot chdir to $tmp_dir\n");
670
            $this->storeTestResult(\core\common\Entity::L_ERROR, "NSIS modules test - problem with temporary directory permissions, cannot continue");
671
            return;
672
        }
673
        $exe = 'tt.exe';
674
        $NSIS_Module_status = [];
675
        foreach ($this->NSISModules as $module) {
676
            unset($out);
677
            exec(\config\ConfAssistant::PATHS['makensis'] . " -V1 '-X!include $module' '-XOutFile $exe' '-XSection X' '-XSectionEnd'", $out, $retval);
678
            if ($retval > 0) {
679
                $NSIS_Module_status[$module] = 0;
680
            } else {
681
                $NSIS_Module_status[$module] = 1;
682
            }
683
        }
684
        if (is_file($exe)) {
685
            unlink($exe);
686
        }
687
        foreach ($NSIS_Module_status as $module => $status) {
688
            if ($status == 1) {
689
                $this->storeTestResult(\core\common\Entity::L_OK, "NSIS module <strong>$module</strong> was found.");
690
            } else {
691
                $this->storeTestResult(\core\common\Entity::L_ERROR, "NSIS module <strong>$module</strong> was not found or is not working correctly.");
692
            }
693
        }
694
    }
695
696
    /**
697
     * test access to downloads directories
698
     * 
699
     * @return void
700
     */
701
    private function testDirectories()
702
    {
703
        $Dir1 = \core\common\Entity::createTemporaryDirectory('installer', 0);
704
        $dir1 = $Dir1['dir'];
705
        $base1 = $Dir1['base'];
706
        if ($dir1) {
707
            $this->storeTestResult(\core\common\Entity::L_OK, "Installer cache directory is writable.");
708
            \core\common\Entity::rrmdir($dir1);
709
        } else {
710
            $this->storeTestResult(\core\common\Entity::L_ERROR, "Installer cache directory $base1 does not exist or is not writable!");
711
            $this->fatalError = true;
712
        }
713
        $Dir2 = \core\common\Entity::createTemporaryDirectory('test', 0);
714
        $dir2 = $Dir2['dir'];
715
        $base2 = $Dir2['base'];
716
        if ($dir2) {
717
            $this->storeTestResult(\core\common\Entity::L_OK, "Test directory is writable.");
718
            \core\common\Entity::rrmdir($dir2);
719
        } else {
720
            $this->storeTestResult(\core\common\Entity::L_ERROR, "Test directory $base2 does not exist or is not writable!");
721
            $this->fatalError = true;
722
        }
723
        $Dir3 = \core\common\Entity::createTemporaryDirectory('logo', 0);
724
        $dir3 = $Dir3['dir'];
725
        $base3 = $Dir3['base'];
726
        if ($dir3) {
727
            $this->storeTestResult(\core\common\Entity::L_OK, "Logos cache directory is writable.");
728
            \core\common\Entity::rrmdir($dir3);
729
        } else {
730
            $this->storeTestResult(\core\common\Entity::L_ERROR, "Logos cache directory $base3 does not exist or is not writable!");
731
        }
732
    }
733
734
    /**
735
     * test if all required locales are enabled
736
     * 
737
     * @return void
738
     */
739
    private function testLocales()
740
    {
741
        $locales = shell_exec("locale -a");
742
        $allthere = "";
743
        foreach (\config\Master::LANGUAGES as $onelanguage) {
744
            if (preg_match("/" . $onelanguage['locale'] . "/", $locales) == 0) {
745
                $allthere .= $onelanguage['locale'] . " ";
746
            }
747
        }
748
        if ($allthere == "") {
749
            $this->storeTestResult(\core\common\Entity::L_OK, "All of your configured locales are available on your system.");
750
        } else {
751
            $this->storeTestResult(\core\common\Entity::L_WARN, "Some of your configured locales (<strong>$allthere</strong>) are not installed and will not be displayed correctly!");
752
        }
753
    }
754
755
    const DEFAULTS = [
756
        ["SETTING" => \config\Master::APPEARANCE['from-mail'],
757
            "DEFVALUE" => "[email protected]",
758
            "COMPLAINTSTRING" => "APPEARANCE/from-mail ",
759
            "REQUIRED" => FALSE,],
760
        ["SETTING" => \config\Master::APPEARANCE['support-contact']['url'],
761
            "DEFVALUE" => "[email protected]?body=Only%20English%20language%20please!",
762
            "COMPLAINTSTRING" => "APPEARANCE/support-contact/url ",
763
            "REQUIRED" => FALSE,],
764
        ["SETTING" => \config\Master::APPEARANCE['support-contact']['display'],
765
            "DEFVALUE" => "[email protected]",
766
            "COMPLAINTSTRING" => "APPEARANCE/support-contact/display ",
767
            "REQUIRED" => FALSE,],
768
        ["SETTING" => \config\Master::APPEARANCE['support-contact']['developer-mail'],
769
            "DEFVALUE" => "[email protected]",
770
            "COMPLAINTSTRING" => "APPEARANCE/support-contact/mail ",
771
            "REQUIRED" => FALSE,],
772
        ["SETTING" => \config\Master::APPEARANCE['abuse-mail'],
773
            "DEFVALUE" => "[email protected]",
774
            "COMPLAINTSTRING" => "APPEARANCE/abuse-mail ",
775
            "REQUIRED" => FALSE,],
776
        ["SETTING" => \config\Master::APPEARANCE['MOTD'],
777
            "DEFVALUE" => "Release Candidate. All bugs to be shot on sight!",
778
            "COMPLAINTSTRING" => "APPEARANCE/MOTD ",
779
            "REQUIRED" => FALSE,],
780
        ["SETTING" => \config\Master::APPEARANCE['webcert_CRLDP'],
781
            "DEFVALUE" => ['list', 'of', 'CRL', 'pointers'],
782
            "COMPLAINTSTRING" => "APPEARANCE/webcert_CRLDP ",
783
            "REQUIRED" => TRUE,],
784
        ["SETTING" => \config\Master::APPEARANCE['webcert_OCSP'],
785
            "DEFVALUE" => ['list', 'of', 'OCSP', 'pointers'],
786
            "COMPLAINTSTRING" => "APPEARANCE/webcert_OCSP ",
787
            "REQUIRED" => TRUE,],
788
        ["SETTING" => \config\Master::DB['INST']['host'],
789
            "DEFVALUE" => "db.host.example",
790
            "COMPLAINTSTRING" => "DB/INST ",
791
            "REQUIRED" => TRUE,],
792
        ["SETTING" => \config\Master::DB['INST']['host'],
793
            "DEFVALUE" => "db.host.example",
794
            "COMPLAINTSTRING" => "DB/USER ",
795
            "REQUIRED" => TRUE,],
796
        ["SETTING" => \config\Master::DB['EXTERNAL']['host'],
797
            "DEFVALUE" => "customerdb.otherhost.example",
798
            "COMPLAINTSTRING" => "DB/EXTERNAL ",
799
            "REQUIRED" => FALSE,],
800
    ];
801
802
    /**
803
     * test if defaults in the config have been replaced with some real values
804
     * 
805
     * @return void
806
     */
807
    private function testDefaults()
808
    {
809
        $defaultvalues = "";
810
        $missingvalues = "";
811
        // all the checks for equality with a shipped default value
812
        foreach (SanityTests::DEFAULTS as $oneCheckItem) {
813
            if ($oneCheckItem['REQUIRED'] && !$oneCheckItem['SETTING']) {
814
                $missingvalues .= $oneCheckItem["COMPLAINTSTRING"];
815
            } elseif ($oneCheckItem['SETTING'] == $oneCheckItem["DEFVALUE"]) {
816
                $defaultvalues .= $oneCheckItem["COMPLAINTSTRING"];
817
            }
818
        }
819
        // additional checks for defaults, which are not simple equality checks
820
        if (isset(\config\Diagnostics::RADIUSTESTS['UDP-hosts'][0]) && \config\Diagnostics::RADIUSTESTS['UDP-hosts'][0]['ip'] == "192.0.2.1") {
821
            $defaultvalues .= "RADIUSTESTS/UDP-hosts ";
822
        }
823
824
825
        if (isset(\config\Diagnostics::RADIUSTESTS['TLS-clientcerts'])) {
826
            foreach (\config\Diagnostics::RADIUSTESTS['TLS-clientcerts'] as $cadata) {
827
                foreach ($cadata['certificates'] as $cert_files) {
828
                    if (file_get_contents(ROOT . "/config/cli-certs/" . $cert_files['public']) === FALSE) {
829
                        $defaultvalues .= "CERTIFICATE/" . $cert_files['public'] . " ";
830
                    }
831
                    if (file_get_contents(ROOT . "/config/cli-certs/" . $cert_files['private']) === FALSE) {
832
                        $defaultvalues .= "CERTIFICATE/" . $cert_files['private'] . " ";
833
                    }
834
                }
835
            }
836
        }
837
838
        if ($defaultvalues != "") {
839
            $this->storeTestResult(\core\common\Entity::L_WARN, "Your configuration in config/config.php contains unchanged default values or links to inexistent files: <strong>$defaultvalues</strong>!");
840
        } else {
841
            $this->storeTestResult(\core\common\Entity::L_OK, "Your configuration does not contain any unchanged defaults, which is a good sign.");
842
        }
843
    }
844
845
    /**
846
     * test access to databases
847
     * 
848
     * @return void
849
     */
850
    private function testDatabases()
851
    {
852
        $databaseName1 = 'INST';
853
        try {
854
            $db1 = DBConnection::handle($databaseName1);
855
            $res1 = $db1->exec('SELECT * FROM profile_option_dict');
856
            if ($res1->num_rows == $this->profileOptionCount) {
857
                $this->storeTestResult(\core\common\Entity::L_OK, "The $databaseName1 database appears to be OK.");
858
            } else {
859
                $this->storeTestResult(\core\common\Entity::L_ERROR, "The $databaseName1 database is reachable but probably not updated to this version of CAT.");
860
            }
861
        } catch (Exception $e) {
862
            $this->storeTestResult(\core\common\Entity::L_ERROR, "Connection to the  $databaseName1 database failed");
863
        }
864
865
        $databaseName2 = 'USER';
866
        try {
867
            $db2 = DBConnection::handle($databaseName2);
868
            if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
869
                $res2 = $db2->exec('desc view_admin');
870
                if ($res2->num_rows == $this->viewAdminCount) {
871
                    $this->storeTestResult(\core\common\Entity::L_OK, "The $databaseName2 database appears to be OK.");
872
                } else {
873
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "The $databaseName2 is reachable but there is something wrong with the schema");
874
                }
875
            } else {
876
                $this->storeTestResult(\core\common\Entity::L_OK, "The $databaseName2 database appears to be OK.");
877
            }
878
        } catch (Exception $e) {
879
            $this->storeTestResult(\core\common\Entity::L_ERROR, "Connection to the  $databaseName2 database failed");
880
        }
881
882
        $databaseName3 = 'EXTERNAL';
883
        if (!empty(\config\Master::DB[$databaseName3])) {
884
            try {
885
                $db3 = DBConnection::handle($databaseName3);
886
                if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
887
                    $res3 = $db3->exec('desc view_admin');
888
                    if ($res3->num_rows == $this->viewAdminCount) {
889
                        $this->storeTestResult(\core\common\Entity::L_OK, "The $databaseName3 database appears to be OK.");
890
                    } else {
891
                        $this->storeTestResult(\core\common\Entity::L_ERROR, "The $databaseName3 is reachable but there is something wrong with the schema");
892
                    }
893
                } else {
894
                    $this->storeTestResult(\core\common\Entity::L_OK, "The $databaseName3 database appears to be OK.");
895
                }
896
            } catch (Exception $e) {
897
898
                $this->storeTestResult(\core\common\Entity::L_ERROR, "Connection to the  $databaseName3 database failed");
899
            }
900
        }
901
    }
902
903
    /**
904
     * test devices.php for the no_cache option
905
     * 
906
     * @return void
907
     */
908
    private function testDeviceCache()
909
    {
910
        if ((!empty(\devices\Devices::$Options['no_cache'])) && \devices\Devices::$Options['no_cache']) {
911
            $global_no_cache = 1;
912
        } else {
913
            $global_no_cache = 0;
914
        }
915
916
        if ($global_no_cache == 1) {
917
            $this->storeTestResult(\core\common\Entity::L_WARN, "Devices no_cache global option is set, this is not a good idea in a production setting\n");
918
        }
919
        $Devs = \devices\Devices::listDevices();
920
        $no_cache_dev = '';
921
        $no_cache_dev_count = 0;
922
        if ($global_no_cache) {
923
            foreach ($Devs as $dev => $D) {
924
                if (empty($D['options']['no_cache']) || $D['options']['no_cache'] != 0) {
925
                    $no_cache_dev .= $dev . " ";
926
                    $no_cache_dev_count++;
927
                }
928
            }
929
        } else {
930
            foreach ($Devs as $dev => $D) {
931
                if (!empty($D['options']['no_cache']) && $D['options']['no_cache'] != 0) {
932
                    $no_cache_dev .= $dev . " ";
933
                    $no_cache_dev_count++;
934
                }
935
            }
936
        }
937
938
939
        if ($no_cache_dev_count > 1) {
940
            $this->storeTestResult(\core\common\Entity::L_WARN, "The following devices will not be cached: $no_cache_dev");
941
        }
942
        if ($no_cache_dev_count == 1) {
943
            $this->storeTestResult(\core\common\Entity::L_WARN, "The following device will not be cached: $no_cache_dev");
944
        }
945
    }
946
947
    /**
948
     * test if mailer works
949
     * 
950
     * @return void
951
     */
952
    private function testMailer()
953
    {
954
        if (empty(\config\Master::APPEARANCE['abuse-mail']) || \config\Master::APPEARANCE['abuse-mail'] == "[email protected]") {
955
            $this->storeTestResult(\core\common\Entity::L_ERROR, "Your abuse-mail has not been set, cannot continue with mailer tests.");
956
            return;
957
        }
958
        $mail = new \PHPMailer\PHPMailer\PHPMailer();
959
        $mail->isSMTP();
960
        $mail->Port = 587;
961
        $mail->SMTPAuth = true;
962
        $mail->SMTPSecure = 'tls';
963
        $mail->Host = \config\Master::MAILSETTINGS['host'];
964
        $mail->Username = \config\Master::MAILSETTINGS['user'];
965
        $mail->Password = \config\Master::MAILSETTINGS['pass'];
966
        $mail->SMTPOptions = \config\Master::MAILSETTINGS['options'];
967
        $mail->WordWrap = 72;
968
        $mail->isHTML(FALSE);
969
        $mail->CharSet = 'UTF-8';
970
        $mail->From = \config\Master::APPEARANCE['from-mail'];
971
        $mail->FromName = \config\Master::APPEARANCE['productname'] . " Invitation System";
972
        $mail->addAddress(\config\Master::APPEARANCE['abuse-mail']);
973
        $mail->Subject = "testing CAT configuration mail";
974
        $mail->Body = "Testing CAT mailing\n";
975
        $sent = $mail->send();
976
        if ($sent) {
977
            $this->storeTestResult(\core\common\Entity::L_OK, "mailer settings appear to be working, check " . \config\Master::APPEARANCE['abuse-mail'] . " mailbox if the message was receiced.");
978
        } else {
979
            $this->storeTestResult(\core\common\Entity::L_ERROR, "mailer settings failed, check the Config::MAILSETTINGS");
980
        }
981
    }
982
983
    /**
984
     * TODO test if RADIUS connections work
985
     * 
986
     * @return void
987
     */
988
    private function testUDPhosts()
989
    {
990
//        if(empty)
991
    }
992
}
993