Support.php 19.6 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
20
    /**
     * @param array $queryArray Empty or prefilled assoc array with url parameter
21
     * @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
50
     * @return string Querystring (e.g.: id=23&type=99
51
52
53
54
55
56
57
58
59
60
61
62
63
64
     */
    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);
    }
65
66

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

        // 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;
    }

87
88
89
    /**
     * Format's an attribute: $type=$value. If $flagOmitEmpty==true && $value=='': return ''.
     *
Carsten  Rose's avatar
Carsten Rose committed
90
91
     * @param string $type
     * @param string $value
Carsten  Rose's avatar
Carsten Rose committed
92
     * @param bool $flagOmitEmpty
93
94
95
     * @return string
     */
    public static function doAttribute($type, $value, $flagOmitEmpty = true) {
96
        if ($flagOmitEmpty && $value === "") {
97
            return '';
98
99
        }

100
        switch (strtolower($type)) {
101
102
103
104
105
106
107
            case 'size':
            case 'maxlength':
                // empty or '0' for attributes of type 'size' or 'maxlenght' result in unsuable input elements: skip this.
                if ($value === '' || $value == 0) {
                    return '';
                }
                break;
108
109
110
111
112
            // 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;
113
114
115
            default:
                break;
        }
116

117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
        $value = self::escapeDoubleTick(trim($value));
        return $type . '="' . $value . '" ';
    }

    /**
     * Escapes Double Ticks ("), which are not already escaped.
     *
     * @param $str
     * @return string
     */
    public static function escapeDoubleTick($str) {
        $newStr = '';

        for ($ii = 0; $ii < strlen($str); $ii++) {
            if ($str[$ii] === '"') {
                if ($ii === 0 || $str[$ii - 1] != '\\') {
                    $newStr .= '\\';
                }
            }
            $newStr .= $str[$ii];
        }

        return $newStr;
140
141
    }

142
143
    /**
     * Wraps some $inner fragment with a CSS styled $tooltipText . CSS is configured in 'Resources/Public/qfq-jqw.css'.
144
     *
145
     * Based on: http://www.w3schools.com/howto/howto_css_tooltip.asp
146
     *
Carsten  Rose's avatar
Carsten Rose committed
147
148
     * @param string $before
     * @param string $tooltipText
149
150
     * @return string
     */
151
    public static function appendTooltip($before, $tooltipText) {
152

153
154
155
156
        // addslashes, htmlentities & htmlspecialchars
        // str_replace('"', '&quot;', $tooltipText)

        return $before . "<img src='" . GFX_INFO . "' title=\"" . htmlentities($tooltipText) . "\">";
157
158
    }

159
    /**
160
     * Search for the parameter $needle in $haystack. The arguments has to be seperated by ','.
161
     *
162
     * Returns false if not found or index of found place. Be carefull: use unary operator to compare for 'false'
163
     *
Carsten  Rose's avatar
Carsten Rose committed
164
165
     * @param string $needle
     * @param string $haystack
166
     * @return boolean     true if found, else false
167
     */
168
169
170
171
    public static function findInSet($needle, $haystack) {
        $arr = explode(',', $haystack);

        return array_search($needle, $arr) !== false;
172
    }
173

174
    /**
175
     * Converts a dateTime String to the international format:
176
177
178
179
     * 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
180
     * @param string $dateTimeString
181
     * @return string
182
     * @throws UserFormException
183
     */
184
    public static function dateTimeGermanToInternational($dateTimeString) {
185
186
187
        $dateRaw = '';
        $timeRaw = '';

188
189
190
191
192

//        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})?$';

193
194
195
196
197
198
        $tmpArr = explode(' ', $dateTimeString);
        switch (count($tmpArr)) {
            case 0:
                return '';

            case 1:
199
                if (strpos($tmpArr[0], ':') === false) {
200
                    $dateRaw = $tmpArr[0];
201
202
                } else {
                    $timeRaw = $tmpArr[0];
203
204
205
206
207
208
209
210
211
                }
                break;

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

            default:
212
                throw new UserFormException('Date/time format not recognised.', ERROR_DATE_TIME_FORMAT_NOT_RECOGNISED);
213
214
215
216
217
218
                break;
        }

        if ($dateRaw === '') {
            $date = '0000-00-00';
        } else {
219
            // International format: YYYY-MM-DD
220
221

            if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateRaw) === 1) {
222
223
224
                $date = $dateRaw;

                // German format: 1.1.01 - 11.12.1234
225
            } elseif (preg_match('/^\d{1,2}\.\d{1,2}\.\d{2}(\d{2})?$/', $dateRaw) === 1) {
226
227
228
229
230
231
232
233
234
235
236
                $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);
237
238
239
240
241
242
            }
        }

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

247
248
249
250
251
252
253
254
255
            $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:
256
                    throw new UserFormException('Date/time format not recognised.', ERROR_DATE_TIME_FORMAT_NOT_RECOGNISED);
257
258
259
260
261
262
                    break;
            }
        }

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

264
265
266
    /**
     * @param string $type date | datetime | time
     * @param string $format FORMAT_DATE_INTERNATIONAL | FORMAT_DATE_GERMAN
Carsten  Rose's avatar
Carsten Rose committed
267
     * @param string $showSeconds
268
269
270
271
272
273
274
     * @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
275
            $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})';
276
277
        } else {
            // FORMAT_DATE_INTERNATIONAL: [d]d.[m]m.[yy]yy | 00.00.0000
Carsten  Rose's avatar
Carsten Rose committed
278
            $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)';
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
        }

        // 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
307
308
309
310
     * @param string $dateFormat
     * @param string $showZero
     * @param string $showTime
     * @param string $showSeconds
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
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
380
381
382
383
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
     * @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
     * @param string $showZero '0' | '1'
     * @param string $showTime '0' | '1'
     * @param string $showSeconds '0' | '1'
     * @return string
     */
    private static function dateTimeZero($dateFormat, $showZero, $showTime, $showSeconds) {

        if ($showZero == 0)
            return '';

        // $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
428
     * @param string $dateString
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
     * @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
     * @return string
     * @throws UserFormException
     */
    public static function getDateTimePlaceholder(array $formElement) {

        $timePattern = ($formElement[FE_SHOW_SECONDS] == 1) ? 'hh:mm:ss' : 'hh:mm';
470
        switch ($formElement[FE_TYPE]) {
471
            case 'date':
472
                $placeholder = $formElement[FE_DATE_FORMAT];
473
474
                break;
            case 'datetime':
475
                $placeholder = $formElement[FE_DATE_FORMAT] . ' ' . $timePattern;
476
477
478
479
480
                break;
            case 'time':
                $placeholder = $timePattern;
                break;
            default:
481
                throw new UserFormException("Unexpected Formelement type: '" . $formElement[FE_TYPE] . "'", ERROR_FORMELEMENT_TYPE);
482
483
484
485
486
487
        }

        return $placeholder;
    }


488
489
490
    /**
     * Encrypt curly braces by an uncommon string. Helps preventing unwished action on curly braces.
     *
Carsten  Rose's avatar
Carsten Rose committed
491
     * @param string $text
492
493
     * @return mixed
     */
494
495
    public
    static function encryptDoubleCurlyBraces($text) {
496
497
        $text = str_replace('{{', LONG_CURLY_OPEN, $text);
        $text = str_replace('}}', LONG_CURLY_CLOSE, $text);
498
499
500
501
502
503
504

        return $text;
    }

    /**
     * Decrypt curly braces by an uncommon string. Helps preventing unwished action on curly braces
     *
Carsten  Rose's avatar
Carsten Rose committed
505
     * @param string $text
506
507
508
     * @return mixed
     */
    public static function decryptDoubleCurlyBraces($text) {
509
510
        $text = str_replace(LONG_CURLY_OPEN, '{{', $text);
        $text = str_replace(LONG_CURLY_CLOSE, '}}', $text);
511
512
513
514

        return $text;
    }

515
516
517
518
519
520
521
522
523
524
525
526
527
528
    /**
     * @param int $length Length of the required hash string
     * @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);
    }

529
    /**
Carsten  Rose's avatar
Carsten Rose committed
530
531
     * 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
532
533
     * @param string $url
     * @param string $param
534
535
536
537
538
     * @return string
     */
    public static function concatUrlParam($url, $param) {
        if ($param == '')
            return $url;
539

540
541
542
        $token = (strpos($url, '?') === false) ? '?' : '&';
        return $url . $token . $param;
    }
543

544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
    /**
     * Set Defaults for the current formElement.
     *
     * @param array $formElement
     * @return array
     */
    public static function setFeDefaults(array $formElement) {

        $store = Store::getInstance();

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

559
560
561
        if ($formElement[FE_MODE_SQL] != '')
            $formElement[FE_MODE] = $formElement[FE_MODE_SQL];

562
563
564
        return $formElement;
    }

565
    /**
Carsten  Rose's avatar
Carsten Rose committed
566
567
     * @param array $arr
     * @param string $index
568
     * @param string $value
569
     * @param string|bool $overwriteThis If there is already something which is equal to $overwrite: take new default.
570
     * @return mixed
571
     */
572
    public static function setIfNotSet(array &$arr, $index, $value = '', $overwriteThis = false) {
573

574
        if (!isset($arr[$index])) {
575
            $arr[$index] = $value;
576
577
578
579
580
        }

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

        return $arr[$index];
583
    }
584

Carsten  Rose's avatar
Carsten Rose committed
585
    /**
Carsten  Rose's avatar
Carsten Rose committed
586
587
     * @param string $filename
     * @param string $extend
Carsten  Rose's avatar
Carsten Rose committed
588
589
590
591
592
593
     * @return string
     */
    public static function extendFilename($filename, $extend) {
        return $filename . $extend;
    }

594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
    /**
     * Creates all necessary directories in $pathFileName, but not the last part, the filename. A filename has to be specified.
     *
     * @param string $pathFileName Path with Filename
     * @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 .= "/";
        }
    }
631
}