Passed
Push — master ( 5c87ed...e4bb53 )
by Stefan
04:05
created

OptionParser::sendOptionsToDatabase()   C

Complexity

Conditions 11
Paths 10

Size

Total Lines 32
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 32
c 0
b 0
f 0
rs 5.2653
cc 11
eloc 24
nc 10
nop 5

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * ******************************************************************************
5
 * 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
namespace web\lib\admin;
13
14
use Exception;
15
16
?>
17
<?php
18
19
require_once(dirname(dirname(dirname(dirname(__FILE__)))) . "/config/_config.php");
20
21
/**
22
 * This class parses HTML field input from POST and FILES and extracts valid and authorized options to be set.
23
 * 
24
 * @author Stefan Winter <[email protected]>
25
 */
26
class OptionParser {
27
28
    /**
29
     * an instance of the InputValidation class which we use heavily for syntax checks.
30
     * 
31
     * @var \web\lib\common\InputValidation
32
     */
33
    private $validator;
34
35
    /**
36
     * an instance of the UIElements() class to draw some UI widgets from.
37
     * 
38
     * @var UIElements
39
     */
40
    private $uiElements;
41
42
    /**
43
     * a handle for the Options singleton
44
     * 
45
     * @var \core\Options
46
     */
47
    private $optioninfoObject;
48
49
    /**
50
     * initialises the various handles.
51
     */
52
    public function __construct() {
53
        $this->validator = new \web\lib\common\InputValidation();
54
        $this->uiElements = new UIElements();
55
        $this->optioninfoObject = \core\Options::instance();
56
    }
57
58
    /**
59
     * Verifies whether an incoming upload was actually valid data
60
     * 
61
     * @param string $optiontype for which option was the data uploaded
62
     * @param string $incomingBinary the uploaded data
63
     * @return boolean whether the data was valid
64
     */
65
    private function checkUploadSanity(string $optiontype, string $incomingBinary) {
66
        switch ($optiontype) {
67
            case "general:logo_file":
68
            case "fed:logo_file":
69
            case "internal:logo_from_url":
70
                // we check logo_file with ImageMagick
71
                return $this->validator->image($incomingBinary);
72
            case "eap:ca_file":
73
                // echo "Checking $optiontype with file $filename";
74
                $func = new \core\common\X509;
75
                $cert = $func->processCertificate($incomingBinary);
76
                if (is_array($cert)) { // could also be FALSE if it was incorrect incoming data
77
                    return TRUE;
78
                }
79
                // the certificate seems broken
80
                return FALSE;
81
            case "support:info_file":
82
                $info = new \finfo();
0 ignored issues
show
Bug introduced by
The call to finfo::finfo() has too few arguments starting with options. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

82
                $info = /** @scrutinizer ignore-call */ new \finfo();

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
83
                $filetype = $info->buffer($incomingBinary, FILEINFO_MIME_TYPE);
84
85
                // we only take plain text files in UTF-8!
86
                if ($filetype == "text/plain" && iconv("UTF-8", "UTF-8", $incomingBinary) !== FALSE) {
87
                    return TRUE;
88
                }
89
                return FALSE;
90
            default:
91
                return FALSE;
92
        }
93
    }
94
95
    /**
96
     * Known-good options are sometimes converted, this function takes care of that.
97
     * 
98
     * Cases in point:
99
     * - CA import by URL reference: fetch cert from URL and store it as CA file instead
100
     * - Logo import by URL reference: fetch logo from URL and store it as logo file instead
101
     * - CA file: mangle the content so that *only* the valid content remains (raw input may contain line breaks or spaces which are valid, but some supplicants choke upon)
102
     * 
103
     * @param array $options the list of options we got
104
     * @param array $good by-reference: the future list of actually imported options
105
     * @param array $bad by-reference: the future list of submitted but rejected options
106
     * @return array the options, post-processed
107
     */
108
    private function postProcessValidAttributes(array $options, array &$good, array &$bad) {
109
        foreach ($options as $index => $iterateOption) {
110
            foreach ($iterateOption as $name => $optionPayload) {
111
                switch ($name) {
112
                    case "eap:ca_url": // eap:ca_url becomes eap:ca_file by downloading the file
113
                        $finalOptionname = "eap:ca_file";
114
                    // intentional fall-through, treatment identical to logo_url
115
                    case "general:logo_url": // logo URLs become logo files by downloading the file
116
                        $finalOptionname = $finalOptionname ?? "general:logo_file";
117
                        if (empty($optionPayload['content'])) {
118
                            break;
119
                        }
120
                        $bindata = \core\common\OutsideComm::downloadFile($optionPayload['content']);
121
                        unset($options[$index]);
122
                        if ($bindata === FALSE) {
123
                            $bad[] = $name;
124
                            break;
125
                        }
126
                        if ($this->checkUploadSanity($finalOptionname, $bindata)) {
127
                            $good[] = $name;
128
                            $options[] = [$finalOptionname => ['lang' => NULL, 'content' => base64_encode($bindata)]];
129
                        } else {
130
                            $bad[] = $name;
131
                        }
132
                        break;
133
                    case "eap:ca_file": // CA files get split (PEM files can contain more than one CA cert)
134
                        // the data being processed here is always "good": 
135
                        // if it was eap:ca_file initially then its sanity was checked in step 1;
136
                        // if it was eap:ca_url then it was checked after we downloaded it
137
                        if (empty($optionPayload['content']) || preg_match('/^ROWID-/', $optionPayload['content'])) {
138
                            break;
139
                        }
140
                        $content = base64_decode($optionPayload['content']);
141
                        unset($options[$index]);
142
                        $x509 = new \core\common\X509();
143
                        $cAFiles = $x509->splitCertificate($content);
144
                        foreach ($cAFiles as $cAFile) {
145
                            $options[] = ["eap:ca_file" => ['lang' => NULL, 'content' => base64_encode($x509->pem2der($cAFile))]];
146
                        }
147
                        $good[] = $name;
148
                        break;
149
                    default:
150
                        $good[] = $name; // all other options were checked and are sane in step 1 already
151
                        break;
152
                }
153
            }
154
        }
155
156
        return $options;
157
    }
158
159
    /**
160
     * extracts a coordinate pair from _POST (if any) and returns it in our 
161
     * standard attribute notation
162
     * 
163
     * @param array $postArray
164
     * @param array $good
165
     * @return array
166
     */
167
    private function postProcessCoordinates(array $postArray, array &$good) {
168
        if (!empty($postArray['geo_long']) && !empty($postArray['geo_lat'])) {
169
170
            $lat = $this->validator->coordinate($postArray['geo_lat']);
171
            $lon = $this->validator->coordinate($postArray['geo_long']);
172
            $good[] = ("general:geo_coordinates");
173
            return [0 => ["general:geo_coordinates" => ['lang' => NULL, 'content' => json_encode(["lon" => $lon, "lat" => $lat])]]];
174
        }
175
        return [];
176
    }
177
178
    /**
179
     * creates HTML code for a user-readable summary of the imports
180
     * @param array $good list of actually imported options
181
     * @param array $bad list of submitted but rejected options
182
     * @param array $mlAttribsWithC list of language-variant options
183
     * @return string HTML code
184
     */
185
    private function displaySummaryInUI(array $good, array $bad, array $mlAttribsWithC) {
186
        $retval = "";
187
        // don't do your own table - only the <tr>s here
188
        // list all attributes that were set correctly
189
        $listGood = array_count_values($good);
190
        $uiElements = new UIElements();
191
        foreach ($listGood as $name => $count) {
192
            /// number of times attribute is present, and its name
193
            /// Example: "5x Support E-Mail"
194
            $retval .= $this->uiElements->boxOkay(sprintf(_("%dx %s"), $count, $uiElements->displayName($name)));
195
        }
196
        // list all atributes that had errors
197
        $listBad = array_count_values($bad);
198
        foreach ($listBad as $name => $count) {
199
            $retval .= $this->uiElements->boxError(sprintf(_("%dx %s"), (int) $count, $uiElements->displayName($name)));
200
        }
201
        // list multilang without default
202
        foreach ($mlAttribsWithC as $attribName => $isitsetornot) {
203
            if ($isitsetornot == FALSE) {
204
                $retval .= $this->uiElements->boxWarning(sprintf(_("You did not set a 'default language' value for %s. This means we can only display this string for installers which are <strong>exactly</strong> in the language you configured. For the sake of all other languages, you may want to edit the profile again and populate the 'default/other' language field."), $uiElements->displayName($attribName)));
205
            }
206
        }
207
        return $retval;
208
    }
209
210
    /**
211
     * Incoming data is in $_POST and possibly in $_FILES. Collate values into 
212
     * one array according to our name and numbering scheme.
213
     * 
214
     * @param array $postArray _POST
215
     * @param array $filesArray _FILES
216
     * @return array
217
     */
218
    private function collateOptionArrays(array $postArray, array $filesArray) {
219
220
        $optionarray = $postArray['option'] ?? [];
221
        $valuearray = $postArray['value'] ?? [];
222
        $filesarray = $filesArray['value']['tmp_name'] ?? [];
223
224
        $iterator = array_merge($optionarray, $valuearray, $filesarray);
225
226
        return $iterator;
227
    }
228
229
    /**
230
     * The very end of the processing: clean input data gets sent to the database
231
     * for storage
232
     * 
233
     * @param mixed $object for which object are the options
234
     * @param array $options the options to store
235
     * @param array $pendingattributes list of attributes which are already stored but may need to be deleted
236
     * @param string $device when the $object is Profile, this indicates device-specific attributes
237
     * @param int $eaptype when the $object is Profile, this indicates eap-specific attributes
238
     * @return array list of attributes which were previously stored but are to be deleted now
239
     * @throws Exception
240
     */
241
    private function sendOptionsToDatabase($object, array $options, array $pendingattributes, string $device = NULL, int $eaptype = NULL) {
242
        $retval = [];
243
        foreach ($options as $iterateOption) {
244
            foreach ($iterateOption as $name => $optionPayload) {
245
                $optiontype = $this->optioninfoObject->optionType($name);
246
                // some attributes are in the DB and were only called by reference
247
                // keep those which are still referenced, throw the rest away
248
                if ($optiontype["type"] == \core\Options::TYPECODE_FILE && preg_match("/^ROWID-.*-([0-9]+)/", $optionPayload['content'], $retval)) {
249
                    unset($pendingattributes[$retval[1]]);
250
                    continue;
251
                }
252
                switch (get_class($object)) {
253
                    case 'core\\ProfileRADIUS':
254
                        if ($device !== NULL) {
255
                            $object->addAttributeDeviceSpecific($name, $optionPayload['lang'], $optionPayload['content'], $device);
256
                        } elseif ($eaptype !== NULL) {
257
                            $object->addAttributeEAPSpecific($name, $optionPayload['lang'], $optionPayload['content'], $eaptype);
258
                        } else {
259
                            $object->addAttribute($name, $optionPayload['lang'], $optionPayload['content']);
260
                        }
261
                        break;
262
                    case 'core\\IdP':
263
                    case 'core\\User':
264
                    case 'core\\Federation':
265
                        $object->addAttribute($name, $optionPayload['lang'], $optionPayload['content']);
266
                        break;
267
                    default:
268
                        throw new Exception("This type of object can't have options that are parsed by this file!");
269
                }
270
            }
271
        }
272
        return $pendingattributes;
273
    }
274
275
    /**
276
     * filters the input to find syntactically correctly submitted attributes
277
     * 
278
     * @param array $listOfEntries list of POST and FILES entries
279
     * @param array $multilangAttrsWithC by-reference: future list of language-variant options and their "default lang" state
280
     * @param array $bad by-reference: future list of submitted but rejected options
281
     * @return array sanitised list of options
282
     * @throws Exception
283
     */
284
    private function sanitiseInputs(array $listOfEntries, array &$multilangAttrsWithC, array &$bad) {
285
        $retval = [];
286
        foreach ($listOfEntries as $objId => $objValueRaw) {
287
// pick those without dash - they indicate a new value        
288
            if (preg_match('/^S[0123456789]*$/', $objId)) {
289
                $objValue = $this->validator->optionName(preg_replace('/#.*$/', '', $objValueRaw));
290
                $optioninfo = $this->optioninfoObject->optionType($objValue);
291
                $lang = NULL;
292
                if ($optioninfo["flag"] == "ML") {
293
                    if (isset($listOfEntries["$objId-lang"])) {
294
                        if (!isset($multilangAttrsWithC[$objValue])) { // on first sight, initialise the attribute as "no C language set"
295
                            $multilangAttrsWithC[$objValue] = FALSE;
296
                        }
297
                        $lang = $listOfEntries["$objId-lang"];
298
                        if ($lang == "") { // user forgot to select a language
299
                            $lang = "C";
300
                        }
301
                    } else {
302
                        $bad[] = $objValue;
303
                        continue;
304
                    }
305
                    // did we get a C language? set corresponding value to TRUE
306
                    if ($lang == "C") {
307
                        $multilangAttrsWithC[$objValue] = TRUE;
308
                    }
309
                }
310
311
                // many of the cases below condense due to identical treatment
312
                // except validator function to call and where in POST the
313
                // content is
314
                $validators = [
315
                    \core\Options::TYPECODE_TEXT => ["function" => "string", "field" => \core\Options::TYPECODE_TEXT, "extraarg" => [TRUE]],
316
                    \core\Options::TYPECODE_COORDINATES => ["function" => "coordJsonEncoded", "field" => \core\Options::TYPECODE_TEXT, "extraarg" => []],
317
                    \core\Options::TYPECODE_BOOLEAN => ["function" => "boolean", "field" => \core\Options::TYPECODE_BOOLEAN, "extraarg" => []],
318
                    \core\Options::TYPECODE_INTEGER => ["function" => "integer", "field" => \core\Options::TYPECODE_INTEGER, "extraarg" => []],
319
                ];
320
321
                switch ($optioninfo["type"]) {
322
                    case \core\Options::TYPECODE_TEXT:
323
                    case \core\Options::TYPECODE_COORDINATES:
324
                    case \core\Options::TYPECODE_INTEGER:
325
                        $varName = "$objId-" . $validators[$optioninfo['type']]['field'];
326
                        if (!empty($listOfEntries[$varName])) {
327
                            $content = call_user_func_array([$this->validator, $validators[$optioninfo['type']]['function']], array_merge([$listOfEntries[$varName]], $validators[$optioninfo['type']]['extraarg']));
328
                            break;
329
                        }
330
                        continue 2;
331
                    case \core\Options::TYPECODE_BOOLEAN:
332
                        $varName = "$objId-" . \core\Options::TYPECODE_BOOLEAN;
333
                        if (!empty($listOfEntries[$varName])) {
334
                            $contentValid = $this->validator->boolean($listOfEntries[$varName]);
335
                            if ($contentValid) {
336
                                $content = "on";
337
                            } else {
338
                                $bad[] = $objValue;
339
                                continue 2;
340
                            }
341
                            break;
342
                        }
343
                        continue 2;
344
                    case \core\Options::TYPECODE_STRING:
345
                        if (!empty($listOfEntries["$objId-" . \core\Options::TYPECODE_STRING])) {
346
                            switch ($objValue) {
347
                                case "media:consortium_OI":
348
                                    $content = $this->validator->consortiumOI($listOfEntries["$objId-" . \core\Options::TYPECODE_STRING]);
349
                                    if ($content === FALSE) {
350
                                        $bad[] = $objValue;
351
                                        continue 3;
352
                                    }
353
                                    break;
354
                                case "media:remove_SSID":
355
                                    $content = $this->validator->string($listOfEntries["$objId-" . \core\Options::TYPECODE_STRING]);
356
                                    if ($content == "eduroam") {
357
                                        $bad[] = $objValue;
358
                                        continue 3;
359
                                    }
360
                                    break;
361
                                default:
362
                                    $content = $this->validator->string($listOfEntries["$objId-" . \core\Options::TYPECODE_STRING]);
363
                                    break;
364
                            }
365
                            break;
366
                        }
367
                        continue 2;
368
                    case \core\Options::TYPECODE_FILE:
369
                        if (!empty($listOfEntries["$objId-" . \core\Options::TYPECODE_STRING])) { // was already in, by ROWID reference, extract
370
                            // ROWID means it's a multi-line string (simple strings are inline in the form; so allow whitespace)
371
                            $content = $this->validator->string(urldecode($listOfEntries["$objId-" . \core\Options::TYPECODE_STRING]), TRUE);
372
                            break;
373
                        } else if (isset($listOfEntries["$objId-" . \core\Options::TYPECODE_FILE]) && ($listOfEntries["$objId-" . \core\Options::TYPECODE_FILE] != "")) { // let's do the download
374
                            $rawContent = \core\common\OutsideComm::downloadFile("file:///" . $listOfEntries["$objId-" . \core\Options::TYPECODE_FILE]);
375
376
                            if ($rawContent === FALSE || !$this->checkUploadSanity($objValue, $rawContent)) {
377
                                $bad[] = $objValue;
378
                                continue 2;
379
                            }
380
                            $content = base64_encode($rawContent);
381
                            break;
382
                        }
383
                        continue 2;
384
                    default:
385
                        throw new Exception("Internal Error: Unknown option type " . $objValue . "!");
386
                }
387
                // lang can be NULL here, if it's not a multilang attribute, or a ROWID reference. Never mind that.
388
                $retval[] = ["$objValue" => ["lang" => $lang, "content" => $content]];
389
            }
390
        }
391
        return $retval;
392
    }
393
394
    /**
395
     * The main function: takes all HTML field inputs, makes sense of them and stores valid data in the database
396
     * 
397
     * @param mixed $object The object for which attributes were submitted
398
     * @param array $postArray incoming attribute names and values as submitted with $_POST
399
     * @param array $filesArray incoming attribute names and values as submitted with $_FILES
400
     * @param int $eaptype for eap-specific attributes (only used where $object is a ProfileRADIUS instance)
401
     * @param string $device for device-specific attributes (only used where $object is a ProfileRADIUS instance)
402
     * @return string text to be displayed in UI with the summary of attributes added
403
     * @throws Exception
404
     */
405
    public function processSubmittedFields($object, array $postArray, array $filesArray, int $eaptype = NULL, string $device = NULL) {
406
407
        // construct new array with all non-empty options for later feeding into DB
408
        // $multilangAttrsWithC is a helper array to keep track of multilang 
409
        // options that were set in a specific language but are not 
410
        // accompanied by a "default" language setting
411
        // if there are some without C by the end of processing, we need to warn
412
        // the admin that this attribute is "invisible" in certain languages
413
        // attrib_name -> boolean
414
415
        $multilangAttrsWithC = [];
416
417
        // these two variables store which attributes were processed 
418
        // successfully vs. which were discarded because in some way malformed
419
420
        $good = [];
421
        $bad = [];
422
423
        // Step 1: collate option names, option values and uploaded files (by 
424
        // filename reference) into one array for later handling
425
426
        $iterator = $this->collateOptionArrays($postArray, $filesArray);
427
428
        // Step 2: sieve out malformed input
429
430
        $cleanData = $this->sanitiseInputs($iterator, $multilangAttrsWithC, $bad);
431
432
        // Step 3: now we have clean input data. Some attributes need special care:
433
        // URL-based attributes need to be downloaded to get their actual content
434
        // CA files may need to be split (PEM can contain multiple CAs 
435
436
        $optionsStep2 = $this->postProcessValidAttributes($cleanData, $good, $bad);
437
438
        // Step 4: coordinates do not follow the usual POST array as they are 
439
        // two values forming one attribute; extract those two as an extra step
440
441
        $options = array_merge($optionsStep2, $this->postProcessCoordinates($postArray, $good));
442
443
        // Step 5: push all the received options to the database. Keep mind of 
444
        // the list of existing database entries that are to be deleted.
445
        // 5a: first deletion step: purge all old content except file-based attributes;
446
        //     then take note of which file-based attributes are now stale
447
        if ($device === NULL && $eaptype === NULL) {
448
            $remaining = $object->beginflushAttributes();
449
            $killlist = $this->sendOptionsToDatabase($object, $options, $remaining);
450
        } elseif ($device !== NULL) {
451
            $remaining = $object->beginFlushMethodLevelAttributes(0, $device);
452
            $killlist = $this->sendOptionsToDatabase($object, $options, $remaining, $device);
453
        } else {
454
            $remaining = $object->beginFlushMethodLevelAttributes($eaptype, "");
455
            $killlist = $this->sendOptionsToDatabase($object, $options, $remaining, "", $eaptype);
456
        }
457
        // 5b: finally, kill the stale file-based attributes which are not wanted any more.
458
        $object->commitFlushAttributes($killlist);
459
460
        // finally: return HTML code that gives feedback about what we did. 
461
        // In some cases, callers won't actually want to display it; so simply
462
        // do not echo the return value. Reasons not to do this is if we working
463
        // e.g. from inside an overlay
464
465
        return $this->displaySummaryInUI($good, $bad, $multilangAttrsWithC);
466
    }
467
468
}
469