Evaluate.php 17.5 KB
Newer Older
Carsten  Rose's avatar
Carsten Rose committed
1
2
3
4
5
6
7
8
<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 1/12/16
 * Time: 4:36 PM
 */

Marc Egger's avatar
Marc Egger committed
9
namespace IMATHUZH\Qfq\Core;
Carsten  Rose's avatar
Carsten Rose committed
10

Marc Egger's avatar
Marc Egger committed
11
12
use IMATHUZH\Qfq\Core\Database\Database;
use IMATHUZH\Qfq\Core\Helper\KeyValueStringParser;
13
14
use IMATHUZH\Qfq\Core\Helper\OnString;
use IMATHUZH\Qfq\Core\Helper\Support;
Marc Egger's avatar
Marc Egger committed
15
use IMATHUZH\Qfq\Core\Report\Link;
16
17
18
19
use IMATHUZH\Qfq\Core\Report\Tablesorter;
use IMATHUZH\Qfq\Core\Store\Sip;
use IMATHUZH\Qfq\Core\Store\Store;
use IMATHUZH\Qfq\Core\Typo3\Password;
Carsten  Rose's avatar
Carsten Rose committed
20
21


22
const EVALUATE_DB_INDEX_DEFAULT = 0;
Carsten  Rose's avatar
Carsten Rose committed
23
24
25
26
/**
 * Class Evaluate
 * @package qfq
 */
Carsten  Rose's avatar
Carsten Rose committed
27
class Evaluate {
28
29
30
    /**
     * @var Store
     */
Carsten  Rose's avatar
Carsten Rose committed
31
    private $store = null;
32

33
    /**
Carsten  Rose's avatar
Carsten Rose committed
34
     * @var Database[] - Array of Database instantiated class
35
     */
36
    private $dbArray = array();
37

38
39
40
41
42
    /**
     * @var Link
     */
    private $link = null;

43
44
45
46
47
    /**
     * @var Tablesorter
     */
    private $tablesorter = null;

48
    private $dbIndex = EVALUATE_DB_INDEX_DEFAULT;
Carsten  Rose's avatar
Carsten Rose committed
49
50
51
52
    private $startDelimiter = '';
    private $startDelimiterLength = 0;
    private $endDelimiter = '';
    private $endDelimiterLength = 0;
53
54
    private $sqlKeywords = array('SELECT ', 'INSERT ', 'DELETE ', 'UPDATE ', 'SHOW ', 'REPLACE ', 'TRUNCATE ', 'DESCRIBE ', 'EXPLAIN ', 'SET ');

55
    private $escapeTypeDefault = '';
56

57

58
//    private $debugStack = array();
Carsten  Rose's avatar
Carsten Rose committed
59
60


61
    /**
Marc Egger's avatar
Marc Egger committed
62
     * @param Store $store
Carsten  Rose's avatar
Carsten Rose committed
63
64
65
     * @param Database $db
     * @param string $startDelimiter
     * @param string $endDelimiter
Marc Egger's avatar
Marc Egger committed
66
67
     * @throws \CodeException
     * @throws \UserFormException
68
     */
Carsten  Rose's avatar
Carsten Rose committed
69
70
    public function __construct(Store $store, Database $db, $startDelimiter = '{{', $endDelimiter = '}}') {
        $this->store = $store;
71
72

        $this->dbArray[EVALUATE_DB_INDEX_DEFAULT] = $db;
Carsten  Rose's avatar
Carsten Rose committed
73
74
75
76
        $this->startDelimiter = $startDelimiter;
        $this->startDelimiterLength = strlen($startDelimiter);
        $this->endDelimiter = $endDelimiter;
        $this->endDelimiterLength = strlen($endDelimiter);
77
        $this->escapeTypeDefault = $this->store::getVar(F_ESCAPE_TYPE_DEFAULT, STORE_SYSTEM);
78
        if (empty($this->escapeTypeDefault) || $this->escapeTypeDefault == TOKEN_ESCAPE_CONFIG) {
79
            $this->escapeTypeDefault = $this->store::getVar(SYSTEM_ESCAPE_TYPE_DEFAULT, STORE_SYSTEM);
80
        }
Carsten  Rose's avatar
Carsten Rose committed
81
82
83
    }

    /**
84
     * Evaluate a whole array or an array of arrays.
85
     *
Carsten  Rose's avatar
Carsten Rose committed
86
     * @param       $tokenArray
87
88
     * @param array $skip Optional Array with keynames, which will not be evaluated.
     * @param array $debugStack
Carsten  Rose's avatar
Carsten Rose committed
89
     *
90
     * @return array
Marc Egger's avatar
Marc Egger committed
91
92
93
94
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
95
     */
96
    public function parseArray($tokenArray, array $skip = array(), &$debugStack = array()) {
97
98
        $arr = array();

99
100
101
        // In case there is an Element 'fillStoreVar', process that first (if not defined to skip).
        $flagSkipFillStoreVar = (array_search(FE_FILL_STORE_VAR, $skip) !== false);
        if (!$flagSkipFillStoreVar && !empty($tokenArray[FE_FILL_STORE_VAR]) && is_string($tokenArray[FE_FILL_STORE_VAR])) {
102

103
104
105
            $arr = $this->parse($tokenArray[FE_FILL_STORE_VAR], ROW_REGULAR, 0, $debugStack);
            if (!empty($arr)) {
                $this->store::appendToStore($arr[0], STORE_VAR);
106
107
108
109
            }
            unset($tokenArray[FE_FILL_STORE_VAR]);
        }

110
        foreach ($tokenArray as $key => $value) {
111
112

            if (array_search($key, $skip) !== false) {
113
                $arr[$key] = $value;
114
115
116
                continue;
            }

117
            if (is_array($value)) {
118
                $arr[] = $this->parseArray($value, $skip);
119
            } else {
120
                $value = Support::handleEscapeSpaceComment($value);
121

122
                $arr[$key] = $this->parse($value, ROW_IMPLODE_ALL, 0, $debugStack);
123
            }
124
125
126
127
128
129
        }

        return $arr;
    }

    /**
Carsten  Rose's avatar
Carsten Rose committed
130
131
     * Recursive evaluation of 'line'. Constant string, Variables or SQL Query or all of them. All queries will be
     * fired. In case of an 'INSERT' statement, return the last_insert_id().
132
133
     *
     * Token to replace have to be enclosed by '{{' and '}}'
134
     *
135
     * @param string $line
136
     * @param string $sqlMode ROW_IMPLODE | ROW_REGULAR | ... - might be overwritten in $line by '{{!...'
137
     * @param int $recursion
Carsten  Rose's avatar
Carsten Rose committed
138
     *
139
140
     * @param array $debugStack
     * @param string $foundInStore
141
     * @return array|mixed|null|string
Marc Egger's avatar
Marc Egger committed
142
143
144
145
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
Carsten  Rose's avatar
Carsten Rose committed
146
     */
147
    public function parse($line, $sqlMode = ROW_IMPLODE_ALL, $recursion = 0, &$debugStack = array(), &$foundInStore = '') {
148

Carsten  Rose's avatar
Carsten Rose committed
149
150
151
152
        if ($line === '') {
            return '';
        }

153
        $flagTokenReplaced = false;
Carsten  Rose's avatar
Carsten Rose committed
154
155

        if ($recursion > 4) {
Marc Egger's avatar
Marc Egger committed
156
            throw new \UserFormException(
Marc Egger's avatar
Marc Egger committed
157
                json_encode([ERROR_MESSAGE_TO_USER => 'Recursion too deep', ERROR_MESSAGE_TO_DEVELOPER => "Level: $recursion, Line: $line"]),
158
                ERROR_RECURSION_TOO_DEEP);
Carsten  Rose's avatar
Carsten Rose committed
159
160
        }

161
        $result = $line;
Carsten  Rose's avatar
Carsten Rose committed
162

163
        $debugIndent = str_repeat(' ', $recursion);
164
        $debugLocal[] = $debugIndent . "Parse: $result";
Carsten  Rose's avatar
Carsten Rose committed
165

166
        $posFirstClose = strpos($result, $this->endDelimiter);
167
        $posLastClose = strrpos($result, $this->endDelimiter);
168

169
        // Variables like 'fillStoreVar' might contain SQL statements. Put them in store in case a DB exception is thrown.
170
        $this->store::setVar(SYSTEM_SQL_RAW, $line, STORE_SYSTEM);
171

172
173
174
        while ($posFirstClose !== false) {

            $posMatchOpen = strrpos(substr($result, 0, $posFirstClose), $this->startDelimiter);
Carsten  Rose's avatar
Carsten Rose committed
175
            if ($posMatchOpen === false) {
Marc Egger's avatar
Marc Egger committed
176
                throw new \UserFormException(
Marc Egger's avatar
Marc Egger committed
177
                    json_encode([ERROR_MESSAGE_TO_USER => 'Missing open delimiter', ERROR_MESSAGE_TO_DEVELOPER => "Text: $result"]),
178
                    ERROR_MISSING_OPEN_DELIMITER);
Carsten  Rose's avatar
Carsten Rose committed
179
180
            }

181
182
183
            $pre = substr($result, 0, $posMatchOpen);
            $post = substr($result, $posFirstClose + $this->endDelimiterLength);
            $match = substr($result, $posMatchOpen + $this->startDelimiterLength, $posFirstClose - $posMatchOpen - $this->startDelimiterLength);
Carsten  Rose's avatar
Carsten Rose committed
184

185
186
            $tmpSqlMode = ($posFirstClose == $posLastClose) ? $sqlMode : ROW_IMPLODE_ALL;
            $evaluated = $this->substitute($match, $foundInStore, $tmpSqlMode);
187

188
189
190
            // newline
            $debugLocal[] = '';

191
            $debugLocal[] = $debugIndent . "Replace: $match";
Carsten  Rose's avatar
Carsten Rose committed
192

193
            if ($foundInStore === '') {
194
                // Encode the non replaceable part as preparation not to process again. Recode them at the end.
195
                $evaluated = Support::encryptDoubleCurlyBraces($this->startDelimiter . $match . $this->endDelimiter);
196
                $debugLocal[] = $debugIndent . "BY: <nothing found - not replaced>";
197

198
199
200
            } else {

                $flagTokenReplaced = true;
Carsten  Rose's avatar
Carsten Rose committed
201

202
203
204
                // If an array is returned, break everything and return this assoc array.
                if (is_array($evaluated)) {
                    $result = $evaluated;
205
                    $debugLocal[] = $debugIndent . "BY: array(" . count($result) . ")";
206
207
                    break;
                }
208

209
                $debugLocal[] = $debugIndent . "BY: $evaluated";
Carsten  Rose's avatar
Carsten Rose committed
210

211
                // More to substitute in the new evaluated result? Start recursion just with the new result..
212
213
214
215
216
217
                if ($foundInStore === TOKEN_FOUND_STOP_REPLACE) {
                    $evaluated = Support::encryptDoubleCurlyBraces($evaluated);
                } else {
                    if (strpos($evaluated, $this->endDelimiter) !== false) {
                        $evaluated = $this->parse($evaluated, ROW_IMPLODE_ALL, $recursion + 1, $debugLocal, $foundInStore);
                    }
218
219
                }
            }
220
            $result = $pre . $evaluated . $post;
221

222
223
            $posFirstClose = strpos($result, $this->endDelimiter);
        }
Carsten  Rose's avatar
Carsten Rose committed
224

225
226
        $result = Support::decryptDoubleCurlyBraces($result);

227
        if ($flagTokenReplaced === true) {
228
229
230
            if (is_array($result)) {
                $str = "array(" . count($result) . ")";
            } else {
231
                $str = "$result";
232
233
            }
            $debugLocal[] = $debugIndent . "FINAL: " . $str;
234

235
            $debugStack = $debugLocal;
Carsten  Rose's avatar
Carsten Rose committed
236
237
        }

238
        return $result;
Carsten  Rose's avatar
Carsten Rose committed
239
240
    }

241
242
243
244
245
    /**
     * @param $arrToken
     * @param $dbIndex
     * @param $foundInStore
     * @return string
Marc Egger's avatar
Marc Egger committed
246
247
248
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
249
     */
250
    private function inlineLink($arrToken, $dbIndex, &$foundInStore) {
251
252
253
254

        $token = OnString::trimQuote(trim(implode(' ', $arrToken)));

        if ($this->link === null) {
255
            $this->link = new Link($this->store::getSipInstance(), $dbIndex);
256
257
258
259
260
261
262
263
264
265
266
267
        }

        $foundInStore = TOKEN_FOUND_AS_COLUMN;

        return $this->link->renderLink($token);
    }

    /**
     * @param $arrToken
     * @param $dbIndex
     * @param $foundInStore
     * @return string
Marc Egger's avatar
Marc Egger committed
268
269
270
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
271
     */
272
    private function inlineDataDndApi($arrToken, $dbIndex, &$foundInStore) {
273
274

        $token = OnString::trimQuote(trim(implode(' ', $arrToken)));
275
276
277

        # Include current SIP store, to fetch SIP parameter later.
        $token .= '&' . DND_FORM_SIP_VALUES . '=' . $this->store::getVar(SIP_SIP, STORE_SIP);
278
        if (empty($token)) {
Marc Egger's avatar
Marc Egger committed
279
            throw new \UserReportException('Missing form name for "data-dnd-api"', ERROR_MISSING_FORM);
280
281
282
        }

        if ($this->link === null) {
283
            $this->link = new Link($this->store::getSipInstance(), $dbIndex);
284
285
286
287
        }

        $foundInStore = TOKEN_FOUND_AS_COLUMN;

288
        $s = $this->link->renderLink('U:' . $token . '|s|r:8');
289
290

        // Flag to add DND JS code later on.
291
        $this->store::setVar(SYSTEM_DRAG_AND_DROP_JS, 'true', STORE_SYSTEM);
292

Marc Egger's avatar
Marc Egger committed
293
        // data-dnd-api="typo3conf/ext/qfq/qfq/Api/dragAndDrop.php?s={{'U:form=<form name>[&paramX=<any value>]|s|r:8' AS _link}}"
294
295
296
        return DND_DATA_DND_API . '="' . API_DIR . '/' . API_DRAG_AND_DROP_PHP . '?s=' . $s . '"';
    }

Carsten  Rose's avatar
Carsten Rose committed
297
298
    /**
     * Tries to substitute $token.
299
     * Token might be:
300
     *   a) a SQL statement to fire
301
     *   b) fetch from a store. Syntax: '\[db index\]form:[store]:[sanitize]:[escape]:[default]:[type violate message]', ''
302
     *
303
     * The token have to be *without* Delimiter '{{' , '}}'
304
     * If neither a) or b) match, return the token itself.
Carsten  Rose's avatar
Carsten Rose committed
305
     *
306
     * @param string $token
307
     * @param string $foundInStore Returns the name of the store where $key has been found. If $key is not found, return ''.
308
     * @param string $sqlMode - ROW_IMPLODE | ROW_REGULAR | ... - might be overwritten in $line by '{{!...'
Carsten  Rose's avatar
Carsten Rose committed
309
     *
310
     * @return array|null|string
Marc Egger's avatar
Marc Egger committed
311
312
313
314
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
Carsten  Rose's avatar
Carsten Rose committed
315
     */
316
    public function substitute($token, &$foundInStore = '', $sqlMode = ROW_IMPLODE_ALL) {
Carsten  Rose's avatar
Carsten Rose committed
317
318

        $token = trim($token);
319
        $dbIndex = $this->dbIndex;
320
        $flagWipe = false;
321
322

        // Check if the $token starts with '[<int>]...' - yes: open the necessary database.
323
        if (strlen($token) > 2 && $token[0] === '[') {
324
            if ($token[2] !== ']') {
Marc Egger's avatar
Marc Egger committed
325
                throw new \UserFormException(json_encode(
326
                    [ERROR_MESSAGE_TO_USER => "Missing token ']' on position 3",
Marc Egger's avatar
Marc Egger committed
327
                        ERROR_MESSAGE_TO_DEVELOPER => "In string '$token'"]), ERROR_TOKEN_MISSING);
328
329
330
331
332
333
334
335
            }
            $dbIndex = $token[1];
            $token = trim(substr($token, 3));

            if (empty($this->dbArray[$dbIndex])) {
                $this->dbArray[$dbIndex] = new Database($dbIndex);
            }
        }
Carsten  Rose's avatar
Carsten Rose committed
336

337
338
339
340
        if ($token === '') {
            return '';
        }

341
        // Get SQL column / row separated
Carsten  Rose's avatar
Carsten Rose committed
342
        if ($token[0] === '!') {
343
            $token = trim(substr($token, 1));
Carsten  Rose's avatar
Carsten Rose committed
344
345
346
            $sqlMode = ROW_REGULAR;
        }

347
        // Extract token: check if this is a 'variable', 'SQL Statement', 'link', 'data-dnd-api'
348
        $arrToken = explode(' ', $token);
349

350
        // Variable Type 'SQL Statement'
351
        if (in_array(strtoupper($arrToken[VAR_INDEX_VALUE] . ' '), $this->sqlKeywords)) {
352
            $foundInStore = TOKEN_FOUND_IN_STORE_QUERY;
Carsten  Rose's avatar
Carsten Rose committed
353

354
            return $this->dbArray[$dbIndex]->sql($token, $sqlMode);
Carsten  Rose's avatar
Carsten Rose committed
355
356
        }

357
358

        // Variable Type '... AS _link', '... as data-dnd-api', '... AS _tablesorter-view-saver'
359
        $countToken = count($arrToken);
360
        if ($countToken > 2 && strtolower($arrToken[$countToken - 2]) == 'as') {
361
362
363

            $type = OnString::stripFirstCharIf('_', $arrToken[$countToken - 1]);

364
            array_pop($arrToken); // remove 'link' | 'data-dnd-api' | 'tablesorter-view-saver'
365
            array_pop($arrToken); // remove 'as'
Carsten  Rose's avatar
Carsten Rose committed
366

367
368
369
370
371
372
373
374
            switch (strtolower($type)) {
                case COLUMN_LINK:
                    return ($this->inlineLink($arrToken, $dbIndex, $foundInStore));
                    break;

                case DND_DATA_DND_API:
                    return ($this->inlineDataDndApi($arrToken, $dbIndex, $foundInStore));
                    break;
375

376
377
378
379
380
381
382
383
                case TABLESORTER_VIEW_SAVER:
                    if ($this->tablesorter === null) {
                        $this->tablesorter = new Tablesorter($dbIndex);
                    }
                    return ($this->tablesorter->inlineTablesorterView($arrToken[VAR_INDEX_VALUE], $foundInStore));
                    break;
                default:
                    break;
384
385
386
            }
        }

387
388
        // explode for: <key>:<store priority>:<sanitize class>:<escape>:<default>:<type violate message>
        $arrToken = array_merge(KeyValueStringParser::explodeEscape(':', $token, 6), [null, null, null, null, null, null]);
389

390
391
        $escapeTypes = (empty($arrToken[VAR_INDEX_ESCAPE])) ? $this->escapeTypeDefault : $arrToken[VAR_INDEX_ESCAPE];
        $typeMessageViolate = ($arrToken[VAR_INDEX_MESSAGE] === null || $arrToken[VAR_INDEX_MESSAGE] === '') ? SANITIZE_TYPE_MESSAGE_VIOLATE_CLASS : $arrToken[VAR_INDEX_MESSAGE];
Carsten  Rose's avatar
Carsten Rose committed
392
393

        // search for value in stores
394
        $value = $this->store::getVar($arrToken[VAR_INDEX_VALUE], $arrToken[VAR_INDEX_STORE], $arrToken[VAR_INDEX_SANATIZE], $foundInStore, $typeMessageViolate);
Carsten  Rose's avatar
Carsten Rose committed
395

396
397
        // escape ticks
        if (is_string($value)) {
398
            // Process all escape requests in the given order.
399
            for ($ii = 0; $ii < strlen($escapeTypes); $ii++) {
400
                $escape = $escapeTypes[$ii];
401
402
403
                if ($escape == TOKEN_ESCAPE_CONFIG) {
                    $escape = $this->escapeTypeDefault;
                }
404
405
406
407
408
409
410
                switch ($escape) {
                    case TOKEN_ESCAPE_SINGLE_TICK:
                        $value = str_replace("'", "\\'", $value);
                        break;
                    case TOKEN_ESCAPE_DOUBLE_TICK:
                        $value = str_replace('"', '\\"', $value);
                        break;
411
412
413
                    case TOKEN_ESCAPE_COLON:
                        $value = str_replace(':', '\\:', $value);
                        break;
414
                    case TOKEN_ESCAPE_LDAP_FILTER:
415
416
                        $value = Support::ldap_escape($value, null, LDAP_ESCAPE_FILTER);
                        break;
417
                    case TOKEN_ESCAPE_LDAP_DN:
418
419
                        $value = Support::ldap_escape($value, null, LDAP_ESCAPE_DN);
                        break;
420
                    case TOKEN_ESCAPE_MYSQL:
421
                        $value = $this->dbArray[$dbIndex]->realEscapeString($value);
422
423
424
                        break;
                    case TOKEN_ESCAPE_NONE: // do nothing
                        break;
425
                    case TOKEN_ESCAPE_PASSWORD_T3FE:
426
                        $value = Password::getHash($value);
427
                        break;
428
429
430
431
                    case TOKEN_ESCAPE_STOP_REPLACE:
                        $value = Support::encryptDoubleCurlyBraces($value);
                        break;
                    case TOKEN_ESCAPE_EXCEPTION:
432
                        // empty values will be handled later.
433
                        break;
434
435
436
                    case TOKEN_ESCAPE_WIPE:
                        $flagWipe = true;
                        break;
437
                    default:
Marc Egger's avatar
Marc Egger committed
438
                        throw new \UserFormException("Unknown escape qualifier: $escape", ERROR_UNKNOW_SANITIZE_CLASS);
439
440
                        break;
                }
441
            }
442
443
444
        } else {
            // In case the value is not found and the escape class forces a full stop
            if (strpos($escapeTypes, TOKEN_ESCAPE_EXCEPTION) !== false) {
Marc Egger's avatar
Marc Egger committed
445
                throw new \UserFormException($arrToken[VAR_INDEX_MESSAGE] ?? '', ERROR_QUIT_QFQ_REGULAR);
446
            }
447
448
        }

449
        // Not found and a default is given: take the default.
Carsten  Rose's avatar
Carsten Rose committed
450
        if ($foundInStore == '' && $arrToken[VAR_INDEX_DEFAULT] != '') {
451
            $foundInStore = TOKEN_FOUND_AS_DEFAULT;
452
            $value = str_replace('\\:', ':', $arrToken[VAR_INDEX_DEFAULT]);
453
        }
454

455
456
457
        if ($flagWipe) {
            switch ($foundInStore) {
                case STORE_SIP:
458
                    $this->store::unsetVar($arrToken[VAR_INDEX_VALUE], STORE_SIP);
459
460

                    $sip = new Sip();
461
                    $sip->removeKeyFromSip($this->store::getVar(SIP_SIP, STORE_SIP), $arrToken[VAR_INDEX_VALUE]);
462
463
464
465
466
                    break;
                case STORE_EMPTY:
                case STORE_ZERO:
                    break;
                default:
Carsten  Rose's avatar
Carsten Rose committed
467
                    throw new \UserReportException("Wipe not implemented for store $foundInStore", ERROR_WIPE_NOT_IMPLEMENTED_FOR_STORE);
468
469
470
            }
        }

471
        return $value;
Carsten  Rose's avatar
Carsten Rose committed
472
    }
473

474
475
476
    /**
     * @return string
     */
477
478
479
//    public function getDebug() {
//        return '<pre>' . implode("\n", $this->debugStack) . '</pre>';
//    }
480
}