Passed
Push — master ( 92b079...56770a )
by Tomasz
15:05
created

Federation::getIdentityProvidersCertStatus()   B

Complexity

Conditions 8
Paths 20

Size

Total Lines 40
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 30
c 0
b 0
f 0
dl 0
loc 40
rs 8.1954
cc 8
nc 20
nop 0
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
 * This file contains the Federation class.
25
 * 
26
 * @author Stefan Winter <[email protected]>
27
 * @author Tomasz Wolniewicz <[email protected]>
28
 * 
29
 * @package Developer
30
 * 
31
 */
32
33
namespace core;
34
35
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...
36
37
/**
38
 * This class represents an consortium federation.
39
 * 
40
 * It is semantically a country(!). Do not confuse this with a TLD; a federation
41
 * may span more than one TLD, and a TLD may be distributed across multiple federations.
42
 *
43
 * Example: a federation "fr" => "France" may also contain other TLDs which
44
 *              belong to France in spite of their different TLD
45
 * Example 2: Domains ending in .edu are present in multiple different
46
 *              federations
47
 *
48
 * @author Stefan Winter <[email protected]>
49
 * @author Tomasz Wolniewicz <[email protected]>
50
 *
51
 * @license see LICENSE file in root directory
52
 *
53
 * @package Developer
54
 */
55
class Federation extends EntityWithDBProperties
56
{
57
58
    /**
59
     * the handle to the FRONTEND database (only needed for some stats access)
60
     * 
61
     * @var DBConnection
62
     */
63
    private $frontendHandle;
64
65
    /**
66
     * the top-level domain of the Federation
67
     * 
68
     * @var string
69
     */
70
    public $tld;
71
72
    private $idpArray = [];
73
    /**
74
     * retrieve the statistics from the database in an internal array representation
75
     * 
76
     * @param string $detail
77
     * @return array
78
     */
79
    private function downloadStatsCore($detail = '')
80
    {
81
        if ($detail !== 'ORGANISATIONS' && $detail !== 'PROFILES' && $detail !== 'FEDERATION') {
82
            $detail = 'NONE';
83
        }
84
        
85
        $grossAdmin = 0;
86
        $grossUser = 0;
87
        $grossSilverbullet = 0;
88
        $dataArray = [];
89
        $cohesionQuery = [
90
            'ORGANISATIONS' => "SELECT profile.inst_id AS inst_id, downloads.device_id AS dev_id, sum(downloads.downloads_user) AS dl_user, sum(downloads.downloads_silverbullet) as dl_sb, sum(downloads.downloads_admin) AS dl_admin FROM downloads JOIN profile ON downloads.profile_id=profile.profile_id JOIN institution ON profile.inst_id=institution.inst_id WHERE institution.country = ? GROUP BY profile.inst_id, downloads.device_id",
91
            'PROFILES' => "SELECT profile.inst_id AS inst_id, profile.profile_id AS profile_id, downloads.device_id AS dev_id, sum(downloads.downloads_user) AS dl_user, sum(downloads.downloads_silverbullet) as dl_sb, sum(downloads.downloads_admin) AS dl_admin FROM downloads JOIN profile ON downloads.profile_id=profile.profile_id JOIN institution ON profile.inst_id=institution.inst_id WHERE institution.country = ? GROUP BY profile.inst_id, profile.profile_id, downloads.device_id",
92
            'FEDERATION' => "SELECT downloads.device_id AS dev_id, sum(downloads.downloads_user) AS dl_user, sum(downloads.downloads_silverbullet) AS dl_sb, sum(downloads.downloads_admin) AS dl_admin FROM profile JOIN institution ON profile .inst_id = institution.inst_id JOIN downloads ON profile.profile_id = downloads.profile_id WHERE institution.country = ? AND profile.profile_id = downloads.profile_id GROUP BY device_id",
93
            'NONE' => "SELECT downloads.device_id as dev_id, sum(downloads.downloads_user) as dl_user, sum(downloads.downloads_silverbullet) AS dl_sb, sum(downloads.downloads_admin) as dl_admin FROM profile JOIN institution ON profile .inst_id = institution.inst_id JOIN downloads ON profile.profile_id = downloads.profile_id WHERE profile.inst_id = institution.inst_id AND institution.country = ? AND profile.profile_id = downloads.profile_id group by device_id"
94
        ];
95
        // first, find out which profiles belong to this federation
96
        $downloadsList = $this->databaseHandle->exec($cohesionQuery[$detail], "s", $this->tld);
97
        $deviceArray = \devices\Devices::listDevices();
98
        while ($queryResult = mysqli_fetch_object(/** @scrutinizer ignore-type */ $downloadsList)) {
99
            if ($detail === 'NONE' || $detail === 'FEDERATION') {
100
                $grossAdmin = $grossAdmin + $queryResult->dl_admin;
101
                $grossSilverbullet = $grossSilverbullet + $queryResult->dl_sb;
102
                $grossUser = $grossUser + $queryResult->dl_user;
103
                if ($detail === 'NONE') {
104
                    continue;
105
                }
106
            }    
107
            if (isset($deviceArray[$queryResult->dev_id])) {
108
                $displayName = $deviceArray[$queryResult->dev_id]['display'];
109
            } else { // this device has stats, but doesn't exist in current config. We don't even know its display name, so display its raw representation
110
                $displayName = sprintf(_("(discontinued) %s"), $queryResult->dev_id);
111
            }
112
            if ($detail === 'FEDERATION') {
113
                $dataArray[$displayName] = ["ADMIN" => $queryResult->dl_admin, "SILVERBULLET" => $queryResult->dl_sb, "USER" => $queryResult->dl_user];
114
            } else {
115
                $inst_id = $queryResult->inst_id;            
116
                if (!isset($dataArray[$inst_id])) {
117
                    $dataArray[$inst_id] = [];
118
                }            
119
                if ($detail === 'ORGANISATIONS') {       
120
                    $dataArray[$inst_id][$displayName] = ["ADMIN" => $queryResult->dl_admin, "SILVERBULLET" => $queryResult->dl_sb, "USER" => $queryResult->dl_user];
121
                }
122
                if ($detail === 'PROFILES') {
123
                    $profile_id = $queryResult->profile_id;
124
                    if (!isset($dataArray[$inst_id][$profile_id])) {
125
                        $dataArray[$inst_id][$profile_id] = [];
126
                    }
127
                    $dataArray[$inst_id][$profile_id][$displayName] = ["ADMIN" => $queryResult->dl_admin, "SILVERBULLET" => $queryResult->dl_sb, "USER" => $queryResult->dl_user];
128
                }
129
            }
130
        }
131
        if ($detail === 'NONE' || $detail === 'FEDERATION') {
132
            $dataArray["TOTAL"] = ["ADMIN" => $grossAdmin, "SILVERBULLET" => $grossSilverbullet, "USER" => $grossUser];
133
        }
134
        return $dataArray;
135
    }
136
137
    /**
138
     * when a Federation attribute changes, invalidate caches of all IdPs 
139
     * in that federation (e.g. change of fed logo changes the actual 
140
     * installers)
141
     * 
142
     * @return void
143
     */
144
    public function updateFreshness()
145
    {
146
        $idplist = $this->listIdentityProviders();
147
        foreach ($idplist as $idpDetail) {
148
            $idpDetail['instance']->updateFreshness();
149
        }
150
    }
151
152
    /**
153
     * gets the download statistics for the federation
154
     * @param string $format either as an html *table* or *XML* or *JSON*
155
     * @return string|array
156
     * @throws Exception
157
     */
158
    public function downloadStats($format, $detail = '')
159
    {
160
        $data = $this->downloadStatsCore($detail);
161
        $retstring = "";
162
163
        switch ($format) {
164
            case "table":
165
                foreach ($data as $device => $numbers) {
166
                    if ($device == "TOTAL") {
167
                        continue;
168
                    }
169
                    $retstring .= "<tr><td>$device</td><td>".$numbers['ADMIN']."</td><td>".$numbers['SILVERBULLET']."</td><td>".$numbers['USER']."</td></tr>";
170
                }
171
                $retstring .= "<tr><td><strong>TOTAL</strong></td><td><strong>".$data['TOTAL']['ADMIN']."</strong></td><td><strong>".$data['TOTAL']['SILVERBULLET']."</strong></td><td><strong>".$data['TOTAL']['USER']."</strong></td></tr>";
172
                break;
173
            case "XML":
174
                // the calls to date() operate on current date, so there is no chance for a FALSE to be returned. Silencing scrutinizer.
175
                $retstring .= "<federation id='$this->tld' ts='"./** @scrutinizer ignore-type */ date("Y-m-d")."T"./** @scrutinizer ignore-type */ date("H:i:s")."'>\n";
176
                foreach ($data as $device => $numbers) {
177
                    if ($device == "TOTAL") {
178
                        continue;
179
                    }
180
                    $retstring .= "  <device name='".$device."'>\n    <downloads group='admin'>".$numbers['ADMIN']."</downloads>\n    <downloads group='managed_idp'>".$numbers['SILVERBULLET']."</downloads>\n    <downloads group='user'>".$numbers['USER']."</downloads>\n  </device>";
181
                }
182
                $retstring .= "<total>\n  <downloads group='admin'>".$data['TOTAL']['ADMIN']."</downloads>\n  <downloads group='managed_idp'>".$data['TOTAL']['SILVERBULLET']."</downloads>\n  <downloads group='user'>".$data['TOTAL']['USER']."</downloads>\n</total>\n";
183
                $retstring .= "</federation>";
184
                break;
185
            case "array":
186
                return $data;
187
            default:
188
                throw new Exception("Statistics can be requested only in 'table' or 'XML' format!");
189
        }
190
        return $retstring;
191
    }
192
193
    /**
194
     *
195
     * Constructs a Federation object.
196
     *
197
     * @param string $fedname textual representation of the Federation object
198
     *                        Example: "lu" (for Luxembourg)
199
     * @throws Exception
200
     */
201
    public function __construct($fedname)
202
    {
203
204
        // initialise the superclass variables
205
206
        $this->databaseType = "INST";
207
        $this->entityOptionTable = "federation_option";
208
        $this->entityIdColumn = "federation_id";
209
210
        $cat = new CAT();
211
        if (!isset($cat->knownFederations[$fedname])) {
212
            throw new Exception("This federation is not known to the system!");
213
        }
214
        $this->identifier = 0; // we do not use the numeric ID of a federation
215
        // $fedname is unvetted input. We do know it's correct because of the 
216
        // knownFederations check above - so no security issue - but Scrutinizer
217
        // doesn't realise it because we assign the literal incoming value. 
218
        // Let's make this assignment more dumb so that it passes the SC checks.
219
        // Equivalent to the following line, but assigning processed indexes
220
        // instead of the identical user input.
221
        // $this->tld = $fedname;
222
        $fedIdentifiers = array_keys($cat->knownFederations);
223
        $this->tld = $fedIdentifiers[array_search(strtoupper($fedname), $fedIdentifiers)];
224
        $this->name = $cat->knownFederations[$this->tld];
225
        // end of spoon-feed
226
        
227
        parent::__construct(); // we now have access to our database handle
228
229
        $handle = DBConnection::handle("FRONTEND");
230
        if ($handle instanceof DBConnection) {
231
            $this->frontendHandle = $handle;
232
        } else {
233
            throw new Exception("This database type is never an array!");
234
        }
235
        $this->loggerInstance->debug(4, $fedname, "Creating federation:", " \n");
236
        // fetch attributes from DB; populates $this->attributes array
237
        $this->attributes = $this->retrieveOptionsFromDatabase("SELECT DISTINCT option_name, option_lang, option_value, row_id 
238
                                            FROM $this->entityOptionTable
239
                                            WHERE $this->entityIdColumn = ?
240
                                            ORDER BY option_name", "FED");
241
242
243
        $this->attributes[] = array("name" => "internal:country",
244
            "lang" => NULL,
245
            "value" => $this->tld,
246
            "level" => Options::LEVEL_FED,
247
            "row_id" => 0,
248
            "flag" => NULL);
249
250
        if (\config\Master::FUNCTIONALITY_LOCATIONS['CONFASSISTANT_RADIUS'] != 'LOCAL' && \config\Master::FUNCTIONALITY_LOCATIONS['CONFASSISTANT_SILVERBULLET'] == 'LOCAL') {
251
            // this instance exclusively does SB, so it is not necessary to ask
252
            // fed ops whether they want to enable it or not. So always add it
253
            // to the list of fed attributes
254
            $this->attributes[] = array("name" => "fed:silverbullet",
255
                "lang" => NULL,
256
                "value" => "on",
257
                "level" => Options::LEVEL_FED,
258
                "row_id" => 0,
259
                "flag" => NULL);
260
        }
261
262
        $this->idpListActive = [];
263
        $this->idpListAll = [];
264
    }
265
266
    /**
267
     * Creates a new IdP inside the federation.
268
     * 
269
     * @param string $type          type of institution - IdP, SP or IdPSP
270
     * @param string $ownerId       Persistent identifier of the user for whom this IdP is created (first administrator)
271
     * @param string $level         Privilege level of the first administrator (was he blessed by a federation admin or a peer?)
272
     * @param string $mail          e-mail address with which the user was invited to administer (useful for later user identification if the user chooses a "funny" real name)
273
     * @param string $bestnameguess name of the IdP, if already known, in the best-match language
274
     * @return integer identifier of the new IdP
275
     * @throws Exception
276
     */
277
    public function newIdP($type, $ownerId, $level, $mail = NULL, $bestnameguess = NULL)
278
    {
279
        $this->databaseHandle->exec("INSERT INTO institution (country, type) VALUES('$this->tld', '$type')");
280
        $identifier = $this->databaseHandle->lastID();
281
282
        if ($identifier == 0 || !$this->loggerInstance->writeAudit($ownerId, "NEW", "Organisation $identifier")) {
283
            $text = "<p>Could not create a new ".common\Entity::$nomenclature_participant."!</p>";
284
            echo $text;
285
            throw new Exception($text);
286
        }
287
288
        if ($ownerId != "PENDING") {
289
            if ($mail === NULL) {
290
                throw new Exception("New IdPs in a federation need a mail address UNLESS created by API without OwnerId");
291
            }
292
            $this->databaseHandle->exec("INSERT INTO ownership (user_id,institution_id, blesslevel, orig_mail) VALUES(?,?,?,?)", "siss", $ownerId, $identifier, $level, $mail);
293
        }
294
        if ($bestnameguess === NULL) {
295
            $bestnameguess = "(no name yet, identifier $identifier)";
296
        }
297
        $admins = $this->listFederationAdmins();
298
299
        switch ($type) {
300
            case IdP::TYPE_IDP:
301
                $prettyPrintType = common\Entity::$nomenclature_idp;
302
                break;
303
            case IdP::TYPE_SP:
304
                $prettyPrintType = common\Entity::$nomenclature_hotspot;
305
                break;
306
            default:
307
                /// IdP and SP
308
                $prettyPrintType = sprintf(_("%s and %s"), common\Entity::$nomenclature_idp, common\Entity::$nomenclature_hotspot);
309
        }
310
311
        $consortium = \config\ConfAssistant::CONSORTIUM['display_name'];
312
        $productShort = \config\Master::APPEARANCE['productname'];
313
        $productLong = \config\Master::APPEARANCE['productname_long'];
314
        // notify the fed admins...
315
316
        foreach ($admins as $id) {
317
            $user = new User($id);
318
            /// arguments are: 1. nomenclature for the type of organisation being created (IdP/SP/both)
319
            ///                2. IdP name; 
320
            ///                3. consortium name (e.g. eduroam); 
321
            ///                4. federation shortname, e.g. "LU"; 
322
            ///                5. nomenclature for "institution"
323
            ///                6. product name (e.g. eduroam CAT); 
324
            ///                7. product long name (e.g. eduroam Configuration Assistant Tool)
325
            $message = sprintf(_("Hi,
326
327
the invitation for the new %s %s in your %s federation %s has been used and the %s was created in %s.
328
329
We thought you might want to know.
330
331
Best regards,
332
333
%s"),
334
                    $prettyPrintType,
335
                    $bestnameguess,
336
                    $consortium,
337
                    strtoupper($this->tld),
338
                    common\Entity::$nomenclature_participant,
339
                    $productShort,
340
                    $productLong);
341
            /// organisation
342
            if (\config\Master::MAILSETTINGS['notify_nro']) {
343
                $retval = $user->sendMailToUser(sprintf(_("%s in your federation was created"), common\Entity::$nomenclature_participant), $message);
344
                if ($retval === FALSE) {
345
                    $this->loggerInstance->debug(2, "Mail to federation admin was NOT sent!\n");
346
                }
347
            }
348
        }
349
350
        return $identifier;
351
    }
352
353
    /**
354
     * list of all institutions. Fetched once from the DB and then stored in
355
     * this variable
356
     * 
357
     * @var array
358
     */
359
    private $idpListAll;
360
361
    /**
362
     * list of all active institutions. Fetched once from the DB and then stored
363
     * in this variable
364
     * 
365
     * @var array
366
     */
367
    private $idpListActive;
368
369
    /**
370
     * fetches all known certificate information for RADIUS/TLS certs from the DB
371
     * 
372
     * @return array
373
     */
374
    public function listTlsCertificates()
375
    {
376
        $certQuery = "SELECT ca_name, request_serial, distinguished_name, status, expiry, certificate, revocation_pin FROM federation_servercerts WHERE federation_id = ?";
377
        $upperTld = strtoupper($this->tld);
378
        $certList = $this->databaseHandle->exec($certQuery, "s", $upperTld);
379
        $retArray = [];
380
        // SELECT -> resource, not boolean
381
        while ($certListResult = mysqli_fetch_object(/** @scrutinizer ignore-type */ $certList)) {
382
            $retArray[] = [
383
                'CA' => $certListResult->ca_name,
384
                'REQSERIAL' => $certListResult->request_serial,
385
                'DN' => $certListResult->distinguished_name,
386
                'STATUS' => $certListResult->status,
387
                'EXPIRY' => $certListResult->expiry,
388
                'CERT' => $certListResult->certificate,
389
                'REVPIN' => $certListResult->revocation_pin,
390
            ];
391
        }
392
        return$retArray;
393
    }
394
395
    /**
396
     * requests a new certificate
397
     * 
398
     * @param string $user       the user ID requesting the certificate
399
     * @param array  $csr        the CSR with some metainfo in an array
400
     * @param int    $expiryDays how long should the cert be valid, in days
401
     * @return void
402
     */
403
    public function requestCertificate($user, $csr, $expiryDays)
404
    {
405
        $revocationPin = common\Entity::randomString(10, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
406
        $newReq = new CertificationAuthorityEduPkiServer();
407
        $reqserial = $newReq->sendRequestToCa($csr, $revocationPin, $expiryDays);
408
        $this->loggerInstance->writeAudit($user, "NEW", "Certificate request - NRO: ".$this->tld." - serial: ".$reqserial." - subject: ".$csr['SUBJECT']);
409
        $reqQuery = "INSERT INTO federation_servercerts "
410
                ."(federation_id, ca_name, request_serial, distinguished_name, status, revocation_pin) "
411
                ."VALUES (?, 'eduPKI', ?, ?, 'REQUESTED', ?)";
412
        $this->databaseHandle->exec($reqQuery, "siss", $this->tld, $reqserial, $csr['SUBJECT'], $revocationPin);
413
    }
414
415
    /**
416
     * fetches new cert info from the CA
417
     * 
418
     * @param int $reqSerial the request serial number that is to be updated
419
     * @return void
420
     */
421
    public function updateCertificateStatus($reqSerial)
422
    {
423
        $ca = new CertificationAuthorityEduPkiServer();
424
        $entryInQuestion = $ca->pickupFinalCert($reqSerial, FALSE);
425
        if ($entryInQuestion === FALSE) {
426
            return; // no update to fetch
427
        }
428
        $certDetails = openssl_x509_parse($entryInQuestion['CERT']);
429
        $expiry = "20".$certDetails['validTo'][0].$certDetails['validTo'][1]."-".$certDetails['validTo'][2].$certDetails['validTo'][3]."-".$certDetails['validTo'][4].$certDetails['validTo'][5];
430
        openssl_x509_export($entryInQuestion['CERT'], $pem);
431
        $updateQuery = "UPDATE federation_servercerts SET status = 'ISSUED', certificate = ?, expiry = ? WHERE ca_name = 'eduPKI' AND request_serial = ?";
432
        $this->databaseHandle->exec($updateQuery, "ssi", $pem, $expiry, $reqSerial);
433
    }
434
435
    /**
436
     * revokes a certificate.
437
     * 
438
     * @param int $reqSerial the request serial whose associated cert is to be revoked
439
     * @return void
440
     */
441
    public function triggerRevocation($reqSerial)
442
    {
443
        // revocation at the CA side works with the serial of the certificate, not the request
444
        // so find that out first
445
        // This is a select, so tell Scrutinizer about the type-safety of the result
446
        $certInfoResource = $this->databaseHandle->exec("SELECT certificate FROM federation_servercerts WHERE ca_name = 'eduPKI' AND request_serial = ?", "i", $reqSerial);
447
        $certInfo = mysqli_fetch_row(/** @scrutinizer ignore-type */ $certInfoResource);
448
        if ($certInfo === NULL) {
449
            return; // cert not found, nothing to revoke
450
        }
451
        $certData = openssl_x509_parse($certInfo[0]);
452
        $serial = $certData['full_details']['serialNumber'];
453
        $eduPki = new CertificationAuthorityEduPkiServer();
454
        $eduPki->revokeCertificate($serial);
455
        $this->databaseHandle->exec("UPDATE federation_servercerts SET status = 'REVOKED' WHERE ca_name = 'eduPKI' AND request_serial = ?", "i", $reqSerial);
456
    }
457
    /**
458
     * Gets an array of certificate status (as most critical) from all profiles
459
     * per IdP - passing over the non-active profiles
460
     */
461
    public function getIdentityProvidersCertStatus() {
462
        $query = "SELECT distinct profile.profile_id  FROM profile JOIN profile_option ON profile.profile_id = profile_option.profile_id WHERE option_name='profile:production' AND profile.sufficient_config = 1";
463
        $activeProfiles = [];
464
        $result = $this->databaseHandle->exec($query);
465
        $rows = $result->fetch_all();
466
        foreach ($rows as $row) {
467
           $activeProfiles[] = $row[0];
468
        }
469
        $query = "SELECT institution.inst_id AS inst_id, profile.profile_id AS profile_id, profile_option.option_value AS cert FROM profile_option JOIN profile ON profile_option.profile_id=profile.profile_id JOIN institution ON profile.inst_id=institution.inst_id WHERE profile_option.option_name='eap:ca_file' and institution.country='".$this->tld."'";        
470
        $result = $this->databaseHandle->exec($query);
471
        $rows = $result->fetch_all();
472
        $x509 = new \core\common\X509();
473
        $certsStatus = [];
474
        $idpCertStatus = [];
475
        foreach ($rows as $row) {
476
            $inst = $row[0];
477
            $profile = $row[1];
478
            // pass any rofile which is not active
479
            if (!in_array($profile, $activeProfiles)) {
480
                continue;
481
            }
482
            $encodedCert = $row[2];
483
            if (!isset($idpCertStatus[$inst])) {
484
                $idpCertStatus[$inst] = \core\AbstractProfile::CERT_STATUS_OK;
485
            }
486
            
487
            // check if we have already seen this cert if not, continue analysis
488
            if (!isset($certsStatus[$encodedCert])) {
489
                $tm = $x509->processCertificate(base64_decode($encodedCert))['full_details']['validTo_time_t'] - time();
490
                if ($tm < \config\ConfAssistant::CERT_WARNINGS['expiry_critical']) {
491
                    $certsStatus[$encodedCert] = \core\AbstractProfile::CERT_STATUS_ERROR;
492
                } elseif ($tm < \config\ConfAssistant::CERT_WARNINGS['expiry_warning']) {
493
                    $certsStatus[$encodedCert] = \core\AbstractProfile::CERT_STATUS_WARN;
494
                } else {
495
                    $certsStatus[$encodedCert] = \core\AbstractProfile::CERT_STATUS_OK;
496
                }
497
            }
498
            $idpCertStatus[$inst] = max($idpCertStatus[$inst], $certsStatus[$encodedCert]);
499
        }
500
        return $idpCertStatus;
501
    }
502
    
503
    /**
504
     * Lists all Identity Providers in this federation
505
     *
506
     * @param int $activeOnly if set to non-zero will list only those institutions which have some valid profiles defined.
507
     * @return array (Array of IdP instances)
508
     *
509
     */
510
    public function listIdentityProviders($activeOnly = 0)
511
    {
512
        // maybe we did this exercise before?
513
        if ($activeOnly != 0 && count($this->idpListActive) > 0) {
514
            return $this->idpListActive;
515
        }
516
        if ($activeOnly == 0 && count($this->idpListAll) > 0) {
517
            return $this->idpListAll;
518
        }
519
        // the one for activeOnly is much more complex:
520
        if ($activeOnly != 0) {
521
            $allIDPs = $this->databaseHandle->exec("SELECT distinct institution.inst_id AS inst_id
522
               FROM institution
523
               JOIN profile ON institution.inst_id = profile.inst_id
524
               WHERE institution.country = '$this->tld' 
525
               AND profile.showtime = 1
526
               ORDER BY inst_id");
527
        } else {         // default query is:
528
        $allIDPs = $this->databaseHandle->exec("SELECT institution.inst_id AS inst_id,
529
            GROUP_CONCAT(DISTINCT REGEXP_REPLACE(profile.realm, '.*@', '') SEPARATOR '===') AS realms
530
            FROM institution LEFT JOIN profile ON institution.inst_id = profile.inst_id
531
               WHERE country = '$this->tld' GROUP BY institution.inst_id ORDER BY inst_id");
532
533
        }
534
        $returnarray = [];
535
        // SELECT -> resource, not boolean
536
        while ($idpQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $allIDPs)) {
537
            if (isset($this->idpArray[$idpQuery->inst_id])) {
538
                $idp = $this->idpArray[$idpQuery->inst_id];
539
            } else {
540
                $idp = new IdP($idpQuery->inst_id);
541
                $this->idpArray[$idpQuery->inst_id] = $idp;
542
            }
543
            if (!isset($idpQuery->realms)) {
544
                $idpQuery->realms = '';
545
            }
546
            $name = $idp->name;
547
            $idpInfo = ['entityID' => $idp->identifier,
548
                'title' => $name,
549
                'country' => strtoupper($idp->federation),
550
                'instance' => $idp,
551
                'realms' => $idpQuery->realms]
552
                 ;
553
            $returnarray[$idp->identifier] = $idpInfo;
554
        }
555
        if ($activeOnly != 0) { // we're only doing this once.
556
            $this->idpListActive = $returnarray;
557
        } else {
558
            $this->idpListAll = $returnarray;
559
        }
560
        return $returnarray;
561
    }
562
563
    /**
564
     * returns an array with information about the authorised administrators of the federation
565
     * 
566
     * @return array list of the admins of this federation
567
     */
568
    public function listFederationAdmins()
569
    {
570
        $returnarray = [];
571
        $query = "SELECT user_id FROM user_options WHERE option_name = 'user:fedadmin' AND option_value = ?";
572
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
573
            $query = "SELECT eptid as user_id FROM view_admin WHERE role = 'fedadmin' AND realm = ?";
574
        }
575
        $userHandle = DBConnection::handle("USER"); // we need something from the USER database for a change
576
        $upperFed = strtoupper($this->tld);
577
        // SELECT -> resource, not boolean
578
        $admins = $userHandle->exec($query, "s", $upperFed);
579
580
        while ($fedAdminQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $admins)) {
581
            $returnarray[] = $fedAdminQuery->user_id;
582
        }
583
        return $returnarray;
584
    }
585
586
    /**
587
     * cross-checks in the EXTERNAL customer DB which institutions exist there for the federations
588
     * 
589
     * @param bool   $unmappedOnly if set to TRUE, only returns those which do not have a known mapping to our internally known institutions
590
     * @param string $type         which type of entity to search for
591
     * @return array
592
     */
593
    public function listExternalEntities($unmappedOnly, $type = NULL)
594
    {
595
        $allExternals = [];
596
        $usedarray = [];
597
        $returnarray = [];
598
        if ($unmappedOnly) { // find out which entities are already mapped
599
            $syncstate = IdP::EXTERNAL_DB_SYNCSTATE_SYNCED;
600
            $alreadyUsed = $this->databaseHandle->exec("SELECT DISTINCT external_db_id FROM institution 
601
                                                                                                     WHERE external_db_id IS NOT NULL 
602
                                                                                                     AND external_db_syncstate = ?", "i", $syncstate);
603
            $pendingInvite = $this->databaseHandle->exec("SELECT DISTINCT external_db_uniquehandle FROM invitations 
604
                                                                                                      WHERE external_db_uniquehandle IS NOT NULL 
605
                                                                                                      AND invite_created >= TIMESTAMPADD(DAY, -1, NOW()) 
606
                                                                                                      AND used = 0");
607
            // SELECT -> resource, no boolean
608
            while ($alreadyUsedQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $alreadyUsed)) {
609
                $usedarray[] = $alreadyUsedQuery->external_db_id;
610
            }
611
            // SELECT -> resource, no boolean
612
            while ($pendingInviteQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $pendingInvite)) {
613
                if (!in_array($pendingInviteQuery->external_db_uniquehandle, $usedarray)) {
614
                    $usedarray[] = $pendingInviteQuery->external_db_uniquehandle;
615
                }
616
            }
617
        }
618
619
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
620
            $externalDB = CAT::determineExternalConnection();
621
            // need to convert our internal notion of participant types to those of eduroam DB
622
            $allExternals = $externalDB->listExternalEntities($this->tld, $type);
623
        }
624
        foreach ($allExternals as $oneExternal) {
625
            if (!in_array($oneExternal["ID"], $usedarray)) {
626
                $returnarray[] = $oneExternal;
627
            }
628
        }
629
        return $returnarray;
630
    }
631
632
    const UNKNOWN_IDP = -1;
633
    const AMBIGUOUS_IDP = -2;
634
635
    /**
636
     * for a MySQL list of institutions, find an institution or find out that
637
     * there is no single best match
638
     * 
639
     * @param \mysqli_result $dbResult the query object to work with
640
     * @param string         $country  used to return the country of the inst, if can be found out
641
     * @return int the identifier of the inst, or one of the special return values if unsuccessful
642
     */
643
    private static function findCandidates(\mysqli_result $dbResult, &$country)
644
    {
645
        $retArray = [];
646
        while ($row_id = mysqli_fetch_object($dbResult)) {
647
            if (!in_array($row_id->id, $retArray)) {
648
                $retArray[] = $row_id->id;
649
                $country = strtoupper($row_id->country);
650
            }
651
        }
652
        if (count($retArray) <= 0) {
653
            return Federation::UNKNOWN_IDP;
654
        }
655
        if (count($retArray) > 1) {
656
            return Federation::AMBIGUOUS_IDP;
657
        }
658
659
        return array_pop($retArray);
660
    }
661
662
    /**
663
     * If we are running diagnostics, our input from the user is the realm. We
664
     * need to find out which IdP this realm belongs to.
665
     * @param string $realm the realm to search for
666
     * @return array an array with two entries, CAT ID and DB ID, with either the respective ID of the IdP in the system, or UNKNOWN_IDP or AMBIGUOUS_IDP
667
     */
668
    public static function determineIdPIdByRealm($realm)
669
    {
670
        $country = NULL;
671
        $candidatesExternalDb = Federation::UNKNOWN_IDP;
672
        $dbHandle = DBConnection::handle("INST");
673
        $realmSearchStringCat = "%@$realm";
674
        $candidateCatQuery = $dbHandle->exec("SELECT p.profile_id as id, i.country as country FROM profile p, institution i WHERE p.inst_id = i.inst_id AND p.realm LIKE ?", "s", $realmSearchStringCat);
675
        // this is a SELECT returning a resource, not a boolean
676
        $candidatesCat = Federation::findCandidates(/** @scrutinizer ignore-type */ $candidateCatQuery, $country);
677
678
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED        
679
            $externalHandle = DBConnection::handle("EXTERNAL");
680
            $realmSearchStringDb1 = "$realm";
681
            $realmSearchStringDb2 = "%,$realm";
682
            $realmSearchStringDb3 = "$realm,%";
683
            $realmSearchStringDb4 = "%,$realm,%";
684
            $candidateExternalQuery = $externalHandle->exec("SELECT id_institution as id, country FROM view_active_idp_institution WHERE inst_realm LIKE ? or inst_realm LIKE ? or inst_realm LIKE ? or inst_realm LIKE ?", "ssss", $realmSearchStringDb1, $realmSearchStringDb2, $realmSearchStringDb3, $realmSearchStringDb4);
685
            // SELECT -> resource, not boolean
686
            $candidatesExternalDb = Federation::findCandidates(/** @scrutinizer ignore-type */ $candidateExternalQuery, $country);
687
        }
688
689
        return ["CAT" => $candidatesCat, "EXTERNAL" => $candidatesExternalDb, "FEDERATION" => $country];
690
    }
691
}