SelectQuery::setSelectLimit()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
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;
0 ignored issues
show
Bug introduced by
The type Lagdo\Facades\Logger was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
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
introduced by
The trait Lagdo\DbAdmin\Db\Facades\Select\SelectTrait requires some properties which are not provided by Lagdo\DbAdmin\Db\Facades\Select\SelectQuery: $type, $str
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);
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
        $match = $this->driver->quote($this->utils->input->values['fulltext'][$i]);
322
        if (isset($this->utils->input->values['boolean'][$i])) {
323
            $match .= ' IN BOOLEAN MODE';
324
        }
325
        return 'MATCH (' . implode(', ', $columns) . ') AGAINST (' . $match . ')';
326
    }
327
328
    /**
329
     * @param SelectEntity $selectEntity
330
     *
331
     * @return void
332
     */
333
    private function setSelectWhere(SelectEntity $selectEntity): void
334
    {
335
        $selectEntity->where = [];
336
        foreach ($selectEntity->indexes as $i => $index) {
337
            if ($index->type === 'FULLTEXT' && $this->utils->input->values['fulltext'][$i] !== '') {
338
                $selectEntity->where[] = $this->getMatchExpression($index, $i);
339
            }
340
        }
341
        foreach ((array) $this->utils->input->values['where'] as $value) {
342
            if (($value['col'] !== '' ||  $value['val'] !== '') &&
343
                in_array($value['op'], $this->driver->operators())) {
344
                $selectEntity->where[] = $this
345
                    ->getSelectExpression($value, $selectEntity->fields);
346
            }
347
        }
348
    }
349
350
    /**
351
     * @param SelectEntity $selectEntity
352
     *
353
     * @return void
354
     */
355
    private function setSelectOrder(SelectEntity $selectEntity): void
356
    {
357
        $values = $this->utils->input->values;
358
        $selectEntity->order = [];
359
        foreach ($values['order'] as $key => $value) {
360
            if ($value !== '') {
361
                $regexp = '~^((COUNT\(DISTINCT |[A-Z0-9_]+\()(`(?:[^`]|``)+`|"(?:[^"]|"")+")\)|COUNT\(\*\))$~';
362
                if (preg_match($regexp, $value) !== false) {
363
                    $value = $this->driver->escapeId($value);
364
                }
365
                if (isset($values['desc'][$key]) && intval($values['desc'][$key]) !== 0) {
366
                    $value .= ' DESC';
367
                }
368
                $selectEntity->order[] = $value;
369
            }
370
        }
371
    }
372
373
    /**
374
     * @param SelectEntity $selectEntity
375
     *
376
     * @return void
377
     */
378
    private function setSelectLimit(SelectEntity $selectEntity): void
379
    {
380
        $selectEntity->limit = intval($this->utils->input->values['limit'] ?? 50);
381
    }
382
383
    /**
384
     * @param SelectEntity $selectEntity
385
     *
386
     * @return void
387
     */
388
    private function setSelectTextLength(SelectEntity $selectEntity): void
389
    {
390
        $selectEntity->textLength = intval($this->utils->input->values['text_length'] ?? 100);
391
    }
392
393
    /**
394
     * @param SelectEntity $selectEntity
395
     *
396
     * @return void
397
     */
398
    private function setPrimaryKey(SelectEntity $selectEntity): void
399
    {
400
        $primary = null;
401
        $selectEntity->unselected = [];
402
        foreach ($selectEntity->indexes as $index) {
403
            if ($index->type == "PRIMARY") {
404
                $primary = array_flip($index->columns);
405
                $selectEntity->unselected = ($selectEntity->select ? $primary : []);
406
                foreach ($selectEntity->unselected as $key => $val) {
407
                    if (in_array($this->driver->escapeId($key), $selectEntity->select)) {
408
                        unset($selectEntity->unselected[$key]);
409
                    }
410
                }
411
                break;
412
            }
413
        }
414
415
        $oid = $selectEntity->tableStatus->oid;
416
        if ($oid && !$primary) {
417
            /*$primary = */$selectEntity->unselected = [$oid => 0];
418
            $selectEntity->indexes[] = ["type" => "PRIMARY", "columns" => [$oid]];
419
        }
420
    }
421
422
    /**
423
     * @param SelectEntity $selectEntity
424
     *
425
     * @return void
426
     */
427
    public function setSelectQuery(SelectEntity $selectEntity): void
428
    {
429
        $query = $this->driver->buildSelectQuery($selectEntity->tableSelect);
430
        // From adminer.inc.php
431
        $selectEntity->query = str_replace("\n", " ", $query);
432
    }
433
434
    /**
435
     * @param SelectEntity $selectEntity
436
     *
437
     * @return void
438
     */
439
    private function setSelectOptions(SelectEntity $selectEntity): void
440
    {
441
        $selectEntity->options = [
442
            'columns' => $this->getColumnsOptions($selectEntity->select,
443
                $selectEntity->columns, $selectEntity->queryOptions),
444
            'filters' => $this->getFiltersOptions($selectEntity->columns,
445
                $selectEntity->indexes, $selectEntity->queryOptions),
446
            'sorting' => $this->getSortingOptions($selectEntity->columns,
447
                $selectEntity->queryOptions),
448
            'limit' => $this->getLimitOptions($selectEntity->limit),
449
            'length' => $this->getLengthOptions($selectEntity->textLength),
450
            // 'action' => $this->getActionOptions($selectEntity->indexes),
451
        ];
452
    }
453
454
    /**
455
     * @param SelectEntity $selectEntity
456
     *
457
     * @return void
458
     */
459
    private function setSelectEntity(SelectEntity $selectEntity): void
460
    {
461
        $select2 = $selectEntity->select;
462
        $group2 = $selectEntity->group;
463
        if (empty($select2)) {
464
            $select2[] = "*";
465
            $convert_fields = $this->driver->convertFields($selectEntity->columns,
466
                $selectEntity->fields, $selectEntity->select);
467
            if ($convert_fields) {
468
                $select2[] = substr($convert_fields, 2);
469
            }
470
        }
471
        foreach ($selectEntity->select as $key => $val) {
472
            $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...
473
            if ($field && ($as = $this->driver->convertField($field))) {
474
                $select2[$key] = "$as AS $val";
475
            }
476
        }
477
        $isGroup = count($selectEntity->group) < count($selectEntity->select);
478
        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...
479
            foreach ($unselected as $key => $val) {
480
                $select2[] = $this->driver->escapeId($key);
481
                if (!empty($group2)) {
482
                    $group2[] = $this->driver->escapeId($key);
483
                }
484
            }
485
        }
486
487
        // From driver.inc.php
488
        $selectEntity->tableSelect = new TableSelectEntity($selectEntity->table,
489
            $select2, $selectEntity->where, $group2, $selectEntity->order,
490
            $selectEntity->limit, $selectEntity->page);
491
    }
492
493
    /**
494
     * Print action box in select
495
     *
496
     * @param array $indexes
497
     *
498
     * @return array
499
     */
500
    // private function getActionOptions(array $indexes)
501
    // {
502
    //     $columns = [];
503
    //     foreach ($indexes as $index) {
504
    //         $current_key = \reset($index->columns);
505
    //         if ($index->type != "FULLTEXT" && $current_key) {
506
    //             $columns[$current_key] = 1;
507
    //         }
508
    //     }
509
    //     $columns[""] = 1;
510
    //     return ['columns' => $columns];
511
    // }
512
513
    /**
514
     * Print command box in select
515
     *
516
     * @return bool whether to print default commands
517
     */
518
    // private function getCommandOptions()
519
    // {
520
    //     return !$this->driver->isInformationSchema($this->driver->database());
521
    // }
522
523
    /**
524
     * Print import box in select
525
     *
526
     * @return bool whether to print default import
527
     */
528
    // private function getImportOptions()
529
    // {
530
    //     return !$this->driver->isInformationSchema($this->driver->database());
531
    // }
532
533
    /**
534
     * Print extra text in the end of a select form
535
     *
536
     * @param array $emailFields Fields holding e-mails
537
     * @param array $columns Selectable columns
538
     *
539
     * @return array
540
     */
541
    // private function getEmailOptions(array $emailFields, array $columns)
542
    // {
543
    // }
544
}
545