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

Criteria::isLegacyLogEnabled()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 3
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 6
rs 10
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()
228
    {
229
        $ret   = '';
230
        $count = count($this->criteriaElements);
231
        if ($count > 0) {
232
            $render_string = $this->criteriaElements[0]->render();
233
            for ($i = 1; $i < $count; ++$i) {
234
                if (!$render = $this->criteriaElements[$i]->render()) {
235
                    continue;
236
                }
237
                $render_string .= (empty($render_string) ? '' : ' ' . $this->conditions[$i] . ' ') . $render;
238
            }
239
            $ret = empty($render_string) ? '' : "({$render_string})";
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()
251
    {
252
        $ret = $this->render();
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
290
    /** @var string|null Optional column wrapper function with sprintf format, e.g. 'LOWER(%s)' */
291
    public $function;
292
293
    /** @var string Column name or expression (backticks handled for simple columns) */
294
    public $column;
295
296
    /** @var string SQL operator (=, <, >, LIKE, IN, IS NULL, etc.) */
297
    public $operator;
298
299
    /** @var mixed Value for the operator: scalar for most ops, array or "(a,b)" for IN/NOT IN */
300
    public $value;
301
302
    /** @var bool Allow empty string values to render (default false = skip empty) */
303
    protected $allowEmptyValue = false;
304
305
    /** @var bool Allow inner wildcards in LIKE (default false = escape inner % and _) */
306
    protected $allowInnerWildcards = false;
307
308
    /** @var bool Global default for allowing inner wildcards in LIKE across all instances */
309
    protected static $defaultAllowInnerWildcards = false;
310
    /** @var bool|null Cached legacy log flag */
311
    private static $legacyLogEnabled = null;
312
313
    /**
314
     * Initialize logging flag once
315
     */
316
    private static function isLegacyLogEnabled(): bool
317
    {
318
        if (self::$legacyLogEnabled === null) {
319
            self::$legacyLogEnabled = defined('XOOPS_DB_LEGACY_LOG') && XOOPS_DB_LEGACY_LOG;
320
        }
321
        return self::$legacyLogEnabled;
322
    }
323
324
    /**
325
     * Set the global default for allowing inner wildcards in LIKE patterns.
326
     * Useful during migrations of legacy modules that intentionally use inner wildcards.
327
     *
328
     * @param bool $on
329
     * @return void
330
     */
331
    public static function setDefaultAllowInnerWildcards(bool $on = true): void
332
    {
333
        self::$defaultAllowInnerWildcards = $on;
334
    }
335
336
    /**
337
     * Opt-in per instance for intentional inner wildcards in LIKE patterns.
338
     * Default remains secure (inner %/_ escaped).
339
     *
340
     * @param bool $on
341
     * @return $this
342
     */
343
    public function allowInnerWildcards(bool $on = true): self
344
    {
345
        $this->allowInnerWildcards = $on;
346
        return $this;
347
    }
348
349
    /**
350
     * Constructor
351
     *
352
     * @param string      $column
353
     * @param mixed       $value
354
     * @param string      $operator
355
     * @param string|null $prefix
356
     * @param string|null $function  sprintf format string, e.g. 'LOWER(%s)'
357
     * @param bool        $allowEmptyValue
358
     */
359
    public function __construct($column, $value = '', $operator = '=', $prefix = '', $function = '', $allowEmptyValue = false)
360
    {
361
        $this->prefix           = $prefix;
362
        $this->function         = $function;
363
        $this->column           = $column;
364
        $this->value            = $value;
365
        $this->operator         = $operator;
366
        $this->allowEmptyValue  = $allowEmptyValue;
367
        $this->allowInnerWildcards = self::$defaultAllowInnerWildcards;
368
369
        // Legacy always-true workaround: new Criteria(1, '1', '=') → no WHERE
370
        if ((int)$column === 1 && (int)$value === 1 && $operator === '=') {
371
            $this->column = '';
372
            $this->value  = '';
373
        }
374
    }
375
376
    /**
377
     * Render the SQL fragment (no leading WHERE)
378
     *
379
     * @param \XoopsDatabase|null $db Database connection
380
     * @return string SQL fragment
381
     * @throws RuntimeException if database connection is not available
382
     */
383
    public function render(?\XoopsDatabase $db = null): string
384
    {
385
        if ($db === null) {
386
            $db = \XoopsDatabaseFactory::getDatabaseConnection();
387
        }
388
389
        if (!$db) {
0 ignored issues
show
introduced by
$db is of type XoopsDatabase, thus it always evaluated to true.
Loading history...
390
            throw new RuntimeException("Database connection required to render Criteria");
391
        }
392
393
        $col = (string)($this->column ?? '');
394
395
        if ($col === '') {
396
            return '';
397
        }
398
399
        $backtick = (strpos($col, '.') === false && strpos($col, '(') === false) ? '`' : '';
400
        $clause = (empty($this->prefix) ? '' : "{$this->prefix}.") . $backtick . $col . $backtick;
401
402
        if (!empty($this->function)) {
403
            // function should be a trusted sprintf pattern, e.g. 'LOWER(%s)'
404
            $clause = sprintf($this->function, $clause);
405
        }
406
407
        $op = strtoupper((string)$this->operator);
408
409
        // Null checks require no value
410
        if ($op === 'IS NULL' || $op === 'IS NOT NULL') {
411
            return $clause . ' ' . $op;
412
        }
413
414
        $valStr = (string)$this->value;
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: preformatted string "(...)"
434
            // Early return if logging disabled (performance optimization)
435
            if (!self::isLegacyLogEnabled()) {
436
            return $clause . ' ' . $op . ' ' . $this->value;
437
        }
438
439
            // Log for migration tracking (only when enabled)
440
            $bt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
441
            $caller = $bt[1] ?? []; // 0 = render(), 1 = immediate caller
442
            $file = $caller['file'] ?? 'unknown';
443
            $line = $caller['line'] ?? 0;
444
            $message = sprintf(
445
                'Legacy Criteria IN format used for column "%s" with value "%s" at %s:%d',
446
                $this->column,
447
                is_scalar($this->value) ? (string)$this->value : gettype($this->value),
448
                $file,
449
                $line
450
            );
451
452
            // Prefer XoopsLogger if available
453
            if (class_exists('XoopsLogger')) {
454
                \XoopsLogger::getInstance()->addExtra('CriteriaLegacyIN', $message);
455
        } else {
456
                error_log($message);
457
        }
458
459
            // Optional: deprecation notice in debug mode
460
            if (defined('XOOPS_DEBUG') && XOOPS_DEBUG) {
461
                trigger_error($message, E_USER_DEPRECATED);
462
            }
463
464
            return $clause . ' ' . $op . ' ' . $this->value;
465
        }
466
467
        // LIKE / NOT LIKE – BC: just quote the pattern
468
        if ($op === 'LIKE' || $op === 'NOT LIKE') {
469
            $pattern = (string)$this->value;
470
            $quoted  = $db->quote($pattern);
471
            return $clause . ' ' . $op . ' ' . $quoted;
472
        }
473
474
        // All other operators: =, <, >, <=, >=, !=, <>
475
        // Backtick bypass for column-to-column comparisons
476
        if (strlen($valStr) > 1 && $valStr[0] === '`' && $valStr[strlen($valStr)-1] === '`') {
477
            // Validate backticked value (security: only allow safe chars)
478
            if (preg_match('/^[a-zA-Z0-9_\.\-`]*$/', $valStr)) {
479
                $safeValue = $valStr;
480
        } else {
481
                // Invalid chars in backticked value → use empty backticks (old behavior)
482
                $safeValue = '``';
483
            }
484
        } else {
485
            // Regular value - keep integers unquoted, quote strings
486
            if (is_int($this->value) || (is_string($this->value) && preg_match('/^-?\d+$/', $this->value))) {
487
                $safeValue = (string)(int)$this->value;
488
            } else {
489
                $safeValue = $db->quote((string)$this->value);
490
            }
491
        }
492
493
        return $clause . ' ' . $op . ' ' . $safeValue;
494
    }
495
496
    /**
497
     * Render with leading WHERE clause
498
     *
499
     * @return string SQL WHERE clause or empty string
500
     */
501
    public function renderWhere(): string
502
    {
503
        $cond = $this->render();
504
        return empty($cond) ? '' : "WHERE {$cond}";
505
    }
506
507
    /**
508
     * Generate an LDAP filter from criteria
509
     *
510
     * @return string LDAP filter
511
     */
512
    public function renderLdap(): string
513
    {
514
        if ($this->operator === '>') {
515
            $this->operator = '>=';
516
        }
517
        if ($this->operator === '<') {
518
            $this->operator = '<=';
519
        }
520
521
        if ($this->operator === '!=' || $this->operator === '<>') {
522
            $operator = '=';
523
            $clause   = '(!(' . $this->column . $operator . $this->value . '))';
524
        } else {
525
            if ($this->operator === 'IN') {
526
                $newvalue = str_replace(['(', ')'], '', $this->value);
527
                $tab      = explode(',', $newvalue);
528
                $clause = '';
529
                foreach ($tab as $uid) {
530
                    $clause .= "({$this->column}={$uid})";
531
                }
532
                $clause = '(|' . $clause . ')';
533
            } else {
534
                $clause = '(' . $this->column . $this->operator . $this->value . ')';
535
            }
536
        }
537
538
        return $clause;
539
    }
540
}
541