Passed
Push — release_2_1 ( 0722bc...36e192 )
by Tomasz
26:43
created

InputValidation::integer()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 6
rs 10
cc 2
nc 2
nop 1
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
namespace web\lib\common;
24
25
use \Exception;
0 ignored issues
show
Bug introduced by
The type \Exception was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
26
27
/**
28
 * performs validation of user inputs
29
 */
30
class InputValidation extends \core\common\Entity
31
{
32
33
    /**
34
     * returns a simple HTML <p> element with basic explanations about what was
35
     * wrong with the input
36
     * 
37
     * @param string $customtext explanation provided by the validator function
38
     * @return string
39
     */
40
    private function inputValidationError($customtext)
41
    {
42
        \core\common\Entity::intoThePotatoes();
43
        $retval = "<p>" . _("Input validation error: ") . $customtext . "</p>";
44
        \core\common\Entity::outOfThePotatoes();
45
        return $retval;
46
    }
47
48
    /**
49
     * Is this a known Federation? Optionally, also check if the authenticated
50
     * user is a federation admin of that federation
51
     * @param mixed       $input the ISO code of the federation
52
     * @param string|NULL $owner the authenticated username, optional
53
     * @return \core\Federation
54
     * @throws Exception
55
     */
56
    public function existingFederation($input, $owner = NULL)
57
    {
58
        $cat = new \core\CAT(); // initialises Entity static members
59
        $fedIdentifiers = array_keys($cat->knownFederations);
60
        if (!in_array(strtoupper($input), $fedIdentifiers)) {
61
            throw new Exception($this->inputValidationError(sprintf("This %s does not exist!", \core\common\Entity::$nomenclature_fed)));
62
        }
63
        // totally circular, but this hopefully *finally* make Scrutinizer happier
64
        $correctIndex = array_search(strtoupper($input), $fedIdentifiers);
65
        $postFed = $fedIdentifiers[$correctIndex];
66
67
        $temp = new \core\Federation($postFed);
68
        if ($owner === NULL) {
69
            return $temp;
70
        }
71
72
        foreach ($temp->listFederationAdmins() as $oneowner) {
73
            if ($oneowner == $owner) {
74
                return $temp;
75
            }
76
        }
77
        throw new Exception($this->inputValidationError(sprintf("User is not %s administrator!", \core\common\Entity::$nomenclature_fed)));
78
    }
79
80
    /**
81
     * Is this a known Federation? Optionally, also check if the authenticated
82
     * user is a federation admin of that federation
83
     * @param mixed       $input the ISO code of the federation
84
     * @param string|NULL $owner the authenticated username, optional
85
     * @return array(\core\Federation, string)
86
     * @throws Exception
87
     */
88
    public function existingFederationInt($input, $owner = NULL)
89
    {
90
        $cat = new \core\CAT(); // initialises Entity static members
91
        $fedIdentifiers = array_keys($cat->knownFederations);
92
        if (!in_array(strtoupper($input), $fedIdentifiers)) {
93
            throw new Exception($this->inputValidationError(sprintf("This %s does not exist!", \core\common\Entity::$nomenclature_fed)));
94
        }
95
        // totally circular, but this hopefully *finally* make Scrutinizer happier
96
        $correctIndex = array_search(strtoupper($input), $fedIdentifiers);
97
        $postFed = $fedIdentifiers[$correctIndex];
98
        $temp = new \core\Federation($postFed);
99
        if ($owner === NULL) {
100
            return [$temp,'readonly'];
101
        }
102
        $user = new \core\User($owner);        
103
        foreach ($temp->listFederationAdmins() as $oneowner) {
104
            if ($oneowner == $owner) {
105
                return [$temp, 'fullaccess'];
106
            }
107
        }
108
        if ($user->isSuperadmin()|| $user->isSupport()) {
109
                $this->loggerInstance->debug(4, "You are the superadmin/support\n");
110
                return [$temp,'readonly'];                
111
            }
112
        throw new Exception($this->inputValidationError(sprintf("User is not %s administrator!", \core\common\Entity::$nomenclature_fed)));
113
    }
114
    
115
    /**
116
     * Is this a known IdP? Optionally, also check if the authenticated
117
     * user is an admin of that IdP
118
     * It is a wrapper around existingIdPInt.
119
     * 
120
     * @param mixed            $input             the numeric ID of the IdP in the system
121
     * @param string           $owner             the authenticated username, optional
122
     * @param \core\Federation $claimedFedBinding if set, cross-check that IdP belongs to specified federation (useful in admin API mode)
123
     * @return \core\IdP
124
     * @throws Exception
125
     */
126
    public function existingIdP($input, $owner = NULL, $claimedFedBinding = NULL)
127
    {
128
        $clean = $this->integer($input);
129
        if ($clean === FALSE) {
130
            throw new Exception($this->inputValidationError("Value for IdP is not an integer!"));
131
        }
132
        
133
        $checkResult = $this->existingIdPInt($input, $owner, $claimedFedBinding);
134
        $this->loggerInstance->debug(5, $checkResult, "existingIdP:", "\n");
135
        if ($checkResult[1] == 'fullaccess') {
136
            return $checkResult[0];
137
        }
138
        if ($owner == NULL && $checkResult[1] == 'nouser') {
139
            return $checkResult[0];
140
        }
141
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type core\IdP.
Loading history...
142
    }
143
    
144
    
145
    /**
146
     * Is this a known IdP? Optionally, also check if the authenticated
147
     * user is an admin of that IdP or a federation admin for the parent federation
148
     * federaton admins superadmin and support get read-only access, superadmins get readonly access as well
149
     * @param mixed            $input             the numeric ID of the IdP in the system
150
     * @param string           $owner             the authenticated username, optional
151
     * @param \core\Federation $claimedFedBinding if set, cross-check that IdP belongs to specified federation (useful in admin API mode)
152
     * @return array(\core\IdP, string)
153
     * @throws Exception
154
     */
155
    public function existingIdPInt($input, $owner = NULL, $claimedFedBinding = NULL)
156
    {
157
        $clean = $this->integer($input);
158
        if ($clean === FALSE) {
159
            throw new Exception($this->inputValidationError("Value for IdP is not an integer!"));
160
        }
161
        $temp = new \core\IdP($input); // constructor throws an exception if NX, game over
162
        if ($owner !== NULL) { // check if the authenticated user is allowed to see this institution
163
            $user = new \core\User($owner);        
164
            foreach ($temp->listOwners() as $oneowner) {
165
                if ($oneowner['ID'] == $owner) {
166
                    return [$temp, 'fullaccess'];
167
                }
168
            }
169
            if ($user->isFederationAdmin($temp->federation)) {
170
                $this->loggerInstance->debug(4, "You are fed admin for this IdP\n");
171
                return [$temp,'readonly'];
172
            }
173
            if ($user->isSuperadmin() || $user->isSupport()) {
174
                $this->loggerInstance->debug(4, "You are the superadmin/support\n");
175
                return [$temp,'readonly'];                
176
            }
177
            throw new Exception($this->inputValidationError("This IdP identifier is not accessible!"));
178
        }
179
        if ($claimedFedBinding !== NULL && strtoupper($temp->federation) != strtoupper($claimedFedBinding->tld)) {
180
            throw new Exception($this->inputValidationError("This IdP does not belong to the claimed federation!"));
181
        }
182
        return [$temp,'nouser'];
183
    }
184
185
    /**
186
     * Checks if the input refers to a known Profile. Optionally also takes an
187
     * IdP identifier and then checks if the Profile belongs to the referenced 
188
     * IdP
189
     * 
190
     * @param mixed    $input         the numeric ID of the Profile in the system
191
     * @param int|NULL $idpIdentifier the numeric ID of the IdP in the system, optional
192
     * @return \core\AbstractProfile
193
     * @throws Exception
194
     */
195
    public function existingProfile($input, $idpIdentifier = NULL)
196
    {
197
        $clean = $this->integer($input);
198
        if ($clean === FALSE) {
199
            throw new Exception("Non-integer was passed to Profile validator!");
200
        }
201
        $temp = \core\ProfileFactory::instantiate($clean); // constructor throws an exception if NX, game over
202
203
        if ($idpIdentifier !== NULL && $temp->institution != $idpIdentifier) {
204
            throw new Exception($this->inputValidationError("The profile does not belong to the IdP!"));
205
        }
206
        return $temp;
207
    }
208
209
    /**
210
     * Checks if the input refers to a known DeploymentManaged. Optionally also takes an
211
     * IdP identifier and then checks if the Profile belongs to the referenced 
212
     * IdP
213
     * 
214
     * @param mixed     $input the numeric ID of the Deployment in the system
215
     * @param \core\IdP $idp   the IdP
216
     * @return \core\DeploymentManaged
217
     * @throws Exception
218
     */
219
    public function existingDeploymentManaged($input, $idp)
220
    {
221
        $clean = $this->integer($input);
222
        if ($clean === FALSE) {
223
            throw new Exception("Non-integer was passed to Profile validator!");
224
        }
225
        $temp = new \core\DeploymentManaged($idp, $clean); // constructor throws an exception if NX, game over
226
227
        if ($temp->institution != $idp->identifier) {
228
            throw new Exception($this->inputValidationError("The profile does not belong to the IdP!"));
229
        }
230
        return $temp;
231
    }
232
233
    /**
234
     * Checks if this is a device known to the system
235
     * @param mixed $input the name of the device (index in the Devices.php array)
236
     * @return string returns the same string on success, throws an Exception on failure
237
     * @throws Exception
238
     */
239
    public function existingDevice($input)
240
    {
241
        $devicelist = \devices\Devices::listDevices();
242
        $keyArray = array_keys($devicelist);
243
        if (!isset($devicelist[$input])) {
244
            throw new Exception($this->inputValidationError("This device does not exist!"));
245
        }
246
        $correctIndex = array_search($input, $keyArray);
247
        return $keyArray[$correctIndex];
248
    }
249
250
    /**
251
     * Checks if the input was a valid string.
252
     * 
253
     * @param mixed   $input           a string to be made SQL-safe
254
     * @param boolean $allowWhitespace whether some whitespace (e.g. newlines should be preserved (true) or redacted (false)
255
     * @return string the massaged string
256
     * @throws Exception
257
     */
258
    public function string($input, $allowWhitespace = FALSE)
259
    {
260
        // always chop out invalid characters, and surrounding whitespace
261
        $retvalStep0 = iconv("UTF-8", "UTF-8//TRANSLIT", $input);
262
        if ($retvalStep0 === FALSE) {
263
            throw new Exception("iconv failure for string sanitisation. With TRANSLIT, this should never happen!");
264
        }
265
        $retvalStep1 = trim($retvalStep0);
266
        // if some funny person wants to inject markup tags, remove them        
267
        $retval = htmlspecialchars(strip_tags($retvalStep1), ENT_NOQUOTES);             
268
        if ($retval === '') {
269
            throw new Exception("filter_var failure for string sanitisation.");
270
        }
271
        // unless explicitly wanted, take away intermediate disturbing whitespace
272
        // a simple "space" is NOT disturbing :-)
273
        if ($allowWhitespace === FALSE) {
274
            $afterWhitespace = preg_replace('/(\0|\r|\x0b|\t|\n)/', '', $retval);
275
        } else {
276
            // even if we allow whitespace, not pathological ones!
277
            $afterWhitespace = preg_replace('/(\0|\r|\x0b)/', '', $retval);
278
        }
279
        if (is_array($afterWhitespace)) {
280
            throw new Exception("This function has to be given a string and returns a string. preg_replace has generated an array instead!");
281
        }
282
        return (string) $afterWhitespace;
283
    }
284
285
    /**
286
     * Is this an integer, or a string that represents an integer?
287
     * 
288
     * @param mixed $input the raw input
289
     * @return boolean|int returns the input, or FALSE if it is not an integer-like value
290
     */
291
    public function integer($input)
292
    {
293
        if (is_numeric($input)) {
294
            return (int) $input;
295
        }
296
        return FALSE;
297
    }
298
299
    /**
300
     * Is this a string representing a potentially more than 64-Bit length integer?
301
     * 
302
     * @param string $input the input data which is possibly a really large integer
303
     * @return boolean|string returns the input, or FALSE if it is not an integer-like string
304
     */
305
    public function hugeInteger($input)
306
    {
307
        if (is_numeric($input)) {
308
            return $input;
309
        }
310
        return FALSE;
311
    }
312
313
    /**
314
     * Checks if the input is the hex representation of a Consortium OI (i.e. three
315
     * or five bytes)
316
     * 
317
     * @param mixed $input the raw input
318
     * @return boolean|string returns the input, or FALSE on validation failure
319
     */
320
    public function consortiumOI($input)
321
    {
322
        $shallow = $this->string($input);
323
        if (strlen($shallow) != 6 && strlen($shallow) != 10) {
324
            return FALSE;
325
        }
326
        if (!preg_match("/^[a-fA-F0-9]+$/", $shallow)) {
327
            return FALSE;
328
        }
329
        return $shallow;
330
    }
331
332
    /**
333
     * Is the input an NAI realm? Throws HTML error and returns FALSE if not.
334
     * 
335
     * @param mixed $input the input to check
336
     * @return boolean|string returns the realm, or FALSE if it was malformed
337
     */
338
    public function realm($input)
339
    {
340
        \core\common\Entity::intoThePotatoes();
341
        if (strlen($input) == 0) {
342
            echo $this->inputValidationError(_("Realm is empty!"));
343
            \core\common\Entity::outOfThePotatoes();
344
            return FALSE;
345
        }
346
347
        // basic string checks
348
        $check = $this->string($input);
349
        // list of things to check, and the error they produce
350
        $pregCheck = [
351
            "/@/" => _("Realm contains an @ sign!"),
352
            "/^\./" => _("Realm begins with a . (dot)!"),
353
            "/\.$/" => _("Realm ends with a . (dot)!"),
354
            "/ /" => _("Realm contains spaces!"),
355
        ];
356
357
        // bark on invalid constructs
358
        foreach ($pregCheck as $search => $error) {
359
            if (preg_match($search, $check) == 1) {
360
                echo $this->inputValidationError($error);
361
                \core\common\Entity::outOfThePotatoes();
362
                return FALSE;
363
            }
364
        }
365
366
        if (preg_match("/\./", $check) == 0) {
367
            echo $this->inputValidationError(_("Realm does not contain at least one . (dot)!"));
368
            \core\common\Entity::outOfThePotatoes();
369
            return FALSE;
370
        }
371
372
        // none of the special HTML entities should be here. In case someone wants
373
        // to mount a CSS attack by providing something that matches the realm constructs
374
        // below but has interesting stuff between, mangle the input so that these
375
        // characters do not do any harm.
376
        \core\common\Entity::outOfThePotatoes();
377
        return htmlentities($check, ENT_QUOTES);
378
    }
379
380
    /**
381
     * could this be a valid username? 
382
     * 
383
     * Only checks correct form, not if the user actually exists in the system.
384
     * 
385
     * @param mixed $input the username
386
     * @return string echoes back the input string, or throws an Exception if bogus
387
     * @throws Exception
388
     */
389
    public function syntaxConformUser($input)
390
    {
391
        $retvalStep0 = iconv("UTF-8", "UTF-8//TRANSLIT", $input);
392
        if ($retvalStep0 === FALSE) {
393
            throw new Exception("iconv failure for string sanitisation. With TRANSLIT, this should never happen!");
394
        }
395
        $retvalStep1 = trim($retvalStep0);
396
397
        $retval = preg_replace('/(\0|\r|\x0b|\t|\n)/', '', $retvalStep1);
398
        if ($retval != "" && !ctype_print($retval)) {
399
            throw new Exception($this->inputValidationError("The user identifier is not an ASCII string!"));
400
        }
401
402
        return $retval;
403
    }
404
405
    /**
406
     * could this be a valid token? 
407
     * 
408
     * Only checks correct form, not if the token actually exists in the system.
409
     * @param mixed $input the raw input
410
     * @return string echoes back the input string, or throws an Exception if bogus
411
     * @throws Exception
412
     */
413
    public function token($input)
414
    {
415
        $retval = $input;
416
        if ($input != "" && preg_match('/[^0-9a-fA-F]/', $input) != 0) {
417
            throw new Exception($this->inputValidationError("Token is not a hexadecimal string!"));
418
        }
419
        return $retval;
420
    }
421
422
    /**
423
     * Is this be a valid coordinate vector on one axis?
424
     * 
425
     * @param mixed $input a numeric value in range of a geo coordinate [-180;180]
426
     * @return string returns back the input if all is good; throws an Exception if out of bounds or not numeric
427
     * @throws Exception
428
     */
429
    public function coordinate($input)
430
    {
431
        $oldlocale = setlocale(LC_NUMERIC, 0);
432
        setlocale(LC_NUMERIC, "en_GB");
433
        if (!is_numeric($input)) {
434
            throw new Exception($this->inputValidationError("Coordinate is not a numeric value!"));
435
        }
436
        setlocale(LC_NUMERIC, $oldlocale);
437
        // lat and lon are always in the range of [-180;+180]
438
        if ($input < -180 || $input > 180) {
439
            throw new Exception($this->inputValidationError("Coordinate is out of bounds. Which planet are you from?"));
440
        }
441
        return $input;
442
    }
443
444
    /**
445
     * Is this a valid coordinate pair in JSON encoded representation?
446
     * 
447
     * @param mixed $input the string to be checked: is this a serialised array with lat/lon keys in a valid number range?
448
     * @return string returns $input if checks have passed; throws an Exception if something's wrong
449
     * @throws Exception
450
     */
451
    public function coordJsonEncoded($input)
452
    {
453
        $tentative = json_decode($input, true);
454
        if (is_array($tentative)) {
455
            if (isset($tentative['lon']) && isset($tentative['lat']) && $this->coordinate($tentative['lon']) && $this->coordinate($tentative['lat'])) {
456
                return $input;
457
            }
458
        }
459
        throw new Exception($this->inputValidationError("Wrong coordinate encoding (2.0 uses JSON, not serialize)!"));
460
    }
461
462
    /**
463
     * This checks the state of a HTML GET/POST "boolean".
464
     * 
465
     * If not checked, no value is submitted at all; if checked, has the word "on". 
466
     * Anything else is a big error.
467
     * 
468
     * @param mixed $input the string to test
469
     * @return boolean TRUE if the input was "on". It is not possible in HTML to signal "off"
470
     * @throws Exception
471
     */
472
    public function boolean($input)
473
    {
474
        if ($input != "on") {
475
            throw new Exception($this->inputValidationError("Unknown state of boolean option!"));
476
        }
477
        return TRUE;
478
    }
479
480
    /**
481
     * checks if we have the strings "IdP" "SP" or "IdPSP"
482
     * 
483
     * @param string $partTypeRaw the string to be validated as participant type
484
     * @return string validated result
485
     * @throws Exception
486
     */
487
    public function partType($partTypeRaw)
488
    {
489
        switch ($partTypeRaw) {
490
            case \core\IdP::TYPE_IDP:
491
                return \core\IdP::TYPE_IDP;
492
            case \core\IdP::TYPE_SP:
493
                return \core\IdP::TYPE_SP;
494
            case \core\IdP::TYPE_IDPSP:
495
                return \core\IdP::TYPE_IDPSP;
496
            default:
497
                throw new Exception("Unknown Participant Type!");
498
        }
499
    }
500
501
    const TABLEMAPPING = [
502
        "IdP" => "institution_option",
503
        "Profile" => "profile_option",
504
        "FED" => "federation_option",
505
    ];
506
507
    /**
508
     * Is this a valid database reference? Has the form <tablename>-<rowID> and there
509
     * needs to be actual data at that place
510
     * 
511
     * @param string $input the reference to check
512
     * @return boolean|array the reference split up into "table" and "rowindex", or FALSE
513
     */
514
    public function databaseReference($input)
515
    {
516
        $pregMatches = [];
517
        if (preg_match("/^ROWID-(IdP|Profile|FED)-([0-9]+)$/", $input, $pregMatches) != 1) {
518
            return FALSE;
519
        }
520
        $rownumber = $this->integer($pregMatches[2]);
521
        if ($rownumber === FALSE) {
522
            return FALSE;
523
        }
524
        return ["table" => self::TABLEMAPPING[$pregMatches[1]], "rowindex" => $rownumber];
525
    }
526
527
    /**
528
     * is this a valid hostname?
529
     * 
530
     * @param mixed $input the raw input
531
     * @return boolean|string echoes the hostname, or FALSE if bogus
532
     */
533
    public function hostname($input)
534
    {
535
        // is it a valid IP address (IPv4 or IPv6), or a hostname?
536
        if (filter_var($input, FILTER_VALIDATE_IP) || filter_var($input, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)) {
537
            // if it's a verified IP address or hostname then it does not contain
538
            // rubbish of course. But just to be sure, run htmlspecialchars around it
539
            return htmlspecialchars($input, ENT_QUOTES);
540
        }
541
        return FALSE;
542
    }
543
544
    /**
545
     * is this a valid email address?
546
     * 
547
     * @param mixed $input the raw input
548
     * @return boolean|string echoes the mail address, or FALSE if bogus
549
     */
550
    public function email($input)
551
    {
552
553
        if (filter_var($this->string($input), FILTER_VALIDATE_EMAIL)) {
554
            return $input;
555
        }
556
        // if we get here, it's bogus
557
        return FALSE;
558
    }
559
560
    /**
561
     * is this a well-formed SMS number? Light massaging - leading + will be removed
562
     * @param string $input the raw input
563
     * @return boolean|string
564
     */
565
    public function sms($input)
566
    {
567
        $number = str_replace(' ', '', str_replace(".", "", str_replace("+", "", $input)));
568
        if (!is_numeric($number)) {
569
            return FALSE;
570
        }
571
        return $number;
572
    }
573
574
    /**
575
     * Is this is a language we support? If not, sanitise to our configured default language.
576
     * 
577
     * @param mixed $input the candidate language identifier
578
     * @return string
579
     * @throws Exception
580
     */
581
    public function supportedLanguage($input)
582
    {
583
        if (!array_key_exists($input, \config\Master::LANGUAGES)) {
584
            return \config\Master::APPEARANCE['defaultlocale'];
585
        }
586
        // otherwise, use the inversion trick to convince Scrutinizer that this is
587
        // a vetted value
588
        $retval = array_search(\config\Master::LANGUAGES[$input], \config\Master::LANGUAGES);
589
        if ($retval === FALSE) {
590
            throw new Exception("Impossible: the value we are searching for does exist, because we reference it directly.");
591
        }
592
        return $retval;
593
    }
594
595
    /**
596
     * Makes sure we are not receiving a bogus option name. The called function throws
597
     * an assertion if the name is not known.
598
     * 
599
     * @param mixed $input the unvetted option name
600
     * @return string
601
     */
602
    public function optionName($input)
603
    {
604
        $object = \core\Options::instance();
605
        return $object->assertValidOptionName($input);
606
    }
607
608
    /**
609
     * Checks to see if the input is a valid image of sorts
610
     * 
611
     * @param mixed $binary blob that may or may not be a parseable image
612
     * @return boolean
613
     */
614
    public function image($binary)
615
    {
616
        if (class_exists('\\Gmagick')) { 
617
            $image = new \Gmagick(); 
618
        } else {
619
            $image = new \Imagick();
620
        }
621
        try {
622
            $image->readImageBlob($binary);
623
        } catch (\ImagickException $exception) {
624
            echo "Error" . $exception->getMessage();
625
            return FALSE;
626
        }
627
        // image survived the sanity check
628
        return TRUE;
629
    }
630
631
    /**
632
     * searches for values in GET and POST, and filters the value according to
633
     * which kind of data is expected
634
     * 
635
     * @param string $varName name of the variable in GET/POST
636
     * @param string $filter  which type of filter to apply (safe_text / int)
637
     * @return NULL|string|integer the returned value
638
     */
639
    public function simpleInputFilter($varName, $filter)
640
    {
641
        $safeText = ["options" => ["regexp" => "/^[\w\d-]+$/"]];
642
        switch ($filter) {
643
            case 'safe_text':
644
                $out = filter_input(INPUT_GET, $varName, FILTER_VALIDATE_REGEXP, $safeText) ?? filter_input(INPUT_POST, $varName, FILTER_VALIDATE_REGEXP, $safeText);
645
                break;
646
            case 'int':
647
                $out = filter_input(INPUT_GET, $varName, FILTER_VALIDATE_INT) ?? filter_input(INPUT_POST, $varName, FILTER_VALIDATE_INT);
648
                break;
649
            default:
650
                $out = NULL;
651
                break;
652
        }
653
        if ($out === false) { // an error occurred during the filter_input runs; make this NULL instead then
654
            $out = NULL;
655
        }
656
        return $out;
657
    }
658
659
}
660