Passed
Push — master ( b9138d...4bc8f2 )
by Tomasz
03:40
created

DeviceConfig::findSourceFile()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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