Passed
Pull Request — master (#1593)
by Michael
08:53
created

Criteria::__construct()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 4
eloc 10
c 2
b 1
f 0
nc 2
nop 6
dl 0
loc 14
rs 9.9332
1
<?php
2
/**
3
 * XOOPS Criteria parser for database query
4
 *
5
 * You may not change or alter any portion of this comment or credits
6
 * of supporting developers from this source code or any supporting source code
7
 * which is considered copyrighted (c) material of the original comment or credit authors.
8
 * This program is distributed in the hope that it will be useful,
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * @copyright       (c) 2000-2025 XOOPS Project (https://xoops.org)
13
 * @license             GNU GPL 2 (https://www.gnu.org/licenses/gpl-2.0.html)
14
 * @package             kernel
15
 * @subpackage          database
16
 * @since               2.0.0
17
 * @author              Kazumi Ono <[email protected]>
18
 * @author              Nathan Dial
19
 * @author              Taiwen Jiang <[email protected]>
20
 */
21
defined('XOOPS_ROOT_PATH') || exit('Restricted access');
22
23
/**
24
 * A criteria (grammar?) for a database query.
25
 *
26
 * Abstract base class should never be instantiated directly.
27
 *
28
 * @abstract
29
 */
30
class CriteriaElement
31
{
32
    /**
33
     * Sort order
34
     *
35
     * @var string
36
     */
37
    public $order = 'ASC';
38
39
    /**
40
     *
41
     * @var string
42
     */
43
    public $sort = '';
44
45
    /**
46
     * Number of records to retrieve
47
     *
48
     * @var int
49
     */
50
    public $limit = 0;
51
52
    /**
53
     * Offset of first record
54
     *
55
     * @var int
56
     */
57
    public $start = 0;
58
59
    /**
60
     *
61
     * @var string
62
     */
63
    public $groupby = '';
64
65
    /**
66
     * Constructor
67
     */
68
    public function __construct() {}
69
70
    /**
71
     * Render the criteria element
72
     * @return string
73
     */
74
    public function render() {}
75
76
    /**
77
     *
78
     * @param string $sort
79
     */
80
    public function setSort($sort)
81
    {
82
        $this->sort = $sort;
83
    }
84
85
    /**
86
     *
87
     * @return string
88
     */
89
    public function getSort()
90
    {
91
        return $this->sort;
92
    }
93
94
    /**
95
     *
96
     * @param string $order
97
     */
98
    public function setOrder($order)
99
    {
100
        if ('DESC' === strtoupper($order)) {
101
            $this->order = 'DESC';
102
        }
103
    }
104
105
    /**
106
     *
107
     * @return string
108
     */
109
    public function getOrder()
110
    {
111
        return $this->order;
112
    }
113
114
    /**
115
     *
116
     * @param int $limit
117
     */
118
    public function setLimit($limit = 0)
119
    {
120
        $this->limit = (int) $limit;
121
    }
122
123
    /**
124
     *
125
     * @return int
126
     */
127
    public function getLimit()
128
    {
129
        return $this->limit;
130
    }
131
132
    /**
133
     *
134
     * @param int $start
135
     */
136
    public function setStart($start = 0)
137
    {
138
        $this->start = (int) $start;
139
    }
140
141
    /**
142
     *
143
     * @return int
144
     */
145
    public function getStart()
146
    {
147
        return $this->start;
148
    }
149
150
    /**
151
     *
152
     * @param string $group
153
     */
154
    public function setGroupBy($group)
155
    {
156
        $this->groupby = $group;
157
    }
158
159
    /**
160
     *
161
     * @return string
162
     */
163
    public function getGroupby()
164
    {
165
        return $this->groupby ? " GROUP BY {$this->groupby}" : '';
166
    }
167
    /**
168
     * *#@-
169
     */
170
}
171
172
/**
173
 * Collection of multiple {@link CriteriaElement}s
174
 *
175
 */
176
class CriteriaCompo extends CriteriaElement
177
{
178
    /**
179
     * The elements of the collection
180
     *
181
     * @var array Array of {@link CriteriaElement} objects
182
     */
183
    public $criteriaElements = [];
184
185
    /**
186
     * Conditions
187
     *
188
     * @var array
189
     */
190
    public $conditions = [];
191
192
    /**
193
     * Constructor
194
     *
195
     * @param CriteriaElement|null $ele
196
     * @param string $condition
197
     */
198
    public function __construct(?CriteriaElement $ele = null, $condition = 'AND')
199
    {
200
        if (isset($ele)) {
201
            $this->add($ele, $condition);
202
        }
203
    }
204
205
    /**
206
     * Add an element
207
     *
208
     * @param CriteriaElement|object $criteriaElement
209
     * @param string                 $condition
210
     * @return object reference to this collection
211
     */
212
    public function &add(CriteriaElement $criteriaElement, $condition = 'AND')
213
    {
214
        if (is_object($criteriaElement)) {
215
            $this->criteriaElements[] = & $criteriaElement;
216
            $this->conditions[]       = $condition;
217
        }
218
219
        return $this;
220
    }
221
222
    /**
223
     * Make the criteria into a query string
224
     *
225
     * @return string
226
     */
227
    public function render(?\XoopsDatabase $db = null): string
228
    {
229
        $ret   = '';
230
        $count = count($this->criteriaElements);
231
        if ($count > 0) {
232
            $renderString = $this->criteriaElements[0]->render($db);
233
            for ($i = 1; $i < $count; ++$i) {
234
                if (!$render = $this->criteriaElements[$i]->render($db)) {
235
                    continue;
236
                }
237
                $renderString .= (empty($renderString) ? '' : ' ' . $this->conditions[$i] . ' ') . $render;
238
            }
239
            $ret = empty($renderString) ? '' : "({$renderString})";
240
        }
241
242
        return $ret;
243
    }
244
245
    /**
246
     * Make the criteria into a SQL "WHERE" clause
247
     *
248
     * @return string
249
     */
250
    public function renderWhere(?\XoopsDatabase $db = null): string
251
    {
252
        $ret = $this->render($db);
253
        $ret = ($ret !== '') ? 'WHERE ' . $ret : $ret;
254
255
        return $ret;
256
    }
257
258
    /**
259
     * Generate an LDAP filter from criteria
260
     *
261
     * @return string
262
     * @author Nathan Dial [email protected]
263
     */
264
    public function renderLdap()
265
    {
266
        $retval = '';
267
        $count  = count($this->criteriaElements);
268
        if ($count > 0) {
269
            $retval = $this->criteriaElements[0]->renderLdap();
270
            for ($i = 1; $i < $count; ++$i) {
271
                $cond   = strtoupper($this->conditions[$i]);
272
                $op     = ($cond === 'OR') ? '|' : '&';
273
                $retval = "({$op}{$retval}" . $this->criteriaElements[$i]->renderLdap() . ')';
274
            }
275
        }
276
277
        return $retval;
278
    }
279
}
280
281
/**
282
 * A single criteria
283
 *
284
 */
285
class Criteria extends CriteriaElement
286
{
287
    /** @var string|null Optional table prefix (alias) like "u" for "u.`uname`" */
288
    public $prefix;
289
    /** @var string|null Optional column wrapper function with sprintf format, e.g. 'LOWER(%s)' */
290
    public $function;
291
    /** @var string Column name or expression (backticks handled for simple columns) */
292
    public $column;
293
    /** @var string SQL operator (=, <, >, LIKE, IN, IS NULL, etc.) */
294
    public $operator;
295
    /** @var mixed Value for the operator: scalar for most ops, array or "(a,b)" for IN/NOT IN */
296
    public $value;
297
    /** @var bool Allow empty string values to render (default false = skip empty) */
298
    protected $allowEmptyValue = false;
299
    /** @var bool Allow inner wildcards in LIKE (default false = escape inner % and _) */
300
    protected $allowInnerWildcards = false;
301
    /** @var bool Global default for allowing inner wildcards in LIKE across all instances */
302
    protected static $defaultAllowInnerWildcards = false;
303
    /** @var bool|null Cached legacy log flag */
304
    private static $legacyLogEnabled = null;
305
306
    /**
307
     * Initialize logging flag once
308
     */
309
    private static function isLegacyLogEnabled(): bool
310
    {
311
        if (self::$legacyLogEnabled === null) {
312
            self::$legacyLogEnabled = defined('XOOPS_DB_LEGACY_LOG') && XOOPS_DB_LEGACY_LOG;
313
        }
314
        return self::$legacyLogEnabled;
315
    }
316
317
    /**
318
     * Set the global default for allowing inner wildcards in LIKE patterns.
319
     * Useful during migrations of legacy modules that intentionally use inner wildcards.
320
     *
321
     * @param bool $on
322
     * @return void
323
     */
324
    public static function setDefaultAllowInnerWildcards(bool $on = true): void
325
    {
326
        self::$defaultAllowInnerWildcards = $on;
327
    }
328
329
    /**
330
     * Opt-in per instance for intentional inner wildcards in LIKE patterns.
331
     * Default remains secure (inner %/_ escaped).
332
     *
333
     * @param bool $on
334
     * @return $this
335
     */
336
    public function allowInnerWildcards(bool $on = true): self
337
    {
338
        $this->allowInnerWildcards = $on;
339
        return $this;
340
    }
341
342
    /**
343
     * Constructor
344
     *
345
     * @param string      $column
346
     * @param mixed       $value
347
     * @param string      $operator
348
     * @param string|null $prefix
349
     * @param string|null $function  sprintf format string, e.g. 'LOWER(%s)'
350
     * @param bool        $allowEmptyValue
351
     */
352
    public function __construct($column, $value = '', $operator = '=', $prefix = '', $function = '', $allowEmptyValue = false)
353
    {
354
        $this->prefix           = $prefix;
355
        $this->function         = $function;
356
        $this->column           = $column;
357
        $this->value            = $value;
358
        $this->operator         = $operator;
359
        $this->allowEmptyValue  = $allowEmptyValue;
360
        $this->allowInnerWildcards = self::$defaultAllowInnerWildcards;
361
362
        // Legacy always-true workaround: new Criteria(1, '1', '=') → no WHERE
363
        if ((int)$column === 1 && (int)$value === 1 && $operator === '=') {
364
            $this->column = '';
365
            $this->value  = '';
366
        }
367
    }
368
369
    /**
370
     * Render the SQL fragment (no leading WHERE)
371
     *
372
     * @param \XoopsDatabase|null $db Database connection
373
     * @return string SQL fragment
374
     * @throws \RuntimeException if database connection is not available
375
     */
376
    public function render(?\XoopsDatabase $db = null)
377
    {
378
        // 1) Explicit injection
379
        // 2) Legacy global
380
        // 3) Factory
381
        if ($db === null && isset($GLOBALS['xoopsDB']) && $GLOBALS['xoopsDB'] instanceof \XoopsDatabase) {
382
            $db = $GLOBALS['xoopsDB'];
383
        }
384
385
        if ($db === null && class_exists('\XoopsDatabaseFactory')) {
386
            $db = \XoopsDatabaseFactory::getDatabaseConnection();
387
        }
388
389
        if (!$db) {
390
            throw new \RuntimeException('Database connection required to render Criteria');
391
        }
392
393
        $col = (string)($this->column ?? '');
394
395
        if ($col === '') {
396
            // Legacy "always true" workaround → no predicate at all
397
            return '';
398
        }
399
400
        $backtick = (strpos($col, '.') === false && strpos($col, '(') === false) ? '`' : '';
401
        $clause = (empty($this->prefix) ? '' : "{$this->prefix}.") . $backtick . $col . $backtick;
402
403
        if (!empty($this->function)) {
404
            // function should be a trusted sprintf pattern, e.g. 'LOWER(%s)'
405
            $clause = sprintf($this->function, $clause);
406
        }
407
408
        $op = strtoupper((string)$this->operator);
409
        $valStr = (string)$this->value;
410
411
        if ($op === 'IS NULL' || $op === 'IS NOT NULL') {
412
            return $clause . ' ' . $op;
413
        }
414
415
        if (trim($valStr) === '' && !$this->allowEmptyValue) {
416
            return '';
417
        }
418
419
        // IN / NOT IN
420
        if ($op === 'IN' || $op === 'NOT IN') {
421
            if (is_array($this->value)) {
422
                $parts = [];
423
                foreach ($this->value as $v) {
424
                    if (is_int($v) || (is_string($v) && preg_match('/^-?\d+$/', $v))) {
425
                        $parts[] = (string)(int)$v;
426
                    } else {
427
                        $parts[] = $db->quote((string)$v);
428
                    }
429
                }
430
            return $clause . ' ' . $op . ' (' . implode(',', $parts) . ')';
431
        }
432
433
            // Legacy format: validate before passing through
434
            if (!preg_match('/^\s*\([^)]*\)\s*$/', (string)$this->value)) {
435
                return $clause . ' ' . $op . ' (' . $db->quote((string)$this->value) . ')';
436
            }
437
438
            if (!self::isLegacyLogEnabled()) {
439
            return $clause . ' ' . $op . ' ' . $this->value;
440
        }
441
442
            // Build message
443
                $message = sprintf(
444
                    'Legacy Criteria IN format used for column "%s" with value "%s"',
445
                    $this->column,
446
                    is_scalar($this->value) ? (string)$this->value : gettype($this->value)
447
                );
448
449
            if (defined('XOOPS_DEBUG') && XOOPS_DEBUG) {
450
            $bt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
451
                $caller = $bt[1] ?? [];
452
            $file = $caller['file'] ?? 'unknown';
453
            $line = $caller['line'] ?? 0;
454
                $message .= sprintf(' at %s:%d', $file, $line);
455
            }
456
457
            // Prefer XoopsLogger if available
458
            if (class_exists('XoopsLogger')) {
459
                \XoopsLogger::getInstance()->addExtra('CriteriaLegacyIN', $message);
460
        } else {
461
                error_log($message);
462
        }
463
464
            // Optional: deprecation notice in debug mode
465
            if (defined('XOOPS_DEBUG') && XOOPS_DEBUG) {
466
                trigger_error($message, E_USER_DEPRECATED);
467
            }
468
469
            return $clause . ' ' . $op . ' ' . $this->value;
470
        }
471
472
        // LIKE / NOT LIKE
473
        if ($op === 'LIKE' || $op === 'NOT LIKE') {
474
            $pattern = (string)$this->value;
475
            $quoted  = $db->quote($pattern);
476
            return $clause . ' ' . $op . ' ' . $quoted;
477
        }
478
479
        // All other operators
480
        if (strlen($valStr) > 2 && $valStr[0] === '`' && $valStr[strlen($valStr) - 1] === '`') {
481
            $inner = substr($valStr, 1, -1);
482
483
            // Allow alphanumeric, underscore, dot, hyphen (valid MySQL identifiers when backticked)
484
            if (preg_match('/^[a-zA-Z0-9_.\-]+$/', $inner)) {
485
                $safeValue = $valStr;
486
        } else {
487
                // Invalid chars in backticked value → use empty backticks (old behavior)
488
                $safeValue = '``';
489
            }
490
        } else {
491
            // Regular value - keep integers unquoted, quote strings
492
            if (is_int($this->value) || (is_string($this->value) && preg_match('/^-?\d+$/', $this->value))) {
493
                $safeValue = (string)(int)$this->value;
494
            } else {
495
                $safeValue = $db->quote((string)$this->value);
496
            }
497
        }
498
499
        return $clause . ' ' . $op . ' ' . $safeValue;
500
    }
501
502
    /**
503
     * Render with leading WHERE clause
504
     *
505
     * @return string SQL WHERE clause or empty string
506
     */
507
    public function renderWhere()
508
    {
509
        $cond = $this->render();
510
        return empty($cond) ? '' : "WHERE {$cond}";
511
    }
512
513
    /**
514
     * Generate an LDAP filter from criteria
515
     *
516
     * @return string LDAP filter
517
     */
518
    public function renderLdap()
519
    {
520
        if ($this->operator === '>') {
521
            $this->operator = '>=';
522
        }
523
        if ($this->operator === '<') {
524
            $this->operator = '<=';
525
        }
526
527
        if ($this->operator === '!=' || $this->operator === '<>') {
528
            $operator = '=';
529
            $clause   = '(!(' . $this->column . $operator . $this->value . '))';
530
        } else {
531
            if ($this->operator === 'IN') {
532
                $newvalue = str_replace(['(', ')'], '', $this->value);
533
                $tab      = explode(',', $newvalue);
534
                $clause = '';
535
                foreach ($tab as $uid) {
536
                    $clause .= "({$this->column}={$uid})";
537
                }
538
                $clause = '(|' . $clause . ')';
539
            } else {
540
                $clause = '(' . $this->column . $this->operator . $this->value . ')';
541
            }
542
        }
543
544
        return $clause;
545
    }
546
}
547