xref: /plugin/struct/meta/Search.php (revision 91c655b4cc7207c34fe7560ef21514d22e892fe8)
1<?php
2
3namespace dokuwiki\plugin\struct\meta;
4
5use dokuwiki\plugin\struct\types\AutoSummary;
6use dokuwiki\plugin\struct\types\DateTime;
7use dokuwiki\plugin\struct\types\Decimal;
8use dokuwiki\plugin\struct\types\Page;
9use dokuwiki\plugin\struct\types\User;
10
11class Search
12{
13    /**
14     * This separator will be used to concat multi values to flatten them in the result set
15     */
16    public const CONCAT_SEPARATOR = "\n!_-_-_-_-_!\n";
17
18    /**
19     * The list of known and allowed comparators
20     * (order matters)
21     */
22    public static $COMPARATORS = array(
23        '<=', '>=', '=*', '=', '<', '>', '!=', '!~', '~', ' IN '
24    );
25
26    /** @var \helper_plugin_struct_db */
27    protected $dbHelper;
28
29    /** @var  \helper_plugin_sqlite */
30    protected $sqlite;
31
32    /** @var Schema[] list of schemas to query */
33    protected $schemas = array();
34
35    /** @var Column[] list of columns to select */
36    protected $columns = array();
37
38    /** @var array the sorting of the result */
39    protected $sortby = array();
40
41    /** @var array the filters */
42    protected $filter = array();
43
44    /** @var array list of aliases tables can be referenced by */
45    protected $aliases = array();
46
47    /** @var  int begin results from here */
48    protected $range_begin = 0;
49
50    /** @var  int end results here */
51    protected $range_end = 0;
52
53    /** @var int the number of results */
54    protected $count = -1;
55    /** @var  string[] the PIDs of the result rows */
56    protected $result_pids = null;
57    /** @var  array the row ids of the result rows */
58    protected $result_rids = [];
59    /** @var  array the revisions of the result rows */
60    protected $result_revs = [];
61
62    /** @var bool Include latest = 1 in select query */
63    protected $selectLatest = true;
64
65    /**
66     * Search constructor.
67     */
68    public function __construct()
69    {
70        /** @var  $dbHelper */
71        $this->dbHelper = plugin_load('helper', 'struct_db');
72        $this->sqlite = $this->dbHelper->getDB();
73    }
74
75    public function getDb()
76    {
77        return $this->sqlite;
78    }
79
80    /**
81     * Add a schema to be searched
82     *
83     * Call multiple times for multiple schemas.
84     *
85     * @param string $table
86     * @param string $alias
87     */
88    public function addSchema($table, $alias = '')
89    {
90        $schema = new Schema($table);
91        if (!$schema->getId()) {
92            throw new StructException('schema missing', $table);
93        }
94
95        $this->schemas[$schema->getTable()] = $schema;
96        if ($alias) $this->aliases[$alias] = $schema->getTable();
97    }
98
99    /**
100     * Add a column to be returned by the search
101     *
102     * Call multiple times for multiple columns. Be sure the referenced tables have been
103     * added before
104     *
105     * @param string $colname may contain an alias
106     */
107    public function addColumn($colname)
108    {
109        if ($this->processWildcard($colname)) return; // wildcard?
110        if ($colname[0] == '-') { // remove column from previous wildcard lookup
111            $colname = substr($colname, 1);
112            foreach ($this->columns as $key => $col) {
113                if ($col->getLabel() == $colname) unset($this->columns[$key]);
114            }
115            return;
116        }
117
118        $col = $this->findColumn($colname);
119        if (!$col) return; //FIXME do we really want to ignore missing columns?
120        $this->columns[] = $col;
121    }
122
123    /**
124     * Add sorting options
125     *
126     * Call multiple times for multiple columns. Be sure the referenced tables have been
127     * added before
128     *
129     * @param string $colname may contain an alias
130     * @param bool $asc sort direction (ASC = true, DESC = false)
131     * @param bool $nc set true for caseinsensitivity
132     */
133    public function addSort($colname, $asc = true, $nc = true)
134    {
135        $col = $this->findColumn($colname);
136        if (!$col) return; //FIXME do we really want to ignore missing columns?
137
138        $this->sortby[$col->getFullQualifiedLabel()] = array($col, $asc, $nc);
139    }
140
141    /**
142     * Returns all set sort columns
143     *
144     * @return array
145     */
146    public function getSorts()
147    {
148        return $this->sortby;
149    }
150
151    /**
152     * Adds a filter
153     *
154     * @param string $colname may contain an alias
155     * @param string|string[] $value
156     * @param string $comp @see self::COMPARATORS
157     * @param string $op either 'OR' or 'AND'
158     */
159    public function addFilter($colname, $value, $comp, $op = 'OR')
160    {
161        /* Convert certain filters into others
162         * this reduces the number of supported filters to implement in types */
163        if ($comp == '*~') {
164            $value = $this->filterWrapAsterisks($value);
165            $comp = '~';
166        } elseif ($comp == '<>') {
167            $comp = '!=';
168        }
169
170        if (!in_array($comp, self::$COMPARATORS))
171            throw new StructException("Bad comperator. Use " . join(',', self::$COMPARATORS));
172        if ($op != 'OR' && $op != 'AND')
173            throw new StructException('Bad filter type . Only AND or OR allowed');
174
175        $col = $this->findColumn($colname);
176        if (!$col) return; // ignore missing columns, filter might have been for different schema
177
178        // map filter operators to SQL syntax
179        switch ($comp) {
180            case '~':
181                $comp = 'LIKE';
182                break;
183            case '!~':
184                $comp = 'NOT LIKE';
185                break;
186            case '=*':
187                $comp = 'REGEXP';
188                break;
189        }
190
191        // we use asterisks, but SQL wants percents
192        if ($comp == 'LIKE' || $comp == 'NOT LIKE') {
193            $value = $this->filterChangeToLike($value);
194        }
195
196        if ($comp == ' IN ' && !is_array($value)) {
197            $value = $this->parseFilterValueList($value);
198            //col IN ('a', 'b', 'c') is equal to col = 'a' OR 'col = 'b' OR col = 'c'
199            $comp = '=';
200        }
201
202        // add the filter
203        $this->filter[] = array($col, $value, $comp, $op);
204    }
205
206    /**
207     * Parse SQLite row value into array
208     *
209     * @param string $value
210     * @return string[]
211     */
212    protected function parseFilterValueList($value)
213    {
214        $Handler = new FilterValueListHandler();
215        $LexerClass = class_exists('\Doku_Lexer') ? '\Doku_Lexer' : '\dokuwiki\Parsing\Lexer\Lexer';
216        $isLegacy = $LexerClass === '\Doku_Lexer';
217        /** @var \Doku_Lexer|\dokuwiki\Parsing\Lexer\Lexer $Lexer */
218        $Lexer = new $LexerClass($Handler, 'base', true);
219
220
221        $Lexer->addEntryPattern('\(', 'base', 'row');
222        $Lexer->addPattern('\s*,\s*', 'row');
223        $Lexer->addExitPattern('\)', 'row');
224
225        $Lexer->addEntryPattern('"', 'row', 'double_quote_string');
226        $Lexer->addSpecialPattern('\\\\"', 'double_quote_string', 'escapeSequence');
227        $Lexer->addExitPattern('"', 'double_quote_string');
228
229        $Lexer->addEntryPattern("'", 'row', 'singleQuoteString');
230        $Lexer->addSpecialPattern("\\\\'", 'singleQuoteString', 'escapeSequence');
231        $Lexer->addExitPattern("'", 'singleQuoteString');
232
233        $Lexer->mapHandler('double_quote_string', 'singleQuoteString');
234
235        $Lexer->addSpecialPattern('[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?', 'row', 'number');
236
237        $res = $Lexer->parse($value);
238
239        $currentMode = $isLegacy ? $Lexer->_mode->getCurrent() : $Lexer->getModeStack()->getCurrent();
240        if (!$res || $currentMode != 'base') {
241            throw new StructException('invalid row value syntax');
242        }
243
244        return $Handler->getRow();
245    }
246
247    /**
248     * Wrap given value in asterisks
249     *
250     * @param string|string[] $value
251     * @return string|string[]
252     */
253    protected function filterWrapAsterisks($value)
254    {
255        $map = function ($input) {
256            return "*$input*";
257        };
258
259        if (is_array($value)) {
260            $value = array_map($map, $value);
261        } else {
262            $value = $map($value);
263        }
264        return $value;
265    }
266
267    /**
268     * Change given string to use % instead of *
269     *
270     * @param string|string[] $value
271     * @return string|string[]
272     */
273    protected function filterChangeToLike($value)
274    {
275        $map = function ($input) {
276            return str_replace('*', '%', $input);
277        };
278
279        if (is_array($value)) {
280            $value = array_map($map, $value);
281        } else {
282            $value = $map($value);
283        }
284        return $value;
285    }
286
287    /**
288     * Set offset for the results
289     *
290     * @param int $offset
291     */
292    public function setOffset($offset)
293    {
294        $limit = 0;
295        if ($this->range_end) {
296            // if there was a limit set previously, the range_end needs to be recalculated
297            $limit = $this->range_end - $this->range_begin;
298        }
299        $this->range_begin = $offset;
300        if ($limit) $this->setLimit($limit);
301    }
302
303    /**
304     * Limit results to this number
305     *
306     * @param int $limit Set to 0 to disable limit again
307     */
308    public function setLimit($limit)
309    {
310        if ($limit) {
311            $this->range_end = $this->range_begin + $limit;
312        } else {
313            $this->range_end = 0;
314        }
315    }
316
317    /**
318     * Allows disabling default 'latest = 1' clause in select statement
319     *
320     * @param bool $selectLatest
321     */
322    public function setSelectLatest($selectLatest): void
323    {
324        $this->selectLatest = $selectLatest;
325    }
326
327    /**
328     * Return the number of results (regardless of limit and offset settings)
329     *
330     * Use this to implement paging. Important: this may only be called after running @return int
331     * @see execute()
332     *
333     */
334    public function getCount()
335    {
336        if ($this->count < 0) throw new StructException('Count is only accessible after executing the search');
337        return $this->count;
338    }
339
340    /**
341     * Returns the PID associated with each result row
342     *
343     * Important: this may only be called after running @return \string[]
344     * @see execute()
345     *
346     */
347    public function getPids()
348    {
349        if ($this->result_pids === null)
350            throw new StructException('PIDs are only accessible after executing the search');
351        return $this->result_pids;
352    }
353
354    /**
355     * Returns the rid associated with each result row
356     *
357     * Important: this may only be called after running @return array
358     * @see execute()
359     *
360     */
361    public function getRids()
362    {
363        if ($this->result_rids === null)
364            throw new StructException('rids are only accessible after executing the search');
365        return $this->result_rids;
366    }
367
368    /**
369     * Returns the rid associated with each result row
370     *
371     * Important: this may only be called after running @return array
372     * @see execute()
373     *
374     */
375    public function getRevs()
376    {
377        if ($this->result_revs === null)
378            throw new StructException('revs are only accessible after executing the search');
379        return $this->result_revs;
380    }
381
382    /**
383     * Execute this search and return the result
384     *
385     * The result is a two dimensional array of Value()s.
386     *
387     * This will always query for the full result (not using offset and limit) and then
388     * return the wanted range, setting the count (@return Value[][]
389     * @see getCount) to the whole result number
390     *
391     */
392    public function execute()
393    {
394        list($sql, $opts) = $this->getSQL();
395
396        /** @var \PDOStatement $res */
397        $res = $this->sqlite->query($sql, $opts);
398        if ($res === false) throw new StructException("SQL execution failed for\n\n$sql");
399
400        $this->result_pids = array();
401        $result = array();
402        $cursor = -1;
403        $pageidAndRevOnly = array_reduce($this->columns, function ($pageidAndRevOnly, Column $col) {
404            return $pageidAndRevOnly && ($col->getTid() == 0);
405        }, true);
406        while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
407            $cursor++;
408            if ($cursor < $this->range_begin) continue;
409            if ($this->range_end && $cursor >= $this->range_end) continue;
410
411            $C = 0;
412            $resrow = array();
413            $isempty = true;
414            foreach ($this->columns as $col) {
415                $val = $row["C$C"];
416                if ($col->isMulti()) {
417                    $val = explode(self::CONCAT_SEPARATOR, $val);
418                }
419                $value = new Value($col, $val);
420                $isempty &= $this->isEmptyValue($value);
421                $resrow[] = $value;
422                $C++;
423            }
424
425            // skip empty rows
426            if ($isempty && !$pageidAndRevOnly) {
427                $cursor--;
428                continue;
429            }
430
431            $this->result_pids[] = $row['PID'];
432            $this->result_rids[] = $row['rid'];
433            $this->result_revs[] = $row['rev'];
434            $result[] = $resrow;
435        }
436
437        $res->closeCursor();
438        $this->count = $cursor + 1;
439        return $result;
440    }
441
442    /**
443     * Transform the set search parameters into a statement
444     *
445     * @return array ($sql, $opts) The SQL and parameters to execute
446     */
447    public function getSQL()
448    {
449        if (!$this->columns) throw new StructException('nocolname');
450
451        $QB = new QueryBuilder();
452
453        // basic tables
454        $first_table = '';
455        foreach ($this->schemas as $schema) {
456            $datatable = 'data_' . $schema->getTable();
457            if ($first_table) {
458                // follow up tables
459                $QB->addLeftJoin($first_table, $datatable, $datatable, "$first_table.pid = $datatable.pid");
460            } else {
461                // first table
462                $QB->addTable($datatable);
463
464                // add conditional page clauses if pid has a value
465                $subAnd = $QB->filters()->whereSubAnd();
466                $subAnd->whereAnd("$datatable.pid = ''");
467                $subOr = $subAnd->whereSubOr();
468                $subOr->whereAnd("GETACCESSLEVEL($datatable.pid) > 0");
469                $subOr->whereAnd("PAGEEXISTS($datatable.pid) = 1");
470                $subOr->whereAnd('(ASSIGNED = 1 OR ASSIGNED IS NULL)');
471
472                // add conditional schema assignment check
473                $QB->addLeftJoin(
474                    $datatable,
475                    'schema_assignments',
476                    '',
477                    "$datatable.pid != ''
478                    AND $datatable.pid = schema_assignments.pid
479                    AND schema_assignments.tbl = '{$schema->getTable()}'"
480                );
481
482                $QB->addSelectColumn($datatable, 'rid');
483                $QB->addSelectColumn($datatable, 'pid', 'PID');
484                $QB->addSelectColumn($datatable, 'rev');
485                $QB->addSelectColumn('schema_assignments', 'assigned', 'ASSIGNED');
486                $QB->addGroupByColumn($datatable, 'pid');
487                $QB->addGroupByColumn($datatable, 'rid');
488
489                $first_table = $datatable;
490            }
491
492            $QB->filters()->whereAnd($this->getSpecialFlagsClause($datatable));
493        }
494
495        // columns to select, handling multis
496        $sep = self::CONCAT_SEPARATOR;
497        $n = 0;
498        foreach ($this->columns as $col) {
499            $CN = 'C' . $n++;
500
501            if ($col->isMulti()) {
502                $datatable = "data_{$col->getTable()}";
503                $multitable = "multi_{$col->getTable()}";
504                $MN = $QB->generateTableAlias('M');
505
506                $QB->addLeftJoin(
507                    $datatable,
508                    $multitable,
509                    $MN,
510                    "$datatable.pid = $MN.pid AND $datatable.rid = $MN.rid AND
511                     $datatable.rev = $MN.rev AND
512                     $MN.colref = {$col->getColref()}"
513                );
514
515                $col->getType()->select($QB, $MN, 'value', $CN);
516                $sel = $QB->getSelectStatement($CN);
517                $QB->addSelectStatement("GROUP_CONCAT_DISTINCT($sel, '$sep')", $CN);
518            } else {
519                $col->getType()->select($QB, 'data_' . $col->getTable(), $col->getColName(), $CN);
520                $QB->addGroupByStatement($CN);
521            }
522        }
523
524        // where clauses
525        if (!empty($this->filter)) {
526            $userWHERE = $QB->filters()->where('AND');
527        }
528        foreach ($this->filter as $filter) {
529            /** @var Column $col */
530            list($col, $value, $comp, $op) = $filter;
531
532            $datatable = "data_{$col->getTable()}";
533            $multitable = "multi_{$col->getTable()}";
534
535            /** @var $col Column */
536            if ($col->isMulti()) {
537                $MN = $QB->generateTableAlias('MN');
538
539                $QB->addLeftJoin(
540                    $datatable,
541                    $multitable,
542                    $MN,
543                    "$datatable.pid = $MN.pid AND $datatable.rid = $MN.rid AND
544                     $datatable.rev = $MN.rev AND
545                     $MN.colref = {$col->getColref()}"
546                );
547                $coltbl = $MN;
548                $colnam = 'value';
549            } else {
550                $coltbl = $datatable;
551                $colnam = $col->getColName();
552            }
553
554            $col->getType()->filter($userWHERE, $coltbl, $colnam, $comp, $value, $op); // type based filter
555        }
556
557        // sorting - we always sort by the single val column
558        foreach ($this->sortby as $sort) {
559            list($col, $asc, $nc) = $sort;
560            /** @var $col Column */
561            $colname = $col->getColName(false);
562            if ($nc) $colname .= ' COLLATE NOCASE';
563            $col->getType()->sort($QB, 'data_' . $col->getTable(), $colname, $asc ? 'ASC' : 'DESC');
564        }
565
566        return $QB->getSQL();
567    }
568
569    /**
570     * Returns all the columns that where added to the search
571     *
572     * @return Column[]
573     */
574    public function getColumns()
575    {
576        return $this->columns;
577    }
578
579    /**
580     * All the schemas currently added
581     *
582     * @return Schema[]
583     */
584    public function getSchemas()
585    {
586        return array_values($this->schemas);
587    }
588
589    /**
590     * Checks if the given column is a * wildcard
591     *
592     * If it's a wildcard all matching columns are added to the column list, otherwise
593     * nothing happens
594     *
595     * @param string $colname
596     * @return bool was wildcard?
597     */
598    protected function processWildcard($colname)
599    {
600        list($colname, $table) = $this->resolveColumn($colname);
601        if ($colname !== '*') return false;
602
603        // no table given? assume the first is meant
604        if ($table === null) {
605            $schema_list = array_keys($this->schemas);
606            $table = $schema_list[0];
607        }
608
609        $schema = $this->schemas[$table] ?? null;
610        if (!$schema) return false;
611        $this->columns = array_merge($this->columns, $schema->getColumns(false));
612        return true;
613    }
614
615    /**
616     * Split a given column name into table and column
617     *
618     * Handles Aliases. Table might be null if none given.
619     *
620     * @param $colname
621     * @return array (colname, table)
622     */
623    protected function resolveColumn($colname)
624    {
625        if (!$this->schemas) throw new StructException('noschemas');
626
627        // resolve the alias or table name
628        @list($table, $colname) = array_pad(explode('.', $colname, 2), 2, '');
629        if (!$colname) {
630            $colname = $table;
631            $table = null;
632        }
633        if ($table && isset($this->aliases[$table])) {
634            $table = $this->aliases[$table];
635        }
636
637        if (!$colname) throw new StructException('nocolname');
638
639        return array($colname, $table);
640    }
641
642    /**
643     * Find a column to be used in the search
644     *
645     * @param string $colname may contain an alias
646     * @return bool|Column
647     */
648    public function findColumn($colname, $strict = false)
649    {
650        if (!$this->schemas) throw new StructException('noschemas');
651        $schema_list = array_keys($this->schemas);
652
653        // add "fake" column for special col
654        if ($colname == '%pageid%') {
655            return new PageColumn(0, new Page(), $schema_list[0]);
656        }
657        if ($colname == '%title%') {
658            return new PageColumn(0, new Page(array('usetitles' => true)), $schema_list[0]);
659        }
660        if ($colname == '%lastupdate%') {
661            return new RevisionColumn(0, new DateTime(), $schema_list[0]);
662        }
663        if ($colname == '%lasteditor%') {
664            return new UserColumn(0, new User(), $schema_list[0]);
665        }
666        if ($colname == '%lastsummary%') {
667            return new SummaryColumn(0, new AutoSummary(), $schema_list[0]);
668        }
669        if ($colname == '%rowid%') {
670            return new RowColumn(0, new Decimal(), $schema_list[0]);
671        }
672        if ($colname == '%published%') {
673            return new PublishedColumn(0, new Decimal(), $schema_list[0]);
674        }
675
676        list($colname, $table) = $this->resolveColumn($colname);
677
678        /*
679         * If table name is given search only that, otherwise if no strict behavior
680         * is requested by the caller, try all assigned schemas for matching the
681         * column name.
682         */
683        if ($table !== null && isset($this->schemas[$table])) {
684            $schemas = array($table => $this->schemas[$table]);
685        } elseif ($table === null || !$strict) {
686            $schemas = $this->schemas;
687        } else {
688            return false;
689        }
690
691        // find it
692        $col = false;
693        foreach ($schemas as $schema) {
694            if (empty($schema)) {
695                continue;
696            }
697            $col = $schema->findColumn($colname);
698            if ($col) break;
699        }
700
701        return $col;
702    }
703
704    /**
705     * Check if the given row is empty or references our own row
706     *
707     * @param Value $value
708     * @return bool
709     */
710    protected function isEmptyValue(Value $value)
711    {
712        if ($value->isEmpty()) return true;
713        if ($value->getColumn()->getTid() == 0) return true;
714        return false;
715    }
716
717    /**
718     * @param string $datatable
719     * @return string
720     */
721    protected function getSpecialFlagsClause($datatable)
722    {
723        $latestClause = "IS_PUBLISHER($datatable.pid)";
724        if ($this->selectLatest) {
725            $latestClause .= " AND $datatable.latest = 1";
726        }
727        $publishedClause = "IS_PUBLISHER($datatable.pid) !=1 AND $datatable.published = 1";
728
729        return "( ($latestClause) OR ($publishedClause) )";
730    }
731}
732