Passed
Push — master ( 09cfdd...94b89f )
by Stefan
07:21 queued 03:30
created

DeviceConfig::translateString()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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