Passed
Push — release_2_1 ( 584353...81e271 )
by Tomasz
27:15
created

Federation::downloadStatsCore()   F

Complexity

Conditions 15
Paths 492

Size

Total Lines 51
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 37
c 0
b 0
f 0
dl 0
loc 51
rs 2.4554
cc 15
nc 492
nop 1

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