Passed
Push — release_2_1 ( 101877...251144 )
by Tomasz
09:31
created

Federation   F

Complexity

Total Complexity 84

Size/Duplication

Total Lines 617
Duplicated Lines 0 %

Importance

Changes 6
Bugs 1 Features 0
Metric Value
wmc 84
eloc 294
c 6
b 1
f 0
dl 0
loc 617
rs 2

15 Methods

Rating   Name   Duplication   Size   Complexity  
A listTlsCertificates() 0 19 2
A updateCertificateStatus() 0 12 2
A triggerRevocation() 0 15 2
A updateFreshness() 0 5 2
B downloadStatsCore() 0 48 11
B downloadStats() 0 33 8
A __construct() 0 62 5
A requestCertificate() 0 10 1
B newIdP() 0 74 11
B listExternalEntities() 0 37 10
B getIdentityProvidersCertStatus() 0 40 8
A findCandidates() 0 17 5
A determineIdPIdByRealm() 0 22 4
A listFederationAdmins() 0 16 5
B listIdentityProviders() 0 43 8

How to fix   Complexity   

Complex Class

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