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