Passed
Push — main ( 3310d4...08974e )
by Thierry
02:20
created

SelectQuery::getWhereCondition()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 15
nc 1
nop 2
dl 0
loc 18
rs 9.7666
c 0
b 0
f 0
1
<?php
2
3
namespace Lagdo\DbAdmin\Db\Page\Dql;
4
5
use Lagdo\DbAdmin\Db\Page\AppPage;
6
use Lagdo\DbAdmin\Driver\DriverInterface;
7
use Lagdo\DbAdmin\Driver\Entity\IndexEntity;
8
use Lagdo\DbAdmin\Driver\Entity\TableFieldEntity;
9
use Lagdo\DbAdmin\Driver\Entity\TableSelectEntity;
10
use Lagdo\DbAdmin\Driver\Utils\Utils;
11
use Exception;
12
13
use function count;
14
use function implode;
15
use function intval;
16
use function in_array;
17
use function preg_match;
18
use function str_replace;
19
20
/**
21
 * Prepare a select query using the user provided options.
22
 */
23
class SelectQuery
24
{
25
    /**
26
     * @var SelectOptions
27
     */
28
    private $selectOptions;
29
30
    /**
31
     * The constructor
32
     *
33
     * @param AppPage $page
34
     * @param DriverInterface $driver
35
     * @param Utils $utils
36
     */
37
    public function __construct(private AppPage $page,
38
        private DriverInterface $driver, private Utils $utils)
39
    {
40
        $this->selectOptions = new SelectOptions($this->driver, $this->utils);
41
    }
42
43
    /**
44
     * @param SelectEntity $selectEntity
45
     *
46
     * @return void
47
     */
48
    private function setFieldsOptions(SelectEntity $selectEntity): void
49
    {
50
        $selectEntity->rights = []; // privilege => 0
51
        $selectEntity->columns = []; // selectable columns
52
        $selectEntity->textLength = 0;
53
        foreach ($selectEntity->fields as $key => $field) {
54
            $name = $this->page->fieldName($field);
55
            if (isset($field->privileges["select"]) && $name != "") {
56
                $selectEntity->columns[$key] = html_entity_decode(strip_tags($name), ENT_QUOTES);
57
                if ($this->page->isShortable($field)) {
58
                    $this->setSelectTextLength($selectEntity);
59
                }
60
            }
61
            $selectEntity->rights[] = $field->privileges;
62
        }
63
    }
64
65
    /**
66
     * Find out foreign keys for each column
67
     *
68
     * @param SelectEntity $selectEntity
69
     *
70
     * @return void
71
     */
72
    private function setForeignKeys(SelectEntity $selectEntity): void
73
    {
74
        $selectEntity->foreignKeys = [];
75
        foreach ($this->driver->foreignKeys($selectEntity->table) as $foreignKey) {
76
            foreach ($foreignKey->source as $val) {
77
                $selectEntity->foreignKeys[$val][] = $foreignKey;
78
            }
79
        }
80
    }
81
82
    /**
83
     * @param array $value
84
     *
85
     * @return bool
86
     */
87
    private function colHasValidValue(array $value): bool
88
    {
89
        return $value['fun'] === 'count' ||
90
            ($value['col'] !== '' && (!$value['fun'] ||
91
                in_array($value['fun'], $this->driver->functions()) ||
92
                in_array($value['fun'], $this->driver->grouping())));
93
    }
94
95
    /**
96
     * @param array $where AND conditions
97
     * @param array $foreignKeys
98
     *
99
     * @return bool
100
     */
101
    // private function setSelectEmail(array $where, array $foreignKeys)
102
    // {
103
    //     return false;
104
    // }
105
106
    /**
107
     * @param SelectEntity $selectEntity
108
     *
109
     * @return void
110
     */
111
    private function setSelectColumns(SelectEntity $selectEntity): void
112
    {
113
        $selectEntity->select = []; // select expressions, empty for *
114
        $selectEntity->group = []; // expressions without aggregation - will be used for GROUP BY if an aggregation function is used
115
        $values = $this->utils->input->values;
116
        foreach ($values['columns'] as $key => $value) {
117
            if ($this->colHasValidValue($value)) {
118
                $column = '*';
119
                if ($value['col'] !== '') {
120
                    $column = $this->driver->escapeId($value['col']);
121
                }
122
                $selectEntity->select[$key] = $this->page->applySqlFunction($value['fun'], $column);
123
                if (!in_array($value['fun'], $this->driver->grouping())) {
124
                    $selectEntity->group[] = $selectEntity->select[$key];
125
                }
126
            }
127
        }
128
    }
129
130
    /**
131
     * @param array $value
132
     * @param array $fields
133
     *
134
     * @return string
135
     */
136
    private function getWhereCondition(array $value, array $fields): string
137
    {
138
        $op = $value['op'];
139
        $val = $value['val'];
140
        $col = $value['col'];
141
142
        return match(true) {
143
            preg_match('~IN$~', $op) => " $op " .
144
                (($in = $this->driver->processLength($val)) !== '' ? $in : '(NULL)'),
145
            $op === 'SQL' => " $val", // SQL injection
146
            $op === 'LIKE %%' => ' LIKE ' . $this->page
147
                ->getUnconvertedFieldValue($fields[$col], "%$val%"),
148
            $op === 'ILIKE %%' => ' ILIKE ' . $this->page
149
                ->getUnconvertedFieldValue($fields[$col], "%$val%"),
150
            $op === 'FIND_IN_SET' => ')',
151
            !preg_match('~NULL$~', $op) => " $op " .
152
                $this->page->getUnconvertedFieldValue($fields[$col], $val),
153
            default => " $op",
154
        };
155
    }
156
157
    /**
158
     * @param TableFieldEntity $field
159
     * @param array $value
160
     *
161
     * @return bool
162
     */
163
    private function selectFieldIsValid(TableFieldEntity $field, array $value): bool
164
    {
165
        $op = $value['op'];
166
        $val = $value['val'];
167
        $in = preg_match('~IN$~', $op) ? ',' : '';
168
169
        return (preg_match('~^[-\d.' . $in . ']+$~', $val) ||
170
                !preg_match('~' . $this->driver->numberRegex() . '|bit~', $field->type)) &&
171
            (!preg_match("~[\x80-\xFF]~", $val) ||
172
                preg_match('~char|text|enum|set~', $field->type)) &&
173
            (!preg_match('~date|timestamp~', $field->type) ||
174
                preg_match('~^\d+-\d+-\d+~', $val));
175
    }
176
177
    /**
178
     * @param array $value
179
     * @param array $fields
180
     *
181
     * @return string
182
     */
183
    private function getSelectExpression(array $value, array $fields): string
184
    {
185
        $op = $value['op'];
186
        $col = $value['col'];
187
        $prefix = '';
188
        if ($op === 'FIND_IN_SET') {
189
            $prefix = $op .'(' . $this->driver->quote($value['val']) . ', ';
190
        }
191
        $condition = $this->getWhereCondition($value, $fields);
192
        if ($col !== '') {
193
            return $prefix . $this->driver->convertSearch($this->driver->escapeId($col),
194
                    $value, $fields[$col]) . $condition;
195
        }
196
        // find anywhere
197
        $clauses = [];
198
        foreach ($fields as $name => $field) {
199
            if ($this->selectFieldIsValid($field, $value)) {
200
                $clauses[] = $prefix . $this->driver->convertSearch($this->driver->escapeId($name),
201
                        $value, $field) . $condition;
202
            }
203
        }
204
205
        return empty($clauses) ? '1 = 0' : ('(' . implode(' OR ', $clauses) . ')');
206
    }
207
208
    /**
209
     * @param IndexEntity $index
210
     * @param int $i
211
     *
212
     * @return string
213
     */
214
    private function getMatchExpression(IndexEntity $index, int $i): string
215
    {
216
        $columns = array_map(function ($column) {
217
            return $this->driver->escapeId($column);
218
        }, $index->columns);
219
        $fulltext = $this->utils->input->values['fulltext'][$i] ?? '';
220
        $match = $this->driver->quote($fulltext);
221
        if (isset($this->utils->input->values['boolean'][$i])) {
222
            $match .= ' IN BOOLEAN MODE';
223
        }
224
225
        return 'MATCH (' . implode(', ', $columns) . ') AGAINST (' . $match . ')';
226
    }
227
228
    /**
229
     * @param SelectEntity $selectEntity
230
     *
231
     * @return void
232
     */
233
    private function setSelectWhere(SelectEntity $selectEntity): void
234
    {
235
        $selectEntity->where = [];
236
        foreach ($selectEntity->indexes as $i => $index) {
237
            $fulltext = $this->utils->input->values['fulltext'][$i] ?? '';
238
            if ($index->type === 'FULLTEXT' && $fulltext !== '') {
239
                $selectEntity->where[] = $this->getMatchExpression($index, $i);
240
            }
241
        }
242
        foreach ((array) $this->utils->input->values['where'] as $value) {
243
            if (($value['col'] !== '' ||  $value['val'] !== '') &&
244
                in_array($value['op'], $this->driver->operators())) {
245
                $selectEntity->where[] = $this
246
                    ->getSelectExpression($value, $selectEntity->fields);
247
            }
248
        }
249
    }
250
251
    /**
252
     * @param SelectEntity $selectEntity
253
     *
254
     * @return void
255
     */
256
    private function setSelectOrder(SelectEntity $selectEntity): void
257
    {
258
        $values = $this->utils->input->values;
259
        $selectEntity->order = [];
260
        foreach ($values['order'] as $key => $value) {
261
            if ($value !== '') {
262
                $regexp = '~^((COUNT\(DISTINCT |[A-Z0-9_]+\()(`(?:[^`]|``)+`|"(?:[^"]|"")+")\)|COUNT\(\*\))$~';
263
                if (preg_match($regexp, $value) !== false) {
264
                    $value = $this->driver->escapeId($value);
265
                }
266
                if (isset($values['desc'][$key]) && intval($values['desc'][$key]) !== 0) {
267
                    $value .= ' DESC';
268
                }
269
                $selectEntity->order[] = $value;
270
            }
271
        }
272
    }
273
274
    /**
275
     * @param SelectEntity $selectEntity
276
     *
277
     * @return void
278
     */
279
    private function setSelectLimit(SelectEntity $selectEntity): void
280
    {
281
        $selectEntity->limit = intval($this->utils->input->values['limit'] ?? 50);
282
    }
283
284
    /**
285
     * @param SelectEntity $selectEntity
286
     *
287
     * @return void
288
     */
289
    private function setSelectTextLength(SelectEntity $selectEntity): void
290
    {
291
        $selectEntity->textLength = intval($this->utils->input->values['text_length'] ?? 100);
292
    }
293
294
    /**
295
     * @param SelectEntity $selectEntity
296
     *
297
     * @return void
298
     */
299
    private function setPrimaryKey(SelectEntity $selectEntity): void
300
    {
301
        $primary = null;
302
        $selectEntity->unselected = [];
303
        foreach ($selectEntity->indexes as $index) {
304
            if ($index->type === "PRIMARY") {
305
                $primary = array_flip($index->columns);
306
                $selectEntity->unselected = ($selectEntity->select ? $primary : []);
307
                foreach ($selectEntity->unselected as $key => $val) {
308
                    if (in_array($this->driver->escapeId($key), $selectEntity->select)) {
309
                        unset($selectEntity->unselected[$key]);
310
                    }
311
                }
312
                break;
313
            }
314
        }
315
316
        $oid = $selectEntity->tableStatus->oid;
317
        if ($oid && !$primary) {
318
            /*$primary = */$selectEntity->unselected = [$oid => 0];
319
            // Make an index for the OID
320
            $index = new IndexEntity();
321
            $index->type = "PRIMARY";
322
            $index->columns = [$oid];
323
            $selectEntity->indexes[] = $index;
324
        }
325
    }
326
327
    /**
328
     * @param SelectEntity $selectEntity
329
     *
330
     * @return void
331
     */
332
    private function setSelectEntity(SelectEntity $selectEntity): void
333
    {
334
        $select2 = $selectEntity->select;
335
        $group2 = $selectEntity->group;
336
        if (empty($select2)) {
337
            $select2[] = "*";
338
            $convert_fields = $this->driver->convertFields($selectEntity->columns,
339
                $selectEntity->fields, $selectEntity->select);
340
            if ($convert_fields) {
341
                $select2[] = substr($convert_fields, 2);
342
            }
343
        }
344
        foreach ($selectEntity->select as $key => $val) {
345
            $field = $fields[$this->driver->unescapeId($val)] ?? null;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $fields does not exist. Did you maybe mean $convert_fields?
Loading history...
346
            if ($field && ($as = $this->driver->convertField($field))) {
347
                $select2[$key] = "$as AS $val";
348
            }
349
        }
350
        $isGroup = count($selectEntity->group) < count($selectEntity->select);
351
        if (!$isGroup && !empty($unselected)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $unselected seems to never exist and therefore empty should always be true.
Loading history...
352
            foreach ($unselected as $key => $val) {
353
                $select2[] = $this->driver->escapeId($key);
354
                if (!empty($group2)) {
355
                    $group2[] = $this->driver->escapeId($key);
356
                }
357
            }
358
        }
359
360
        // From driver.inc.php
361
        $selectEntity->tableSelect = new TableSelectEntity($selectEntity->table,
362
            $select2, $selectEntity->where, $group2, $selectEntity->order,
363
            $selectEntity->limit, $selectEntity->page);
364
    }
365
366
    /**
367
     * Get required data for select on tables
368
     *
369
     * @param SelectEntity $selectEntity
370
     *
371
     * @return SelectEntity
372
     * @throws Exception
373
     */
374
    public function prepareSelect(SelectEntity $selectEntity): SelectEntity
375
    {
376
        $this->selectOptions->setDefaultOptions($selectEntity);
377
378
        // From select.inc.php
379
        $selectEntity->fields = $this->driver->fields($selectEntity->table);
380
        $this->setFieldsOptions($selectEntity);
381
        if (!$selectEntity->columns && $this->driver->support("table")) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $selectEntity->columns of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
382
            throw new Exception($this->utils->trans->lang('Unable to select the table') .
383
                ($selectEntity->fields ? "." : ": " . $this->driver->error()));
384
        }
385
386
        $selectEntity->indexes = $this->driver->indexes($selectEntity->table);
387
        $this->setForeignKeys($selectEntity);
388
        $this->setSelectColumns($selectEntity);
389
390
        $this->setSelectWhere($selectEntity);
391
        $this->setSelectOrder($selectEntity);
392
        $this->setSelectLimit($selectEntity);
393
        $this->setPrimaryKey($selectEntity);
394
395
        // $set = null;
396
        // if(isset($rights["insert"]) || !this->driver->support("table")) {
397
        //     $set = "";
398
        //     foreach((array) $queryOptions["where"] as $val) {
399
        //         if($foreignKeys[$val["col"]] && count($foreignKeys[$val["col"]]) == 1 && ($val["op"] == "="
400
        //             || (!$val["op"] && !preg_match('~[_%]~', $val["val"])) // LIKE in Editor
401
        //         )) {
402
        //             $set .= "&set" . urlencode("[" . $this->driver->bracketEscape($val["col"]) . "]") . "=" . urlencode($val["val"]);
403
        //         }
404
        //     }
405
        // }
406
        // $this->page->selectLinks($tableStatus, $set);
407
408
        // if($page == "last")
409
        // {
410
        //     $isGroup = count($group) < count($select);
411
        //     $found_rows = $this->driver->result($this->driver->getRowCountQuery($table, $where, $isGroup, $group));
412
        //     $page = \floor(\max(0, $found_rows - 1) / $limit);
413
        // }
414
415
        $this->selectOptions->setSelectOptions($selectEntity);
416
        $this->setSelectEntity($selectEntity);
417
418
        $query = $this->driver->buildSelectQuery($selectEntity->tableSelect);
419
        // From adminer.inc.php
420
        $selectEntity->query = str_replace("\n", " ", $query);
421
422
        return $selectEntity;
423
    }
424
}
425