IdP   F
last analyzed

Complexity

Total Complexity 81

Size/Duplication

Total Lines 513
Duplicated Lines 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 81
eloc 203
c 1
b 1
f 0
dl 0
loc 513
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 destroy() 0 36 5
A updateFreshness() 0 5 1
A maxProfileStatus() 0 8 2
A maxOpenRoamingStatus() 0 8 3
A eligibility() 0 11 4
A isPrimaryOwner() 0 8 4
B getExternalDBSyncCandidates() 0 34 11
A profileCount() 0 10 2
A deploymentCount() 0 10 2
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 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();
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 ... ---\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" : "");
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
    
175
    const PROFILES_INDEX = [
176
        self::PROFILES_INCOMPLETE => 'PROFILES_INCOMPLETE',
177
        self::PROFILES_CONFIGURED => 'PROFILES_CONFIGURED',
178
        self::PROFILES_SHOWTIME => 'PROFILES_SHOWTIME',
179
    ];
180
181
    /**
182
     * looks through all the profiles of the inst and determines the highest prod-ready level among the profiles
183
     * @return int highest level of completeness of all the profiles of the inst
184
     */
185
    public function maxProfileStatus()
186
    {
187
        $allProfiles = $this->databaseHandle->exec("SELECT sufficient_config + showtime AS maxlevel FROM profile WHERE inst_id = $this->identifier ORDER BY maxlevel DESC LIMIT 1");
188
        // SELECT yields a resource, not a boolean
189
        while ($res = mysqli_fetch_object(/** @scrutinizer ignore-type */ $allProfiles)) {
190
            return $res->maxlevel;
191
        }
192
        return self::PROFILES_INCOMPLETE;
193
    }
194
195
    /**
196
     * looks through all the profiles of the inst and determines the highest 
197
     * participation/conformance level for OpenRoaming
198
     * 
199
     * @return int highest level of completeness of all the profiles of the inst
200
     */
201
    public function maxOpenRoamingStatus()
202
    {
203
        $allProfiles = $this->databaseHandle->exec("SELECT MIN(openroaming) AS maxlevel FROM profile WHERE inst_id = $this->identifier");
204
        // SELECT yields a resource, not a boolean
205
        while ($res = mysqli_fetch_object(/** @scrutinizer ignore-type */ $allProfiles)) {
206
            return (is_numeric($res->maxlevel) ? (int)$res->maxlevel : AbstractProfile::OVERALL_OPENROAMING_LEVEL_NO ); // insts without profiles should get a "NO"
207
        }
208
        return AbstractProfile::OVERALL_OPENROAMING_LEVEL_NO;
209
    }
210
    
211
    
212
    /** This function retrieves an array of authorised users which can
213
     * manipulate this institution.
214
     * 
215
     * @return array owners of the institution; numbered array with members ID, MAIL and LEVEL
216
     */
217
    public function listOwners()
218
    {
219
        $returnarray = [];
220
        $admins = $this->databaseHandle->exec("SELECT user_id, orig_mail, blesslevel FROM ownership WHERE institution_id = $this->identifier ORDER BY user_id");
221
        // SELECT -> resource, not boolean
222
        while ($ownerQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $admins)) {
223
            $returnarray[] = ['ID' => $ownerQuery->user_id, 'MAIL' => $ownerQuery->orig_mail, 'LEVEL' => $ownerQuery->blesslevel];
224
        }
225
        return $returnarray;
226
    }
227
228
    /**
229
     * Primary owners are allowed to invite other (secondary) admins to the institution
230
     * 
231
     * @param string $user ID of a logged-in user
232
     * @return boolean TRUE if this user is an admin with FED-level blessing
233
     */
234
    public function isPrimaryOwner($user)
235
    {
236
        foreach ($this->listOwners() as $oneOwner) {
237
            if ($oneOwner['ID'] == $user && $oneOwner['LEVEL'] == "FED") {
238
                return TRUE;
239
            }
240
        }
241
        return FALSE;
242
    }
243
244
    /**
245
     * This function gets the profile count for a given IdP.
246
     * 
247
     * The count could be retrieved from the listProfiles method
248
     * but this is less expensive.
249
     *
250
     * @return int profile count
251
     */
252
    public function profileCount()
253
    {
254
        $result = $this->databaseHandle->exec("SELECT profile_id FROM profile 
255
             WHERE inst_id = $this->identifier");
256
        // SELECT -> resource, not boolean
257
        $numberOfRows = mysqli_num_rows(/** @scrutinizer ignore-type */ $result);
258
        if (is_string($numberOfRows)) {
259
            throw new Exception("Number of profiles > PHP_MAX_INT?");
260
        }
261
        return $numberOfRows;
262
    }
263
264
    /**
265
     * This function gets the deployment count for a given IdP.
266
     *
267
     * @return int deployment count
268
     */
269
    public function deploymentCount()
270
    {
271
        $result = $this->databaseHandle->exec("SELECT deployment_id FROM deployment
272
             WHERE inst_id = $this->identifier");
273
        // SELECT -> resource, not boolean
274
        $numberOfRows = mysqli_num_rows(/** @scrutinizer ignore-type */ $result);
275
        if (is_string($numberOfRows)) {
276
            throw new Exception("Number of deployments > PHP_MAX_INT?");
277
        }
278
        return $numberOfRows;
279
    }
280
281
    const ELIGIBILITY_IDP = "IdP";
282
    const ELIGIBILITY_SP = "SP";
283
284
    /**
285
     * checks whether the participant is an IdP, an SP, or both.
286
     * 
287
     * @return array list of eligibilities
288
     */
289
    public function eligibility()
290
    {
291
        $eligibilites = $this->databaseHandle->exec("SELECT type FROM institution WHERE inst_id = $this->identifier");
292
        while ($iterator = mysqli_fetch_object(/** @scrutinizer ignore-type */ $eligibilites)) {
293
            switch ($iterator->type) {
294
                case "IdP":
295
                    return [IdP::ELIGIBILITY_IDP];
296
                case "SP":
297
                    return [IdP::ELIGIBILITY_SP];
298
                default:
299
                    return [IdP::ELIGIBILITY_IDP, IdP::ELIGIBILITY_SP];
300
            }
301
        }
302
    }
303
304
    /**
305
     * This function sets the timestamp of last modification of the child profiles to the current timestamp.
306
     * 
307
     * This is needed for installer caching: all installers which are on disk 
308
     * must be re-created if an attribute changes. This timestamp here
309
     * is used to determine if the installer on disk is still new enough.
310
     * 
311
     * @return void
312
     */
313
    public function updateFreshness()
314
    {
315
        // freshness is always defined for *Profiles*
316
        // IdP needs to update timestamp of all its profiles if an IdP-wide attribute changed
317
        $this->databaseHandle->exec("UPDATE profile SET last_change = CURRENT_TIMESTAMP WHERE inst_id = '$this->identifier'");
318
    }
319
320
    /**
321
     * Adds a new profile to this IdP.
322
     * 
323
     * Only creates the DB entry for the Profile. If you want to add attributes later, see Profile::addAttribute().
324
     *
325
     * @param string $type exactly "RADIUS" or "SILVERBULLET", all other values throw an Exception
326
     * @return AbstractProfile|NULL new Profile object if successful, or NULL if an error occurred
327
     * @throws Exception
328
     */
329
    public function newProfile(string $type)
330
    {
331
        $this->databaseHandle->exec("INSERT INTO profile (inst_id) VALUES($this->identifier)");
332
        $identifier = $this->databaseHandle->lastID();
333
        if ($identifier > 0) {
334
            switch ($type) {
335
                case AbstractProfile::PROFILETYPE_RADIUS:
336
                    return new ProfileRADIUS($identifier, $this);
337
                case AbstractProfile::PROFILETYPE_SILVERBULLET:
338
                    $theProfile = new ProfileSilverbullet($identifier, $this);
339
                    $theProfile->addSupportedEapMethod(new \core\common\EAP(\core\common\EAP::EAPTYPE_SILVERBULLET), 1);
340
                    $theProfile->setRealm($this->identifier . "-" . $theProfile->identifier . "." . strtolower($this->federation) . strtolower(\config\ConfAssistant::SILVERBULLET['realm_suffix']));
341
                    return $theProfile;
342
                default:
343
                    throw new Exception("This type of profile is unknown and can not be added.");
344
            }
345
        }
346
        return NULL;
347
    }
348
349
    /**
350
     * Adds a new hotspot deployment to this IdP.
351
     * 
352
     * Only creates the DB entry for the deployment. If you want to add attributes later, see Profile::addAttribute().
353
     *
354
     * @param string $type       exactly "RADIUS-SP" or "MANAGED-SP", all other values throw an Exception
355
     * @param string $consortium name of the consortium to attach this *Managed* SP to
356
     * @return DeploymentManaged the newly created deployment
357
     * @throws Exception
358
     */
359
    public function newDeployment(string $type, string $consortium = "eduroam")
360
    {
361
        switch ($type) {
362
            case AbstractDeployment::DEPLOYMENTTYPE_CLASSIC:
363
                // classic deployment exist in the eduroam DB. We don't do anything here.
364
                throw new Exception("This type of deployment is handled externally and requesting it here makes no sense.");
365
            case AbstractDeployment::DEPLOYMENTTYPE_MANAGED:
366
                $this->databaseHandle->exec("INSERT INTO deployment (inst_id) VALUES($this->identifier)");
367
                $identifier = $this->databaseHandle->lastID();
368
                return new DeploymentManaged($this, $identifier, $consortium);
369
            default:
370
                throw new Exception("This type of deployment is unknown and can not be added.");
371
        }
372
    }
373
374
    /**
375
     * deletes the IdP and all its profiles
376
     * 
377
     * @return void
378
     * @throws Exception
379
     */
380
    public function destroy()
381
    {
382
        common\Entity::intoThePotatoes();
383
        /* delete all profiles */
384
        foreach ($this->listProfiles() as $profile) {
385
            $profile->destroy();
386
        }
387
        /* double-check that all profiles are gone */
388
        $profiles = $this->listProfiles();
389
390
        if (count($profiles) > 0) {
391
            throw new Exception("This IdP shouldn't have any profiles any more!");
392
        }
393
394
        $this->databaseHandle->exec("DELETE FROM ownership WHERE institution_id = $this->identifier");
395
        $this->databaseHandle->exec("DELETE FROM institution_option WHERE institution_id = $this->identifier");
396
        $this->databaseHandle->exec("DELETE FROM institution WHERE inst_id = $this->identifier");
397
398
        // notify federation admins
399
        if (\config\Master::MAILSETTINGS['notify_nro']) {
400
            $fed = new Federation($this->federation);
401
            foreach ($fed->listFederationAdmins() as $id) {
402
                $user = new User($id);
403
                $message = sprintf(_("Hi,
404
405
    the %s %s in your %s federation %s has been deleted from %s.
406
407
    We thought you might want to know.
408
409
    Best regards,
410
411
    %s"), common\Entity::$nomenclature_participant, $this->name, \config\ConfAssistant::CONSORTIUM['display_name'], strtoupper($fed->name), \config\Master::APPEARANCE['productname'], \config\Master::APPEARANCE['productname_long']);
412
                $user->sendMailToUser(sprintf(_("%s in your federation was deleted"), common\Entity::$nomenclature_participant), $message);
413
            }
414
        }
415
        common\Entity::outOfThePotatoes();
416
    }
417
418
    /**
419
     * Performs a lookup in an external database to determine matching entities to this IdP. 
420
     * 
421
     * The business logic of this function is roaming consortium specific; if no match algorithm is known for the consortium, FALSE is returned.
422
     * 
423
     * @param string $type which type of entity are you looking for?
424
     * @return array list of entities in external database that correspond to this IdP
425
     */
426
    public function getExternalDBSyncCandidates($type)
427
    {
428
        $usedarray = [];
429
        $matchingCandidates = [];
430
        $syncstate = self::EXTERNAL_DB_SYNCSTATE_SYNCED;
431
        $alreadyUsed = $this->databaseHandle->exec("SELECT DISTINCT external_db_id FROM institution WHERE external_db_id IS NOT NULL AND external_db_syncstate = ?", "i", $syncstate);
432
        // SELECT -> resource, not boolean
433
        while ($alreadyUsedQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $alreadyUsed)) {
434
            $usedarray[] = $alreadyUsedQuery->external_db_id;
435
        }
436
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
437
            // extract all institutions from the country
438
            $list = [];
439
            $lowerFed = strtolower($this->federation);
440
            $eduroamDb = new ExternalEduroamDBData();
441
            $candidateList = $eduroamDb->listExternalEntities($lowerFed, $type);
442
            // and split them into ID, LANG, NAME pairs (operating on a resource, not boolean)
443
            foreach ($candidateList as $oneCandidate) {
444
                if (in_array($oneCandidate['ID'], $usedarray)) {
445
                    continue;
446
                }
447
                $list[] = $oneCandidate;
448
            }
449
            // now see if any of the languages in CAT match the best one we have got from DB
450
            $mynames = $this->getAttributes("general:instname");
451
            foreach ($mynames as $onename) {
452
                foreach ($list as $listentry) {
453
                    if ($onename['value'] == $listentry['name'] && array_search($listentry['ID'], $matchingCandidates) === FALSE) {
454
                        $matchingCandidates[] = $listentry['ID'];
455
                    }
456
                }
457
            }
458
        }
459
        return $matchingCandidates;
460
    }
461
462
    /**
463
     * returns the state of sync with the external DB.
464
     * 
465
     * @return int
466
     */
467
    public function getExternalDBSyncState()
468
    {
469
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
470
            return $this->externalDbSyncstate;
471
        }
472
        return self::EXTERNAL_DB_SYNCSTATE_NOTSUBJECTTOSYNCING;
473
    }
474
475
    /**
476
     * Retrieves the external DB identifier of this institution. Returns FALSE if no ID is known.
477
     * 
478
     * @return string|boolean the external identifier; or FALSE if no external ID is known
479
     */
480
    public function getExternalDBId()
481
    {
482
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
483
            $idQuery = $this->databaseHandle->exec("SELECT external_db_id FROM institution WHERE inst_id = $this->identifier AND external_db_syncstate = " . self::EXTERNAL_DB_SYNCSTATE_SYNCED);
484
            // SELECT -> it's a resource, not a boolean
485
            if (mysqli_num_rows(/** @scrutinizer ignore-type */ $idQuery) == 0) {
486
                return FALSE;
487
            }
488
            $externalIdQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $idQuery);
489
            return $externalIdQuery->external_db_id;
490
        }
491
        return FALSE;
492
    }
493
494
    /**
495
     * Associates the external DB id with a CAT id
496
     * 
497
     * @param string $identifier the external DB id, which can be alphanumeric
498
     * @return void
499
     */
500
    public function setExternalDBId(string $identifier)
501
    {
502
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
503
            $syncState = self::EXTERNAL_DB_SYNCSTATE_SYNCED;
504
            $alreadyUsed = $this->databaseHandle->exec("SELECT DISTINCT external_db_id FROM institution WHERE external_db_id = ? AND external_db_syncstate = ?", "si", $identifier, $syncState);
505
            // SELECT -> resource, not boolean
506
            if (mysqli_num_rows(/** @scrutinizer ignore-type */ $alreadyUsed) == 0) {
507
                $this->databaseHandle->exec("UPDATE institution SET external_db_id = ?, external_db_syncstate = ? WHERE inst_id = ?", "sii", $identifier, $syncState, $this->identifier);
508
            }
509
        }
510
    }
511
512
    /**
513
     * removes the link between a CAT institution and the external DB
514
     * 
515
     * @return void
516
     */
517
    public function removeExternalDBId()
518
    {
519
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
520
            if ($this->getExternalDBId() !== FALSE) {
521
                $syncState = self::EXTERNAL_DB_SYNCSTATE_NOT_SYNCED;
522
                $this->databaseHandle->exec("UPDATE institution SET external_db_id = NULL, external_db_syncstate = ? WHERE inst_id = ?", "ii", $syncState, $this->identifier);
523
            }
524
        }
525
    }
526
527
    public const INSTNAME_CHANGED = 1;
528
529
    /**
530
     * 
531
     * @param IdP $old the IdP instance with the old state
532
     * @param IdP $new the IdP instance with the new state
533
     * @return array list of changed things, and details about the change
534
     */
535
    public static function significantChanges($old, $new)
536
    {
537
        // check if the name of the inst was changed (in any language)
538
        $retval = [];
539
        $baseline = [];
540
        $newvalues = [];
541
        foreach ($old->getAttributes("general:instname") as $oldname) {
542
            $baseline[$oldname['lang']] = $oldname['value'];
543
        }
544
        foreach ($new->getAttributes("general:instname") as $newname) {
545
            $newvalues[$newname['lang']] = $newname['value'];
546
        }
547
        foreach ($baseline as $lang => $value) {
548
            if (!key_exists($lang, $newvalues)) {
549
                $retval[IdP::INSTNAME_CHANGED] .= "#[Language " . strtoupper($lang) . "] DELETED";
550
            } else {
551
                if ($value != $newvalues[$lang]) {
552
                    $retval[IdP::INSTNAME_CHANGED] .= "#[Language " . strtoupper($lang) . "] CHANGED from '" . $baseline[$lang] . "' to '" . $newvalues[$lang] . "'";
553
                }
554
            }
555
        }
556
        foreach ($newvalues as $lang => $value) {
557
            if (!key_exists($lang, $baseline)) {
558
                $retval[IdP::INSTNAME_CHANGED] .= "#[Language " . strtoupper($lang) . "] ADDED as '" . $value . "'";
559
            }
560
        }
561
        return $retval;
562
    }
563
}
564