Test Failed
Push — master ( 30a668...1b9405 )
by Tomasz
32:49 queued 10s
created

DeviceConfig::getNetworks()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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