SelectQuery::selectFieldIsValid()   B
last analyzed

Complexity

Conditions 7
Paths 22

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 9
c 1
b 0
f 0
nc 22
nop 2
dl 0
loc 11
rs 8.8333
1
<?php
2
3
namespace Lagdo\DbAdmin\Db\Facades\Select;
4
5
use Lagdo\DbAdmin\Admin\Traits\InputFieldTrait;
6
use Lagdo\DbAdmin\Db\Facades\AbstractFacade;
7
use Lagdo\DbAdmin\Driver\Entity\IndexEntity;
8
use Lagdo\DbAdmin\Driver\Entity\TableFieldEntity;
9
use Lagdo\DbAdmin\Driver\Entity\TableSelectEntity;
10
use Lagdo\Facades\Logger;
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 strtoupper;
19
use function str_replace;
20
21
22
class SelectQuery extends AbstractFacade
23
{
24
    use InputFieldTrait;
0 ignored issues
show
Bug introduced by
The trait Lagdo\DbAdmin\Admin\Traits\InputFieldTrait requires the property $name which is not provided by Lagdo\DbAdmin\Db\Facades\Select\SelectQuery.
Loading history...
25
    use SelectTrait;
0 ignored issues
show
Bug introduced by
The trait Lagdo\DbAdmin\Db\Facades\Select\SelectTrait requires the property $str which is not provided by Lagdo\DbAdmin\Db\Facades\Select\SelectQuery.
Loading history...
26
27
    /**
28
     * Get required data for select on tables
29
     *
30
     * @param SelectEntity $selectEntity
31
     *
32
     * @return SelectEntity
33
     * @throws Exception
34
     */
35
    public function prepareSelect(SelectEntity $selectEntity): SelectEntity
36
    {
37
        $this->setDefaultOptions($selectEntity);
38
39
        // From select.inc.php
40
        $selectEntity->fields = $this->driver->fields($selectEntity->table);
0 ignored issues
show
Bug introduced by
The method fields() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

40
        /** @scrutinizer ignore-call */ 
41
        $selectEntity->fields = $this->driver->fields($selectEntity->table);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
41
        $this->setFieldsOptions($selectEntity);
42
        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...
43
            throw new Exception($this->utils->trans->lang('Unable to select the table') .
44
                ($selectEntity->fields ? "." : ": " . $this->driver->error()));
45
        }
46
47
        $selectEntity->indexes = $this->driver->indexes($selectEntity->table);
48
        $this->setForeignKeys($selectEntity);
49
        $this->setSelectColumns($selectEntity);
50
51
        $this->setSelectWhere($selectEntity);
52
        $this->setSelectOrder($selectEntity);
53
        $this->setSelectLimit($selectEntity);
54
        $this->setPrimaryKey($selectEntity);
55
56
        // $set = null;
57
        // if(isset($rights["insert"]) || !this->driver->support("table")) {
58
        //     $set = "";
59
        //     foreach((array) $queryOptions["where"] as $val) {
60
        //         if($foreignKeys[$val["col"]] && count($foreignKeys[$val["col"]]) == 1 && ($val["op"] == "="
61
        //             || (!$val["op"] && !preg_match('~[_%]~', $val["val"])) // LIKE in Editor
62
        //         )) {
63
        //             $set .= "&set" . urlencode("[" . $this->driver->bracketEscape($val["col"]) . "]") . "=" . urlencode($val["val"]);
64
        //         }
65
        //     }
66
        // }
67
        // $this->admin->selectLinks($tableStatus, $set);
68
69
        // if($page == "last")
70
        // {
71
        //     $isGroup = count($group) < count($select);
72
        //     $found_rows = $this->driver->result($this->driver->getRowCountQuery($table, $where, $isGroup, $group));
73
        //     $page = \floor(\max(0, $found_rows - 1) / $limit);
74
        // }
75
76
        $this->setSelectOptions($selectEntity);
77
        $this->setSelectEntity($selectEntity);
78
        $this->setSelectQuery($selectEntity);
79
80
        return $selectEntity;
81
    }
82
83
    /**
84
     * @param SelectEntity $selectEntity
85
     *
86
     * @return void
87
     */
88
    private function setDefaultOptions(SelectEntity $selectEntity): void
89
    {
90
        $defaultOptions = [
91
            'columns' => [],
92
            'where' => [],
93
            'order' => [],
94
            'desc' => [],
95
            'fulltext' => [],
96
            'limit' => '50',
97
            'text_length' => '100',
98
            'page' => '1',
99
        ];
100
        foreach ($defaultOptions as $name => $value) {
101
            if (!isset($this->utils->input->values[$name])) {
102
                $this->utils->input->values[$name] = $value;
103
            }
104
            if (!isset($selectEntity->queryOptions[$name])) {
105
                $selectEntity->queryOptions[$name] = $value;
106
            }
107
        }
108
        $page = intval($selectEntity->queryOptions['page']);
109
        if ($page > 0) {
110
            $page -= 1; // Page numbers start at 0 here, instead of 1.
111
        }
112
        $selectEntity->queryOptions['page'] = $page;
113
        $selectEntity->page = $page;
114
    }
115
116
    /**
117
     * @param SelectEntity $selectEntity
118
     *
119
     * @return void
120
     */
121
    private function setFieldsOptions(SelectEntity $selectEntity): void
122
    {
123
        $selectEntity->rights = []; // privilege => 0
124
        $selectEntity->columns = []; // selectable columns
125
        $selectEntity->textLength = 0;
126
        foreach ($selectEntity->fields as $key => $field) {
127
            $name = $this->admin->fieldName($field);
128
            if (isset($field->privileges["select"]) && $name != "") {
129
                $selectEntity->columns[$key] = html_entity_decode(strip_tags($name), ENT_QUOTES);
130
                if ($this->admin->isShortable($field)) {
131
                    $this->setSelectTextLength($selectEntity);
132
                }
133
            }
134
            $selectEntity->rights[] = $field->privileges;
135
        }
136
    }
137
138
    /**
139
     * Find out foreign keys for each column
140
     *
141
     * @param SelectEntity $selectEntity
142
     *
143
     * @return void
144
     */
145
    private function setForeignKeys(SelectEntity $selectEntity): void
146
    {
147
        $selectEntity->foreignKeys = [];
148
        foreach ($this->driver->foreignKeys($selectEntity->table) as $foreignKey) {
149
            foreach ($foreignKey->source as $val) {
150
                $selectEntity->foreignKeys[$val][] = $foreignKey;
151
            }
152
        }
153
    }
154
155
    /**
156
     * @param array $value
157
     *
158
     * @return bool
159
     */
160
    private function colHasValidValue(array $value): bool
161
    {
162
        return $value['fun'] === 'count' ||
163
            ($value['col'] !== '' && (!$value['fun'] ||
164
                in_array($value['fun'], $this->driver->functions()) ||
165
                in_array($value['fun'], $this->driver->grouping())));
166
    }
167
168
    /**
169
     * @param array $where AND conditions
170
     * @param array $foreignKeys
171
     *
172
     * @return bool
173
     */
174
    // private function setSelectEmail(array $where, array $foreignKeys)
175
    // {
176
    //     return false;
177
    // }
178
179
    /**
180
     * Apply SQL function
181
     *
182
     * @param string $function
183
     * @param string $column escaped column identifier
184
     *
185
     * @return string
186
     */
187
    public function applySqlFunction(string $function, string $column): string
188
    {
189
        if (!$function) {
190
            return $column;
191
        }
192
        if ($function === 'unixepoch') {
193
            return "DATETIME($column, '$function')";
194
        }
195
        if ($function === 'count distinct') {
196
            return "COUNT(DISTINCT $column)";
197
        }
198
        return strtoupper($function) . "($column)";
199
    }
200
201
    /**
202
     * @param SelectEntity $selectEntity
203
     *
204
     * @return void
205
     */
206
    private function setSelectColumns(SelectEntity $selectEntity): void
207
    {
208
        $selectEntity->select = []; // select expressions, empty for *
209
        $selectEntity->group = []; // expressions without aggregation - will be used for GROUP BY if an aggregation function is used
210
        $values = $this->utils->input->values;
211
        foreach ($values['columns'] as $key => $value) {
212
            if ($this->colHasValidValue($value)) {
213
                $column = '*';
214
                if ($value['col'] !== '') {
215
                    $column = $this->driver->escapeId($value['col']);
216
                }
217
                $selectEntity->select[$key] = $this->applySqlFunction($value['fun'], $column);
218
                if (!in_array($value['fun'], $this->driver->grouping())) {
219
                    $selectEntity->group[] = $selectEntity->select[$key];
220
                }
221
            }
222
        }
223
    }
224
225
    /**
226
     * @param array $value
227
     * @param array $fields
228
     *
229
     * @return string
230
     */
231
    private function getWhereCondition(array $value, array $fields): string
232
    {
233
        $op = $value['op'];
234
        $val = $value['val'];
235
        $col = $value['col'];
236
        if (preg_match('~IN$~', $op)) {
237
            $in = $this->driver->processLength($val);
238
            return " $op " . ($in !== '' ? $in : '(NULL)');
239
        }
240
        if ($op === 'SQL') {
241
            return ' ' . $val; // SQL injection
242
        }
243
        if ($op === 'LIKE %%') {
244
            return ' LIKE ' . $this->getUnconvertedFieldValue($fields[$col], "%$val%");
245
        }
246
        if ($op === 'ILIKE %%') {
247
            return ' ILIKE ' . $this->getUnconvertedFieldValue($fields[$col], "%$val%");
248
        }
249
        if ($op === 'FIND_IN_SET') {
250
            return ')';
251
        }
252
        if (!preg_match('~NULL$~', $op)) {
253
            return " $op " . $this->getUnconvertedFieldValue($fields[$col], $val);
254
        }
255
        return " $op";
256
    }
257
258
    /**
259
     * @param TableFieldEntity $field
260
     * @param array $value
261
     *
262
     * @return bool
263
     */
264
    private function selectFieldIsValid(TableFieldEntity $field, array $value): bool
265
    {
266
        $op = $value['op'];
267
        $val = $value['val'];
268
        $in = preg_match('~IN$~', $op) ? ',' : '';
269
        return (preg_match('~^[-\d.' . $in . ']+$~', $val) ||
270
                !preg_match('~' . $this->driver->numberRegex() . '|bit~', $field->type)) &&
271
            (!preg_match("~[\x80-\xFF]~", $val) ||
272
                preg_match('~char|text|enum|set~', $field->type)) &&
273
            (!preg_match('~date|timestamp~', $field->type) ||
274
                preg_match('~^\d+-\d+-\d+~', $val));
275
    }
276
277
    /**
278
     * @param array $value
279
     * @param array $fields
280
     *
281
     * @return string
282
     */
283
    private function getSelectExpression(array $value, array $fields): string
284
    {
285
        $op = $value['op'];
286
        $col = $value['col'];
287
        $prefix = '';
288
        if ($op === 'FIND_IN_SET') {
289
            $prefix = $op .'(' . $this->driver->quote($value['val']) . ', ';
290
        }
291
        $condition = $this->getWhereCondition($value, $fields);
292
        if ($col !== '') {
293
            return $prefix . $this->driver->convertSearch($this->driver->escapeId($col),
294
                    $value, $fields[$col]) . $condition;
295
        }
296
        // find anywhere
297
        $clauses = [];
298
        foreach ($fields as $name => $field) {
299
            if ($this->selectFieldIsValid($field, $value)) {
300
                $clauses[] = $prefix . $this->driver->convertSearch($this->driver->escapeId($name),
301
                        $value, $field) . $condition;
302
            }
303
        }
304
        if (empty($clauses)) {
305
            return '1 = 0';
306
        }
307
        return '(' . implode(' OR ', $clauses) . ')';
308
    }
309
310
    /**
311
     * @param IndexEntity $index
312
     * @param int $i
313
     *
314
     * @return string
315
     */
316
    private function getMatchExpression(IndexEntity $index, int $i): string
317
    {
318
        $columns = array_map(function ($column) {
319
            return $this->driver->escapeId($column);
320
        }, $index->columns);
321
        $fulltext = $this->utils->input->values['fulltext'][$i] ?? '';
322
        $match = $this->driver->quote($fulltext);
323
        if (isset($this->utils->input->values['boolean'][$i])) {
324
            $match .= ' IN BOOLEAN MODE';
325
        }
326
        return 'MATCH (' . implode(', ', $columns) . ') AGAINST (' . $match . ')';
327
    }
328
329
    /**
330
     * @param SelectEntity $selectEntity
331
     *
332
     * @return void
333
     */
334
    private function setSelectWhere(SelectEntity $selectEntity): void
335
    {
336
        $selectEntity->where = [];
337
        foreach ($selectEntity->indexes as $i => $index) {
338
            $fulltext = $this->utils->input->values['fulltext'][$i] ?? '';
339
            if ($index->type === 'FULLTEXT' && $fulltext !== '') {
340
                $selectEntity->where[] = $this->getMatchExpression($index, $i);
341
            }
342
        }
343
        foreach ((array) $this->utils->input->values['where'] as $value) {
344
            if (($value['col'] !== '' ||  $value['val'] !== '') &&
345
                in_array($value['op'], $this->driver->operators())) {
346
                $selectEntity->where[] = $this
347
                    ->getSelectExpression($value, $selectEntity->fields);
348
            }
349
        }
350
    }
351
352
    /**
353
     * @param SelectEntity $selectEntity
354
     *
355
     * @return void
356
     */
357
    private function setSelectOrder(SelectEntity $selectEntity): void
358
    {
359
        $values = $this->utils->input->values;
360
        $selectEntity->order = [];
361
        foreach ($values['order'] as $key => $value) {
362
            if ($value !== '') {
363
                $regexp = '~^((COUNT\(DISTINCT |[A-Z0-9_]+\()(`(?:[^`]|``)+`|"(?:[^"]|"")+")\)|COUNT\(\*\))$~';
364
                if (preg_match($regexp, $value) !== false) {
365
                    $value = $this->driver->escapeId($value);
366
                }
367
                if (isset($values['desc'][$key]) && intval($values['desc'][$key]) !== 0) {
368
                    $value .= ' DESC';
369
                }
370
                $selectEntity->order[] = $value;
371
            }
372
        }
373
    }
374
375
    /**
376
     * @param SelectEntity $selectEntity
377
     *
378
     * @return void
379
     */
380
    private function setSelectLimit(SelectEntity $selectEntity): void
381
    {
382
        $selectEntity->limit = intval($this->utils->input->values['limit'] ?? 50);
383
    }
384
385
    /**
386
     * @param SelectEntity $selectEntity
387
     *
388
     * @return void
389
     */
390
    private function setSelectTextLength(SelectEntity $selectEntity): void
391
    {
392
        $selectEntity->textLength = intval($this->utils->input->values['text_length'] ?? 100);
393
    }
394
395
    /**
396
     * @param SelectEntity $selectEntity
397
     *
398
     * @return void
399
     */
400
    private function setPrimaryKey(SelectEntity $selectEntity): void
401
    {
402
        $primary = null;
403
        $selectEntity->unselected = [];
404
        foreach ($selectEntity->indexes as $index) {
405
            if ($index->type === "PRIMARY") {
406
                $primary = array_flip($index->columns);
407
                $selectEntity->unselected = ($selectEntity->select ? $primary : []);
408
                foreach ($selectEntity->unselected as $key => $val) {
409
                    if (in_array($this->driver->escapeId($key), $selectEntity->select)) {
410
                        unset($selectEntity->unselected[$key]);
411
                    }
412
                }
413
                break;
414
            }
415
        }
416
417
        $oid = $selectEntity->tableStatus->oid;
418
        if ($oid && !$primary) {
419
            /*$primary = */$selectEntity->unselected = [$oid => 0];
420
            // Make an index for the OID
421
            $index = new IndexEntity();
422
            $index->type = "PRIMARY";
423
            $index->columns = [$oid];
424
            $selectEntity->indexes[] = $index;
425
        }
426
    }
427
428
    /**
429
     * @param SelectEntity $selectEntity
430
     *
431
     * @return void
432
     */
433
    public function setSelectQuery(SelectEntity $selectEntity): void
434
    {
435
        $query = $this->driver->buildSelectQuery($selectEntity->tableSelect);
436
        // From adminer.inc.php
437
        $selectEntity->query = str_replace("\n", " ", $query);
438
    }
439
440
    /**
441
     * @param SelectEntity $selectEntity
442
     *
443
     * @return void
444
     */
445
    private function setSelectOptions(SelectEntity $selectEntity): void
446
    {
447
        $selectEntity->options = [
448
            'columns' => $this->getColumnsOptions($selectEntity->select,
449
                $selectEntity->columns, $selectEntity->queryOptions),
450
            'filters' => $this->getFiltersOptions($selectEntity->columns,
451
                $selectEntity->indexes, $selectEntity->queryOptions),
452
            'sorting' => $this->getSortingOptions($selectEntity->columns,
453
                $selectEntity->queryOptions),
454
            'limit' => $this->getLimitOptions($selectEntity->limit),
455
            'length' => $this->getLengthOptions($selectEntity->textLength),
456
            // 'action' => $this->getActionOptions($selectEntity->indexes),
457
        ];
458
    }
459
460
    /**
461
     * @param SelectEntity $selectEntity
462
     *
463
     * @return void
464
     */
465
    private function setSelectEntity(SelectEntity $selectEntity): void
466
    {
467
        $select2 = $selectEntity->select;
468
        $group2 = $selectEntity->group;
469
        if (empty($select2)) {
470
            $select2[] = "*";
471
            $convert_fields = $this->driver->convertFields($selectEntity->columns,
472
                $selectEntity->fields, $selectEntity->select);
473
            if ($convert_fields) {
474
                $select2[] = substr($convert_fields, 2);
475
            }
476
        }
477
        foreach ($selectEntity->select as $key => $val) {
478
            $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...
479
            if ($field && ($as = $this->driver->convertField($field))) {
480
                $select2[$key] = "$as AS $val";
481
            }
482
        }
483
        $isGroup = count($selectEntity->group) < count($selectEntity->select);
484
        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...
485
            foreach ($unselected as $key => $val) {
486
                $select2[] = $this->driver->escapeId($key);
487
                if (!empty($group2)) {
488
                    $group2[] = $this->driver->escapeId($key);
489
                }
490
            }
491
        }
492
493
        // From driver.inc.php
494
        $selectEntity->tableSelect = new TableSelectEntity($selectEntity->table,
495
            $select2, $selectEntity->where, $group2, $selectEntity->order,
496
            $selectEntity->limit, $selectEntity->page);
497
    }
498
499
    /**
500
     * Print action box in select
501
     *
502
     * @param array $indexes
503
     *
504
     * @return array
505
     */
506
    // private function getActionOptions(array $indexes)
507
    // {
508
    //     $columns = [];
509
    //     foreach ($indexes as $index) {
510
    //         $current_key = \reset($index->columns);
511
    //         if ($index->type != "FULLTEXT" && $current_key) {
512
    //             $columns[$current_key] = 1;
513
    //         }
514
    //     }
515
    //     $columns[""] = 1;
516
    //     return ['columns' => $columns];
517
    // }
518
519
    /**
520
     * Print command box in select
521
     *
522
     * @return bool whether to print default commands
523
     */
524
    // private function getCommandOptions()
525
    // {
526
    //     return !$this->driver->isInformationSchema($this->driver->database());
527
    // }
528
529
    /**
530
     * Print import box in select
531
     *
532
     * @return bool whether to print default import
533
     */
534
    // private function getImportOptions()
535
    // {
536
    //     return !$this->driver->isInformationSchema($this->driver->database());
537
    // }
538
539
    /**
540
     * Print extra text in the end of a select form
541
     *
542
     * @param array $emailFields Fields holding e-mails
543
     * @param array $columns Selectable columns
544
     *
545
     * @return array
546
     */
547
    // private function getEmailOptions(array $emailFields, array $columns)
548
    // {
549
    // }
550
}
551