Support.php 30.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 1/28/16
 * Time: 8:05 AM
 */

namespace qfq;

11
require_once(__DIR__ . '/../Constants.php');
Carsten  Rose's avatar
Carsten Rose committed
12
require_once(__DIR__ . '/Sanitize.php');
13

14
15
16
const LONG_CURLY_OPEN = '#/+open+/#';
const LONG_CURLY_CLOSE = '#/+close+/#';

17
18
class Support {

19
    /**
Carsten  Rose's avatar
Carsten Rose committed
20
21
     * @param array  $queryArray Empty or prefilled assoc array with url parameter
     * @param string $mode       PARAM_T3_NO_ID, PARAM_T3_ALL
22
     */
23
    public static function appendTypo3ParameterToArray(array &$queryArray, $mode = PARAM_T3_ALL) {
24
25
//        if (isset($_GET['id']))
//            $queryArray['id'] = self::getCurrentPage();
26

27
        $store = Store::getInstance();
28

29
30
31
32
33
34
35
36
37
        if ($mode === PARAM_T3_ALL) {
            $queryArray['id'] = $store->getVar(TYPO3_PAGE_ID, STORE_TYPO3);
        }

        // TYPE
        $tmp = $store->getVar(TYPO3_PAGE_TYPE, STORE_TYPO3);
        if ($tmp !== false && $tmp != 0) {
            $queryArray['type'] = $tmp;
        }
38

39
40
41
42
43
        // Language
        $tmp = $store->getVar(TYPO3_PAGE_LANGUAGE, STORE_TYPO3);
        if ($tmp !== false && $tmp != 0) {
            $queryArray['L'] = $tmp;
        }
44
45
    }

46
    /**
47
48
     * Builds a urlencoded query string of an assoc array.
     *
49
     * @param array $queryArray
Carsten  Rose's avatar
Carsten Rose committed
50
     *
51
     * @return string Querystring (e.g.: id=23&type=99
52
53
54
55
56
57
58
59
60
61
62
63
64
65
     */
    public static function arrayToQueryString(array $queryArray) {
        $items = array();

        foreach ($queryArray as $key => $value) {
            if (is_int($key)) {
                $items[] = urlencode($value);
            } else {
                $items[] = $key . '=' . urlencode($value);
            }
        }

        return implode('&', $items);
    }
66
67

    /**
Carsten  Rose's avatar
Carsten Rose committed
68
69
     * Extract Tag(s) from $tag (eg: <div><input class="form-control">, might contain further attributes) and wrap it
     * around
Carsten  Rose's avatar
Carsten Rose committed
70
     * $value. If $flagOmitEmpty==true && $value=='': return ''.
71
     *
Carsten  Rose's avatar
Carsten Rose committed
72
73
     * @param string     $tag
     * @param string     $value
74
     * @param bool|false $omitIfValueEmpty
Carsten  Rose's avatar
Carsten Rose committed
75
     *
76
77
78
     * @return string
     */
    public static function wrapTag($tag, $value, $omitIfValueEmpty = false) {
79
80
81
82
83
84
85
86
87
88
89
90

        $tag = trim($tag);

        if ($tag == '' || ($omitIfValueEmpty && $value == "")) {
            return $value;
        }

        $tagArray = explode('>', $tag, 2);
        if (count($tagArray) > 1 && $tagArray[1] != '') {
            $value = self::wrapTag($tagArray[1], $value, $omitIfValueEmpty);
            $tag = $tagArray[0] . '>';
        }
91
92
93
94
95
96
97
98
99
100

        // a) <div class="container-fluid">, b) <label>
        $arr = explode(' ', $tag);

        $tagPlain = (count($arr) === 1) ? substr($arr[0], 1, strlen($arr[0]) - 2) : substr($arr[0], 1);
        $closing = '</' . $tagPlain . '>';

        return $tag . $value . $closing;
    }

101
102
103
104
105
    /**
     * Wraps some $inner fragment with a CSS styled $tooltipText . CSS is configured in 'Resources/Public/qfq-jqw.css'.
     *
     * Based on: http://www.w3schools.com/howto/howto_css_tooltip.asp
     *
106
     * @param string $htmlId
107
     * @param string $tooltipText
Carsten  Rose's avatar
Carsten Rose committed
108
     *
109
110
111
112
113
114
115
     * @return string
     */
    public static function doTooltip($htmlId, $tooltipText) {

        return "<img " . self::doAttribute('id', $htmlId) . " src='" . GFX_INFO . "' title=\"" . htmlentities($tooltipText) . "\">";
    }

116
117
    /**
     * Format's an attribute: $type=$value. If $flagOmitEmpty==true && $value=='': return ''.
118
     * Add's a space at the end.
119
     *
Carsten  Rose's avatar
Carsten Rose committed
120
     * @param string       $type
121
     * @param string|array $value
Carsten  Rose's avatar
Carsten Rose committed
122
123
124
     * @param bool         $flagOmitEmpty
     * @param string       $modeEscape
     *
125
126
     * @return string correctly fomratted attribute. Space at the end.
     * @throws CodeException
127
     */
128
    public static function doAttribute($type, $value, $flagOmitEmpty = true, $modeEscape = ESCAPE_WITH_BACKSLASH) {
129
130
131
132
133
134

        // several attributes might be given as an array - concat to a string
        if (is_array($value)) {
            $value = implode(' ', $value);
        }

135
        if ($flagOmitEmpty && $value === "") {
136
            return '';
137
138
        }

139
        switch (strtolower($type)) {
140
141
            case 'size':
            case 'maxlength':
142
                // empty or '0' for attributes of type 'size' or 'maxlength' result in unsuable input elements: skip this.
143
144
145
146
                if ($value === '' || $value == 0) {
                    return '';
                }
                break;
147
148
149
150
151
            // Bad idea to do urlencode on this place: it will convert ?, &, ... which are necessary for a proper URL.
            // Instead the value of a parameter needs to encode. Unfortunately, it's too late on this place.
//            case 'href':
//                $value = urlencode($value);
//                break;
152
153
154
            default:
                break;
        }
155

156
157
        $value = self::escapeDoubleTick(trim($value), $modeEscape);

158
159
160
161
162
        return $type . '="' . $value . '" ';
    }

    /**
     * Escapes Double Ticks ("), which are not already escaped.
163
164
165
     * modeEscape: ESCAPE_WITH_BACKSLASH | ESCAPE_WITH_HTML_QUOTE
     *
     * TinyMCE: Encoding JS Attributes (keys & values) for TinyMCE needs to be encapsulated in '&quot;' instead of '\"'.
166
     *
Carsten  Rose's avatar
Carsten Rose committed
167
     * @param        $str
168
     * @param string $modeEscape
Carsten  Rose's avatar
Carsten Rose committed
169
     *
170
     * @return string
171
     * @throws CodeException
172
     */
173
    public static function escapeDoubleTick($str, $modeEscape = ESCAPE_WITH_BACKSLASH) {
174
175
176
177
178
        $newStr = '';

        for ($ii = 0; $ii < strlen($str); $ii++) {
            if ($str[$ii] === '"') {
                if ($ii === 0 || $str[$ii - 1] != '\\') {
179
180
181
182
183
184
185
186
187
188
                    switch ($modeEscape) {
                        case ESCAPE_WITH_BACKSLASH:
                            $newStr .= '\\';
                            break;
                        case ESCAPE_WITH_HTML_QUOTE:
                            $newStr .= '&quot;';
                            continue 2;
                        default:
                            throw new CodeException('Unknown modeEscape=' . $modeEscape, ERROR_UNKNOWN_ESCAPE_MODE);
                    }
189
190
191
192
193
194
                }
            }
            $newStr .= $str[$ii];
        }

        return $newStr;
195
196
    }

197
198
199
200
    /**
     * Format's an attribute and inserts them at the beginning of the $htmlTag:
     * If $flagOmitEmpty==true && $value=='': insert nothing
     *
Carsten  Rose's avatar
Carsten Rose committed
201
202
     * @param string       $htmlTag with open and closing angle.
     * @param string       $type
203
     * @param string|array $value
Carsten  Rose's avatar
Carsten Rose committed
204
205
206
     * @param bool         $flagOmitEmpty
     * @param string       $modeEscape
     *
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
     * @return string correctly fomratted attribute. Space at the end.
     * @throws CodeException
     */
    public static function insertAttribute($htmlTag, $type, $value, $flagOmitEmpty = true, $modeEscape = ESCAPE_WITH_BACKSLASH) {
        $htmlTag = trim($htmlTag);

        // e.g. '<div class=...' will be exploded to '<div' and 'class=...'
        $parts = explode(' ', $htmlTag, 2);
        if (count($parts) < 2) {
            if (strlen($htmlTag) < 3) {
                throw new CodeException('HTML Token too short (<3 chars):' . $htmlTag, ERROR_HTML_TOKEN_TOO_SHORT);
            } else {
                $parts[0] = substr($htmlTag, 0, -1);
                $parts[1] = '>';
            }
        }

        $attr = self::doAttribute($type, $value, $flagOmitEmpty, $modeEscape);

        return $parts[0] . ' ' . $attr . $parts[1];
    }

229
    /**
230
     * Search for the parameter $needle in $haystack. The arguments has to be seperated by ','.
231
     *
232
     * Returns false if not found or index of found place. Be carefull: use unary operator to compare for 'false'
233
     *
Carsten  Rose's avatar
Carsten Rose committed
234
235
     * @param string $needle
     * @param string $haystack
Carsten  Rose's avatar
Carsten Rose committed
236
     *
237
     * @return boolean     true if found, else false
238
     */
239
240
241
242
    public static function findInSet($needle, $haystack) {
        $arr = explode(',', $haystack);

        return array_search($needle, $arr) !== false;
243
    }
244

245
    /**
246
     * Converts a dateTime String to the international format:
247
248
249
250
     * 1.2.79 > 1979-02-01 00:00:00
     * 01.02.13 3:24 >  1979-02-01 03:24:00
     * 1.2.1979 14:21:5 > 1979-02-01 14:21:05
     *
Carsten  Rose's avatar
Carsten Rose committed
251
     * @param string $dateTimeString
Carsten  Rose's avatar
Carsten Rose committed
252
     *
253
     * @return string
254
     * @throws UserFormException
255
     */
256
    public static function dateTimeGermanToInternational($dateTimeString) {
257
258
259
        $dateRaw = '';
        $timeRaw = '';

260
261
262
263
264

//        const REGEXP_DATE_INT_ = '^\d{2,4}-\d{2}-\d{2}$';
//        const REGEXP_DATE_GER = '^\d{1,2}\.\d{1,2}\.\d{2}(\d{2})?$';
//        const REGEXP_TIME = '^\d{1,2}:\d{1,2}(:\d{1,2})?$';

265
266
267
268
269
270
        $tmpArr = explode(' ', $dateTimeString);
        switch (count($tmpArr)) {
            case 0:
                return '';

            case 1:
271
                if (strpos($tmpArr[0], ':') === false) {
272
                    $dateRaw = $tmpArr[0];
273
274
                } else {
                    $timeRaw = $tmpArr[0];
275
276
277
278
279
280
281
282
283
                }
                break;

            case 2:
                $dateRaw = $tmpArr[0];
                $timeRaw = $tmpArr[1];
                break;

            default:
284
                throw new UserFormException('Date/time format not recognised.', ERROR_DATE_TIME_FORMAT_NOT_RECOGNISED);
285
286
287
288
289
290
                break;
        }

        if ($dateRaw === '') {
            $date = '0000-00-00';
        } else {
291
            // International format: YYYY-MM-DD
292
293

            if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateRaw) === 1) {
294
295
296
                $date = $dateRaw;

                // German format: 1.1.01 - 11.12.1234
297
            } elseif (preg_match('/^\d{1,2}\.\d{1,2}\.\d{2}(\d{2})?$/', $dateRaw) === 1) {
298
299
300
301
302
303
304
305
306
307
308
                $tmpArr = explode('.', $dateRaw);

                if ($tmpArr[2] < 70) {
                    $tmpArr[2] = 2000 + $tmpArr[2];
                } elseif ($tmpArr[2] < 100) {
                    $tmpArr[2] = 1900 + $tmpArr[2];
                }
                $date = sprintf("%04d-%02d-%02d", $tmpArr[2], $tmpArr[1], $tmpArr[0]);

            } else {
                throw new UserFormException('Date/time format not recognised.', ERROR_DATE_TIME_FORMAT_NOT_RECOGNISED);
309
310
311
312
313
314
            }
        }

        if ($timeRaw === '') {
            $time = '00:00:00';
        } else {
315
            if (preg_match('/^\d{1,2}:\d{1,2}(:\d{1,2})?$/', $timeRaw) !== 1) {
316
317
318
                throw new UserFormException('Date/time format not recognised.', ERROR_DATE_TIME_FORMAT_NOT_RECOGNISED);
            }

319
320
321
322
323
324
325
326
327
            $tmpArr = explode(':', $timeRaw);
            switch (count($tmpArr)) {
                case 2:
                    $time = sprintf("%02d:%02d:00", $tmpArr[0], $tmpArr[1]);
                    break;
                case 3:
                    $time = sprintf("%02d:%02d:%02d", $tmpArr[0], $tmpArr[1], $tmpArr[2]);
                    break;
                default:
328
                    throw new UserFormException('Date/time format not recognised.', ERROR_DATE_TIME_FORMAT_NOT_RECOGNISED);
329
330
331
332
333
334
                    break;
            }
        }

        return $date . ' ' . $time;
    }
335

336
337
338
    /**
     * @param string $type date | datetime | time
     * @param string $format FORMAT_DATE_INTERNATIONAL | FORMAT_DATE_GERMAN
Carsten  Rose's avatar
Carsten Rose committed
339
     * @param string $showSeconds
Carsten  Rose's avatar
Carsten Rose committed
340
     *
341
342
343
344
345
346
347
     * @return string
     * @throws UserFormException
     */
    public static function dateTimeRegexp($type, $format) {

        if ($format === FORMAT_DATE_GERMAN) {
            // yyyy-mm-dd | 0000-00-00
Carsten  Rose's avatar
Carsten Rose committed
348
            $date = '(([1-9]|0[1-9]|1[0-9]|2[0-9]|3[01])\.([1-9]|0[1-9]|1[012])\.([0-9]{4}|[0-9]{2})|00\.00\.(00){1,2})';
349
350
        } else {
            // FORMAT_DATE_INTERNATIONAL: [d]d.[m]m.[yy]yy | 00.00.0000
Carsten  Rose's avatar
Carsten Rose committed
351
            $date = '([0-9]{4}-([1-9]|0[1-9]|1[012])-([1-9]|0[1-9]|1[0-9]|2[0-9]|3[01])|0000-00-00)';
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
        }

        // hh:mm[:ss]
        $time = '(0[0-9]|1[0-9]|2[0-3])(:[0-5][0-9]){1,2}';

        switch ($type) {
            case 'date':
                $pattern = $date;
                break;
            case 'datetime':
                $pattern = $date . ' ' . $time;
                break;
            case 'time':
                $pattern = $time;
                break;
            default:
                throw new UserFormException("Unknown mode: '$type'", ERROR_UNKNOWN_MODE);
        }

        return '^' . $pattern . '$';
    }

    /**
     * Parses $dateTimeString. If a date is given, detect international or german format automatically.
     * Convert to $dateFormat. 'yy' and 'd' will be converted to 'yyyy' and 'dd'
     * Returned value will be 'date only', 'datetime' oder 'time only', depending on the input value.
     *
     * @param string $dateTimeString
Carsten  Rose's avatar
Carsten Rose committed
380
381
382
383
     * @param string $dateFormat
     * @param string $showZero
     * @param string $showTime
     * @param string $showSeconds
Carsten  Rose's avatar
Carsten Rose committed
384
     *
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
     * @return string
     * @throws UserFormException
     */
    public static function convertDateTime($dateTimeString, $dateFormat, $showZero, $showTime, $showSeconds) {
        $givenDate = '';
        $givenTime = '';
        $newDate = '';
        $newTime = '';
        $delim = '';

        $dateTimeString = trim($dateTimeString);


        switch ($dateTimeString) {
            case '':
            case '0':
            case '0000-00-00 00:00:00':
            case '0000-00-00':
            case '00:00:00':
                return (self::dateTimeZero($dateFormat, $showZero, $showTime, $showSeconds));
                break;

            default:
                break;
        }

        // Main convert
        $arr = explode(' ', $dateTimeString);
        switch (count($arr)) {
            case 1:
                if (strpos($dateTimeString, ':') === false) {
                    $givenDate = $dateTimeString;
                } else {
                    $givenTime = $dateTimeString;
                }
                break;

            case 2:
                $givenDate = $arr[0];
                $givenTime = $arr[1];
            default:
        }


        // Date
        if ($givenDate != '') {
            if ($givenDate == '0')
                $givenDate = '0000-00-00';

            $arr = self::splitDateToArray($givenDate);

            switch ($dateFormat) {
                case FORMAT_DATE_INTERNATIONAL:
                    $newDate = sprintf("%04d-%02d-%02d", $arr[0], $arr[1], $arr[2]);
                    break;
                case FORMAT_DATE_GERMAN:
                    $newDate = sprintf("%02d.%02d.%04d", $arr[2], $arr[1], $arr[0]);
                default:
            }
        }

        // Time
        if ($givenTime != '') {
            if ($givenTime == '0')
                $givenTime = '0:0:0';

            $arr = explode(':', $givenTime);
            if (count($arr) < 3) {
                $arr[2] = 0;
            }

            if ($showSeconds == 1) {
                $newTime = sprintf("%02d:%02d:%02d", $arr[0], $arr[1], $arr[2]);
            } else {
                $newTime = sprintf("%02d:%02d", $arr[0], $arr[1]);
            }
        }

        if (strlen($dateTimeString) > 15) {
            $delim = ' ';
        }

        return $newDate . $delim . $newTime;
    }

    /**
     * Returns a representation of 0 in a choosen variant.
     *
     * @param string $dateFormat FORMAT_DATE_INTERNATIONAL | FORMAT_DATE_GERMAN
474
     * @param string $showZero
475
     * @param string $showTime   '0' | '1'
476
     * @param string $showSeconds '0' | '1'
Carsten  Rose's avatar
Carsten Rose committed
477
     *
478
479
480
481
     * @return string
     */
    private static function dateTimeZero($dateFormat, $showZero, $showTime, $showSeconds) {

482
        if ($showZero != '1') {
483
            return '';
484
        }
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503

        // $dateFormat (INT/GER),  $showTime, $showSeconds
        $arr[0][0][0] = '0000-00-00';
        $arr[0][0][1] = '0000-00-00';
        $arr[0][1][0] = '0000-00-00 00:00';
        $arr[0][1][1] = '0000-00-00 00:00:00';
        $arr[1][0][0] = '00.00.0000';
        $arr[1][0][1] = '00.00.0000';
        $arr[1][1][0] = '00.00.0000 00:00';
        $arr[1][1][1] = '00.00.0000 00:00:00';

        $showFormat = ($dateFormat === FORMAT_DATE_INTERNATIONAL) ? 0 : 1;

        return $arr[$showFormat][$showTime][$showSeconds];
    }

    /**
     * Split date FORMAT_DATE_GERMAN | FORMAT_DATE_INTERNATIONAL to array with arr[0]=yyyy, arr[1]=mm, arr[2]=dd.
     *
Carsten  Rose's avatar
Carsten Rose committed
504
     * @param string $dateString
Carsten  Rose's avatar
Carsten Rose committed
505
     *
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
     * @return array
     * @throws UserFormException
     */
    private static function splitDateToArray($dateString) {

        if (strpos($dateString, '-') === false) {
            // FORMAT_DATE_GERMAN
            $arr = explode('.', $dateString);
            if (count($arr) != 3) {
                throw new UserFormException("Unexpected format for date: $dateString", ERROR_DATE_UNEXPECTED_FORMAT);
            }
            $tmp = $arr[0];
            $arr[0] = $arr[2];
            $arr[2] = $tmp;
        } else {
            // FORMAT_DATE_INTERNATIONAL
            $arr = explode('-', $dateString);
            if (count($arr) != 3) {
                throw new UserFormException("Unexpected format for date: $dateString", ERROR_DATE_UNEXPECTED_FORMAT);
            }
        }

        // Adjust yy to yyyy. See https://dev.mysql.com/doc/refman/5.7/en/datetime.html > Dates containing two-digit year values ...
        if ($arr[0] < 100) {
            $add = ($arr[0] < 70) ? 2000 : 1900;
            $arr[0] = $add + $arr[0];
        }

        return $arr;
    }

    /**
     * Calculates the placeholder for date/dateTime/local input fields.
     *
     * @param array $formElement
Carsten  Rose's avatar
Carsten Rose committed
541
     *
542
543
544
545
546
547
     * @return string
     * @throws UserFormException
     */
    public static function getDateTimePlaceholder(array $formElement) {

        $timePattern = ($formElement[FE_SHOW_SECONDS] == 1) ? 'hh:mm:ss' : 'hh:mm';
548
        switch ($formElement[FE_TYPE]) {
549
            case 'date':
550
                $placeholder = $formElement[FE_DATE_FORMAT];
551
552
                break;
            case 'datetime':
553
                $placeholder = $formElement[FE_DATE_FORMAT] . ' ' . $timePattern;
554
555
556
557
558
                break;
            case 'time':
                $placeholder = $timePattern;
                break;
            default:
559
                throw new UserFormException("Unexpected Formelement type: '" . $formElement[FE_TYPE] . "'", ERROR_FORMELEMENT_TYPE);
560
561
562
563
564
565
        }

        return $placeholder;
    }


566
567
568
    /**
     * Encrypt curly braces by an uncommon string. Helps preventing unwished action on curly braces.
     *
Carsten  Rose's avatar
Carsten Rose committed
569
     * @param string $text
Carsten  Rose's avatar
Carsten Rose committed
570
     *
571
572
     * @return mixed
     */
573
574
    public
    static function encryptDoubleCurlyBraces($text) {
575
576
        $text = str_replace('{{', LONG_CURLY_OPEN, $text);
        $text = str_replace('}}', LONG_CURLY_CLOSE, $text);
577
578
579
580
581
582
583

        return $text;
    }

    /**
     * Decrypt curly braces by an uncommon string. Helps preventing unwished action on curly braces
     *
Carsten  Rose's avatar
Carsten Rose committed
584
     * @param string $text
Carsten  Rose's avatar
Carsten Rose committed
585
     *
586
587
588
     * @return mixed
     */
    public static function decryptDoubleCurlyBraces($text) {
589
590
591
592
593

        if (!is_string($text)) {
            return $text;
        }

594
595
        $text = str_replace(LONG_CURLY_OPEN, '{{', $text);
        $text = str_replace(LONG_CURLY_CLOSE, '}}', $text);
596
597
598
599

        return $text;
    }

600
601
    /**
     * @param int $length Length of the required hash string
Carsten  Rose's avatar
Carsten Rose committed
602
     *
603
604
605
606
607
608
609
610
611
612
613
614
     * @return string       A random alphanumeric hash
     */
    public static function randomAlphaNum($length) {
        $possible_characters = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $string = "";
        while (strlen($string) < $length) {
            $string .= substr($possible_characters, rand() % (strlen($possible_characters)), 1);
        }

        return ($string);
    }

615
    /**
Carsten  Rose's avatar
Carsten Rose committed
616
617
     * Concatenate URL and Parameter. Depending of if there is a '?' in URL or not,  append the param with '?' or '&'..
     *
Carsten  Rose's avatar
Carsten Rose committed
618
619
     * @param string $url
     * @param string $param
Carsten  Rose's avatar
Carsten Rose committed
620
     *
621
622
623
     * @return string
     */
    public static function concatUrlParam($url, $param) {
624
        if ($param == '') {
625
            return $url;
626
        }
627

628
        $token = (strpos($url, '?') === false) ? '?' : '&';
Carsten  Rose's avatar
Carsten Rose committed
629

630
631
        return $url . $token . $param;
    }
632

633
634
635
636
637
638
639
640
641
642
    /**
     * Concatenate $host, $path and $query. A given $host will always append a '/' if none is given.
     * End of  $path, there is no assumption to append '/' - the user needs full control.
     * $query: trailing 'index.php' will be skipped.
     *
     * If HOST and PATH is combined in a var, pass the value as $hostOrPath, leave $host empty.
     *
     * @param string $host
     * @param string $hostOrPath
     * @param string $query
Carsten  Rose's avatar
Carsten Rose committed
643
     *
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
     * @return string
     * @throws CodeException
     */
    public static function mergeUrlComponents($host, $hostOrPath, $query) {
        $url = '';
        $pre = '';


        if ($host != '' && substr($host, -1, 1) != '/') {
            $host .= '/';
        }

        if ($host != '' && substr($hostOrPath, 0, 1) == '/') {
            $hostOrPath = substr($hostOrPath, 1);
        }

        if ($host != '' || $hostOrPath != '') {
            $url = $host . $hostOrPath;
        }

        if (substr($query, 0, 9) == 'index.php') {
            $query = substr($query, 9);
        }

        if (false !== strpos(substr($query, 1), '?')) {
            throw new CodeException('Found a "?" after the beginning of the query - this is forbidden', ERROR_BROKEN_PARAMETER);
        }

        if ($query != '') {
            $url = $url . '?' . $query;
            $url = str_replace('??', '?', $url);
        }

        return $url;
    }

680
681
682
683
    /**
     * Set Defaults for the current formElement.
     *
     * @param array $formElement
Carsten  Rose's avatar
Carsten Rose committed
684
     *
685
686
     * @return array
     */
687
    public static function setFeDefaults(array $formElement, array $formSpec = array()) {
688
689
690
691
692
693

        $store = Store::getInstance();

        // Some Defaults
        self::setIfNotSet($formElement, FE_SHOW_SECONDS, '0');
        self::setIfNotSet($formElement, FE_SHOW_ZERO, '0');
694
        self::setIfNotSet($formElement, FE_HIDE_ZERO, '0');
695
696
        self::setIfNotSet($formElement, FE_DATE_FORMAT, $store->getVar(SYSTEM_DATE_FORMAT, STORE_SYSTEM));

697
698
699
        self::setIfNotSet($formElement, FE_HTML_BEFORE);
        self::setIfNotSet($formElement, FE_HTML_AFTER);

700
701
        self::setIfNotSet($formElement, FE_SUBRECORD_TABLE_CLASS, 'table table-hover');

702
703
704
705
706
707
708
        if (count($formSpec) > 0) {
            self::setIfNotSet($formElement, F_BS_LABEL_COLUMNS, $formSpec[F_BS_LABEL_COLUMNS], '');
            self::setIfNotSet($formElement, F_BS_INPUT_COLUMNS, $formSpec[F_BS_INPUT_COLUMNS], '');
            self::setIfNotSet($formElement, F_BS_NOTE_COLUMNS, $formSpec[F_BS_NOTE_COLUMNS], '');
        }

        if ($formElement[FE_MODE_SQL] != '') {
709
            $formElement[FE_MODE] = $formElement[FE_MODE_SQL];
710
        }
711

712
713
714
715
        if (isset($formSpec[F_MODE])) {
            $formElement[FE_MODE] = self::applyFormModeToFormElement($formElement[FE_MODE], $formSpec[F_MODE]);
        }

716
717
718
719
720
721
722
723
724
        // Will be used to change dynamicUpdate behaviour
        if (isset($formElement[FE_WRAP_ROW_LABEL_INPUT_NOTE])) {
            $formElement[FE_FLAG_ROW_OPEN_TAG] = Support::findInSet('row', $formElement[FE_WRAP_ROW_LABEL_INPUT_NOTE]);
            $formElement[FE_FLAG_ROW_CLOSE_TAG] = Support::findInSet('/row', $formElement[FE_WRAP_ROW_LABEL_INPUT_NOTE]);
        } else {
            $formElement[FE_FLAG_ROW_OPEN_TAG] = true;
            $formElement[FE_FLAG_ROW_CLOSE_TAG] = false;
        }

725
726
727
        return $formElement;
    }

728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
    /**
     * Depending on $formMode and $feMode, calculate a new $feMode.
     * - If $formMode='' : no change.
     * - If $formMode=F_MODE_READ_ONLY: set feMode=FE_MODE_READ_ONLY, for all visible elements.
     * - If $formMode=F_MODE_REQUIRED_OFF: set feMode=FE_MODE_SHOW, who have have FE_MODE_REQUIRE before.
     *
     * @param string $feMode   FE_MODE_SHOW | FE_MODE_REQUIRED | FE_MODE_READONLY | FE_MODE_HIDDEN |
     * @param string $formMode '' | F_MODE_READONLY | F_MODE_REQUIRED_OFF
     *
     * @return array|string
     * @throws CodeException
     */
    private function applyFormModeToFormElement($feMode, $formMode) {

        if ($formMode == '') {
            return $feMode; //no change
        }

        switch ($feMode) {
            case FE_MODE_HIDDEN:
            case FE_MODE_READONLY:
                break;

            case FE_MODE_SHOW:
            case FE_MODE_REQUIRED:
                if ($formMode == F_MODE_READONLY) {
                    $feMode = FE_MODE_READONLY;
                } elseif ($formMode == F_MODE_REQUIRED_OFF && $feMode = FE_MODE_REQUIRED) {
                    $feMode = FE_MODE_SHOW;
                }
                break;

            default:
                throw new CodeException('Unknown mode: ' . $feMode, ERROR_UNKNOWN_MODE);
        }

        return $feMode;
    }

767
    /**
768
769
770
     * Looks in $arr if there is an element $index. If not, set it to $value.
     * If  $overwriteThis!=false, replace the the original value with $value, if $arr[$index]==$overwriteThis.
     *
771
     * @param array  $arr
Carsten  Rose's avatar
Carsten Rose committed
772
     * @param string $index
773
     * @param string $value
774
     * @param string|bool $overwriteThis If there is already something which is equal to $overwrite: take new default.
Carsten  Rose's avatar
Carsten Rose committed
775
     *
776
     * @return mixed
777
     */
778
    public static function setIfNotSet(array &$arr, $index, $value = '', $overwriteThis = false) {
779

780
        if (!isset($arr[$index])) {
781
            $arr[$index] = $value;
782
783
784
785
786
        }

        if ($overwriteThis !== false && $arr[$index] === $overwriteThis) {
            $arr[$index] = $value;
        }
787
788

        return $arr[$index];
789
    }
790

Carsten  Rose's avatar
Carsten Rose committed
791
    /**
Carsten  Rose's avatar
Carsten Rose committed
792
793
     * @param string $filename
     * @param string $extend
Carsten  Rose's avatar
Carsten Rose committed
794
     *
Carsten  Rose's avatar
Carsten Rose committed
795
796
797
798
799
800
     * @return string
     */
    public static function extendFilename($filename, $extend) {
        return $filename . $extend;
    }

801
    /**
Carsten  Rose's avatar
Carsten Rose committed
802
803
     * Creates all necessary directories in $pathFileName, but not the last part, the filename. A filename has to be
     * specified.
804
805
     *
     * @param string $pathFileName Path with Filename
Carsten  Rose's avatar
Carsten Rose committed
806
     *
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
     * @throws UserFormException
     */
    public static function mkDirParent($pathFileName) {
        $path = "";

        // Teile "Directory/File.Extension" auf
        $pathParts = pathinfo($pathFileName);

        // Zerlege Pfad in einzelne Directories
        $arr = explode("/", $pathParts["dirname"]);

        // Durchlaufe die einzelnen Dirs und überprüfe ob sie angelegt sind.
        // Wenn nicht, lege sie an.
        foreach ($arr as $part) {
            $path .= $part;

            // Check ob der Pfad ein Link ist
            if ("link" == @filetype($path)) {
                if ("0" == ($path1 = readlink($path))) {
                    throw new UserFormException("Can't create '$pathFileName': '$path' contains an invalid link.", ERROR_IO_INVALID_LINK);
                }
            } else {
                if (file_exists($path)) {
                    if ("dir" != filetype($path)) {
                        throw new UserFormException("Can't create '$pathFileName': There is already a file with the same name as '$path'", ERROR_IO_DIR_EXIST_AS_FILE);
                    }
                } else
                    mkdir($path, 0700);
            }

            $path .= "/";
        }
    }
840
841

    /**
842
843
     * Convert 'false' and 'empty' to '0'.
     *
844
     * @param $val
Carsten  Rose's avatar
Carsten Rose committed
845
     *
846
847
848
849
850
     * @return string
     */
    public static function falseEmptyToZero($val) {
        return ($val == '' || $val == false) ? '0' : $val;
    }
851

852
853
854
855
856
857
    /**
     * Check if the string starts with the comment sign - return an empty string.
     * Check if the string starts with an escaped comment sign - strip the escape character.
     * Check if the string starts or ends with an 'escape space' - strip the escape character.
     *
     * @param string $str
Carsten  Rose's avatar
Carsten Rose committed
858
     *
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
     * @return string
     */
    public static function handleEscapeSpaceComment($str) {

        $str = trim($str);

        // Skip comments.
        if (substr($str, 0, 1) == '#') {
            $str = ''; // It's necessary to create an empty entry - E.g. Form.title will not exist if is a comment, but later processing expects that there is an string.
        } else {
            switch (substr($str, 0, 2)) {
                case '\#':
                case '\ ':
                    $str = substr($str, 1);
                    break;
                default:
                    break;
            }

            if (substr($str, -1) == '\\') {
                $str = substr($str, 0, strlen($str) - 1);
            }
        }

        return $str;
    }

886
887
888
889
890
    /**
     * TODO: as soon as we don't support PHP 5.6.0 anymore, this local implemention can be removed.
     * Workaround for PHP < 5.6.0: there is no ldap_escape() - use this code instead.
     *
     * @param string $subject The subject string
Carsten  Rose's avatar
Carsten Rose committed
891
892
893
894
     * @param string $ignore  Set of characters to leave untouched
     * @param int    $flags   Any combination of LDAP_ESCAPE_* flags to indicate the
     *                        set(s) of characters to escape.
     *
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
     * @return string
     **/
    public static function ldap_escape($subject, $ignore = '', $flags = 0) {

        if (function_exists('ldap_escape')) {

            return ldap_escape($subject, $ignore, $flags);

        } else {

//            define('LDAP_ESCAPE_FILTER', 0x01);
//            define('LDAP_ESCAPE_DN',     0x02);

            static $charMaps = array(
                LDAP_ESCAPE_FILTER => array('\\', '*', '(', ')', "\x00"),
                LDAP_ESCAPE_DN => array('\\', ',', '=', '+', '<', '>', ';', '"', '#'),
            );
            // Pre-process the char maps on first call
            if (!isset($charMaps[0])) {
                $charMaps[0] = array();
                for ($i = 0; $i < 256; $i++) {
                    $charMaps[0][chr($i)] = sprintf('\\%02x', $i);;
                }
                for ($i = 0, $l = count($charMaps[LDAP_ESCAPE_FILTER]); $i < $l; $i++) {
                    $chr = $charMaps[LDAP_ESCAPE_FILTER][$i];
                    unset($charMaps[LDAP_ESCAPE_FILTER][$i]);
                    $charMaps[LDAP_ESCAPE_FILTER][$chr] = $charMaps[0][$chr];
                }
                for ($i = 0, $l = count($charMaps[LDAP_ESCAPE_DN]); $i < $l; $i++) {
                    $chr = $charMaps[LDAP_ESCAPE_DN][$i];
                    unset($charMaps[LDAP_ESCAPE_DN][$i]);
                    $charMaps[LDAP_ESCAPE_DN][$chr] = $charMaps[0][$chr];
                }
            }
            // Create the base char map to escape
            $flags = (int)$flags;
            $charMap = array();
            if ($flags & LDAP_ESCAPE_FILTER) {
                $charMap += $charMaps[LDAP_ESCAPE_FILTER];
            }
            if ($flags & LDAP_ESCAPE_DN) {
                $charMap += $charMaps[LDAP_ESCAPE_DN];
            }
            if (!$charMap) {
                $charMap = $charMaps[0];
            }
            // Remove any chars to ignore from the list
            $ignore = (string)$ignore;
            for ($i = 0, $l = strlen($ignore); $i < $l; $i++) {
                unset($charMap[$ignore[$i]]);
            }
            // Do the main replacement
            $result = strtr($subject, $charMap);
            // Encode leading/trailing spaces if LDAP_ESCAPE_DN is passed
            if ($flags & LDAP_ESCAPE_DN) {
                if ($result[0] === ' ') {
                    $result = '\\20' . substr($result, 1);
                }
                if ($result[strlen($result) - 1] === ' ') {
                    $result = substr($result, 0, -1) . '\\20';
                }
            }

            return $result;
        }
    }

962

963
}