Test Failed
Branch release_2_0 (c903e3)
by Stefan
07:31
created

DeviceConfig   F

Complexity

Total Complexity 90

Size/Duplication

Total Lines 743
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 90
eloc 279
dl 0
loc 743
rs 2
c 0
b 0
f 0

20 Methods

Rating   Name   Duplication   Size   Complexity  
A setSupportedEapMethods() 0 4 1
A __construct() 0 18 2
A getAttribute() 0 2 2
A copyFile() 0 15 4
A writeDeviceInfo() 0 2 1
B saveCertificateFiles() 0 33 7
A translateString() 0 19 5
A calculatePreferredEapType() 0 10 4
A getDeviceId() 0 9 3
A getConsortia() 0 13 5
A saveLogoFile() 0 25 4
B getInstallerBasename() 0 31 8
A determineOuterIdString() 0 9 5
A findSourceFile() 0 8 3
A getProfileAttributes() 0 10 2
C setup() 0 75 13
A saveInfoFile() 0 12 3
B getSSIDs() 0 34 10
B translateFile() 0 32 7
A dumpAttibutes() 0 5 1

How to fix   Complexity   

Complex Class

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

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