Federation   F
last analyzed

Complexity

Total Complexity 91

Size/Duplication

Total Lines 634
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 91
eloc 307
c 4
b 0
f 0
dl 0
loc 634
rs 2

15 Methods

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

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