Federation   F
last analyzed

Complexity

Total Complexity 90

Size/Duplication

Total Lines 628
Duplicated Lines 0 %

Importance

Changes 6
Bugs 1 Features 0
Metric Value
wmc 90
eloc 301
c 6
b 1
f 0
dl 0
loc 628
rs 2

15 Methods

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