AbstractProfile   F
last analyzed

Complexity

Total Complexity 152

Size/Duplication

Total Lines 990
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 152
eloc 445
c 3
b 0
f 0
dl 0
loc 990
rs 2

26 Methods

Rating   Name   Duplication   Size   Complexity  
A testCache() 0 17 5
A addDatabaseAttributes() 0 8 1
B significantChanges() 0 42 10
A destroy() 0 5 1
A readinessLevel() 0 13 3
F openroamingRedinessTest() 0 117 22
A prepShowtime() 0 14 6
B incrementDownloadStats() 0 20 7
A getEapMethodsinOrderOfPreference() 0 13 4
B getCollapsedAttributes() 0 34 10
A __construct() 0 32 4
C isEapTypeDefinitionComplete() 0 33 12
A fetchEAPMethods() 0 14 2
A setOpenRoamingReadinessInfo() 0 3 1
A getRealmCheckOuterUsername() 0 19 4
A certificateStatus() 0 20 4
A addSupportedEapMethod() 0 5 1
F listDevices() 0 96 28
A saveDownloadDetails() 0 9 3
B getUserDownloadStats() 0 27 7
B readyForShowtime() 0 28 9
A addInternalAttributes() 0 14 2
A setRealm() 0 4 1
A updateFreshness() 0 3 1
A getFreshness() 0 6 2
A profileFromRealm() 0 10 2

How to fix   Complexity   

Complex Class

Complex classes like AbstractProfile 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 AbstractProfile, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/*
4
 * *****************************************************************************
5
 * Contributions to this work were made on behalf of the GÉANT project, a 
6
 * project that has received funding from the European Union’s Framework 
7
 * Programme 7 under Grant Agreements No. 238875 (GN3) and No. 605243 (GN3plus),
8
 * Horizon 2020 research and innovation programme under Grant Agreements No. 
9
 * 691567 (GN4-1) and No. 731122 (GN4-2).
10
 * On behalf of the aforementioned projects, GEANT Association is the sole owner
11
 * of the copyright in all material which was developed by a member of the GÉANT
12
 * project. GÉANT Vereniging (Association) is registered with the Chamber of 
13
 * Commerce in Amsterdam with registration number 40535155 and operates in the 
14
 * UK as a branch of GÉANT Vereniging.
15
 * 
16
 * Registered office: Hoekenrode 3, 1102BR Amsterdam, The Netherlands. 
17
 * UK branch address: City House, 126-130 Hills Road, Cambridge CB2 1PQ, UK
18
 *
19
 * License: see the web/copyright.inc.php file in the file structure or
20
 *          <base_url>/copyright.php after deploying the software
21
 */
22
23
/**
24
 * This file contains the AbstractProfile class. It contains common methods for
25
 * both RADIUS/EAP profiles and SilverBullet profiles
26
 *
27
 * @author Stefan Winter <[email protected]>
28
 * @author Tomasz Wolniewicz <[email protected]>
29
 *
30
 * @package Developer
31
 *
32
 */
33
34
namespace core;
35
36
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...
37
38
/**
39
 * This class represents an EAP Profile.
40
 * Profiles can inherit attributes from their IdP, if the IdP has some. Otherwise,
41
 * one can set attribute in the Profile directly. If there is a conflict between
42
 * IdP-wide and Profile-wide attributes, the more specific ones (i.e. Profile) win.
43
 * 
44
 * @author Stefan Winter <[email protected]>
45
 * @author Tomasz Wolniewicz <[email protected]>
46
 *
47
 * @license see LICENSE file in root directory
48
 *
49
 * @package Developer
50
 */
51
abstract class AbstractProfile extends EntityWithDBProperties
52
{
53
54
    const HIDDEN = -1;
55
    const AVAILABLE = 0;
56
    const UNAVAILABLE = 1;
57
    const INCOMPLETE = 2;
58
    const NOTCONFIGURED = 3;
59
    const PROFILETYPE_RADIUS = "RADIUS";
60
    const PROFILETYPE_SILVERBULLET = "SILVERBULLET";
61
    public const SERVERNAME_ADDED = 2;
62
    public const CA_ADDED = 3;
63
    public const CA_CLASH_ADDED = 4;
64
    public const SERVER_CERT_ADDED = 5;
65
    public const CA_ROOT_NO_EXT = 6;
66
67
    /**
68
     * DB identifier of the parent institution of this profile
69
     * @var integer
70
     */
71
    public $institution;
72
73
    /**
74
     * name of the parent institution of this profile in the current language
75
     * @var string
76
     */
77
    public $instName;
78
79
    /**
80
     * realm of this profile (empty string if unset)
81
     * @var string
82
     */
83
    public $realm;
84
85
    /**
86
     * This array holds the supported EAP types (in object representation). 
87
     * 
88
     * They are not synced against the DB after instantiation.
89
     * 
90
     * @var array
91
     */
92
    protected $privEaptypes;
93
94
    /**
95
     * number of profiles of the IdP this profile is attached to
96
     * 
97
     * @var integer
98
     */
99
    protected $idpNumberOfProfiles;
100
101
    /**
102
     * IdP-wide attributes of the IdP this profile is attached to
103
     * 
104
     * @var array
105
     */
106
    protected $idpAttributes;
107
108
    /**
109
     * Federation level attributes that this profile is attached to via its IdP
110
     * 
111
     * @var array
112
     */
113
    protected $fedAttributes;
114
115
    /**
116
     * This class also needs to handle frontend operations, so needs its own
117
     * access to the FRONTEND database. This member stores the corresponding 
118
     * handle.
119
     * 
120
     * @var DBConnection
121
     */
122
    protected $frontendHandle;
123
124
    /**
125
     * readiness levels for OpenRoaming column in profiles)
126
     */
127
    const OVERALL_OPENROAMING_LEVEL_NO = 4;
128
    const OVERALL_OPENROAMING_LEVEL_GOOD = 3;
129
    const OVERALL_OPENROAMING_LEVEL_NOTE = 2;
130
    const OVERALL_OPENROAMING_LEVEL_WARN = 1;
131
    const OVERALL_OPENROAMING_LEVEL_ERROR = 0;
132
    
133
/**
134
 * constants used for displaying messages
135
 */    
136
    const OPENROAMING_ALL_GOOD = 24;
137
    const OPENROAMING_NO_REALM = 17; //none
138
    const OPENROAMING_BAD_SRV = 16; //none
139
    const OPENROAMING_BAD_NAPTR = 10; // warning
140
    const OPENROAMING_SOME_BAD_CONNECTIONS = 8; //warning
141
    const OPENROAMING_NO_DNSSEC = 8; //warning
142
    const OPENROAMING_NO_NAPTR = 3; //error
143
    const OPENROAMING_BAD_NAPTR_RESOLVE = 2; //error
144
    const OPENROAMING_BAD_SRV_RESOLVE = 1; //error
145
    const OPENROAMING_BAD_CONNECTION = 0; //error
146
    
147
    
148
    const READINESS_LEVEL_NOTREADY = 0;
149
    const READINESS_LEVEL_SUFFICIENTCONFIG = 1;
150
    const READINESS_LEVEL_SHOWTIME = 2;
151
    
152
    
153
    const CERT_STATUS_OK = 0;
154
    const CERT_STATUS_WARN = 1;
155
    const CERT_STATUS_ERROR = 2;
156
    
157
    const OVERALL_OPENROAMING_INDEX = [
158
        self::OVERALL_OPENROAMING_LEVEL_NO => 'OVERALL_OPENROAMING_LEVEL_NO',
159
        self::OVERALL_OPENROAMING_LEVEL_GOOD => 'OVERALL_OPENROAMING_LEVEL_GOOD',
160
        self::OVERALL_OPENROAMING_LEVEL_NOTE => 'OVERALL_OPENROAMING_LEVEL_NOTE',
161
        self::OVERALL_OPENROAMING_LEVEL_WARN => 'OVERALL_OPENROAMING_LEVEL_WARN',
162
        self::OVERALL_OPENROAMING_LEVEL_ERROR => 'OVERALL_OPENROAMING_LEVEL_ERROR',      
163
    ];
164
165
    const OPENROAMING_INDEX = [
166
        self::OVERALL_OPENROAMING_LEVEL_NO => 'OVERALL_OPENROAMING_LEVEL_NO',
167
    ];
168
    
169
    const CERT_STATUS_INDEX = [
170
        self::CERT_STATUS_OK => 'CERT_STATUS_OK',
171
        self::CERT_STATUS_WARN => 'CERT_STATUS_WARN',
172
        self::CERT_STATUS_ERROR => 'CERT_STATUS_ERROR',     
173
    ];
174
    
175
    /**
176
     *  generates a detailed log of which installer was downloaded
177
     * 
178
     * @param int    $idpIdentifier the IdP identifier
179
     * @param int    $profileId     the Profile identifier
180
     * @param string $deviceId      the Device identifier
181
     * @param string $area          the download area (user, silverbullet, admin)
182
     * @param string $lang          the language of the installer
183
     * @param int    $eapType       the EAP type of the installer
184
     * @return void
185
     * @throws Exception
186
     */
187
    protected function saveDownloadDetails($idpIdentifier, $profileId, $deviceId, $area, $lang, $eapType, $openRoaming)
188
    {
189
        if (\config\Master::PATHS['logdir']) {
190
            $file = fopen(\config\Master::PATHS['logdir']."/download_details.log", "a");
191
            if ($file === FALSE) {
192
                throw new Exception("Unable to open file for append: $file");
193
            }
194
            fprintf($file, "%-015s;%d;%d;%s;%s;%s;%d;%d\n", microtime(TRUE), $idpIdentifier, $profileId, $deviceId, $area, $lang, $eapType, $openRoaming);
195
            fclose($file);
196
        }
197
    }
198
199
    /**
200
     * checks if security-relevant parameters have changed
201
     * 
202
     * @param AbstractProfile $old old instantiation of a profile to compare against
203
     * @param AbstractProfile $new new instantiation of a profile 
204
     * @return array there are never any user-induced changes in SB
205
     */
206
    public static function significantChanges($old, $new)
207
    {
208
        $retval = [];
209
        // check if a CA was added
210
        $x509 = new common\X509();
211
        $baselineCA = [];
212
        $baselineCApublicKey = [];
213
        foreach ($old->getAttributes("eap:ca_file") as $oldCA) {
214
            $ca = $x509->processCertificate($oldCA['value']);
215
            $baselineCA[$ca['sha1']] = $ca['name'];
216
            $baselineCApublicKey[$ca['sha1']] = $ca['full_details']['public_key'];
217
        }
218
        // remove the new ones that are identical to the baseline
219
        foreach ($new->getAttributes("eap:ca_file") as $newCA) {
220
            $ca = $x509->processCertificate($newCA['value']);
221
            if (array_key_exists($ca['sha1'], $baselineCA) || $ca['root'] != 1) {
222
                // do nothing; we assume here that SHA1 doesn't clash
223
                continue;
224
            }
225
            // check if a CA with identical DN was added - alert NRO if so
226
            $foundSHA1 = array_search($ca['name'], $baselineCA);
227
            if ($foundSHA1 !== FALSE) {
228
                // but only if the public key does not match
229
                if ($baselineCApublicKey[$foundSHA1] === $ca['full_details']['public_key']) {
230
                    continue;
231
                }
232
                $retval[AbstractProfile::CA_CLASH_ADDED] .= "#SHA1 for CA with DN '".$ca['name']."' has SHA1 fingerprints (pre-existing) "./** @scrutinizer ignore-type */ array_search($ca['name'], $baselineCA)." and (added) ".$ca['sha1'];
233
            } else {
234
                $retval[AbstractProfile::CA_ADDED] .= "#CA with DN '"./** @scrutinizer ignore-type */ print_r($ca['name'], TRUE)."' and SHA1 fingerprint ".$ca['sha1']." was added as trust anchor";
235
            }
236
        }
237
        // check if a servername was added
238
        $baselineNames = [];
239
        foreach ($old->getAttributes("eap:server_name") as $oldName) {
240
            $baselineNames[] = $oldName['value'];
241
        }
242
        foreach ($new->getAttributes("eap:server_name") as $newName) {
243
            if (!in_array($newName['value'], $baselineNames)) {
244
                $retval[AbstractProfile::SERVERNAME_ADDED] .= "#New server name '".$newName['value']."' added";
245
            }
246
        }
247
        return $retval;
248
    }
249
250
    /**
251
     * Tests OpenRoaming aspects of the profile like DNS settings and server reachibility
252
     * 
253
     * @return array of arrays of the form [['level' => $level, 'explanation' => $explanation, 'reason' => $reason]];
254
     */
255
    public function openroamingRedinessTest() {
256
        // do OpenRoaming initial diagnostic checks
257
        // numbers correspond to RFC7585Tests::OVERALL_LEVEL
258
        $results = [];
259
        $resultLevel = $this::OVERALL_OPENROAMING_LEVEL_GOOD; // assume all is well, degrade if we have concrete findings to suggest otherwise
260
        $tag = "aaa+auth:radius.tls.tcp";
261
        // do we know the realm at all? Notice if not.
262
        if (!isset($this->getAttributes("internal:realm")[0]['value'])) {
263
            $explanation = _("The profile information does not include the realm, so no DNS checks for OpenRoaming can be executed.");
264
            $level = $this::OVERALL_OPENROAMING_LEVEL_NOTE;
265
            $reason = $this::OPENROAMING_NO_REALM;
266
            $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
267
            $resultLevel = min([$resultLevel, $level]);
268
        } else {
269
            $dnsChecks = new \core\diag\RFC7585Tests($this->getAttributes("internal:realm")[0]['value'], $tag);
270
            $relevantNaptrRecords = $dnsChecks->relevantNAPTR();
271
            if ($relevantNaptrRecords <= 0) {
272
                $explanation = _("There is no relevant DNS NAPTR record ($tag) for this realm. OpenRoaming will not work.");
273
                $reason = $this::OPENROAMING_NO_NAPTR;
274
                $level = $this::OVERALL_OPENROAMING_LEVEL_ERROR;
275
                $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
276
                $resultLevel = min([$resultLevel, $level]);
277
            } else {
278
                $recordCompliance = $dnsChecks->relevantNAPTRcompliance();
279
                if ($recordCompliance != \core\diag\AbstractTest::RETVAL_OK) {
280
                    $explanation = _("The DNS NAPTR record ($tag) for this realm is not syntax conform. OpenRoaming will likely not work.");
281
                    $reason = $this::OPENROAMING_BAD_NAPTR;
282
                    $level = $this::OVERALL_OPENROAMING_LEVEL_WARN;
283
                    $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
284
                    $resultLevel = min([$resultLevel, $level]);
285
                }
286
                // check if target is the expected one, if set by NRO
287
                foreach ($this->fedAttributes as $attr) {
288
                    if ($attr['name'] === 'fed:openroaming_customtarget') {
289
                        $customText = $attr['value'];
290
                    } else {
291
                        $customText = '';
292
                    }
293
                }
294
                if ($customText !== '') {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $customText seems to be defined by a foreach iteration on line 287. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
295
                    foreach ($dnsChecks->NAPTR_records as $orpointer) {
296
                        if ($orpointer["replacement"] != $customText) {
297
                            $explanation = _("The SRV target of an OpenRoaming NAPTR record is unexpected.");
298
                            $reason = $this::OPENROAMING_BAD_SRV;
299
                            $level = $this::OVERALL_OPENROAMING_LEVEL_NOTE;
300
                            $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
301
                            $resultLevel = min([$resultLevel, $level]);
302
                        }
303
                    }
304
                }
305
                $srvResolution = $dnsChecks->relevantNAPTRsrvResolution();
306
                $hostnameResolution = $dnsChecks->relevantNAPTRhostnameResolution();
307
308
                if ($srvResolution <= 0) {
309
                    $explanation = _("The DNS SRV target for NAPTR $tag does not resolve. OpenRoaming will not work.");
310
                    $level = $this::OVERALL_OPENROAMING_LEVEL_ERROR;
311
                    $reason = $this::OPENROAMING_BAD_NAPTR_RESOLVE;
312
                    $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
313
                    $resultLevel = min([$resultLevel, $this::OVERALL_OPENROAMING_LEVEL_ERROR]);
314
                } elseif ($hostnameResolution <= 0) {
315
                    $explanation = _("The DNS hostnames in the SRV records do not resolve to actual host IPs. OpenRoaming will not work.");
316
                    $level = $this::OVERALL_OPENROAMING_LEVEL_ERROR;
317
                    $reason = $this::OPENROAMING_BAD_SRV_RESOLVE;
318
                    $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
319
                    $resultLevel = min([$resultLevel, $level]);
320
                }
321
                // connect to all IPs we found and see if they are really an OpenRoaming server
322
                $allHostsOkay = TRUE;
323
                $oneHostOkay = FALSE;
324
                $testCandidates = [];
325
                foreach ($dnsChecks->NAPTR_hostname_records as $oneServer) {
326
                    $testCandidates[$oneServer['hostname']][] = ($oneServer['family'] == "IPv4" ? $oneServer['IP'] : "[".$oneServer['IP']."]").":".$oneServer['port'];
327
                }
328
                foreach ($testCandidates as $oneHost => $listOfIPs) {
329
                    $connectionTests = new \core\diag\RFC6614Tests(array_values($listOfIPs), $oneHost, "openroaming");
330
                    // for now (no OpenRoaming client certs available) only run server-side tests
331
                    foreach ($listOfIPs as $oneIP) {
332
                        $connectionResult = $connectionTests->cApathCheck($oneIP);
333
                        if ($connectionResult != \core\diag\AbstractTest::RETVAL_OK || ( isset($connectionTests->TLS_CA_checks_result['cert_oddity']) && count($connectionTests->TLS_CA_checks_result['cert_oddity']) > 0)) {
334
                            $allHostsOkay = FALSE;
335
                        } else {
336
                            $oneHostOkay = TRUE;
337
                        }
338
                    }
339
                }
340
                if (!$allHostsOkay) {
341
                    if (!$oneHostOkay) {
342
                        $explanation = _("When connecting to the discovered OpenRoaming endpoints, they all had errors. OpenRoaming will likely not work.");
343
                        $level = $this::OVERALL_OPENROAMING_LEVEL_ERROR;
344
                        $reason = $this::OPENROAMING_BAD_CONNECTION;
345
                        $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
346
                        $resultLevel = min([$resultLevel, $level]);
347
                    } else {
348
                        $explanation = _("When connecting to the discovered OpenRoaming endpoints, only a subset of endpoints had no errors.");
349
                        $level = $this::OVERALL_OPENROAMING_LEVEL_WARN;
350
                        $reason = $this::OPENROAMING_SOME_BAD_CONNECTIONS;
351
                        $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
352
                        $resultLevel = min([$resultLevel, $level]);
353
                    }
354
                }
355
            }
356
        }
357
        if (!$dnsChecks->allResponsesSecure) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $dnsChecks does not seem to be defined for all execution paths leading up to this point.
Loading history...
358
            $explanation = _("At least one DNS response was NOT secured using DNSSEC. OpenRoaming ANPs may refuse to connect to the endpoint.");
359
            $level = $this::OVERALL_OPENROAMING_LEVEL_WARN;
360
            $reason = $this::OPENROAMING_NO_DNSSEC;
361
            $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
362
            $resultLevel = min([$resultLevel, $level]);
363
        }
364
        if ($resultLevel == $this::OVERALL_OPENROAMING_LEVEL_GOOD) {
365
            $explanation = _("Initial diagnostics regarding the DNS part of OpenRoaming (including DNSSEC) were successful.");
366
            $level = $this::OVERALL_OPENROAMING_LEVEL_GOOD;
367
            $reason = $this::OPENROAMING_ALL_GOOD;
368
            $results = [['level' => $level, 'explanation' => $explanation, 'reason' => $reason]];
369
        }               
370
        $this->setOpenRoamingReadinessInfo($resultLevel);
371
        return $results;
372
    }
373
    
374
    /**
375
     * Takes note of the OpenRoaming participation and conformance level
376
     * 
377
     * @param int $level the readiness level, as determined by RFC7585Tests
378
     * @return void
379
     */
380
    public function setOpenRoamingReadinessInfo(int $level)
381
    {
382
            $this->databaseHandle->exec("UPDATE profile SET openroaming = ? WHERE profile_id = ?", "ii", $level, $this->identifier);
383
    }
384
385
    /**
386
     * each profile has supported EAP methods, so get this from DB, Silver Bullet has one
387
     * static EAP method.
388
     * 
389
     * @return array list of supported EAP methods
390
     */
391
    protected function fetchEAPMethods()
392
    {
393
        $eapMethod = $this->databaseHandle->exec("SELECT eap_method_id 
394
                                                        FROM supported_eap supp 
395
                                                        WHERE supp.profile_id = $this->identifier 
396
                                                        ORDER by preference");
397
        $eapTypeArray = [];
398
        // SELECTs never return a boolean, it's always a resource
399
        while ($eapQuery = (mysqli_fetch_object(/** @scrutinizer ignore-type */ $eapMethod))) {
400
            $eaptype = new common\EAP($eapQuery->eap_method_id);
401
            $eapTypeArray[] = $eaptype;
402
        }
403
        $this->loggerInstance->debug(4, "This profile supports the following EAP types:\n"./** @scrutinizer ignore-type */ print_r($eapTypeArray, true));
404
        return $eapTypeArray;
405
    }
406
407
    /**
408
     * Class constructor for existing profiles (use IdP::newProfile() to actually create one). Retrieves all attributes and 
409
     * supported EAP types from the DB and stores them in the priv_ arrays.
410
     * 
411
     * sub-classes need to set the property $realm, $name themselves!
412
     * 
413
     * @param int $profileIdRaw identifier of the profile in the DB
414
     * @param IdP $idpObject    optionally, the institution to which this Profile belongs. Saves the construction of the IdP instance. If omitted, an extra query and instantiation is executed to find out.
415
     * @throws Exception
416
     */
417
    public function __construct($profileIdRaw, $idpObject = NULL)
418
    {
419
        $this->databaseType = "INST";
420
        parent::__construct(); // we now have access to our INST database handle and logging
421
        $handle = DBConnection::handle("FRONTEND");
422
        if ($handle instanceof DBConnection) {
423
            $this->frontendHandle = $handle;
424
        } else {
425
            throw new Exception("This database type is never an array!");
426
        }
427
        $profile = $this->databaseHandle->exec("SELECT inst_id FROM profile WHERE profile_id = ?", "i", $profileIdRaw);
428
        // SELECT always yields a resource, never a boolean
429
        if ($profile->num_rows == 0) {
430
            $this->loggerInstance->debug(2, "Profile $profileIdRaw not found in database!\n");
431
            throw new Exception("Profile $profileIdRaw not found in database!");
432
        }
433
        $this->identifier = $profileIdRaw;
434
        $profileQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $profile);
435
        if (!($idpObject instanceof IdP)) {
436
            $this->institution = $profileQuery->inst_id;
437
            $idp = new IdP($this->institution);
438
        } else {
439
            $idp = $idpObject;
440
            $this->institution = $idp->identifier;
441
        }
442
443
        $this->instName = $idp->name;
444
        $this->idpNumberOfProfiles = $idp->profileCount();
445
        $this->idpAttributes = $idp->getAttributes();
446
        $fedObject = new Federation($idp->federation);
447
        $this->fedAttributes = $fedObject->getAttributes();
448
        $this->loggerInstance->debug(4, "--- END Constructing new AbstractProfile object ... ---\n");
449
    }
450
451
    /**
452
     * find a profile, given its realm
453
     * 
454
     * @param string $realm the realm for which we are trying to find a profile
455
     * @return int|false the profile identifier, if any
456
     */
457
    public static function profileFromRealm($realm)
458
    {
459
        // static, need to create our own handle
460
        $handle = DBConnection::handle("INST");
461
        $execQuery = $handle->exec("SELECT profile_id FROM profile WHERE realm LIKE '%@$realm'");
462
        // a SELECT query always yields a resource, not a boolean
463
        if ($profileIdQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $execQuery)) {
464
            return $profileIdQuery->profile_id;
465
        }
466
        return FALSE;
467
    }
468
469
    /**
470
     * Constructs the outer ID which should be used during realm tests. Obviously
471
     * can only do something useful if the realm is known to the system.
472
     * 
473
     * @return string the outer ID to use for realm check operations
474
     * @throws Exception
475
     */
476
    public function getRealmCheckOuterUsername()
477
    {
478
        $realm = $this->getAttributes("internal:realm")[0]['value'] ?? FALSE;
479
        if ($realm == FALSE) { // we can't really return anything useful here
480
            throw new Exception("Unable to construct a realmcheck username if the admin did not tell us the realm. You shouldn't have called this function in this context.");
481
        }
482
        if (count($this->getAttributes("internal:checkuser_outer")) > 0) {
483
            // we are supposed to use a specific outer username for checks, 
484
            // which is different from the outer username we put into installers
485
            return $this->getAttributes("internal:checkuser_value")[0]['value']."@".$realm;
486
        }
487
        if (count($this->getAttributes("internal:use_anon_outer")) > 0) {
488
            // no special check username, but there is an anon outer ID for
489
            // installers - so let's use that one
490
            return $this->getAttributes("internal:anon_local_value")[0]['value']."@".$realm;
491
        }
492
        // okay, no guidance on outer IDs at all - but we need *something* to
493
        // test with for the RealmChecks. So:
494
        return "@".$realm;
495
    }
496
497
    /**
498
     * update the last_changed timestamp for this profile
499
     * 
500
     * @return void
501
     */
502
    public function updateFreshness()
503
    {
504
        $this->databaseHandle->exec("UPDATE profile SET last_change = CURRENT_TIMESTAMP WHERE profile_id = $this->identifier");
505
    }
506
507
    /**
508
     * gets the last-modified timestamp (useful for caching "dirty" check)
509
     * 
510
     * @return string the date in string form, as returned by SQL
511
     */
512
    public function getFreshness()
513
    {
514
        $execLastChange = $this->databaseHandle->exec("SELECT last_change FROM profile WHERE profile_id = $this->identifier");
515
        // SELECT always returns a resource, never a boolean
516
        if ($freshnessQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $execLastChange)) {
517
            return $freshnessQuery->last_change;
518
        }
519
    }
520
    /**
521
     * tests if the configurator needs to be regenerated
522
     * returns the configurator path or NULL if regeneration is required
523
     */
524
    /**
525
     * This function tests if the configurator needs to be regenerated 
526
     * (properties of the Profile may have changed since the last configurator 
527
     * generation).
528
     * SilverBullet will always return NULL here because all installers are new!
529
     * 
530
     * @param string $device device ID to check
531
     * @return mixed a string with the path to the configurator download, or NULL if it needs to be regenerated
532
     */
533
534
    /**
535
     * This function tests if the configurator needs to be regenerated (properties of the Profile may have changed since the last configurator generation).
536
     * 
537
     * @param string $device device ID to check
538
     * @return mixed a string with the path to the configurator download, or NULL if it needs to be regenerated
539
     */
540
    public function testCache($device, $openRoaming)
541
    {
542
        $returnValue = ['cache' => NULL, 'mime' => NULL];
543
        $lang = $this->languageInstance->getLang();
544
        $result = $this->frontendHandle->exec("SELECT download_path, mime, UNIX_TIMESTAMP(installer_time) AS tm FROM downloads WHERE profile_id = ? AND device_id = ? AND lang = ? AND openroaming = ?", "issi", $this->identifier, $device, $lang, $openRoaming);
545
        // SELECT queries always return a resource, not a boolean
546
        if ($result && $cache = mysqli_fetch_object(/** @scrutinizer ignore-type */ $result)) {
547
            $execUpdate = $this->databaseHandle->exec("SELECT UNIX_TIMESTAMP(last_change) AS last_change FROM profile WHERE profile_id = $this->identifier");
548
            // SELECT queries always return a resource, not a boolean
549
            if ($lastChange = mysqli_fetch_object(/** @scrutinizer ignore-type */ $execUpdate)->last_change) {
550
                if ($lastChange < $cache->tm) {
551
                    $this->loggerInstance->debug(4, "Installer cached:$cache->download_path\n");
552
                    $returnValue = ['cache' => $cache->download_path, 'mime' => $cache->mime];
553
                }
554
            }
555
        }
556
        return $returnValue;
557
    }
558
559
    /**
560
     * Updates database with new installer location. Actually does stuff when
561
     * caching is possible; is a noop if not
562
     * 
563
     * @param string $device         the device identifier string
564
     * @param string $path           the path where the new installer can be found
565
     * @param string $mime           the mime type of the new installer
566
     * @param int    $integerEapType the inter-representation of the EAP type that is configured in this installer
567
     * @return void
568
     */
569
    abstract public function updateCache($device, $path, $mime, $integerEapType, $openRoaming);
570
571
    /** Toggle anonymous outer ID support.
572
     *
573
     * @param boolean $shallwe TRUE to enable outer identities (needs valid $realm), FALSE to disable
574
     * @return void
575
     */
576
    abstract public function setAnonymousIDSupport($shallwe);
577
578
    /**
579
     * Log a new download for our stats
580
     * 
581
     * @param string $device the device id string
582
     * @param string $area   either admin or user
583
     * @return boolean TRUE if incrementing worked, FALSE if not
584
     */
585
    public function incrementDownloadStats($device, $area, $openRoaming)
586
    {
587
        if ($area == "admin" || $area == "user" || $area == "silverbullet") {
588
            $lang = $this->languageInstance->getLang();
589
            $this->frontendHandle->exec("INSERT INTO downloads (profile_id, device_id, lang, openroaming, downloads_$area) VALUES (? ,?, ?, ?, 1) ON DUPLICATE KEY UPDATE downloads_$area = downloads_$area + 1", "issi", $this->identifier, $device, $lang, $openRoaming);
590
            // get eap_type from the downloads table
591
            $eapTypeQuery = $this->frontendHandle->exec("SELECT eap_type FROM downloads WHERE profile_id = ? AND device_id = ? AND lang = ?", "iss", $this->identifier, $device, $lang);
592
            // SELECT queries always return a resource, not a boolean
593
            if (!$eapTypeQuery || !$eapO = mysqli_fetch_object(/** @scrutinizer ignore-type */ $eapTypeQuery)) {
594
                $this->loggerInstance->debug(2, "Error getting EAP_type from the database\n");
595
            } else {
596
                if ($eapO->eap_type == NULL) {
597
                    $this->loggerInstance->debug(2, "EAP_type not set in the database\n");
598
                } else {
599
                    $this->saveDownloadDetails($this->institution, $this->identifier, $device, $area, $this->languageInstance->getLang(), $eapO->eap_type, $openRoaming);
600
                }
601
            }
602
            return TRUE;
603
        }
604
        return FALSE;
605
    }
606
607
    /**
608
     * Retrieve current download stats from database, either for one specific device or for all devices
609
     * 
610
     * @param string $device the device id string
611
     * @return mixed user downloads of this profile; if device is given, returns the counter as int, otherwise an array with devicename => counter
612
     */
613
    public function getUserDownloadStats($device = NULL)
614
    {
615
        $columnName = "downloads_user";
616
        if ($this instanceof \core\ProfileSilverbullet) {
617
            $columnName = "downloads_silverbullet";
618
        }
619
        $returnarray = [];
620
        $numbers = $this->frontendHandle->exec("SELECT device_id, SUM($columnName) AS downloads_user FROM downloads WHERE profile_id = ? GROUP BY device_id", "i", $this->identifier);
621
        // SELECT queries always return a resource, not a boolean
622
        while ($statsQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $numbers)) {
623
            $returnarray[$statsQuery->device_id] = $statsQuery->downloads_user;
624
        }
625
        if ($device !== NULL) {
626
            if (isset($returnarray[$device])) {
627
                return $returnarray[$device];
628
            }
629
            return 0;
630
        }
631
        // we should pretty-print the device names
632
        $finalarray = [];
633
        $devlist = \devices\Devices::listDevices($this->identifier);
634
        foreach ($returnarray as $devId => $count) {
635
            if (isset($devlist[$devId])) {
636
                $finalarray[$devlist[$devId]['display']] = $count;
637
            }
638
        }
639
        return $finalarray;
640
    }
641
642
    /**
643
     * Deletes the profile from database and uninstantiates itself.
644
     * Works fine also for Silver Bullet; the first query will simply do nothing
645
     * because there are no stored options
646
     * 
647
     * @return void
648
     */
649
    public function destroy()
650
    {
651
        $this->databaseHandle->exec("DELETE FROM profile_option WHERE profile_id = $this->identifier");
652
        $this->databaseHandle->exec("DELETE FROM supported_eap WHERE profile_id = $this->identifier");
653
        $this->databaseHandle->exec("DELETE FROM profile WHERE profile_id = $this->identifier");
654
    }
655
656
    /**
657
     * Specifies the realm of this profile.
658
     * 
659
     * Forcefully type-hinting $realm parameter to string - Scrutinizer seems to
660
     * think that it can alternatively be an array<integer,?> which looks like a
661
     * false positive. If there really is an issue, let PHP complain about it at
662
     * runtime.
663
     * 
664
     * @param string $realm the realm (potentially with the local@ part that should be used for anonymous identities)
665
     * @return void
666
     */
667
    public function setRealm(string $realm)
668
    {
669
        $this->databaseHandle->exec("UPDATE profile SET realm = ? WHERE profile_id = ?", "si", $realm, $this->identifier);
670
        $this->realm = $realm;
671
    }
672
673
    /**
674
     * register new supported EAP method for this profile
675
     *
676
     * @param \core\common\EAP $type       The EAP Type, as defined in class EAP
677
     * @param int              $preference preference of this EAP Type. If a preference value is re-used, the order of EAP types of the same preference level is undefined.
678
     * @return void
679
     */
680
    public function addSupportedEapMethod(\core\common\EAP $type, $preference)
681
    {
682
        $eapInt = $type->getIntegerRep();
683
        $this->databaseHandle->exec("INSERT INTO supported_eap (profile_id, eap_method_id, preference) VALUES (?, ?, ?)", "iii", $this->identifier, $eapInt, $preference);
684
        $this->updateFreshness();
685
    }
686
687
    /**
688
     * Produces an array of EAP methods supported by this profile, ordered by preference
689
     * 
690
     * @param int $completeOnly if set and non-zero limits the output to methods with complete information
691
     * @return array list of EAP methods, (in object representation)
692
     */
693
    public function getEapMethodsinOrderOfPreference($completeOnly = 0)
694
    {
695
        $temparray = [];
696
697
        if ($completeOnly == 0) {
698
            return $this->privEaptypes;
699
        }
700
        foreach ($this->privEaptypes as $type) {
701
            if ($this->isEapTypeDefinitionComplete($type) === true) {
702
                $temparray[] = $type;
703
            }
704
        }
705
        return($temparray);
706
    }
707
708
    /**
709
     * Performs a sanity check for a given EAP type - did the admin submit enough information to create installers for him?
710
     * 
711
     * @param common\EAP $eaptype the EAP type
712
     * @return mixed TRUE if the EAP type is complete; an array of missing attributes if it's incomplete; FALSE if it's incomplete for other reasons
713
     */
714
    public function isEapTypeDefinitionComplete($eaptype)
715
    {
716
        if ($eaptype->needsServerCACert() && $eaptype->needsServerName()) {
717
            $missing = [];
718
            // silverbullet needs a support email address configured
719
            if ($eaptype->getIntegerRep() == common\EAP::INTEGER_SILVERBULLET && count($this->getAttributes("support:email")) == 0) {
720
                return ["support:email"];
721
            }
722
            $cnOption = $this->getAttributes("eap:server_name"); // cannot be set per device or eap type
723
            $caOption = $this->getAttributes("eap:ca_file"); // cannot be set per device or eap type
724
725
            if (count($caOption) > 0 && count($cnOption) > 0) {// see if we have at least one root CA cert
726
                foreach ($caOption as $oneCa) {
727
                    $x509 = new \core\common\X509();
728
                    $caParsed = $x509->processCertificate($oneCa['value']);
729
                    if ($caParsed['root'] == 1) {
730
                        return TRUE;
731
                    }
732
                }
733
                $missing[] = "eap:ca_file";
734
            }
735
            if (count($caOption) == 0) {
736
                $missing[] = "eap:ca_file";
737
            }
738
            if (count($cnOption) == 0) {
739
                $missing[] = "eap:server_name";
740
            }
741
            if (count($missing) == 0) {
742
                return TRUE;
743
            }
744
            return $missing;
745
        }
746
        return TRUE;
747
    }
748
749
    /**
750
     * list all devices marking their availabiblity and possible redirects
751
     *
752
     * @return array of device ids display names and their status
753
     */
754
    public function listDevices()
755
    {
756
        $returnarray = [];
757
        $redirect = $this->getAttributes("device-specific:redirect"); // this might return per-device ones or the general one
758
        // if it was a general one, we are done. Find out if there is one such
759
        // which has device = NULL
760
        $generalRedirect = NULL;
761
        foreach ($redirect as $index => $oneRedirect) {
762
            if ($oneRedirect["level"] == Options::LEVEL_PROFILE) {
763
                $generalRedirect = $index;
764
            }
765
        }
766
        if ($generalRedirect !== NULL) { // could be index 0
767
            return [['id' => '0', 'redirect' => $redirect[$generalRedirect]['value']]];
768
        }
769
        $preferredEap = $this->getEapMethodsinOrderOfPreference(1);
770
        $eAPOptions = [];
771
        if (count($this->getAttributes("media:openroaming")) == 1 && $this->getAttributes("media:openroaming")[0]['value'] == 'always-preagreed') {
772
            $orAlways = 1;
773
        } else {
774
            $orAlways = 0;
775
        }
776
        
777
        foreach (\devices\Devices::listDevices($this->identifier, $orAlways) as $deviceIndex => $deviceProperties) {
778
            $factory = new DeviceFactory($deviceIndex);
779
            $dev = $factory->device;
780
            // find the attribute pertaining to the specific device
781
            $group = '';
782
            $redirectUrl = 0;
783
            $redirects = [];
784
            foreach ($redirect as $index => $oneRedirect) {
785
                if ($oneRedirect["device"] == $deviceIndex) {
786
                    $redirects[] = $oneRedirect;
787
                }
788
            }
789
            if (count($redirects) > 0) {
790
                $redirectUrl = $this->languageInstance->getLocalisedValue($redirects);
791
            }
792
            $devStatus = self::AVAILABLE;
793
            $message = 0;
794
            if (isset($deviceProperties['options']) && isset($deviceProperties['options']['message']) && $deviceProperties['options']['message']) {
795
                $message = $deviceProperties['options']['message'];
796
            }
797
            if (isset($deviceProperties['group'])) {
798
                $group = $deviceProperties['group'];
799
            }
800
            $eapCustomtext = 0;
801
            $deviceCustomtext = 0;
802
            $geteduroam = 0;
803
            if ($redirectUrl === 0) {
804
                if (isset($deviceProperties['options']) && isset($deviceProperties['options']['redirect']) && $deviceProperties['options']['redirect']) {
805
                    $devStatus = self::HIDDEN;
806
                } else {
807
                    $dev->calculatePreferredEapType($preferredEap);
808
                    $eap = $dev->selectedEap;
809
                    if (count($eap) > 0) {
810
                        if (isset($eAPOptions["eap-specific:customtext"][serialize($eap)])) {
811
                            $eapCustomtext = $eAPOptions["eap-specific:customtext"][serialize($eap)];
812
                        } else {
813
                            // fetch customtexts from method-level attributes
814
                            $eapCustomtext = 0;
815
                            $customTextAttributes = [];
816
                            $attributeList = $this->getAttributes("eap-specific:customtext"); // eap-specific attributes always have the array index 'eapmethod' set
817
                            foreach ($attributeList as $oneAttribute) {
818
                                if ($oneAttribute["eapmethod"] == $eap) {
819
                                    $customTextAttributes[] = $oneAttribute;
820
                                }
821
                            }
822
                            if (count($customTextAttributes) > 0) {
823
                                $eapCustomtext = $this->languageInstance->getLocalisedValue($customTextAttributes);
824
                            }
825
                            $eAPOptions["eap-specific:customtext"][serialize($eap)] = $eapCustomtext;
826
                        }
827
                        // fetch customtexts for device
828
                        $customTextAttributes = [];
829
                        $attributeList = $this->getAttributes("device-specific:customtext");
830
                        foreach ($attributeList as $oneAttribute) {
831
                            if ($oneAttribute["device"] == $deviceIndex) { // device-specific attributes always have the array index "device" set
832
                                $customTextAttributes[] = $oneAttribute;
833
                            }
834
                        }
835
                        $deviceCustomtext = $this->languageInstance->getLocalisedValue($customTextAttributes);
836
                    } else {
837
                        $devStatus = self::UNAVAILABLE;
838
                    }
839
                    $geteduroamOpts = $this->getAttributes("device-specific:geteduroam");
840
                    foreach ($geteduroamOpts as $dev) {
841
                        if ($dev['device'] == $deviceIndex) {
842
                            $geteduroam = $dev['value'] == 'on' ? 1 : 0;
843
                        }
844
                    }
845
                }
846
            }
847
            $returnarray[] = ['id' => $deviceIndex, 'display' => $deviceProperties['display'], 'status' => $devStatus, 'redirect' => $redirectUrl, 'eap_customtext' => $eapCustomtext, 'device_customtext' => $deviceCustomtext, 'message' => $message, 'options' => $deviceProperties['options'], 'group' => $group, 'geteduroam' => $geteduroam];
848
        }
849
        return $returnarray;
850
    }
851
852
    /**
853
     * prepare profile attributes for device modules
854
     * Gets profile attributes taking into account the most specific level on which they may be defined
855
     * as well as the chosen language.
856
     * can be called with an optional $eap argument
857
     * 
858
     * @param array $eap if specified, retrieves all attributes except those not pertaining to the given EAP type
859
     * @return array list of attributes in collapsed style (index is the attrib name, value is an array of different values)
860
     */
861
    public function getCollapsedAttributes($eap = [])
862
    {
863
        $collapsedList = [];
864
        foreach ($this->getAttributes() as $attribute) {
865
            // filter out eap-level attributes not pertaining to EAP type $eap
866
            if (count($eap) > 0 && isset($attribute['eapmethod']) && $attribute['eapmethod'] != 0 && $attribute['eapmethod'] != $eap) {
867
                continue;
868
            }
869
            // create new array indexed by attribute name
870
            
871
            if (isset($attribute['device'])) {
872
                $collapsedList[$attribute['name']][$attribute['device']][] = $attribute['value'];
873
            } else {
874
                $collapsedList[$attribute['name']][] = $attribute['value'];
875
            } 
876
            // and keep all language-variant names in a separate sub-array
877
            if ($attribute['flag'] == "ML") {
878
                $collapsedList[$attribute['name']]['langs'][$attribute['lang']] = $attribute['value'];
879
            }
880
        }
881
        // once we have the final list, populate the respective "best-match"
882
        // language to choose for the ML attributes
883
884
        foreach ($collapsedList as $attribName => $valueArray) {
885
            if (isset($valueArray['langs'])) { // we have at least one language-dependent name in this attribute
886
                // for printed names on screen:
887
                // assign to exact match language, fallback to "default" language, fallback to English, fallback to whatever comes first in the list
888
                $collapsedList[$attribName][0] = $valueArray['langs'][$this->languageInstance->getLang()] ?? $valueArray['langs']['C'] ?? $valueArray['langs']['en'] ?? array_shift($valueArray['langs']);
889
                // for names usable in filesystems (closer to good old ASCII...)
890
                // prefer English, otherwise the "default" language, otherwise the same that we got above
891
                $collapsedList[$attribName][1] = $valueArray['langs']['en'] ?? $valueArray['langs']['C'] ?? $collapsedList[$attribName][0];
892
            }
893
        }
894
        return $collapsedList;
895
    }
896
    
897
    /**
898
     * Does the profile contain enough information to generate installers with
899
     * it? Silverbullet will always return TRUE; RADIUS profiles need to do some
900
     * heavy lifting here.
901
     * 
902
     * @return int one of the constants above which tell if enough info is set to enable installers
903
     */
904
    public function readinessLevel()
905
    {
906
        $result = $this->databaseHandle->exec("SELECT sufficient_config, showtime FROM profile WHERE profile_id = ?", "i", $this->identifier);
907
        // SELECT queries always return a resource, not a boolean
908
        $configQuery = mysqli_fetch_row(/** @scrutinizer ignore-type */ $result);
909
        if ($configQuery[0] == "0") {
910
            return self::READINESS_LEVEL_NOTREADY;
911
        }
912
        // at least fully configured, if not showtime!
913
        if ($configQuery[1] == "0") {
914
            return self::READINESS_LEVEL_SUFFICIENTCONFIG;
915
        }
916
        return self::READINESS_LEVEL_SHOWTIME;
917
    }
918
919
    /**
920
     * Checks all profile certificates validity periods comparing to the pre-defined
921
     * thresholds and returns the most critical status.
922
     * 
923
     * @return int - one of constants defined in this profile
924
     */
925
    public function certificateStatus()
926
    {
927
        $query = "SELECT option_value AS cert FROM profile_option  WHERE option_name='eap:ca_file' AND profile_id = ?";        
928
        $result = $this->databaseHandle->exec($query, "i", $this->identifier);
929
        $rows = $result->fetch_all();
930
        $x509 = new \core\common\X509();
931
        $profileStatus = self::CERT_STATUS_OK;
932
        foreach ($rows as $row) {
933
            $encodedCert = $row[0];
934
            $tm = $x509->processCertificate(base64_decode($encodedCert))['full_details']['validTo_time_t']- time();
935
            if ($tm < \config\ConfAssistant::CERT_WARNINGS['expiry_critical']) {
936
                $certStatus = self::CERT_STATUS_ERROR;
937
            } elseif ($tm < \config\ConfAssistant::CERT_WARNINGS['expiry_warning']) {
938
                $certStatus = self::CERT_STATUS_WARN;
939
            } else {
940
                $certStatus = self::CERT_STATUS_OK;
941
            }
942
            $profileStatus = max($profileStatus, $certStatus);
943
        }
944
        return $profileStatus;
945
    }
946
947
    /**
948
     * Checks if the profile has enough information to have something to show to end users. This does not necessarily mean
949
     * that there's a fully configured EAP type - it is sufficient if a redirect has been set for at least one device.
950
     * 
951
     * @return boolean TRUE if enough information for showtime is set; FALSE if not
952
     */
953
    private function readyForShowtime()
954
    {
955
        $properConfig = FALSE;
956
        $attribs = $this->getCollapsedAttributes();
957
        // do we have enough to go live? Check if any of the configured EAP methods is completely configured ...
958
        if (sizeof($this->getEapMethodsinOrderOfPreference(1)) > 0) {
959
            $properConfig = TRUE;
960
        }
961
        // if not, it could still be that general redirect has been set
962
        if (!$properConfig) {
963
            if (isset($attribs['device-specific:redirect'])) {
964
                $properConfig = TRUE;
965
            }
966
            // just a per-device redirect? would be good enough... but this is not actually possible:
967
            // per-device redirects can only be set on the "fine-tuning" page, which is only accessible
968
            // if at least one EAP type is fully configured - which is caught above and makes readyForShowtime TRUE already
969
        }
970
        // do we know at least one SSID to configure, or work with wired? If not, it's not ready...
971
        if (!isset($attribs['media:SSID']) &&
972
                (!isset(\config\ConfAssistant::CONSORTIUM['ssid']) || count(\config\ConfAssistant::CONSORTIUM['ssid']) == 0) &&
973
                !isset($attribs['media:wired'])) {
974
            $properConfig = FALSE;
975
        }
976
        // institutions without a name are not really a corner case we should support
977
        if (!isset($attribs['general:instname'])) {
978
            $properConfig = FALSE;
979
        }
980
        return $properConfig;
981
    }
982
983
    /**
984
     * set the showtime property if prepShowTime says that there is enough info *and* the admin flagged the profile for showing
985
     * 
986
     * @return void
987
     */
988
    public function prepShowtime()
989
    {
990
        $properConfig = $this->readyForShowtime();
991
        $this->databaseHandle->exec("UPDATE profile SET sufficient_config = ".($properConfig ? "TRUE" : "FALSE")." WHERE profile_id = ".$this->identifier);
992
993
        $attribs = $this->getCollapsedAttributes();
994
        // if not enough info to go live, set FALSE
995
        // even if enough info is there, admin has the ultimate say: 
996
        //   if he doesn't want to go live, no further checks are needed, set FALSE as well
997
        if (!$properConfig || !isset($attribs['profile:production']) || (isset($attribs['profile:production']) && $attribs['profile:production'][0] != "on")) {
998
            $this->databaseHandle->exec("UPDATE profile SET showtime = FALSE WHERE profile_id = ?", "i", $this->identifier);
999
            return;
1000
        }
1001
        $this->databaseHandle->exec("UPDATE profile SET showtime = TRUE WHERE profile_id = ?", "i", $this->identifier);
1002
    }
1003
1004
    /**
1005
     * internal helper - some attributes are added by the constructor "ex officio"
1006
     * without actual input from the admin. We can streamline their addition in
1007
     * this function to avoid duplication.
1008
     * 
1009
     * @param array $internalAttributes - only names and value
1010
     * @return array full attributes with all properties set
1011
     */
1012
    protected function addInternalAttributes($internalAttributes)
1013
    {
1014
        // internal attributes share many attribute properties, so condense the generation
1015
        $retArray = [];
1016
        foreach ($internalAttributes as $attName => $attValue) {
1017
            $retArray[] = ["name" => $attName,
1018
                "lang" => NULL,
1019
                "value" => $attValue,
1020
                "level" => Options::LEVEL_PROFILE,
1021
                "row_id" => 0,
1022
                "flag" => NULL,
1023
            ];
1024
        }
1025
        return $retArray;
1026
    }
1027
1028
    /**
1029
     * Retrieves profile attributes stored in the database
1030
     * 
1031
     * @return array The attributes in one array
1032
     */
1033
    protected function addDatabaseAttributes()
1034
    {
1035
        $databaseAttributes = $this->retrieveOptionsFromDatabase("SELECT DISTINCT option_name, option_lang, option_value, row_id
1036
                FROM $this->entityOptionTable
1037
                WHERE $this->entityIdColumn = ?
1038
                AND device_id IS NULL AND eap_method_id = 0
1039
                ORDER BY option_name", "Profile");
1040
        return $databaseAttributes;
1041
    }
1042
}
1043