Test Failed
Push — master ( 60b361...3a07f6 )
by Stefan
10:13
created

UIElements   F

Complexity

Total Complexity 60

Size/Duplication

Total Lines 498
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 60
eloc 246
dl 0
loc 498
rs 3.6
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
A boxError() 0 2 1
A previewInfoFileinHTML() 0 14 2
A boxRemark() 0 2 1
A __construct() 0 6 1
A checkROWIDpresence() 0 4 2
A boxFlexible() 0 26 6
D infoblock() 0 68 20
A pngInjectConsortiumLogo() 0 32 1
B previewCAinHTML() 0 30 6
A displaySize() 0 8 3
A instLevelInfoBoxes() 0 33 2
B getBlobFromDB() 0 37 7
A boxOkay() 0 2 1
A previewImageinHTML() 0 6 1
A boxWarning() 0 2 1
B displayName() 0 67 5

How to fix   Complexity   

Complex Class

Complex classes like UIElements often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use UIElements, and based on these observations, apply Extract Interface, too.

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\admin;
24
25
use Exception;
26
27
/**
28
 * This class provides various HTML snippets and other UI-related convenience functions.
29
 * 
30
 * @author Stefan Winter <[email protected]>
31
 */
32
class UIElements extends \core\common\Entity {
33
34
    /**
35
     * the custom displayable variant of the term 'federation'
36
     * 
37
     * @var string
38
     */
39
    public $nomenclatureFed;
40
41
    /**
42
     * the custom displayable variant of the term 'institution'
43
     * 
44
     * @var string
45
     */
46
    public $nomenclatureInst;
47
48
    /**
49
     * Initialises the class.
50
     * 
51
     * Mainly fetches various nomenclature from the config and attempts to translate those into local language. Needs pre-loading some terms.
52
     */
53
    public function __construct() {
54
        // pick up the nomenclature translations from core - no need to repeat
55
        // them here in this catalogue
56
        parent::__construct();
57
        $this->nomenclatureFed = \core\common\Entity::$nomenclature_fed;
58
        $this->nomenclatureInst = \core\common\Entity::$nomenclature_inst;
59
    }
60
61
    /**
62
     * provides human-readable text for the various option names as stored in DB.
63
     * 
64
     * @param string $input raw text in need of a human-readable display variant
65
     * @return string the human-readable variant
66
     * @throws Exception
67
     */
68
    public function displayName($input) {
69
        \core\common\Entity::intoThePotatoes();
70
        $ssidText = _("SSID");
71
        $ssidLegacyText = _("SSID (with WPA/TKIP)");
72
        $passpointOiText = _("HS20 Consortium OI");
73
74
        if (count(CONFIG_CONFASSISTANT['CONSORTIUM']['ssid']) > 0) {
75
            $ssidText = _("Additional SSID");
76
            $ssidLegacyText = _("Additional SSID (with WPA/TKIP)");
77
        }
78
        if (!empty(CONFIG_CONFASSISTANT['CONSORTIUM']['interworking-consortium-oi']) && count(CONFIG_CONFASSISTANT['CONSORTIUM']['interworking-consortium-oi']) > 0) {
79
            $passpointOiText = _("Additional HS20 Consortium OI");
80
        }
81
82
        $displayNames = [_("Support: Web") => "support:url",
83
            _("Support: EAP Types") => "support:eap_types",
84
            _("Support: Phone") => "support:phone",
85
            _("Support: E-Mail") => "support:email",
86
            sprintf(_("%s Name"), $this->nomenclatureInst) => "general:instname",
87
            _("Location") => "general:geo_coordinates",
88
            _("Logo URL") => "general:logo_url",
89
            _("Logo image") => "general:logo_file",
90
            _("Configure Wired Ethernet") => "media:wired",
91
            _("Name (CN) of Authentication Server") => "eap:server_name",
92
            _("Enable device assessment") => "eap:enable_nea",
93
            _("Terms of Use") => "support:info_file",
94
            _("CA Certificate URL") => "eap:ca_url",
95
            _("CA Certificate File") => "eap:ca_file",
96
            _("Profile Display Name") => "profile:name",
97
            _("Production-Ready") => "profile:production",
98
            _("Admin Accepted Terms of Use") => 'hiddenprofile:tou_accepted',
99
            _("Extra text on downloadpage for device") => "device-specific:customtext",
100
            _("Redirection Target") => "device-specific:redirect",
101
            _("Extra text on downloadpage for EAP method") => "eap-specific:customtext",
102
            _("Turn on selection of EAP-TLS User-Name") => "eap-specific:tls_use_other_id",
103
            _("Use GEANTlink TTLS supplicant for W8") => "device-specific:geantlink",
104
            _("Use builtin TTLS supplicant for Windows 10") => "device-specific:builtin_ttls",
105
            _("Profile Description") => "profile:description",
106
            _("Custom Installer Name Suffix") => "profile:customsuffix",
107
            sprintf(_("%s Administrator"), $this->nomenclatureFed) => "user:fedadmin",
108
            _("Real Name") => "user:realname",
109
            _("E-Mail Address") => "user:email",
110
            _("Remove/Disable SSID") => "media:remove_SSID",
111
            _("Mandatory Content Filtering Proxy") => "media:force_proxy",
112
            _("Custom CSS file for User Area") => "fed:css_file",
113
            sprintf(_("%s Logo"), $this->nomenclatureFed) => "fed:logo_file",
114
            _("Preferred Skin for User Area") => "fed:desired_skin",
115
            sprintf(_("Include %s branding in installers"), $this->nomenclatureFed) => "fed:include_logo_installers",
116
            sprintf(_("%s Name"), $this->nomenclatureFed) => "fed:realname",
117
            sprintf(_("%s Homepage"), $this->nomenclatureFed) => "fed:url",
118
            sprintf(_("Custom text in %s Invitations"), $this->nomenclatureInst) => "fed:custominvite",
119
            sprintf(_("Enable %s"), \core\ProfileSilverbullet::PRODUCTNAME) => "fed:silverbullet",
120
            sprintf(_("%s: Do not terminate EAP"), \core\ProfileSilverbullet::PRODUCTNAME) => "fed:silverbullet-noterm",
121
            sprintf(_("%s: max users per profile"), \core\ProfileSilverbullet::PRODUCTNAME) => "fed:silverbullet-maxusers",
122
            sprintf(_("Mint %s with CA on creation"), $this->nomenclatureInst) => "fed:minted_ca_file",
123
            $ssidText => "media:SSID",
124
            $ssidLegacyText => "media:SSID_with_legacy",
125
            $passpointOiText => "media:consortium_OI",
126
        ];
127
128
        $find = array_keys($displayNames, $input, TRUE);
129
130
        if (count($find) == 0) { // this is an error! throw an Exception
131
            throw new \Exception("The translation of an option name was requested, but the option is not known to the system: " . htmlentities($input));
132
        }
133
        \core\common\Entity::outOfThePotatoes();
134
        return $find[0];
135
    }
136
137
    /**
138
     * creates an HTML information block with a list of options from a given category and level
139
     * @param array  $optionlist list of options
140
     * @param string $class      option class of interest
141
     * @param string $level      option level of interest
142
     * @return string HTML code
143
     */
144
    public function infoblock(array $optionlist, string $class, string $level) {
145
        \core\common\Entity::intoThePotatoes();
146
        $locationMarkers = [];
147
        $retval = "";
148
        $optioninfo = \core\Options::instance();
149
150
        foreach ($optionlist as $option) {
151
            $type = $optioninfo->optionType($option['name']);
152
            if (preg_match('/^' . $class . '/', $option['name']) && $option['level'] == "$level") {
153
                // all non-multilang attribs get this assignment ...
154
                $language = "";
155
                $content = $option['value'];
156
                // ... override them with multilang tags if needed
157
                if ($type["flag"] == "ML") {
158
                    $language = _("default/other languages");
159
                    if ($option['lang'] != 'C') {
160
                        $language = CONFIG['LANGUAGES'][$option['lang']]['display'] ?? "(unsupported language)";
161
                    }
162
                }
163
164
                switch ($type["type"]) {
165
                    case "coordinates":
166
                        $coords = json_decode($option['value'], true);
167
                        $locationMarkers[] = $coords;
168
                        break;
169
                    case "file":
170
                        $retval .= "<tr><td>" . $this->displayName($option['name']) . "</td><td>$language</td><td>";
171
                        switch ($option['name']) {
172
                            case "general:logo_file":
173
                            case "fed:logo_file":
174
                                $retval .= $this->previewImageinHTML('ROWID-' . $option['level'] . '-' . $option['row']);
175
                                break;
176
                            case "eap:ca_file":
177
                            // fall-through intended: display both the same way
178
                            case "fed:minted_ca_file":
179
                                $retval .= $this->previewCAinHTML('ROWID-' . $option['level'] . '-' . $option['row']);
180
                                break;
181
                            case "support:info_file":
182
                                $retval .= $this->previewInfoFileinHTML('ROWID-' . $option['level'] . '-' . $option['row']);
183
                                break;
184
                            default:
185
                        }
186
                        break;
187
                    case "boolean":
188
                        if ($option['name'] == "fed:silverbullet" && CONFIG['FUNCTIONALITY_LOCATIONS']['CONFASSISTANT_SILVERBULLET'] == "LOCAL" && CONFIG['FUNCTIONALITY_LOCATIONS']['CONFASSISTANT_RADIUS'] != "LOCAL") {
189
                            // do not display the option at all; it gets auto-set by the ProfileSilverbullet constructor and doesn't have to be seen
190
                            break;
191
                        }
192
                        $retval .= "<tr><td>" . $this->displayName($option['name']) . "</td><td>$language</td><td><strong>" . ($content == "on" ? _("on") : _("off") ) . "</strong></td></tr>";
193
                        break;
194
                    default:
195
                        $retval .= "<tr><td>" . $this->displayName($option['name']) . "</td><td>$language</td><td><strong>$content</strong></td></tr>";
196
                }
197
            }
198
        }
199
        if (count($locationMarkers)) {
200
            $marker = '<markers>';
201
            $locationCount = 0;
202
            foreach ($locationMarkers as $g) {
203
                $locationCount++;
204
                $marker .= '<marker name="' . $locationCount . '" lat="' . $g['lat'] . '" lng="' . $g['lon'] . '" />';
205
            }
206
            $marker .= '<\/markers>'; // some validator says this should be escaped
207
            $jMarker = json_encode($locationMarkers);
208
            $retval .= '<tr><td><script>markers=\'' . $marker . '\'; jmarkers = \'' . $jMarker . '\';</script></td><td></td><td></td></tr>';
209
        }
210
        \core\common\Entity::outOfThePotatoes();
211
        return $retval;
212
    }
213
214
    /**
215
     * creates HTML code to display all information boxes for an IdP
216
     * 
217
     * @param \core\IdP $myInst the IdP in question
218
     * @return string HTML code
219
     */
220
    public function instLevelInfoBoxes(\core\IdP $myInst) {
221
        \core\common\Entity::intoThePotatoes();
222
        $idpoptions = $myInst->getAttributes();
223
        $retval = "<div class='infobox'>
224
        <h2>" . sprintf(_("General %s details"), $this->nomenclatureInst) . "</h2>
225
        <table>
226
            <tr>
227
                <td>
228
                    " . _("Country:") . "
229
                </td>
230
                <td>
231
                </td>
232
                <td>
233
                    <strong>";
234
        $myFed = new \core\Federation($myInst->federation);
235
        $retval .= $myFed->name;
236
        $retval .= "</strong>
237
                </td>
238
            </tr>" . $this->infoblock($idpoptions, "general", "IdP") . "
239
        </table>
240
    </div>";
241
242
        $blocks = [["support", _("Global Helpdesk Details")], ["media", _("Media Properties")]];
243
        foreach ($blocks as $block) {
244
            $retval .= "<div class='infobox'>
245
            <h2>" . $block[1] . "</h2>
246
            <table>" .
247
                    $this->infoblock($idpoptions, $block[0], "IdP") .
248
                    "</table>
249
        </div>";
250
        }
251
        \core\common\Entity::outOfThePotatoes();
252
        return $retval;
253
    }
254
255
    /**
256
     * pretty-prints a file size number in SI "bi" units
257
     * @param int $number the size of the file
258
     * @return string the pretty-print representation of the file size
259
     */
260
    private function displaySize(int $number) {
261
        if ($number > 1024 * 1024) {
262
            return round($number / 1024 / 1024, 2) . " MiB";
263
        }
264
        if ($number > 1024) {
265
            return round($number / 1024, 2) . " KiB";
266
        }
267
        return $number . " B";
268
    }
269
270
    /**
271
     * 
272
     * @param string  $ref         the database reference string
273
     * @param boolean $checkpublic should we check if the requested piece of data is public?
274
     * @return string|boolean the requested data, or FALSE if something went wrong
275
     */
276
    public static function getBlobFromDB($ref, $checkpublic) {
277
        $validator = new \web\lib\common\InputValidation();
278
        $reference = $validator->databaseReference($ref);
279
280
        if ($reference === FALSE) {
1 ignored issue
show
introduced by
The condition $reference === FALSE is always false.
Loading history...
281
            return FALSE;
282
        }
283
284
        // the data is either public (just give it away) or not; in this case, only
285
        // release if the data belongs to admin himself
286
        if ($checkpublic) {
287
288
            $owners = \core\EntityWithDBProperties::isDataRestricted($reference["table"], $reference["rowindex"]);
289
290
            $ownersCondensed = [];
291
292
            if ($owners !== FALSE) { // restricted data, see if we're authenticated and owners of the data
293
                $auth = new \web\lib\admin\Authentication();
294
                if (!$auth->isAuthenticated()) {
295
                    return FALSE; // admin-only, but we are not an admin
296
                }
297
                // we might be called without session context (filepreview) so get the
298
                // context if needed
299
                CAT_session_start();
300
301
                foreach ($owners as $oneowner) {
302
                    $ownersCondensed[] = $oneowner['ID'];
303
                }
304
                if (array_search($_SESSION['user'], $ownersCondensed) === FALSE) {
305
                    return FALSE; // wrong guy
306
                }
307
                // carry on and get the data
308
            }
309
        }
310
311
        $blob = \core\EntityWithDBProperties::fetchRawDataByIndex($reference["table"], $reference["rowindex"]);
312
        return $blob; // this means we might return FALSE here if something was wrong with the original requested reference
313
    }
314
315
    /**
316
     * 
317
     * @param string $reference a reference pointer to a database entry
318
     * @return void
319
     * @throws Exception
320
     */
321
    private function checkROWIDpresence($reference) {
322
        $found = preg_match("/^ROWID-.*/", $reference);
323
        if ($found != 1) { // get excited on not-found AND on execution error
324
            throw new Exception("Error, ROWID expected.");
325
        }
326
    }
327
328
    /**
329
     * creates HTML code to display a nice UI representation of a CA
330
     * 
331
     * @param string $cAReference ROWID pointer to the CA to display
332
     * @return string HTML code
333
     */
334
    public function previewCAinHTML($cAReference) {
335
        \core\common\Entity::intoThePotatoes();
336
        $this->checkROWIDpresence($cAReference);
337
        $rawResult = UIElements::getBlobFromDB($cAReference, FALSE);
338
        if (is_bool($rawResult)) { // we didn't actually get a CA!
1 ignored issue
show
introduced by
The condition is_bool($rawResult) is always true.
Loading history...
339
            $retval = "<div class='ca-summary'>" . _("There was an error while retrieving the certificate from the database!") . "</div>";
340
            \core\common\Entity::outOfThePotatoes();
341
            return $retval;
342
        }
343
        $cAblob = base64_decode($rawResult);
344
345
        $func = new \core\common\X509;
346
        $details = $func->processCertificate($cAblob);
347
        if ($details === FALSE) {
348
            $retval = _("There was an error processing the certificate!");
349
            \core\common\Entity::outOfThePotatoes();
350
            return $retval;
351
        }
352
353
        $details['name'] = preg_replace('/(.)\/(.)/', "$1<br/>$2", $details['name']);
354
        $details['name'] = preg_replace('/\//', "", $details['name']);
355
        $certstatus = ( $details['root'] == 1 ? "R" : "I");
356
        if ($details['ca'] == 0 && $details['root'] != 1) {
357
            $retval = "<div class='ca-summary' style='background-color:red'><div style='position:absolute; right: 0px; width:20px; height:20px; background-color:maroon;  border-radius:10px; text-align: center;'><div style='padding-top:3px; font-weight:bold; color:#ffffff;'>S</div></div>" . _("This is a <strong>SERVER</strong> certificate!") . "<br/>" . $details['name'] . "</div>";
358
            \core\common\Entity::outOfThePotatoes();
359
            return $retval;
360
        }
361
        $retval = "<div class='ca-summary'                                ><div style='position:absolute; right: 0px; width:20px; height:20px; background-color:#0000ff; border-radius:10px; text-align: center;'><div style='padding-top:3px; font-weight:bold; color:#ffffff;'>$certstatus</div></div>" . $details['name'] . "</div>";
362
        \core\common\Entity::outOfThePotatoes();
363
        return $retval;
364
    }
365
366
    /**
367
     * creates HTML code to display a nice UI representation of an image
368
     * 
369
     * @param string $imageReference ROWID pointer to the image to display
370
     * @return string HTML code
371
     */
372
    public function previewImageinHTML($imageReference) {
373
        \core\common\Entity::intoThePotatoes();
374
        $this->checkROWIDpresence($imageReference);
375
        $retval = "<img style='max-width:150px' src='inc/filepreview.php?id=" . $imageReference . "' alt='" . _("Preview of logo file") . "'/>";
376
        \core\common\Entity::outOfThePotatoes();
377
        return $retval;
378
    }
379
380
    /**
381
     * creates HTML code to display a nice UI representation of a TermsOfUse file
382
     * 
383
     * @param string $fileReference ROWID pointer to the file to display
384
     * @return string HTML code
385
     */
386
    public function previewInfoFileinHTML($fileReference) {
387
        \core\common\Entity::intoThePotatoes();
388
        $this->checkROWIDpresence($fileReference);
389
        $fileBlob = UIElements::getBlobFromDB($fileReference, FALSE);
390
        if (is_bool($fileBlob)) { // we didn't actually get a file!
1 ignored issue
show
introduced by
The condition is_bool($fileBlob) is always true.
Loading history...
391
            $retval = "<div class='ca-summary'>" . _("There was an error while retrieving the file from the database!") . "</div>";
392
            \core\common\Entity::outOfThePotatoes();
393
            return $retval;
394
        }
395
        $decodedFileBlob = base64_decode($fileBlob);
396
        $fileinfo = new \finfo();
397
        $retval = "<div class='ca-summary'>" . _("File exists") . " (" . $fileinfo->buffer($decodedFileBlob, FILEINFO_MIME_TYPE) . ", " . $this->displaySize(strlen($decodedFileBlob)) . ")<br/><a href='inc/filepreview.php?id=$fileReference'>" . _("Preview") . "</a></div>";
398
        \core\common\Entity::outOfThePotatoes();
399
        return $retval;
400
    }
401
402
    /**
403
     * creates HTML code for a UI element which informs the user about something.
404
     * 
405
     * @param int    $level         what kind of information is to be displayed?
406
     * @param string $text          the text to display
407
     * @param string $caption       the caption to display
408
     * @param bool   $omittabletags the output usually has tr/td table tags, this option suppresses them
409
     * @return string
410
     */
411
    public function boxFlexible(int $level, string $text = NULL, string $caption = NULL, bool $omittabletags = FALSE) {
412
        \core\common\Entity::intoThePotatoes();
413
        $uiMessages = [
414
            \core\common\Entity::L_OK => ['icon' => '../resources/images/icons/Quetto/check-icon.png', 'text' => _("OK")],
415
            \core\common\Entity::L_REMARK => ['icon' => '../resources/images/icons/Quetto/info-icon.png', 'text' => _("Remark")],
416
            \core\common\Entity::L_WARN => ['icon' => '../resources/images/icons/Quetto/danger-icon.png', 'text' => _("Warning!")],
417
            \core\common\Entity::L_ERROR => ['icon' => '../resources/images/icons/Quetto/no-icon.png', 'text' => _("Error!")],
418
        ];
419
420
        $retval = "";
421
        if (!$omittabletags) {
422
            $retval .= "<tr><td>";
423
        }
424
        $finalCaption = ($caption !== NULL ? $caption : $uiMessages[$level]['text']);
425
        $retval .= "<img class='icon' src='" . $uiMessages[$level]['icon'] . "' alt='" . $finalCaption . "' title='" . $finalCaption . "'/>";
426
        if (!$omittabletags) {
427
            $retval .= "</td><td>";
428
        }
429
        if ($text !== NULL) {
430
            $retval .= $text;
431
        }
432
        if (!$omittabletags) {
433
            $retval .= "</td></tr>";
434
        }
435
        \core\common\Entity::outOfThePotatoes();
436
        return $retval;
437
    }
438
439
    /**
440
     * creates HTML code to display an "all is okay" message
441
     * 
442
     * @param string $text          the text to display
443
     * @param string $caption       the caption to display
444
     * @param bool   $omittabletags the output usually has tr/td table tags, this option suppresses them
445
     * @return string HTML: the box
446
     */
447
    public function boxOkay(string $text = NULL, string $caption = NULL, bool $omittabletags = FALSE) {
448
        return $this->boxFlexible(\core\common\Entity::L_OK, $text, $caption, $omittabletags);
449
    }
450
451
    /**
452
     * creates HTML code to display a "smartass comment" message
453
     * 
454
     * @param string $text          the text to display
455
     * @param string $caption       the caption to display
456
     * @param bool   $omittabletags the output usually has tr/td table tags, this option suppresses them
457
     * @return string HTML: the box
458
     */
459
    public function boxRemark(string $text = NULL, string $caption = NULL, bool $omittabletags = FALSE) {
460
        return $this->boxFlexible(\core\common\Entity::L_REMARK, $text, $caption, $omittabletags);
461
    }
462
463
    /**
464
     * creates HTML code to display a "something's a bit wrong" message
465
     * 
466
     * @param string $text          the text to display
467
     * @param string $caption       the caption to display
468
     * @param bool   $omittabletags the output usually has tr/td table tags, this option suppresses them
469
     * @return string HTML: the box
470
     */
471
    public function boxWarning(string $text = NULL, string $caption = NULL, bool $omittabletags = FALSE) {
472
        return $this->boxFlexible(\core\common\Entity::L_WARN, $text, $caption, $omittabletags);
473
    }
474
475
    /**
476
     * creates HTML code to display a "Whoa! Danger, Will Robinson!" message
477
     * 
478
     * @param string $text          the text to display
479
     * @param string $caption       the caption to display
480
     * @param bool   $omittabletags the output usually has tr/td table tags, this option suppresses them
481
     * @return string HTML: the box
482
     */
483
    public function boxError(string $text = NULL, string $caption = NULL, bool $omittabletags = FALSE) {
484
        return $this->boxFlexible(\core\common\Entity::L_ERROR, $text, $caption, $omittabletags);
485
    }
486
487
    /**
488
     * Injects the consortium logo in the middle of a given PNG.
489
     * 
490
     * Usually used on QR code PNGs - the parameters inform about the structure of
491
     * the QR code so that the logo does not prevent parsing of the QR code.
492
     * 
493
     * @param string $inputpngstring the PNG to edit
494
     * @param int    $symbolsize     size in pixels of one QR "pixel"
495
     * @param int    $marginsymbols  size in pixels of border around the actual QR
496
     * @return string the image with logo centered in the middle
497
     */
498
    public function pngInjectConsortiumLogo(string $inputpngstring, int $symbolsize, int $marginsymbols = 4) {
499
        $loggerInstance = new \core\common\Logging();
500
        $inputgd = imagecreatefromstring($inputpngstring);
501
502
        $loggerInstance->debug(4, "Consortium logo is at: " . ROOT . "/web/resources/images/consortium_logo_large.png");
503
        $logogd = imagecreatefrompng(ROOT . "/web/resources/images/consortium_logo_large.png");
504
505
        $sizeinput = [imagesx($inputgd), imagesy($inputgd)];
506
        $sizelogo = [imagesx($logogd), imagesy($logogd)];
507
        // Q level QR-codes can sustain 25% "damage"
508
        // make our logo cover approx 15% of area to be sure; mind that there's a $symbolsize * $marginsymbols pixel white border around each edge
509
        $totalpixels = ($sizeinput[0] - $symbolsize * $marginsymbols) * ($sizeinput[1] - $symbolsize * $marginsymbols);
510
        $totallogopixels = ($sizelogo[0]) * ($sizelogo[1]);
511
        $maxoccupy = $totalpixels * 0.04;
512
        // find out how much we have to scale down logo to reach 10% QR estate
513
        $scale = sqrt($maxoccupy / $totallogopixels);
514
        $loggerInstance->debug(4, "Scaling info: $scale, $maxoccupy, $totallogopixels\n");
515
        // determine final pixel size - round to multitude of $symbolsize to match exact symbol boundary
516
        $targetwidth = (int)($symbolsize * round($sizelogo[0] * $scale / $symbolsize));
517
        $targetheight = (int)($symbolsize * round($sizelogo[1] * $scale / $symbolsize));
518
        // paint white below the logo, in case it has transparencies (looks bad)
519
        // have one symbol in each direction extra white space
520
        $whiteimage = imagecreate($targetwidth + 2 * $symbolsize, $targetheight + 2 * $symbolsize);
521
        imagecolorallocate($whiteimage, 255, 255, 255);
522
        // also make sure the initial placement is a multitude of 12; otherwise "two half" symbols might be affected
523
        $targetplacementx = (int)($symbolsize * round(($sizeinput[0] / 2 - ($targetwidth - $symbolsize) / 2) / $symbolsize));
524
        $targetplacementy = (int)($symbolsize * round(($sizeinput[1] / 2 - ($targetheight - $symbolsize) / 2) / $symbolsize));
525
        imagecopyresized($inputgd, $whiteimage, $targetplacementx - $symbolsize, $targetplacementy - $symbolsize, 0, 0, $targetwidth + 2 * $symbolsize, $targetheight + 2 * $symbolsize, $targetwidth + 2 * $symbolsize, $targetheight + 2 * $symbolsize);
526
        imagecopyresized($inputgd, $logogd, $targetplacementx, $targetplacementy, 0, 0, $targetwidth, $targetheight, $sizelogo[0], $sizelogo[1]);
527
        ob_start();
528
        imagepng($inputgd);
529
        return ob_get_clean();
530
    }
531
532
}
533