IdP   F
last analyzed

Complexity

Total Complexity 83

Size/Duplication

Total Lines 525
Duplicated Lines 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 83
eloc 212
c 1
b 1
f 0
dl 0
loc 525
rs 2

20 Methods

Rating   Name   Duplication   Size   Complexity  
A listProfiles() 0 14 3
A __construct() 0 43 5
A listDeployments() 0 12 3
A listOwners() 0 9 2
A maxProfileStatus() 0 20 5
A maxOpenRoamingStatus() 0 8 3
A isPrimaryOwner() 0 8 4
A profileCount() 0 10 2
A deploymentCount() 0 10 2
A destroy() 0 36 5
A updateFreshness() 0 5 1
A eligibility() 0 9 3
B getExternalDBSyncCandidates() 0 34 11
B significantChanges() 0 27 8
A newDeployment() 0 12 3
A setExternalDBId() 0 8 5
A getExternalDBSyncState() 0 6 4
A removeExternalDBId() 0 6 5
A getExternalDBId() 0 12 5
A newProfile() 0 18 4

How to fix   Complexity   

Complex Class

Complex classes like IdP 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 IdP, 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 Federation, IdP and Profile classes.
25
 * These should be split into separate files later.
26
 *
27
 * @package Developer
28
 */
29
/**
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 Identity Provider (IdP).
39
 * IdPs have properties of their own, and may have one or more Profiles. The
40
 * profiles can override the institution-wide properties.
41
 *
42
 * @author Stefan Winter <[email protected]>
43
 * @author Tomasz Wolniewicz <[email protected]>
44
 *
45
 * @license see LICENSE file in root directory
46
 *
47
 * @package Developer
48
 */
49
class IdP extends EntityWithDBProperties
50
{
51
52
    const EXTERNAL_DB_SYNCSTATE_NOT_SYNCED = 0;
53
    const EXTERNAL_DB_SYNCSTATE_SYNCED = 1;
54
    const EXTERNAL_DB_SYNCSTATE_NOTSUBJECTTOSYNCING = 2;
55
    const TYPE_IDP = 'IdP';
56
    const TYPE_SP = 'SP';
57
    const TYPE_IDPSP = 'IdPSP';
58
59
    /**
60
     *
61
     * @var integer synchronisation state with external database, if any
62
     */
63
    private $externalDbSyncstate;
64
65
    /**
66
     * The shortname of this IdP's federation
67
     * @var string 
68
     */
69
    public $federation;
70
71
    /**
72
     * The type of participant in DB enum notation
73
     * @var string
74
     */
75
    public $type;
76
77
    /**
78
     * Constructs an IdP object based on its details in the database.
79
     * Cannot be used to define a new IdP in the database! This happens via Federation::newIdP()
80
     *
81
     * @param int $instId the database row_id identifier
82
     * @throws Exception
83
     */
84
    public function __construct(int $instId)
85
    {
86
        $this->databaseType = "INST";
87
        parent::__construct(); // now databaseHandle and logging is available
88
        $this->entityOptionTable = "institution_option";
89
        $this->entityIdColumn = "institution_id";
90
91
        $this->identifier = $instId;
92
93
        $idp = $this->databaseHandle->exec("SELECT inst_id, country,external_db_syncstate, type FROM institution WHERE inst_id = $this->identifier");
94
        // SELECT -> returns resource, not boolean
95
        if (!$instQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $idp)) {
96
            throw new Exception("IdP $this->identifier not found in database!");
97
        }
98
99
        $this->federation = $instQuery->country;
100
        $this->externalDbSyncstate = $instQuery->external_db_syncstate;
101
102
        // fetch attributes from DB; populates $this->attributes array
103
        $this->attributes = $this->retrieveOptionsFromDatabase("SELECT DISTINCT option_name, option_lang, option_value, row_id 
104
                                            FROM $this->entityOptionTable
105
                                            WHERE $this->entityIdColumn = ?  
106
                                            ORDER BY option_name", "IdP");
107
108
        $this->attributes[] = ["name" => "internal:country",
109
            "lang" => NULL,
110
            "value" => $this->federation,
111
            "level" => Options::LEVEL_IDP,
112
            "row_id" => 0,
113
            "flag" => NULL];
114
115
        $this->name = $this->languageInstance->getLocalisedValue($this->getAttributes('general:instname'));
116
        $eligibility = $this->eligibility($instQuery->type);
117
        if (in_array(IdP::ELIGIBILITY_IDP, $eligibility) && in_array(IdP::ELIGIBILITY_SP, $eligibility)) {
118
            $eligType = IdP::TYPE_IDPSP . "";
119
            $this->type = $eligType;
120
        } elseif (in_array(IdP::ELIGIBILITY_IDP, $eligibility)) {
121
            $eligType = IdP::TYPE_IDP . "";
122
        } else {
123
            $eligType = IdP::TYPE_SP . "";
124
        }
125
        $this->type = $eligType;
126
        $this->loggerInstance->debug(4, "--- END Constructing new IdP object $instId ... ---\n");
127
    }
128
129
    /**
130
     * This function retrieves all registered profiles for this IdP from the database
131
     *
132
     * @param bool $activeOnly if and set to non-zero will cause listing of only those institutions which have some valid profiles defined.
133
     * @return \core\AbstractProfile[] list of Profiles of this IdP
134
     */
135
    public function listProfiles(bool $activeOnly = FALSE)
136
    {
137
        $query = "SELECT profile_id FROM profile WHERE inst_id = $this->identifier" . ($activeOnly ? " AND showtime = 1" : "")." ORDER BY preference";
138
        $allProfiles = $this->databaseHandle->exec($query);
139
        $returnarray = [];
140
        // SELECT -> resource, not boolean
141
        while ($profileQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $allProfiles)) {
142
            $oneProfile = ProfileFactory::instantiate($profileQuery->profile_id, $this);
143
            $oneProfile->institution = $this->identifier;
144
            $returnarray[] = $oneProfile;
145
        }
146
147
        $this->loggerInstance->debug(4, "listProfiles: " . /** @scrutinizer ignore-type */ print_r($returnarray, true));
148
        return $returnarray;
149
    }
150
151
    /**
152
     * This function retrieves all SP deployments for this organisation from the database
153
     *
154
     * @param bool $activeOnly if and set to non-zero will cause listing of only those institutions which have some valid profiles defined.
155
     * @return \core\AbstractDeployment[] list of deployments of this IdP
156
     */
157
    public function listDeployments(bool $activeOnly = FALSE)
158
    {
159
        $query = "SELECT deployment_id FROM deployment WHERE inst_id = $this->identifier" . ($activeOnly ? " AND status = " . AbstractDeployment::ACTIVE : "");
160
        $allDeployments = $this->databaseHandle->exec($query);
161
        $returnarray = [];
162
        // SELECT -> resource, not boolean
163
        while ($deploymentQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $allDeployments)) {
164
            $returnarray[] = new DeploymentManaged($this, $deploymentQuery->deployment_id);
165
        }
166
167
        $this->loggerInstance->debug(4, "listDeployments: " . /** @scrutinizer ignore-type */ print_r($returnarray, true));
168
        return $returnarray;
169
    }
170
171
    const PROFILES_INCOMPLETE = 0;
172
    const PROFILES_CONFIGURED = 1;
173
    const PROFILES_SHOWTIME = 2;
174
    const PROFILES_REDIRECTED = 3;
175
    
176
    const PROFILES_INDEX = [
177
        self::PROFILES_INCOMPLETE => 'PROFILES_INCOMPLETE',
178
        self::PROFILES_CONFIGURED => 'PROFILES_CONFIGURED',
179
        self::PROFILES_SHOWTIME => 'PROFILES_SHOWTIME',
180
        self::PROFILES_REDIRECTED => 'PROFILES_REDIRECTED',
181
    ];
182
183
    /**
184
     * looks through all the profiles of the inst and determines the highest prod-ready level among the profiles
185
     * @return int highest level of completeness of all the profiles of the inst or PROFILES_REDIRECTED if all profiles are redirected
186
     */
187
    
188
    public function maxProfileStatus()
189
    {
190
        $redirectProfileIds = [];
191
        $allProfileLevels = $this->databaseHandle->exec("SELECT profile_id, sufficient_config + showtime AS maxlevel FROM profile WHERE inst_id = $this->identifier ORDER BY maxlevel DESC");
192
        // SELECT yields a resource, not a boolean
193
        if ($allProfileLevels->num_rows == 0 ) {
194
            return self::PROFILES_INCOMPLETE;
195
        }
196
        $allProfilesArray = $allProfileLevels->fetch_all(MYSQLI_ASSOC);
197
        $max_level = $allProfilesArray[0]['maxlevel'];        
198
        $redirectProfiles = $this->databaseHandle->exec("SELECT profile.profile_id as profile_id FROM profile JOIN profile_option ON profile.profile_id=profile_option.profile_id WHERE inst_id = $this->identifier AND profile.showtime=1 AND option_name='device-specific:redirect' AND device_id IS NULL");
199
        while ($res = $redirectProfiles->fetch_object()) {
200
            $redirectProfileIds[] = $res->profile_id;
201
        }        
202
        foreach ($allProfilesArray as $profile) {
203
            if (!in_array($profile['profile_id'], $redirectProfileIds)) {
204
                return($max_level);
205
            }            
206
        }
207
        return self::PROFILES_REDIRECTED;
208
    }
209
210
    /**
211
     * looks through all the profiles of the inst and determines the highest 
212
     * participation/conformance level for OpenRoaming
213
     * 
214
     * @return int highest level of completeness of all the profiles of the inst
215
     */
216
    public function maxOpenRoamingStatus()
217
    {
218
        $allProfiles = $this->databaseHandle->exec("SELECT MIN(openroaming) AS maxlevel FROM profile WHERE inst_id = $this->identifier");
219
        // SELECT yields a resource, not a boolean
220
        while ($res = mysqli_fetch_object(/** @scrutinizer ignore-type */ $allProfiles)) {
221
            return (is_numeric($res->maxlevel) ? (int)$res->maxlevel : AbstractProfile::OVERALL_OPENROAMING_LEVEL_NO ); // insts without profiles should get a "NO"
222
        }
223
        return AbstractProfile::OVERALL_OPENROAMING_LEVEL_NO;
224
    }
225
    
226
    
227
    /** This function retrieves an array of authorised users which can
228
     * manipulate this institution.
229
     * 
230
     * @return array owners of the institution; numbered array with members ID, MAIL and LEVEL
231
     */
232
    public function listOwners()
233
    {
234
        $returnarray = [];
235
        $admins = $this->databaseHandle->exec("SELECT user_id, orig_mail, blesslevel FROM ownership WHERE institution_id = $this->identifier ORDER BY user_id");
236
        // SELECT -> resource, not boolean
237
        while ($ownerQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $admins)) {
238
            $returnarray[] = ['ID' => $ownerQuery->user_id, 'MAIL' => $ownerQuery->orig_mail, 'LEVEL' => $ownerQuery->blesslevel];
239
        }
240
        return $returnarray;
241
    }
242
243
    /**
244
     * Primary owners are allowed to invite other (secondary) admins to the institution
245
     * 
246
     * @param string $user ID of a logged-in user
247
     * @return boolean TRUE if this user is an admin with FED-level blessing
248
     */
249
    public function isPrimaryOwner($user)
250
    {
251
        foreach ($this->listOwners() as $oneOwner) {
252
            if ($oneOwner['ID'] == $user && $oneOwner['LEVEL'] == "FED") {
253
                return TRUE;
254
            }
255
        }
256
        return FALSE;
257
    }
258
259
    /**
260
     * This function gets the profile count for a given IdP.
261
     * 
262
     * The count could be retrieved from the listProfiles method
263
     * but this is less expensive.
264
     *
265
     * @return int profile count
266
     */
267
    public function profileCount()
268
    {
269
        $result = $this->databaseHandle->exec("SELECT profile_id FROM profile 
270
             WHERE inst_id = $this->identifier");
271
        // SELECT -> resource, not boolean
272
        $numberOfRows = mysqli_num_rows(/** @scrutinizer ignore-type */ $result);
273
        if (is_string($numberOfRows)) {
274
            throw new Exception("Number of profiles > PHP_MAX_INT?");
275
        }
276
        return $numberOfRows;
277
    }
278
279
    /**
280
     * This function gets the deployment count for a given IdP.
281
     *
282
     * @return int deployment count
283
     */
284
    public function deploymentCount()
285
    {
286
        $result = $this->databaseHandle->exec("SELECT deployment_id FROM deployment
287
             WHERE inst_id = $this->identifier");
288
        // SELECT -> resource, not boolean
289
        $numberOfRows = mysqli_num_rows(/** @scrutinizer ignore-type */ $result);
290
        if (is_string($numberOfRows)) {
291
            throw new Exception("Number of deployments > PHP_MAX_INT?");
292
        }
293
        return $numberOfRows;
294
    }
295
296
    const ELIGIBILITY_IDP = "IdP";
297
    const ELIGIBILITY_SP = "SP";
298
299
    /**
300
     * checks whether the participant is an IdP, an SP, or both.
301
     * 
302
     * @return array list of eligibilities
303
     */
304
    public function eligibility($type)
305
    {
306
        switch ($type) {
307
            case "IdP":
308
                return [IdP::ELIGIBILITY_IDP];
309
            case "SP":
310
                return [IdP::ELIGIBILITY_SP];
311
            default:
312
                return [IdP::ELIGIBILITY_IDP, IdP::ELIGIBILITY_SP];
313
        }
314
    }
315
316
    /**
317
     * This function sets the timestamp of last modification of the child profiles to the current timestamp.
318
     * 
319
     * This is needed for installer caching: all installers which are on disk 
320
     * must be re-created if an attribute changes. This timestamp here
321
     * is used to determine if the installer on disk is still new enough.
322
     * 
323
     * @return void
324
     */
325
    public function updateFreshness()
326
    {
327
        // freshness is always defined for *Profiles*
328
        // IdP needs to update timestamp of all its profiles if an IdP-wide attribute changed
329
        $this->databaseHandle->exec("UPDATE profile SET last_change = CURRENT_TIMESTAMP WHERE inst_id = '$this->identifier'");
330
    }
331
332
    /**
333
     * Adds a new profile to this IdP.
334
     * 
335
     * Only creates the DB entry for the Profile. If you want to add attributes later, see Profile::addAttribute().
336
     *
337
     * @param string $type exactly "RADIUS" or "SILVERBULLET", all other values throw an Exception
338
     * @return AbstractProfile|NULL new Profile object if successful, or NULL if an error occurred
339
     * @throws Exception
340
     */
341
    public function newProfile(string $type)
342
    {
343
        $this->databaseHandle->exec("INSERT INTO profile (inst_id) VALUES($this->identifier)");
344
        $identifier = $this->databaseHandle->lastID();
345
        if ($identifier > 0) {
346
            switch ($type) {
347
                case AbstractProfile::PROFILETYPE_RADIUS:
348
                    return new ProfileRADIUS($identifier, $this);
349
                case AbstractProfile::PROFILETYPE_SILVERBULLET:
350
                    $theProfile = new ProfileSilverbullet($identifier, $this);
351
                    $theProfile->addSupportedEapMethod(new \core\common\EAP(\core\common\EAP::EAPTYPE_SILVERBULLET), 1);
352
                    $theProfile->setRealm($this->identifier . "-" . $theProfile->identifier . "." . strtolower($this->federation) . strtolower(\config\ConfAssistant::SILVERBULLET['realm_suffix']));
353
                    return $theProfile;
354
                default:
355
                    throw new Exception("This type of profile is unknown and can not be added.");
356
            }
357
        }
358
        return NULL;
359
    }
360
361
    /**
362
     * Adds a new hotspot deployment to this IdP.
363
     * 
364
     * Only creates the DB entry for the deployment. If you want to add attributes later, see Profile::addAttribute().
365
     *
366
     * @param string $type       exactly "RADIUS-SP" or "MANAGED-SP", all other values throw an Exception
367
     * @param string $consortium name of the consortium to attach this *Managed* SP to
368
     * @return DeploymentManaged the newly created deployment
369
     * @throws Exception
370
     */
371
    public function newDeployment(string $type, string $consortium = "eduroam")
372
    {
373
        switch ($type) {
374
            case AbstractDeployment::DEPLOYMENTTYPE_CLASSIC:
375
                // classic deployment exist in the eduroam DB. We don't do anything here.
376
                throw new Exception("This type of deployment is handled externally and requesting it here makes no sense.");
377
            case AbstractDeployment::DEPLOYMENTTYPE_MANAGED:
378
                $this->databaseHandle->exec("INSERT INTO deployment (inst_id) VALUES($this->identifier)");
379
                $identifier = $this->databaseHandle->lastID();
380
                return new DeploymentManaged($this, $identifier, $consortium);
381
            default:
382
                throw new Exception("This type of deployment is unknown and can not be added.");
383
        }
384
    }
385
386
    /**
387
     * deletes the IdP and all its profiles
388
     * 
389
     * @return void
390
     * @throws Exception
391
     */
392
    public function destroy()
393
    {
394
        common\Entity::intoThePotatoes();
395
        /* delete all profiles */
396
        foreach ($this->listProfiles() as $profile) {
397
            $profile->destroy();
398
        }
399
        /* double-check that all profiles are gone */
400
        $profiles = $this->listProfiles();
401
402
        if (count($profiles) > 0) {
403
            throw new Exception("This IdP shouldn't have any profiles any more!");
404
        }
405
406
        $this->databaseHandle->exec("DELETE FROM ownership WHERE institution_id = $this->identifier");
407
        $this->databaseHandle->exec("DELETE FROM institution_option WHERE institution_id = $this->identifier");
408
        $this->databaseHandle->exec("DELETE FROM institution WHERE inst_id = $this->identifier");
409
410
        // notify federation admins
411
        if (\config\Master::MAILSETTINGS['notify_nro']) {
412
            $fed = new Federation($this->federation);
413
            foreach ($fed->listFederationAdmins() as $id) {
414
                $user = new User($id);
415
                $message = sprintf(_("Hi,
416
417
    the %s %s in your %s federation %s has been deleted from %s.
418
419
    We thought you might want to know.
420
421
    Best regards,
422
423
    %s"), common\Entity::$nomenclature_participant, $this->name, \config\ConfAssistant::CONSORTIUM['display_name'], strtoupper($fed->name), \config\Master::APPEARANCE['productname'], \config\Master::APPEARANCE['productname_long']);
424
                $user->sendMailToUser(sprintf(_("%s in your federation was deleted"), common\Entity::$nomenclature_participant), $message);
425
            }
426
        }
427
        common\Entity::outOfThePotatoes();
428
    }
429
430
    /**
431
     * Performs a lookup in an external database to determine matching entities to this IdP. 
432
     * 
433
     * The business logic of this function is roaming consortium specific; if no match algorithm is known for the consortium, FALSE is returned.
434
     * 
435
     * @param string $type which type of entity are you looking for?
436
     * @return array list of entities in external database that correspond to this IdP
437
     */
438
    public function getExternalDBSyncCandidates($type)
439
    {
440
        $usedarray = [];
441
        $matchingCandidates = [];
442
        $syncstate = self::EXTERNAL_DB_SYNCSTATE_SYNCED;
443
        $alreadyUsed = $this->databaseHandle->exec("SELECT DISTINCT external_db_id FROM institution WHERE external_db_id IS NOT NULL AND external_db_syncstate = ?", "i", $syncstate);
444
        // SELECT -> resource, not boolean
445
        while ($alreadyUsedQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $alreadyUsed)) {
446
            $usedarray[] = $alreadyUsedQuery->external_db_id;
447
        }
448
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
449
            // extract all institutions from the country
450
            $list = [];
451
            $lowerFed = strtolower($this->federation);
452
            $eduroamDb = new ExternalEduroamDBData();
453
            $candidateList = $eduroamDb->listExternalEntities($lowerFed, $type);
454
            // and split them into ID, LANG, NAME pairs (operating on a resource, not boolean)
455
            foreach ($candidateList as $oneCandidate) {
456
                if (in_array($oneCandidate['ID'], $usedarray)) {
457
                    continue;
458
                }
459
                $list[] = $oneCandidate;
460
            }
461
            // now see if any of the languages in CAT match the best one we have got from DB
462
            $mynames = $this->getAttributes("general:instname");
463
            foreach ($mynames as $onename) {
464
                foreach ($list as $listentry) {
465
                    if ($onename['value'] == $listentry['name'] && array_search($listentry['ID'], $matchingCandidates) === FALSE) {
466
                        $matchingCandidates[] = $listentry['ID'];
467
                    }
468
                }
469
            }
470
        }
471
        return $matchingCandidates;
472
    }
473
474
    /**
475
     * returns the state of sync with the external DB.
476
     * 
477
     * @return int
478
     */
479
    public function getExternalDBSyncState()
480
    {
481
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
482
            return $this->externalDbSyncstate;
483
        }
484
        return self::EXTERNAL_DB_SYNCSTATE_NOTSUBJECTTOSYNCING;
485
    }
486
487
    /**
488
     * Retrieves the external DB identifier of this institution. Returns FALSE if no ID is known.
489
     * 
490
     * @return string|boolean the external identifier; or FALSE if no external ID is known
491
     */
492
    public function getExternalDBId()
493
    {
494
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
495
            $idQuery = $this->databaseHandle->exec("SELECT external_db_id FROM institution WHERE inst_id = $this->identifier AND external_db_syncstate = " . self::EXTERNAL_DB_SYNCSTATE_SYNCED);
496
            // SELECT -> it's a resource, not a boolean
497
            if (mysqli_num_rows(/** @scrutinizer ignore-type */ $idQuery) == 0) {
498
                return FALSE;
499
            }
500
            $externalIdQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $idQuery);
501
            return $externalIdQuery->external_db_id;
502
        }
503
        return FALSE;
504
    }
505
506
    /**
507
     * Associates the external DB id with a CAT id
508
     * 
509
     * @param string $identifier the external DB id, which can be alphanumeric
510
     * @return void
511
     */
512
    public function setExternalDBId(string $identifier)
513
    {
514
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
515
            $syncState = self::EXTERNAL_DB_SYNCSTATE_SYNCED;
516
            $alreadyUsed = $this->databaseHandle->exec("SELECT DISTINCT external_db_id FROM institution WHERE external_db_id = ? AND external_db_syncstate = ?", "si", $identifier, $syncState);
517
            // SELECT -> resource, not boolean
518
            if (mysqli_num_rows(/** @scrutinizer ignore-type */ $alreadyUsed) == 0) {
519
                $this->databaseHandle->exec("UPDATE institution SET external_db_id = ?, external_db_syncstate = ? WHERE inst_id = ?", "sii", $identifier, $syncState, $this->identifier);
520
            }
521
        }
522
    }
523
524
    /**
525
     * removes the link between a CAT institution and the external DB
526
     * 
527
     * @return void
528
     */
529
    public function removeExternalDBId()
530
    {
531
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
532
            if ($this->getExternalDBId() !== FALSE) {
533
                $syncState = self::EXTERNAL_DB_SYNCSTATE_NOT_SYNCED;
534
                $this->databaseHandle->exec("UPDATE institution SET external_db_id = NULL, external_db_syncstate = ? WHERE inst_id = ?", "ii", $syncState, $this->identifier);
535
            }
536
        }
537
    }
538
539
    public const INSTNAME_CHANGED = 1;
540
541
    /**
542
     * 
543
     * @param IdP $old the IdP instance with the old state
544
     * @param IdP $new the IdP instance with the new state
545
     * @return array list of changed things, and details about the change
546
     */
547
    public static function significantChanges($old, $new)
548
    {
549
        // check if the name of the inst was changed (in any language)
550
        $retval = [];
551
        $baseline = [];
552
        $newvalues = [];
553
        foreach ($old->getAttributes("general:instname") as $oldname) {
554
            $baseline[$oldname['lang']] = $oldname['value'];
555
        }
556
        foreach ($new->getAttributes("general:instname") as $newname) {
557
            $newvalues[$newname['lang']] = $newname['value'];
558
        }
559
        foreach ($baseline as $lang => $value) {
560
            if (!key_exists($lang, $newvalues)) {
561
                $retval[IdP::INSTNAME_CHANGED] .= "#[Language " . strtoupper($lang) . "] DELETED";
562
            } else {
563
                if ($value != $newvalues[$lang]) {
564
                    $retval[IdP::INSTNAME_CHANGED] .= "#[Language " . strtoupper($lang) . "] CHANGED from '" . $baseline[$lang] . "' to '" . $newvalues[$lang] . "'";
565
                }
566
            }
567
        }
568
        foreach ($newvalues as $lang => $value) {
569
            if (!key_exists($lang, $baseline)) {
570
                $retval[IdP::INSTNAME_CHANGED] .= "#[Language " . strtoupper($lang) . "] ADDED as '" . $value . "'";
571
            }
572
        }
573
        return $retval;
574
    }
575
}
576