Evaluate.php 17.2 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
    /**
34
     * @var Database[]
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
        // In case there is an Element 'fillStoreVar', process that first.
100
        if (!empty($tokenArray[FE_FILL_STORE_VAR]) && is_string($tokenArray[FE_FILL_STORE_VAR])) {
101

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

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

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

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

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

        return $arr;
    }

    /**
Carsten  Rose's avatar
Carsten Rose committed
129
130
     * 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().
131
132
     *
     * Token to replace have to be enclosed by '{{' and '}}'
133
     *
134
     * @param string $line
135
     * @param string $sqlMode ROW_IMPLODE | ROW_REGULAR | ... - might be overwritten in $line by '{{!...'
136
     * @param int $recursion
Carsten  Rose's avatar
Carsten Rose committed
137
     *
138
139
     * @param array $debugStack
     * @param string $foundInStore
140
     * @return array|mixed|null|string
Marc Egger's avatar
Marc Egger committed
141
142
143
144
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
Carsten  Rose's avatar
Carsten Rose committed
145
     */
146
    public function parse($line, $sqlMode = ROW_IMPLODE_ALL, $recursion = 0, &$debugStack = array(), &$foundInStore = '') {
147

148
        $flagTokenReplaced = false;
Carsten  Rose's avatar
Carsten Rose committed
149
150

        if ($recursion > 4) {
Marc Egger's avatar
Marc Egger committed
151
            throw new \UserFormException(
Marc Egger's avatar
Marc Egger committed
152
                json_encode([ERROR_MESSAGE_TO_USER => 'Recursion too deep', ERROR_MESSAGE_TO_DEVELOPER => "Level: $recursion, Line: $line"]),
153
                ERROR_RECURSION_TOO_DEEP);
Carsten  Rose's avatar
Carsten Rose committed
154
155
        }

156
        $result = $line;
Carsten  Rose's avatar
Carsten Rose committed
157

158
        $debugIndent = str_repeat(' ', $recursion);
159
        $debugLocal[] = $debugIndent . "Parse: $result";
Carsten  Rose's avatar
Carsten Rose committed
160

161
        $posFirstClose = strpos($result, $this->endDelimiter);
162
        $posLastClose = strrpos($result, $this->endDelimiter);
163

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

167
168
169
        while ($posFirstClose !== false) {

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

176
177
178
            $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
179

180
181
            $tmpSqlMode = ($posFirstClose == $posLastClose) ? $sqlMode : ROW_IMPLODE_ALL;
            $evaluated = $this->substitute($match, $foundInStore, $tmpSqlMode);
182

183
184
185
            // newline
            $debugLocal[] = '';

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

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

193
194
195
            } else {

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

197
198
199
                // If an array is returned, break everything and return this assoc array.
                if (is_array($evaluated)) {
                    $result = $evaluated;
200
                    $debugLocal[] = $debugIndent . "BY: array(" . count($result) . ")";
201
202
                    break;
                }
203

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

206
                // More to substitute in the new evaluated result? Start recursion just with the new result..
207
208
209
210
211
212
                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);
                    }
213
214
                }
            }
215
            $result = $pre . $evaluated . $post;
216

217
218
            $posFirstClose = strpos($result, $this->endDelimiter);
        }
Carsten  Rose's avatar
Carsten Rose committed
219

220
221
        $result = Support::decryptDoubleCurlyBraces($result);

222
        if ($flagTokenReplaced === true) {
223
224
225
            if (is_array($result)) {
                $str = "array(" . count($result) . ")";
            } else {
226
                $str = "$result";
227
228
            }
            $debugLocal[] = $debugIndent . "FINAL: " . $str;
229

230
            $debugStack = $debugLocal;
Carsten  Rose's avatar
Carsten Rose committed
231
232
        }

233
        return $result;
Carsten  Rose's avatar
Carsten Rose committed
234
235
    }

236
237
238
239
240
    /**
     * @param $arrToken
     * @param $dbIndex
     * @param $foundInStore
     * @return string
Marc Egger's avatar
Marc Egger committed
241
242
243
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
244
     */
245
    private function inlineLink($arrToken, $dbIndex, &$foundInStore) {
246
247
248
249

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

        if ($this->link === null) {
250
            $this->link = new Link($this->store::getSipInstance(), $dbIndex);
251
252
253
254
255
256
257
258
259
260
261
262
        }

        $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
263
264
265
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
266
     */
267
    private function inlineDataDndApi($arrToken, $dbIndex, &$foundInStore) {
268
269

        $token = OnString::trimQuote(trim(implode(' ', $arrToken)));
270
        if (empty($token)) {
Marc Egger's avatar
Marc Egger committed
271
            throw new \UserReportException('Missing form name for "data-dnd-api"', ERROR_MISSING_FORM);
272
273
274
        }

        if ($this->link === null) {
275
            $this->link = new Link($this->store::getSipInstance(), $dbIndex);
276
277
278
279
        }

        $foundInStore = TOKEN_FOUND_AS_COLUMN;

280
        $s = $this->link->renderLink('U:' . $token . '|s|r:8');
281
282

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

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

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

        $token = trim($token);
311
        $dbIndex = $this->dbIndex;
312
        $flagWipe = false;
313
314

        // Check if the $token starts with '[<int>]...' - yes: open the necessary database.
315
        if (strlen($token) > 2 && $token[0] === '[') {
316
            if ($token[2] !== ']') {
Marc Egger's avatar
Marc Egger committed
317
                throw new \UserFormException(json_encode(
318
                    [ERROR_MESSAGE_TO_USER => "Missing token ']' on position 3",
Marc Egger's avatar
Marc Egger committed
319
                        ERROR_MESSAGE_TO_DEVELOPER => "In string '$token'"]), ERROR_TOKEN_MISSING);
320
321
322
323
324
325
326
327
            }
            $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
328

329
330
331
332
        if ($token === '') {
            return '';
        }

333
        // Get SQL column / row separated
Carsten  Rose's avatar
Carsten Rose committed
334
        if ($token[0] === '!') {
335
            $token = trim(substr($token, 1));
Carsten  Rose's avatar
Carsten Rose committed
336
337
338
            $sqlMode = ROW_REGULAR;
        }

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

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

346
            return $this->dbArray[$dbIndex]->sql($token, $sqlMode);
Carsten  Rose's avatar
Carsten Rose committed
347
348
        }

349
350

        // Variable Type '... AS _link', '... as data-dnd-api', '... AS _tablesorter-view-saver'
351
        $countToken = count($arrToken);
352
        if ($countToken > 2 && strtolower($arrToken[$countToken - 2]) == 'as') {
353
354
355

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

356
            array_pop($arrToken); // remove 'link' | 'data-dnd-api' | 'ablesorter-view-saver'
357
            array_pop($arrToken); // remove 'as'
Carsten  Rose's avatar
Carsten Rose committed
358

359
360
361
362
363
364
365
366
            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;
367

368
369
370
371
372
373
374
375
                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;
376
377
378
            }
        }

379
380
        // 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]);
381

382
383
        $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
384
385

        // search for value in stores
386
        $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
387

388
389
        // escape ticks
        if (is_string($value)) {
390
            // Process all escape requests in the given order.
391
            for ($ii = 0; $ii < strlen($escapeTypes); $ii++) {
392
                $escape = $escapeTypes[$ii];
393
394
395
                if ($escape == TOKEN_ESCAPE_CONFIG) {
                    $escape = $this->escapeTypeDefault;
                }
396
397
398
399
400
401
402
                switch ($escape) {
                    case TOKEN_ESCAPE_SINGLE_TICK:
                        $value = str_replace("'", "\\'", $value);
                        break;
                    case TOKEN_ESCAPE_DOUBLE_TICK:
                        $value = str_replace('"', '\\"', $value);
                        break;
403
404
405
                    case TOKEN_ESCAPE_COLON:
                        $value = str_replace(':', '\\:', $value);
                        break;
406
                    case TOKEN_ESCAPE_LDAP_FILTER:
407
408
                        $value = Support::ldap_escape($value, null, LDAP_ESCAPE_FILTER);
                        break;
409
                    case TOKEN_ESCAPE_LDAP_DN:
410
411
                        $value = Support::ldap_escape($value, null, LDAP_ESCAPE_DN);
                        break;
412
                    case TOKEN_ESCAPE_MYSQL:
413
                        $value = $this->dbArray[$dbIndex]->realEscapeString($value);
414
415
416
                        break;
                    case TOKEN_ESCAPE_NONE: // do nothing
                        break;
417
                    case TOKEN_ESCAPE_PASSWORD_T3FE:
418
                        $value = Password::getHash($value);
419
                        break;
420
421
422
423
                    case TOKEN_ESCAPE_STOP_REPLACE:
                        $value = Support::encryptDoubleCurlyBraces($value);
                        break;
                    case TOKEN_ESCAPE_EXCEPTION:
424
                        // empty values will be handled later.
425
                        break;
426
427
428
                    case TOKEN_ESCAPE_WIPE:
                        $flagWipe = true;
                        break;
429
                    default:
Marc Egger's avatar
Marc Egger committed
430
                        throw new \UserFormException("Unknown escape qualifier: $escape", ERROR_UNKNOW_SANITIZE_CLASS);
431
432
                        break;
                }
433
            }
434
435
436
        } 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
437
                throw new \UserFormException($arrToken[VAR_INDEX_MESSAGE] ?? '', ERROR_QUIT_QFQ_REGULAR);
438
            }
439
440
        }

441
        // Not found and a default is given: take the default.
Carsten  Rose's avatar
Carsten Rose committed
442
        if ($foundInStore == '' && $arrToken[VAR_INDEX_DEFAULT] != '') {
443
            $foundInStore = TOKEN_FOUND_AS_DEFAULT;
444
            $value = str_replace('\\:', ':', $arrToken[VAR_INDEX_DEFAULT]);
445
        }
446

447
448
449
        if ($flagWipe) {
            switch ($foundInStore) {
                case STORE_SIP:
450
                    $this->store::unsetVar($arrToken[VAR_INDEX_VALUE], STORE_SIP);
451
452

                    $sip = new Sip();
453
                    $sip->removeKeyFromSip($this->store::getVar(SIP_SIP, STORE_SIP), $arrToken[VAR_INDEX_VALUE]);
454
455
456
457
458
                    break;
                case STORE_EMPTY:
                case STORE_ZERO:
                    break;
                default:
Carsten  Rose's avatar
Carsten Rose committed
459
                    throw new \UserReportException("Wipe not implemented for store $foundInStore", ERROR_WIPE_NOT_IMPLEMENTED_FOR_STORE);
460
461
462
            }
        }

463
        return $value;
Carsten  Rose's avatar
Carsten Rose committed
464
    }
465

466
467
468
    /**
     * @return string
     */
469
470
471
//    public function getDebug() {
//        return '<pre>' . implode("\n", $this->debugStack) . '</pre>';
//    }
472
}