Passed
Push — release_2_1 ( 81e271...fc59fc )
by Tomasz
12:32
created

Federation::newIdP()   B

Complexity

Conditions 10
Paths 38

Size

Total Lines 72
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 39
c 2
b 1
f 0
dl 0
loc 72
rs 7.6666
cc 10
nc 38
nop 5

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
        $inst_id = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $inst_id is dead and can be removed.
Loading history...
88
        $displayName = '';
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
            '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') {
99
                $grossAdmin = $grossAdmin + $queryResult->dl_admin;
100
                $grossSilverbullet = $grossSilverbullet + $queryResult->dl_sb;
101
                $grossUser = $grossUser + $queryResult->dl_user;
102
                continue;
103
            }    
104
            $inst_id = $queryResult->inst_id;
105
            if (isset($deviceArray[$queryResult->dev_id])) {
106
                $displayName = $deviceArray[$queryResult->dev_id]['display'];
107
            } 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
108
                $displayName = sprintf(_("(discontinued) %s"), $queryResult->dev_id);
109
            }
110
            if (! isset($dataArray[$inst_id])) {
111
                $dataArray[$inst_id] = [];
112
            }            
113
            if ($detail === 'ORGANISATIONS') {       
114
                $dataArray[$inst_id][$displayName] = ["ADMIN" => $queryResult->dl_admin, "SILVERBULLET" => $queryResult->dl_sb, "USER" => $queryResult->dl_user];
115
            }
116
            if ($detail === 'PROFILES') {
117
                $profile_id = $queryResult->profile_id;
118
                if (! isset($dataArray[$inst_id][$profile_id])) {
119
                    $dataArray[$inst_id][$profile_id] = [];
120
                }
121
                $dataArray[$inst_id][$profile_id][$displayName] = ["ADMIN" => $queryResult->dl_admin, "SILVERBULLET" => $queryResult->dl_sb, "USER" => $queryResult->dl_user];
122
            }
123
        }
124
        if ($detail === 'NONE') {
125
            $dataArray["TOTAL"] = ["ADMIN" => $grossAdmin, "SILVERBULLET" => $grossSilverbullet, "USER" => $grossUser];
126
        }
127
        return $dataArray;
128
    }
129
130
    /**
131
     * when a Federation attribute changes, invalidate caches of all IdPs 
132
     * in that federation (e.g. change of fed logo changes the actual 
133
     * installers)
134
     * 
135
     * @return void
136
     */
137
    public function updateFreshness()
138
    {
139
        $idplist = $this->listIdentityProviders();
140
        foreach ($idplist as $idpDetail) {
141
            $idpDetail['instance']->updateFreshness();
142
        }
143
    }
144
145
    /**
146
     * gets the download statistics for the federation
147
     * @param string $format either as an html *table* or *XML* or *JSON*
148
     * @return string|array
149
     * @throws Exception
150
     */
151
    public function downloadStats($format, $detail = '')
152
    {
153
        $data = $this->downloadStatsCore($detail);
154
        $retstring = "";
155
156
        switch ($format) {
157
            case "table":
158
                foreach ($data as $device => $numbers) {
159
                    if ($device == "TOTAL") {
160
                        continue;
161
                    }
162
                    $retstring .= "<tr><td>$device</td><td>" . $numbers['ADMIN'] . "</td><td>" . $numbers['SILVERBULLET'] . "</td><td>" . $numbers['USER'] . "</td></tr>";
163
                }
164
                $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>";
165
                break;
166
            case "XML":
167
                // the calls to date() operate on current date, so there is no chance for a FALSE to be returned. Silencing scrutinizer.
168
                $retstring .= "<federation id='$this->tld' ts='" . /** @scrutinizer ignore-type */ date("Y-m-d") . "T" . /** @scrutinizer ignore-type */ date("H:i:s") . "'>\n";
169
                foreach ($data as $device => $numbers) {
170
                    if ($device == "TOTAL") {
171
                        continue;
172
                    }
173
                    $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>";
174
                }
175
                $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";
176
                $retstring .= "</federation>";
177
                break;
178
            case "array":
179
                return $data;
180
            default:
181
                throw new Exception("Statistics can be requested only in 'table' or 'XML' format!");
182
        }
183
        return $retstring;
184
    }
185
186
    /**
187
     *
188
     * Constructs a Federation object.
189
     *
190
     * @param string $fedname textual representation of the Federation object
191
     *                        Example: "lu" (for Luxembourg)
192
     * @throws Exception
193
     */
194
    public function __construct($fedname)
195
    {
196
197
        // initialise the superclass variables
198
199
        $this->databaseType = "INST";
200
        $this->entityOptionTable = "federation_option";
201
        $this->entityIdColumn = "federation_id";
202
203
        $cat = new CAT();
204
        if (!isset($cat->knownFederations[$fedname])) {
205
            throw new Exception("This federation is not known to the system!");
206
        }
207
        $this->identifier = 0; // we do not use the numeric ID of a federation
208
        // $fedname is unvetted input. We do know it's correct because of the 
209
        // knownFederations check above - so no security issue - but Scrutinizer
210
        // doesn't realise it because we assign the literal incoming value. 
211
        // Let's make this assignment more dumb so that it passes the SC checks.
212
        // Equivalent to the following line, but assigning processed indexes
213
        // instead of the identical user input.
214
        // $this->tld = $fedname;
215
        $fedIdentifiers = array_keys($cat->knownFederations);
216
        $this->tld = $fedIdentifiers[array_search(strtoupper($fedname), $fedIdentifiers)];
217
        $this->name = $cat->knownFederations[$this->tld];
218
        // end of spoon-feed
219
        
220
        parent::__construct(); // we now have access to our database handle
221
222
        $handle = DBConnection::handle("FRONTEND");
223
        if ($handle instanceof DBConnection) {
224
            $this->frontendHandle = $handle;
225
        } else {
226
            throw new Exception("This database type is never an array!");
227
        }
228
        // fetch attributes from DB; populates $this->attributes array
229
        $this->attributes = $this->retrieveOptionsFromDatabase("SELECT DISTINCT option_name, option_lang, option_value, row_id 
230
                                            FROM $this->entityOptionTable
231
                                            WHERE $this->entityIdColumn = ?
232
                                            ORDER BY option_name", "FED");
233
234
235
        $this->attributes[] = array("name" => "internal:country",
236
            "lang" => NULL,
237
            "value" => $this->tld,
238
            "level" => Options::LEVEL_FED,
239
            "row_id" => 0,
240
            "flag" => NULL);
241
242
        if (\config\Master::FUNCTIONALITY_LOCATIONS['CONFASSISTANT_RADIUS'] != 'LOCAL' && \config\Master::FUNCTIONALITY_LOCATIONS['CONFASSISTANT_SILVERBULLET'] == 'LOCAL') {
243
            // this instance exclusively does SB, so it is not necessary to ask
244
            // fed ops whether they want to enable it or not. So always add it
245
            // to the list of fed attributes
246
            $this->attributes[] = array("name" => "fed:silverbullet",
247
                "lang" => NULL,
248
                "value" => "on",
249
                "level" => Options::LEVEL_FED,
250
                "row_id" => 0,
251
                "flag" => NULL);
252
        }
253
254
        $this->idpListActive = [];
255
        $this->idpListAll = [];
256
    }
257
258
    /**
259
     * Creates a new IdP inside the federation.
260
     * 
261
     * @param string $type          type of institution - IdP, SP or IdPSP
262
     * @param string $ownerId       Persistent identifier of the user for whom this IdP is created (first administrator)
263
     * @param string $level         Privilege level of the first administrator (was he blessed by a federation admin or a peer?)
264
     * @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)
265
     * @param string $bestnameguess name of the IdP, if already known, in the best-match language
266
     * @return integer identifier of the new IdP
267
     * @throws Exception
268
     */
269
    public function newIdP($type, $ownerId, $level, $mail = NULL, $bestnameguess = NULL)
270
    {
271
        $this->databaseHandle->exec("INSERT INTO institution (country, type) VALUES('$this->tld', '$type')");
272
        $identifier = $this->databaseHandle->lastID();
273
274
        if ($identifier == 0 || !$this->loggerInstance->writeAudit($ownerId, "NEW", "Organisation $identifier")) {
275
            $text = "<p>Could not create a new " . common\Entity::$nomenclature_participant . "!</p>";
276
            echo $text;
277
            throw new Exception($text);
278
        }
279
280
        if ($ownerId != "PENDING") {
281
            if ($mail === NULL) {
282
                throw new Exception("New IdPs in a federation need a mail address UNLESS created by API without OwnerId");
283
            }
284
            $this->databaseHandle->exec("INSERT INTO ownership (user_id,institution_id, blesslevel, orig_mail) VALUES(?,?,?,?)", "siss", $ownerId, $identifier, $level, $mail);
285
        }
286
        if ($bestnameguess === NULL) {
287
            $bestnameguess = "(no name yet, identifier $identifier)";
288
        }
289
        $admins = $this->listFederationAdmins();
290
291
        switch ($type) {
292
            case IdP::TYPE_IDP:
293
                $prettyPrintType = common\Entity::$nomenclature_idp;
294
                break;
295
            case IdP::TYPE_SP:
296
                $prettyPrintType = common\Entity::$nomenclature_hotspot;
297
                break;
298
            default:
299
                /// IdP and SP
300
                $prettyPrintType = sprintf(_("%s and %s"), common\Entity::$nomenclature_idp, common\Entity::$nomenclature_hotspot);
301
        }
302
303
        $consortium = \config\ConfAssistant::CONSORTIUM['display_name'];
304
        $productShort = \config\Master::APPEARANCE['productname'];
305
        $productLong = \config\Master::APPEARANCE['productname_long'];
306
        // notify the fed admins...
307
308
        foreach ($admins as $id) {
309
            $user = new User($id);
310
            /// arguments are: 1. nomenclature for the type of organisation being created (IdP/SP/both)
311
            ///                2. IdP name; 
312
            ///                3. consortium name (e.g. eduroam); 
313
            ///                4. federation shortname, e.g. "LU"; 
314
            ///                5. nomenclature for "institution"
315
            ///                6. product name (e.g. eduroam CAT); 
316
            ///                7. product long name (e.g. eduroam Configuration Assistant Tool)
317
            $message = sprintf(_("Hi,
318
319
the invitation for the new %s %s in your %s federation %s has been used and the %s was created in %s.
320
321
We thought you might want to know.
322
323
Best regards,
324
325
%s"),
326
                    $prettyPrintType,
327
                    $bestnameguess,
328
                    $consortium,
329
                    strtoupper($this->tld),
330
                    common\Entity::$nomenclature_participant,
331
                    $productShort,
332
                    $productLong);
333
            /// organisation
334
            $retval = $user->sendMailToUser(sprintf(_("%s in your federation was created"), common\Entity::$nomenclature_participant), $message);
335
            if ($retval === FALSE) {
336
                $this->loggerInstance->debug(2, "Mail to federation admin was NOT sent!\n");
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
    /**
449
     * Lists all Identity Providers in this federation
450
     *
451
     * @param int $activeOnly if set to non-zero will list only those institutions which have some valid profiles defined.
452
     * @return array (Array of IdP instances)
453
     *
454
     */
455
    public function listIdentityProviders($activeOnly = 0)
456
    {
457
        // maybe we did this exercise before?
458
        if ($activeOnly != 0 && count($this->idpListActive) > 0) {
459
            return $this->idpListActive;
460
        }
461
        if ($activeOnly == 0 && count($this->idpListAll) > 0) {
462
            return $this->idpListAll;
463
        }
464
        // default query is:
465
        $allIDPs = $this->databaseHandle->exec("SELECT inst_id FROM institution
466
               WHERE country = '$this->tld' ORDER BY inst_id");
467
        // the one for activeOnly is much more complex:
468
        if ($activeOnly) {
469
            $allIDPs = $this->databaseHandle->exec("SELECT distinct institution.inst_id AS inst_id
470
               FROM institution
471
               JOIN profile ON institution.inst_id = profile.inst_id
472
               WHERE institution.country = '$this->tld' 
473
               AND profile.showtime = 1
474
               ORDER BY inst_id");
475
        }
476
477
        $returnarray = [];
478
        // SELECT -> resource, not boolean
479
        while ($idpQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $allIDPs)) {
480
            $idp = new IdP($idpQuery->inst_id);
481
            $name = $idp->name;
482
            $idpInfo = ['entityID' => $idp->identifier,
483
                'title' => $name,
484
                'country' => strtoupper($idp->federation),
485
                'instance' => $idp];
486
            $returnarray[$idp->identifier] = $idpInfo;
487
        }
488
        if ($activeOnly != 0) { // we're only doing this once.
489
            $this->idpListActive = $returnarray;
490
        } else {
491
            $this->idpListAll = $returnarray;
492
        }
493
        return $returnarray;
494
    }
495
496
    /**
497
     * returns an array with information about the authorised administrators of the federation
498
     * 
499
     * @return array list of the admins of this federation
500
     */
501
    public function listFederationAdmins()
502
    {
503
        $returnarray = [];
504
        $query = "SELECT user_id FROM user_options WHERE option_name = 'user:fedadmin' AND option_value = ?";
505
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
506
            $query = "SELECT eptid as user_id FROM view_admin WHERE role = 'fedadmin' AND realm = ?";
507
        }
508
        $userHandle = DBConnection::handle("USER"); // we need something from the USER database for a change
509
        $upperFed = strtoupper($this->tld);
510
        // SELECT -> resource, not boolean
511
        $admins = $userHandle->exec($query, "s", $upperFed);
512
513
        while ($fedAdminQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $admins)) {
514
            $returnarray[] = $fedAdminQuery->user_id;
515
        }
516
        return $returnarray;
517
    }
518
519
    /**
520
     * cross-checks in the EXTERNAL customer DB which institutions exist there for the federations
521
     * 
522
     * @param bool   $unmappedOnly if set to TRUE, only returns those which do not have a known mapping to our internally known institutions
523
     * @param string $type         which type of entity to search for
524
     * @return array
525
     */
526
    public function listExternalEntities($unmappedOnly, $type = NULL)
527
    {
528
        $allExternals = [];
529
        $usedarray = [];
530
        $returnarray = [];
531
        if ($unmappedOnly) { // find out which entities are already mapped
532
            $syncstate = IdP::EXTERNAL_DB_SYNCSTATE_SYNCED;
533
            $alreadyUsed = $this->databaseHandle->exec("SELECT DISTINCT external_db_id FROM institution 
534
                                                                                                     WHERE external_db_id IS NOT NULL 
535
                                                                                                     AND external_db_syncstate = ?", "i", $syncstate);
536
            $pendingInvite = $this->databaseHandle->exec("SELECT DISTINCT external_db_uniquehandle FROM invitations 
537
                                                                                                      WHERE external_db_uniquehandle IS NOT NULL 
538
                                                                                                      AND invite_created >= TIMESTAMPADD(DAY, -1, NOW()) 
539
                                                                                                      AND used = 0");
540
            // SELECT -> resource, no boolean
541
            while ($alreadyUsedQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $alreadyUsed)) {
542
                $usedarray[] = $alreadyUsedQuery->external_db_id;
543
            }
544
            // SELECT -> resource, no boolean
545
            while ($pendingInviteQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $pendingInvite)) {
546
                if (!in_array($pendingInviteQuery->external_db_uniquehandle, $usedarray)) {
547
                    $usedarray[] = $pendingInviteQuery->external_db_uniquehandle;
548
                }
549
            }
550
        }
551
552
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
553
            $externalDB = CAT::determineExternalConnection();
554
            // need to convert our internal notion of participant types to those of eduroam DB
555
            $allExternals = $externalDB->listExternalEntities($this->tld, $type);
556
        }
557
        foreach ($allExternals as $oneExternal) {
558
            if (!in_array($oneExternal["ID"], $usedarray)) {
559
                $returnarray[] = $oneExternal;
560
            }
561
        }
562
        return $returnarray;
563
    }
564
565
    const UNKNOWN_IDP = -1;
566
    const AMBIGUOUS_IDP = -2;
567
568
    /**
569
     * for a MySQL list of institutions, find an institution or find out that
570
     * there is no single best match
571
     * 
572
     * @param \mysqli_result $dbResult the query object to work with
573
     * @param string         $country  used to return the country of the inst, if can be found out
574
     * @return int the identifier of the inst, or one of the special return values if unsuccessful
575
     */
576
    private static function findCandidates(\mysqli_result $dbResult, &$country)
577
    {
578
        $retArray = [];
579
        while ($row_id = mysqli_fetch_object($dbResult)) {
580
            if (!in_array($row_id->id, $retArray)) {
581
                $retArray[] = $row_id->id;
582
                $country = strtoupper($row_id->country);
583
            }
584
        }
585
        if (count($retArray) <= 0) {
586
            return Federation::UNKNOWN_IDP;
587
        }
588
        if (count($retArray) > 1) {
589
            return Federation::AMBIGUOUS_IDP;
590
        }
591
592
        return array_pop($retArray);
593
    }
594
595
    /**
596
     * If we are running diagnostics, our input from the user is the realm. We
597
     * need to find out which IdP this realm belongs to.
598
     * @param string $realm the realm to search for
599
     * @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
600
     */
601
    public static function determineIdPIdByRealm($realm)
602
    {
603
        $country = NULL;
604
        $candidatesExternalDb = Federation::UNKNOWN_IDP;
605
        $dbHandle = DBConnection::handle("INST");
606
        $realmSearchStringCat = "%@$realm";
607
        $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);
608
        // this is a SELECT returning a resource, not a boolean
609
        $candidatesCat = Federation::findCandidates(/** @scrutinizer ignore-type */ $candidateCatQuery, $country);
610
611
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED        
612
            $externalHandle = DBConnection::handle("EXTERNAL");
613
            $realmSearchStringDb1 = "$realm";
614
            $realmSearchStringDb2 = "%,$realm";
615
            $realmSearchStringDb3 = "$realm,%";
616
            $realmSearchStringDb4 = "%,$realm,%";
617
            $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);
618
            // SELECT -> resource, not boolean
619
            $candidatesExternalDb = Federation::findCandidates(/** @scrutinizer ignore-type */ $candidateExternalQuery, $country);
620
        }
621
622
        return ["CAT" => $candidatesCat, "EXTERNAL" => $candidatesExternalDb, "FEDERATION" => $country];
623
    }
624
}