Test Setup Failed
Push — master ( 80c824...0d60d0 )
by Stefan
05:10
created

DeviceConfig::setup()   D

Complexity

Conditions 16
Paths 257

Size

Total Lines 90
Code Lines 53

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
eloc 53
c 3
b 0
f 1
dl 0
loc 90
rs 4.0208
cc 16
nc 257
nop 3

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * *****************************************************************************
5
 * Contributions to this work were made on behalf of the GÉANT project, a 
6
 * project that has received funding from the European Union’s Framework 
7
 * Programme 7 under Grant Agreements No. 238875 (GN3) and No. 605243 (GN3plus),
8
 * Horizon 2020 research and innovation programme under Grant Agreements No. 
9
 * 691567 (GN4-1) and No. 731122 (GN4-2).
10
 * On behalf of the aforementioned projects, GEANT Association is the sole owner
11
 * of the copyright in all material which was developed by a member of the GÉANT
12
 * project. GÉANT Vereniging (Association) is registered with the Chamber of 
13
 * Commerce in Amsterdam with registration number 40535155 and operates in the 
14
 * UK as a branch of GÉANT Vereniging.
15
 * 
16
 * Registered office: Hoekenrode 3, 1102BR Amsterdam, The Netherlands. 
17
 * UK branch address: City House, 126-130 Hills Road, Cambridge CB2 1PQ, UK
18
 *
19
 * License: see the web/copyright.inc.php file in the file structure or
20
 *          <base_url>/copyright.php after deploying the software
21
 */
22
23
/**
24
 * This file defines the abstract Device class
25
 *
26
 * @package ModuleWriting
27
 */
28
/**
29
 * 
30
 */
31
32
namespace core;
33
34
use \Exception;
35
36
/**
37
 * This class defines the API for CAT module writers.
38
 *
39
 * A device is a fairly abstract notion. In most cases it represents
40
 * a particular operating system or a set of operationg systems
41
 * like MS Windows Vista and newer.
42
 *
43
 * The purpose of this class is to preapare a setup for the device configurator,
44
 * collect all necessary information from the database, taking into account
45
 * limitations, that a given device may present (like a set of supported EAP methods).
46
 *
47
 * All that is required from the device module is to produce a conigurator
48
 * file and pass its name back to the API.
49
 *
50
 * 
51
 * @author Tomasz Wolniewicz <[email protected]>
52
 *
53
 * @license see LICENSE file in root directory
54
 * 
55
 * @package ModuleWriting
56
 * @abstract
57
 */
58
abstract class DeviceConfig extends \core\common\Entity
59
{
60
61
    /**
62
     * stores the path to the temporary working directory for a module instance
63
     * @var string $FPATH
64
     */
65
    public $FPATH;
66
67
    /**
68
     * array of specialities - will be displayed on the admin download as "footnote"
69
     * @var array specialities
70
     */
71
    public $specialities;
72
73
    /**
74
     * list of supported EAP methods
75
     * @var array EAP methods
76
     */
77
    public $supportedEapMethods;
78
79
    /**
80
     * sets the supported EAP methods for a device
81
     * 
82
     * @param array $eapArray the list of EAP methods the device supports
83
     * @return void
84
     */
85
    protected function setSupportedEapMethods($eapArray)
86
    {
87
        $this->supportedEapMethods = $eapArray;
88
        $this->loggerInstance->debug(4, "This device (" . __CLASS__ . ") supports the following EAP methods: ");
89
        $this->loggerInstance->debug(4, $this->supportedEapMethods);
90
    }
91
92
    /**
93
     * device module constructor should be defined by each module. 
94
     * The one important thing to do is to call setSupportedEapMethods with an 
95
     * array of EAP methods the device supports
96
     */
97
    public function __construct()
98
    {
99
        parent::__construct();
100
    }
101
102
    /**
103
     * given one or more server name strings, calculate the suffix that is common
104
     * to all of them
105
     * 
106
     * Examples:
107
     * 
108
     * ["host.somewhere.com", "gost.somewhere.com"] => "ost.somewhere.com"
109
     * ["my.server.name"] => "my.server.name"
110
     * ["foo.bar.de", "baz.bar.ge"] => "e"
111
     * ["server1.example.com", "server2.example.com", "serverN.example.com"] => ".example.com"
112
113
     * @return string
114
     */
115
    public function longestNameSuffix()
116
    {
117
        // for all configured server names, find the string that is the longest
118
        // suffix to all of them
119
        $longestSuffix = "";
120
        if (!isset($this->attributes["eap:server_name"])) {
121
            return "";
122
        }
123
        $numStrings = count($this->attributes["eap:server_name"]);
124
        if ($numStrings == 0) {
125
            return "";
126
        }
127
        // always take the candidate character from the first array element, and
128
        // verify whether the other elements have that character in the same 
129
        // position, too
130
        while (TRUE) {
131
            if ($longestSuffix == $this->attributes["eap:server_name"][0]) {
132
                break;
133
            }
134
            $candidate = substr($this->attributes["eap:server_name"][0], -(strlen($longestSuffix) + 1), 1);
135
            for ($iterator = 1; $iterator < $numStrings; $iterator++) {
136
                if (substr($this->attributes["eap:server_name"][$iterator], -(strlen($longestSuffix) + 1), 1) != $candidate) {
137
                    break 2;
138
                }
139
            }
140
            $longestSuffix = $candidate . $longestSuffix;
141
        }
142
        return $longestSuffix;
143
    }
144
145
    /**
146
     * Set up working environment for a device module
147
     *
148
     * Sets up the device module environment taking into account the actual profile
149
     * selected by the user in the GUI. The selected profile is passed as the
150
     * Profile $profile argumant.
151
     *
152
     * This method needs to be called after the device instance has been created (the GUI class does that)
153
     *
154
     * setup performs the following tasks:
155
     * - collect profile attributes and pass them as the attributes property;
156
     * - create the temporary working directory
157
     * - process CA certificates and store them as 'internal:CAs' attribute
158
     * - process and save optional info files and store references to them in
159
     *   'internal:info_file' attribute
160
     * @param AbstractProfile $profile        the profile object which will be passed by the caller
161
     * @param string          $token          the invitation token for silverbullet requests
162
     * @param string          $importPassword the PIN for the installer for silverbullet requests
163
     * @return void
164
     * @throws Exception
165
     * @final not to be redefined
166
     */
167
    final public function setup(AbstractProfile $profile, $token = NULL, $importPassword = NULL)
168
    {
169
        $this->loggerInstance->debug(4, "module setup start\n");
170
        common\Entity::intoThePotatoes();
171
        $purpose = 'installer';
172
        $eaps = $profile->getEapMethodsinOrderOfPreference(1);
173
        $this->calculatePreferredEapType($eaps);
174
        if (count($this->selectedEap) == 0) {
175
            throw new Exception("No EAP type available.");
176
        }
177
        $this->attributes = $this->getProfileAttributes($profile);
178
        $this->deviceUUID = common\Entity::uuid('', 'CAT' . $profile->institution . "-" . $profile->identifier . "-" . $this->device_id);
179
180
181
        // if we are instantiating a Silverbullet profile AND have been given
182
        // a token, attempt to create the client certificate NOW
183
        // then, this is the only instance of the device ever which knows the
184
        // cert and private key. It's not saved anywhere, so it's gone forever
185
        // after code execution!
186
187
        $this->loggerInstance->debug(5, "DeviceConfig->setup() - preliminaries done.\n");
188
        if ($profile instanceof ProfileSilverbullet && $token !== NULL && $importPassword !== NULL) {
189
            $this->clientCert = SilverbulletCertificate::issueCertificate($token, $importPassword, $this->options['clientcert']);
190
            // we need to drag this along; ChromeOS needs it outside the P12 container to encrypt the entire *config* with it.
191
            // Because encrypted private keys are not supported as per spec!
192
            $purpose = 'silverbullet';
193
            // let's keep a record for which device type this token was consumed
194
            $dbInstance = DBConnection::handle("INST");
195
            $certId = $this->clientCert['certObject']->dbId;
196
            $this->attributes['internal:username'] = [$this->clientCert['CN']];
197
            $dbInstance->exec("UPDATE `silverbullet_certificate` SET `device` = ? WHERE `id` = ?", "si", $this->device_id, $certId);
198
        }
199
        $this->loggerInstance->debug(5, "DeviceConfig->setup() - silverbullet checks done.\n");
200
        // create temporary directory, its full path will be saved in $this->FPATH;
201
        $tempDir = \core\common\Entity::createTemporaryDirectory($purpose);
202
        $this->FPATH = $tempDir['dir'];
203
        mkdir($tempDir['dir'] . '/tmp');
204
        chdir($tempDir['dir'] . '/tmp');
205
        $caList = [];
206
        $x509 = new \core\common\X509();
207
        if (isset($this->attributes['eap:ca_file'])) {
208
            foreach ($this->attributes['eap:ca_file'] as $ca) {
209
                $processedCert = $x509->processCertificate($ca);
210
                if (is_array($processedCert)) {
211
                    // add a UUID for convenience (some devices refer to their CAs by a UUID value)
212
                    $processedCert['uuid'] = common\Entity::uuid("", $processedCert['pem']);
213
                    $caList[] = $processedCert;
214
                }
215
            }
216
            $this->attributes['internal:CAs'][0] = $caList;
217
        }
218
219
        if (isset($this->attributes['support:info_file'])) {
220
            $this->attributes['internal:info_file'][0] = $this->saveInfoFile($this->attributes['support:info_file'][0]);
221
        }
222
        if (isset($this->attributes['general:logo_file'])) {
223
            $this->loggerInstance->debug(5, "saving IDP logo\n");
224
            $this->attributes['internal:logo_file'] = $this->saveLogoFile($this->attributes['general:logo_file'], 'idp');
225
        }
226
        if (isset($this->attributes['fed:logo_file'])) {
227
            $this->loggerInstance->debug(5, "saving FED logo\n");
228
            $this->attributes['fed:logo_file'] = $this->saveLogoFile($this->attributes['fed:logo_file'], 'fed');
229
        }
230
        $this->attributes['internal:SSID'] = $this->getSSIDs()['add'];
231
232
        $this->attributes['internal:remove_SSID'] = $this->getSSIDs()['del'];
233
234
        $this->attributes['internal:consortia'] = $this->getConsortia();
235
        
236
        if (isset($this->attributes['media:openroaming']) && ( $this->attribute['media:openroaming'] == "always-preagreed" ) ) {
0 ignored issues
show
Bug introduced by
The property attribute does not exist on core\DeviceConfig. Did you mean attributes?
Loading history...
237
            $this->attributes['internal:openroaming'] = TRUE;
238
        }
239
        // alternatively: if DeviceConfig was called after a user hitting the
240
        // OpenRoaming opt-in button on the end-user download page, also add
241
        // this internal attribute
242
        // TODO
243
        if (FALSE) {
244
            $this->attributes['internal:openroaming'] = TRUE;
245
        }
246
        
247
        $this->attributes['internal:networks'] = $this->getNetworks();
248
249
        $this->support_email_substitute = sprintf(_("your local %s support"), \config\ConfAssistant::CONSORTIUM['display_name']);
250
        $this->support_url_substitute = sprintf(_("your local %s support page"), \config\ConfAssistant::CONSORTIUM['display_name']);
251
252
        if ($this->signer && $this->options['sign']) {
253
            $this->sign = ROOT . '/signer/' . $this->signer;
254
        }
255
        $this->installerBasename = $this->getInstallerBasename();
256
        common\Entity::outOfThePotatoes();
257
    }
258
259
    /**
260
     * Selects the preferred eap method based on profile EAP configuration and device EAP capabilities
261
     *
262
     * @param array $eapArrayofObjects an array of eap methods supported by a given device
263
     * @return void
264
     */
265
    public function calculatePreferredEapType($eapArrayofObjects)
266
    {
267
        $this->selectedEap = [];
268
        foreach ($eapArrayofObjects as $eap) {
269
            if (in_array($eap->getArrayRep(), $this->supportedEapMethods)) {
270
                $this->selectedEap = $eap->getArrayRep();
271
                break;
272
            }
273
        }
274
        if ($this->selectedEap != []) {
275
            $this->selectedEapObject = new common\EAP($this->selectedEap);
276
        }
277
    }
278
279
    /**
280
     * prepare usage information for the installer
281
     * every device module should override this method
282
     *
283
     * @return string HTML text to be displayed
284
     */
285
    public function writeDeviceInfo()
286
    {
287
        common\Entity::intoThePotatoes();
288
        $retval = _("Sorry, this should not happen - no additional information is available");
289
        common\Entity::outOfThePotatoes();
290
        return $retval;
291
    }
292
293
    /**
294
     * function to return exactly one attribute type
295
     * 
296
     * @param string $attrName the attribute to retrieve
297
     * @return array|NULL the attributes
298
     */
299
    public function getAttribute($attrName)
300
    {
301
        return empty($this->attributes[$attrName]) ? NULL : $this->attributes[$attrName];
302
    }
303
304
    /**
305
     * some modules have a complex directory structure. This helper finds resources
306
     * in that structure. Mostly used in the Windows modules.
307
     * 
308
     * @param  string $file the filename to search for (without path)
309
     * @return string|boolean the filename as found, with path, or FALSE if it does not exist
310
     */
311
    protected function findSourceFile($file)
312
    {
313
        if (is_file($this->module_path . '/Files/' . $this->device_id . '/' . $file)) {
314
            return $this->module_path . '/Files/' . $this->device_id . '/' . $file;
315
        } elseif (is_file($this->module_path . '/Files/' . $file)) {
316
            return $this->module_path . '/Files/' . $file;
317
        } else {
318
            $this->loggerInstance->debug(2, "requested file $file does not exist\n");
319
            return FALSE;
320
        }
321
    }
322
323
    /**
324
     *  Copy a file from the module location to the temporary directory.
325
     *
326
     * If the second argument is provided then the file will be saved under the name 
327
     * taken form this argument. If only one parameter is given, source and destination
328
     * filenames are the same
329
     * Source file can be located either in the Files subdirectory or in the sibdirectory of Files
330
     * named the same as device_id. The second option takes precedence.
331
     *
332
     * @param string $source_name The source file name
333
     * @param string $output_name The destination file name
334
     *
335
     * @return boolean result of the copy operation
336
     * @final not to be redefined
337
     */
338
    final protected function copyFile($source_name, $output_name = NULL)
339
    {
340
        if ($output_name === NULL) {
341
            $output_name = $source_name;
342
        }
343
        $this->loggerInstance->debug(5, "fileCopy($source_name, $output_name)\n");
344
        $source = $this->findSourceFile($source_name);
345
        if ($source === FALSE) {
346
            return FALSE;
347
        }
348
        $this->loggerInstance->debug(5, "Copying $source to $output_name\n");
349
        $result = copy($source, "$output_name");
350
        if (!$result) {
351
            $this->loggerInstance->debug(2, "fileCopy($source_name, $output_name) failed\n");
352
        }
353
        return($result);
354
    }
355
356
    /**
357
     * Save certificate files in either DER or PEM format
358
     *
359
     * Certificate files will be saved in the module working directory.
360
     * 
361
     * saved certificate file names are avalable under the 'file' index
362
     * additional array entries are indexed as 'sha1', 'md5', and 'root'.
363
     * sha1 and md5 are correcponding certificate hashes
364
     * root is set to 1 for the CA roor certicicate and 0 otherwise
365
     * 
366
     * @param string $format only "der" and "pem" are currently allowed
367
     * @return array an array of arrays or empty array on error
368
     * @throws Exception
369
     */
370
    final protected function saveCertificateFiles($format)
371
    {
372
        switch ($format) {
373
            case "der": // fall-thorugh, same treatment
374
            case "pem":
375
                $iterator = 0;
376
                $caFiles = [];
377
                $caArray = $this->attributes['internal:CAs'][0];
378
                if (!$caArray) {
379
                    return([]);
380
                }
381
                foreach ($caArray as $certAuthority) {
382
                    $fileHandle = fopen("cert-$iterator.crt", "w");
383
                    if (!$fileHandle) {
384
                        throw new Exception("problem opening the file");
385
                    }
386
                    if ($format === "pem") {
387
                        fwrite($fileHandle, $certAuthority['pem']);
388
                    } else {
389
                        fwrite($fileHandle, $certAuthority['der']);
390
                    }
391
                    fclose($fileHandle);
392
                    $certAuthorityProps = [];
393
                    $certAuthorityProps['file'] = "cert-$iterator.crt";
394
                    $certAuthorityProps['sha1'] = $certAuthority['sha1'];
395
                    $certAuthorityProps['md5'] = $certAuthority['md5'];
396
                    $certAuthorityProps['root'] = $certAuthority['root'];
397
                    $caFiles[] = $certAuthorityProps;
398
                    $iterator++;
399
                }
400
                return($caFiles);
401
            default:
402
                $this->loggerInstance->debug(2, 'incorrect format value specified');
403
                return([]);
404
        }
405
    }
406
407
    /**
408
     * set of characters to remove from filename strings
409
     */
410
    private const TRANSLIT_SCRUB = '/[ ()\/\'"]+/';
411
412
    /**
413
     * Does a transliteration from UTF-8 to ASCII to get a sane filename
414
     * Takes special characters into account, and always uses English CTYPE
415
     * to avoid introduction of funny characters due to "flying accents"
416
     * 
417
     * @param string $input the input string that is to be transliterated
418
     * @return string the transliterated string
419
     */
420
    private function customTranslit($input)
421
    {
422
        $oldlocale = setlocale(LC_CTYPE, 0);
423
        setlocale(LC_CTYPE, "en_US.UTF-8");
424
        $retval = preg_replace(DeviceConfig::TRANSLIT_SCRUB, '_', iconv("UTF-8", "US-ASCII//TRANSLIT", $input));
425
        setlocale(LC_CTYPE, $oldlocale);
426
        return $retval;
427
    }
428
429
    /**
430
     * Generate installer filename base.
431
     * Device module should use this name adding an extension.
432
     * Normally the device identifier follows the Consortium name.
433
     * The sting taken for the device identifier equals (by default) to the index in the listDevices array,
434
     * but can be overriden with the 'device_id' device option.
435
     * 
436
     * @return string
437
     */
438
    private function getInstallerBasename()
439
    {
440
        $baseName = $this->customTranslit(\config\ConfAssistant::CONSORTIUM['name']) . "-" . $this->getDeviceId();
441
        if (isset($this->attributes['profile:customsuffix'][1])) {
442
            // this string will end up as a filename on a filesystem, so always
443
            // take a latin-based language variant if available
444
            // and then scrub non-ASCII just in case
445
            return $baseName . $this->customTranslit($this->attributes['profile:customsuffix'][1]);
446
        }
447
        // Okay, no custom suffix. 
448
        // Use the configured inst name and apply shortening heuristics
449
        // if an instshortname is set, base on that, otherwise, the normal instname
450
        $attribToUse = (isset($this->attributes['general:instshortname']) ? 'general:instshortname' : 'general:instname');
451
        $lang_pointer = \config\Master::LANGUAGES[$this->languageInstance->getLang()]['latin_based'] == TRUE ? 0 : 1;
452
        $this->loggerInstance->debug(5, "getInstallerBasename1:" . $this->attributes[$attribToUse][$lang_pointer] . "\n");
453
        $inst = $this->customTranslit($this->attributes[$attribToUse][$lang_pointer]);
454
        $this->loggerInstance->debug(4, "getInstallerBasename2:$inst\n");
455
        $Inst_a = explode('_', $inst);
456
        if (count($Inst_a) > 2) {
457
            $inst = '';
458
            foreach ($Inst_a as $i) {
459
                $inst .= $i[0];
460
            }
461
        }
462
        // and if the inst has multiple profiles, add the profile name behin
463
        if ($this->attributes['internal:profile_count'][0] > 1) {
464
            if (!empty($this->attributes['profile:name']) && !empty($this->attributes['profile:name'][$lang_pointer])) {
465
                $profTemp = $this->customTranslit($this->attributes['profile:name'][$lang_pointer]);
466
                $prof = preg_replace('/_+$/', '', $profTemp);
467
                return $baseName . $inst . '-' . $prof;
468
            }
469
        }
470
        return $baseName . $inst;
471
    }
472
473
    /**
474
     * returns the device_id of the current device
475
     * 
476
     * @return string
477
     */
478
    private function getDeviceId()
479
    {
480
        $deviceId = $this->device_id;
481
        if (isset($this->options['device_id'])) {
482
            $deviceId = $this->options['device_id'];
483
        }
484
        if ($deviceId !== '') {
485
            $deviceId .= '-';
486
        }
487
        return $deviceId;
488
    }
489
490
    /**
491
     * returns the list of SSIDs that installers should treat. 
492
     * 
493
     * Includes both SSIDs to be set up (and whether it's a TKIP-mixed or AES-only SSID) and SSIDs to be deleted
494
     * 
495
     * @return array
496
     */
497
    private function getSSIDs()
498
    {
499
        $ssidList = [];
500
        $ssidList['add'] = [];
501
        $ssidList['del'] = [];
502
        if (isset(\config\ConfAssistant::CONSORTIUM['ssid'])) {
503
            foreach (\config\ConfAssistant::CONSORTIUM['ssid'] as $ssid) {
504
                $ssidList['add'][$ssid] = 'AES';
505
                $ssidList['del'][$ssid] = 'TKIP';
506
            }
507
        }
508
        if (isset($this->attributes['media:SSID'])) {
509
            $ssidWpa2 = $this->attributes['media:SSID'];
510
511
            foreach ($ssidWpa2 as $ssid) {
512
                $ssidList['add'][$ssid] = 'AES';
513
            }
514
        }
515
        if (isset($this->attributes['media:remove_SSID'])) {
516
            $ssidRemove = $this->attributes['media:remove_SSID'];
517
            foreach ($ssidRemove as $ssid) {
518
                $ssidList['del'][$ssid] = 'DEL';
519
            }
520
        }
521
        return $ssidList;
522
    }
523
524
    /**
525
     * returns the list of Hotspot 2.0 / Passpoint roaming consortia to set up
526
     * 
527
     * @return array
528
     */
529
    private function getConsortia()
530
    {
531
532
        if (!isset(\config\ConfAssistant::CONSORTIUM['interworking-consortium-oi'])) {
533
            return ([]);
534
        }
535
        $consortia = \config\ConfAssistant::CONSORTIUM['interworking-consortium-oi'];
536
        if (isset($this->attributes['media:consortium_OI'])) {
537
            foreach ($this->attributes['media:consortium_OI'] as $new_oi) {
538
                if (!in_array($new_oi, $consortia)) {
539
                    $consortia[] = $new_oi;
540
                }
541
            }
542
        }
543
        return $consortia;
544
    }
545
    
546
    /**
547
     * return a list of SSIDs definded in the Config networks block
548
     * 
549
     * @return array $ssids
550
     */
551
    private function getConfigSSIDs()
552
    {
553
        $ssids = [];
554
        if (!isset(\config\ConfAssistant::CONSORTIUM['networks'])) {
555
            return [];
556
        }
557
        foreach (\config\ConfAssistant::CONSORTIUM['networks'] as $oneNetwork) {
558
            if (!empty($oneNetwork['ssid'])) {
559
                $ssids = array_merge($ssids, $oneNetwork['ssid']);
560
            }
561
        }
562
        return $ssids;
563
    }
564
    
565
    /**
566
     * return a list of OIs definded in the Config networks block
567
     * 
568
     * @return array $ois
569
     */
570
    private function getConfigOIs()
571
    {
572
        $ois = [];
573
        if (!isset(\config\ConfAssistant::CONSORTIUM['networks'])) {
574
            return [];
575
        }
576
        foreach (\config\ConfAssistant::CONSORTIUM['networks'] as $oneNetwork) {
577
            if (!empty($oneNetwork['oi'])) {
578
                $ois = array_merge($ois, $oneNetwork['oi']);
579
            }
580
        }
581
        return $ois;
582
    }
583
584
    /**
585
     * returns the list of parameters for predefined networks to be configured
586
     * 
587
     * @return array
588
     */
589
    private function getNetworks()
590
    {
591
        $additionalConsortia = [];
592
        $additionalSSIDs = [];
593
        $ssids = $this->getConfigSSIDs();
594
        $ois = $this->getConfigOIs();
595
        $networks = [];
596
        foreach (\config\ConfAssistant::CONSORTIUM['networks'] ?? [] as $netName => $netDetails) {
597
            // only add network blocks if their respective condition is met in this profile
598
            if ($netDetails['condition'] === TRUE || isset($this->attributes[$netDetails['condition']])) { 
599
                $networks[$netName] = $netDetails;
600
            }
601
        }
602
        // add locally defined SSIDs
603
        if (isset($this->attributes['media:SSID'])) {
604
            foreach ($this->attributes['media:SSID'] as $ssid) {
605
                if (!in_array($ssid, $ssids)) {
606
                    $additionalSSIDs[] = $ssid;
607
                }
608
            }
609
        }
610
        // add locally defined OIs
611
        if (isset($this->attributes['media:consortium_OI'])) {
612
            foreach ($this->attributes['media:consortium_OI'] as $new_oi) {
613
                if (!in_array($new_oi, $ois)) {
614
                    $additionalConsortia[] = $new_oi;
615
                }
616
            }
617
        }
618
        if (!empty($additionalConsortia) || !empty($additionalSSIDs)) {
619
            $networks[sprintf('%s Custom Network', CAT::$nomenclature_participant)] = ['ssid' => $additionalSSIDs, 'oi' => $additionalConsortia];
620
        }
621
        return $networks;
622
    }
623
624
    /**
625
     * An array with shorthand definitions for MIME types
626
     * @var array
627
     */
628
    private $mime_extensions = [
629
        'text/plain' => 'txt',
630
        'text/rtf' => 'rtf',
631
        'application/pdf' => 'pdf',
632
    ];
633
634
    /**
635
     * saves a number of logos to a cache directory on disk.
636
     * 
637
     * @param array  $logos list of logos (binary strings each)
638
     * @param string $type  a qualifier what type of logo this is
639
     * @return array list of filenames and the mime types
640
     * @throws Exception
641
     */
642
    private function saveLogoFile($logos, $type)
643
    {
644
        $iterator = 0;
645
        $returnarray = [];
646
        foreach ($logos as $blob) {
647
            $finfo = new \finfo(FILEINFO_MIME_TYPE);
648
            $mime = $finfo->buffer($blob);
649
            $matches = [];
650
            if (preg_match('/^image\/(.*)/', $mime, $matches)) {
651
                $ext = $matches[1];
652
            } else {
653
                $ext = 'unsupported';
654
            }
655
            $this->loggerInstance->debug(5, "saveLogoFile: $mime : $ext\n");
656
            $fileName = 'logo-' . $type . $iterator . '.' . $ext;
657
            $fileHandle = fopen($fileName, "w");
658
            if (!$fileHandle) {
659
                $this->loggerInstance->debug(2, "saveLogoFile failed for: $fileName\n");
660
                throw new Exception("problem opening the file");
661
            }
662
            fwrite($fileHandle, $blob);
663
            fclose($fileHandle);
664
            $returnarray[] = ['name' => $fileName, 'mime' => $ext];
665
            $iterator++;
666
        }
667
        return($returnarray);
668
    }
669
670
    /**
671
     * saves the Terms of Use file onto disk
672
     * 
673
     * @param string $blob the Terms of Use
674
     * @return array with one entry, containging the filename and mime type
675
     * @throws Exception
676
     */
677
    private function saveInfoFile($blob)
678
    {
679
        $finfo = new \finfo(FILEINFO_MIME_TYPE);
680
        $mime = $finfo->buffer($blob);
681
        $ext = isset($this->mime_extensions[$mime]) ? $this->mime_extensions[$mime] : 'usupported';
682
        $this->loggerInstance->debug(5, "saveInfoFile: $mime : $ext\n");
683
        $fileHandle = fopen('local-info.' . $ext, "w");
684
        if ($fileHandle === FALSE) {
685
            throw new Exception("problem opening the file");
686
        }
687
        fwrite($fileHandle, $blob);
688
        fclose($fileHandle);
689
        return(['name' => 'local-info.' . $ext, 'mime' => $ext]);
690
    }
691
692
    /**
693
     * returns the attributes of the profile for which to generate an installer
694
     * 
695
     * In condensed notion, and most specific level only (i.e. ignores overriden attributes from a higher level)
696
     * @param \core\AbstractProfile $profile the Profile in question
697
     * @return array
698
     */
699
    private function getProfileAttributes(AbstractProfile $profile)
700
    {
701
        $bestMatchEap = $this->selectedEap;
702
        if (count($bestMatchEap) > 0) {
703
            $a = $profile->getCollapsedAttributes($bestMatchEap);
704
            $a['eap'] = $bestMatchEap;
705
            $a['all_eaps'] = $profile->getEapMethodsinOrderOfPreference(1);
706
            return($a);
707
        }
708
        echo("No supported eap types found for this profile.\n");
709
        return [];
710
    }
711
712
    /**
713
     * dumps attributes for debugging purposes
714
     *
715
     * dumpAttibutes method is supplied for debuging purposes, it simply dumps the attribute array
716
     * to a file with name passed in the attribute.
717
     * @param string $file the output file name
718
     * @return void
719
     */
720
    protected function dumpAttibutes($file)
721
    {
722
        ob_start();
723
        print_r($this->attributes);
724
        $output = ob_get_clean();
725
        file_put_contents($file, $output);
726
    }
727
728
    /**
729
     * placeholder for the main device method
730
     * @return string
731
     */
732
    abstract public function writeInstaller();
733
734
    /**
735
     * collates the string to use as EAP outer ID
736
     * 
737
     * @return string|NULL
738
     */
739
    protected function determineOuterIdString()
740
    {
741
        $outerId = NULL;
742
        if (isset($this->attributes['internal:use_anon_outer']) && $this->attributes['internal:use_anon_outer'][0] == "1" && isset($this->attributes['internal:realm'])) {
743
            $outerId = "@" . $this->attributes['internal:realm'][0];
744
            if (isset($this->attributes['internal:anon_local_value'])) {
745
                $outerId = $this->attributes['internal:anon_local_value'][0] . $outerId;
746
            }
747
        }
748
        return $outerId;
749
    }
750
751
    /**
752
     * Array passing all options to the device module.
753
     *
754
     * $attrbutes array contains option values defined for the institution and a particular
755
     * profile (possibly overriding one another) ready for the device module to consume.
756
     * 
757
     * For each of the options the value is another array of vales (even if only one value is present).
758
     * Some attributes may be missing if they have not been configured for a viven institution or profile.
759
     *
760
     * The following attributes are meant to be used by device modules:
761
     * - <b>general:geo_coordinates</b> -  geographical coordinates of the institution or a campus
762
     * - <b>support:info_file</b>  -  consent file displayed to the users                                                         
763
     * - <b>general:logo_file</b>  -  file data containing institution logo                                                      
764
     * - <b>support:eap_types</b>  -  URL to a local support page for a specific eap methiod, not to be confused with general:url 
765
     * - <b>support:email</b>      -  email for users to contact for local instructions                                           
766
     * - <b>support:phone</b>      -  telephone number for users to contact for local instructions                                
767
     * - <b>support:url</b>        -  URL where the user will find local instructions       
768
     * - <b>internal:info_file</b> -  the pathname of the info_file saved in the working directory
769
     * - <b>internal:logo_file</b>  -  array of pathnames of logo_files saved in the working directory
770
     * - <b>internal:CAs</b> - the value is an array produced by X509::processCertificate() with the following filds
771
     * - <b>internal:SSID</b> - an array indexed by SSID strings with values either TKIP or AES; if TKIP is set the both WPA/TKIP and WPA2/AES should be set if AES is set the this is a WPA2/AES only SSID; the consortium's defined SSIDs are always set as the first array elements.
772
     * - <b>internal:consortia</b> an array of consortion IO as declared in the Confassistant config
773
     * - <b>internal:networks</b> - an array of network parameters  as declared in the Confassistant config
774
     * - <b>internal:profile_count</b> - the number of profiles for the associated IdP
775
     *
776
     *
777
     * these attributes are available and can be used, but the "internal" attributes are better suited for modules
778
     * -  eap:ca_file    -      certificate of the CA signing the RADIUS server key                                         
779
     * - <b>media:SSID</b>       -  additional SSID to configure, WPA2/AES only (device modules should use internal:SSID)
780
     *
781
     * @var array $attributes
782
     * @see \core\common\X509::processCertificate()
783
     * 
784
     */
785
    public $attributes;
786
787
    /**
788
     * stores the path to the module source location and is used 
789
     * by copyFile and translateFile
790
     * the only reason for it to be a public variable ies that it is set by the DeviceFactory class
791
     * module_path should not be used by module drivers.
792
     * 
793
     * @var string 
794
     */
795
    public $module_path;
796
797
    /**
798
     * The optimal EAP type selected given profile and device
799
     * 
800
     * @var array
801
     */
802
    public $selectedEap;
803
804
    /**
805
     * The optimal EAP type selected given profile and device, as object
806
     * 
807
     * @var \core\common\EAP
808
     */
809
    public $selectedEapObject;
810
811
    /**
812
     * the full path to the profile signing program
813
     * device modules which require signing should use this property to exec the signer
814
     * the signer program must accept two arguments - input and output file names
815
     * the signer program mus operate in the local directory and filenames are relative to this
816
     * directory
817
     *
818
     * @var string
819
     */
820
    public $sign;
821
822
    /**
823
     * the name of the signer program (without full path)
824
     * 
825
     * @var string
826
     */
827
    public $signer;
828
829
    /**
830
     * The string identifier of the device (don't show this to users)
831
     * 
832
     * @var string
833
     */
834
    public $device_id;
835
836
    /**
837
     * See devices-template.php for a list of available options
838
     * 
839
     * @var array
840
     */
841
    public $options;
842
843
    /**
844
     * This string will be shown if no support email was configured by the admin
845
     * 
846
     * @var string 
847
     */
848
    public $support_email_substitute;
849
850
    /**
851
     * This string will be shown if no support URL was configured by the admin
852
     * 
853
     * @var string 
854
     */
855
    public $support_url_substitute;
856
857
    /**
858
     * This string should be used by all installer modules to set the 
859
     * installer file basename.
860
     *
861
     * @var string 
862
     */
863
    public $installerBasename;
864
865
    /**
866
     * stores the PKCS#12 DER representation of a client certificate for 
867
     * SilverBullet along with some metadata in an array
868
     * 
869
     * @var array
870
     */
871
    protected $clientCert = [];
872
873
    /**
874
     * stores identifier used by GEANTLink profiles
875
     * 
876
     * @var string
877
     */
878
    public $deviceUUID;
879
}
880