xref: /plugin/struct/meta/Search.php (revision c498205a7375a8f98f1ee968c0d6d3abe545279e)
1<?php
2
3namespace dokuwiki\plugin\struct\meta;
4
5use dokuwiki\plugin\struct\types\DateTime;
6use dokuwiki\plugin\struct\types\Page;
7
8class Search {
9    /**
10     * This separator will be used to concat multi values to flatten them in the result set
11     */
12    const CONCAT_SEPARATOR = "\n!_-_-_-_-_!\n";
13
14    /**
15     * The list of known and allowed comparators
16     * (order matters)
17     */
18    static public $COMPARATORS = array(
19        '<=', '>=', '=*', '=', '<', '>', '!=', '!~', '~',
20    );
21
22    /** @var  \helper_plugin_sqlite */
23    protected $sqlite;
24
25    /** @var Schema[] list of schemas to query */
26    protected $schemas = array();
27
28    /** @var Column[] list of columns to select */
29    protected $columns = array();
30
31    /** @var array the sorting of the result */
32    protected $sortby = array();
33
34    /** @var array the filters */
35    protected $filter = array();
36
37    /** @var array list of aliases tables can be referenced by */
38    protected $aliases = array();
39
40    /** @var  int begin results from here */
41    protected $range_begin = 0;
42
43    /** @var  int end results here */
44    protected $range_end = 0;
45
46    /** @var int the number of results */
47    protected $count = -1;
48    /** @var  string[] the PIDs of the result rows */
49    protected $result_pids = null;
50
51    /**
52     * Search constructor.
53     */
54    public function __construct() {
55        /** @var \helper_plugin_struct_db $plugin */
56        $plugin = plugin_load('helper', 'struct_db');
57        $this->sqlite = $plugin->getDB();
58    }
59
60    /**
61     * Add a schema to be searched
62     *
63     * Call multiple times for multiple schemas.
64     *
65     * @param string $table
66     * @param string $alias
67     */
68    public function addSchema($table, $alias = '') {
69        $schema = new Schema($table);
70        if(!$schema->getId()) {
71            throw new StructException('schema missing', $table);
72        }
73
74        if($this->schemas &&
75            (
76                $schema->isLookup() ||
77                reset($this->schemas)->isLookup()
78            )
79        ) {
80            throw new StructException('nolookupmix');
81        }
82
83        $this->schemas[$table] = $schema;
84        if($alias) $this->aliases[$alias] = $table;
85    }
86
87    /**
88     * Add a column to be returned by the search
89     *
90     * Call multiple times for multiple columns. Be sure the referenced tables have been
91     * added before
92     *
93     * @param string $colname may contain an alias
94     */
95    public function addColumn($colname) {
96        if($this->processWildcard($colname)) return; // wildcard?
97        $col = $this->findColumn($colname);
98        if(!$col) return; //FIXME do we really want to ignore missing columns?
99        $this->columns[] = $col;
100    }
101
102    /**
103     * Add sorting options
104     *
105     * Call multiple times for multiple columns. Be sure the referenced tables have been
106     * added before
107     *
108     * @param string $colname may contain an alias
109     * @param bool $asc sort direction (ASC = true, DESC = false)
110     */
111    public function addSort($colname, $asc = true) {
112        $col = $this->findColumn($colname);
113        if(!$col) return; //FIXME do we really want to ignore missing columns?
114
115        $this->sortby[$col->getFullQualifiedLabel()] = array($col, $asc);
116    }
117
118    /**
119     * Returns all set sort columns
120     *
121     * @return array
122     */
123    public function getSorts() {
124        return $this->sortby;
125    }
126
127    /**
128     * Adds a filter
129     *
130     * @param string $colname may contain an alias
131     * @param string|string[] $value
132     * @param string $comp @see self::COMPARATORS
133     * @param string $op either 'OR' or 'AND'
134     */
135    public function addFilter($colname, $value, $comp, $op = 'OR') {
136        /* Convert certain filters into others
137         * this reduces the number of supported filters to implement in types */
138        if($comp == '*~') {
139            $value = $this->filterWrapAsterisks($value);
140            $comp = '~';
141        } elseif($comp == '<>') {
142            $comp = '!=';
143        }
144
145        if(!in_array($comp, self::$COMPARATORS)) throw new StructException("Bad comperator. Use " . join(',', self::$COMPARATORS));
146        if($op != 'OR' && $op != 'AND') throw new StructException('Bad filter type . Only AND or OR allowed');
147
148        $col = $this->findColumn($colname);
149        if(!$col) return; // ignore missing columns, filter might have been for different schema
150
151        // map filter operators to SQL syntax
152        switch($comp) {
153            case '~':
154                $comp = 'LIKE';
155                break;
156            case '!~':
157                $comp = 'NOT LIKE';
158                break;
159            case '=*':
160                $comp = 'REGEXP';
161                break;
162        }
163
164        // we use asterisks, but SQL wants percents
165        if($comp == 'LIKE' || $comp == 'NOT LIKE') {
166            $value = $this->filterChangeToLike($value);
167        }
168
169        // add the filter
170        $this->filter[] = array($col, $value, $comp, $op);
171    }
172
173    /**
174     * Wrap given value in asterisks
175     *
176     * @param string|string[] $value
177     * @return string|string[]
178     */
179    protected function filterWrapAsterisks($value) {
180        $map = function ($input) {
181            return "*$input*";
182        };
183
184        if(is_array($value)) {
185            $value = array_map($map, $value);
186        } else {
187            $value = $map($value);
188        }
189        return $value;
190    }
191
192    /**
193     * Change given string to use % instead of *
194     *
195     * @param string|string[] $value
196     * @return string|string[]
197     */
198    protected function filterChangeToLike($value) {
199        $map = function ($input) {
200            return str_replace('*', '%', $input);
201        };
202
203        if(is_array($value)) {
204            $value = array_map($map, $value);
205        } else {
206            $value = $map($value);
207        }
208        return $value;
209    }
210
211    /**
212     * Set offset for the results
213     *
214     * @param int $offset
215     */
216    public function setOffset($offset) {
217        $limit = 0;
218        if($this->range_end) {
219            // if there was a limit set previously, the range_end needs to be recalculated
220            $limit = $this->range_end - $this->range_begin;
221        }
222        $this->range_begin = $offset;
223        if($limit) $this->setLimit($limit);
224    }
225
226    /**
227     * Limit results to this number
228     *
229     * @param int $limit Set to 0 to disable limit again
230     */
231    public function setLimit($limit) {
232        if($limit) {
233            $this->range_end = $this->range_begin + $limit;
234        } else {
235            $this->range_end = 0;
236        }
237    }
238
239    /**
240     * Return the number of results (regardless of limit and offset settings)
241     *
242     * Use this to implement paging. Important: this may only be called after running @see execute()
243     *
244     * @return int
245     */
246    public function getCount() {
247        if($this->count < 0) throw new StructException('Count is only accessible after executing the search');
248        return $this->count;
249    }
250
251    /**
252     * Returns the PID associated with each result row
253     *
254     * Important: this may only be called after running @see execute()
255     *
256     * @return \string[]
257     */
258    public function getPids() {
259        if($this->result_pids === null) throw new StructException('PIDs are only accessible after executing the search');
260        return $this->result_pids;
261    }
262
263    /**
264     * Execute this search and return the result
265     *
266     * The result is a two dimensional array of Value()s.
267     *
268     * This will always query for the full result (not using offset and limit) and then
269     * return the wanted range, setting the count (@see getCount) to the whole result number
270     *
271     * @return Value[][]
272     */
273    public function execute() {
274        list($sql, $opts) = $this->getSQL();
275
276        /** @var \PDOStatement $res */
277        $res = $this->sqlite->query($sql, $opts);
278        if($res === false) throw new StructException("SQL execution failed for\n\n$sql");
279
280        $this->result_pids = array();
281        $result = array();
282        $cursor = -1;
283        while($row = $res->fetch(\PDO::FETCH_ASSOC)) {
284            $cursor++;
285            if($cursor < $this->range_begin) continue;
286            if($this->range_end && $cursor >= $this->range_end) continue;
287
288            $C = 0;
289            $resrow = array();
290            $isempty = true;
291            foreach($this->columns as $col) {
292                $val = $row["C$C"];
293                if($col->isMulti()) {
294                    $val = explode(self::CONCAT_SEPARATOR, $val);
295                }
296                $value = new Value($col, $val);
297                $isempty &= $this->isEmptyValue($value, $row['PID']);
298                $resrow[] = $value;
299                $C++;
300            }
301
302            // skip empty rows
303            if($isempty) {
304                $cursor--;
305                continue;
306            }
307
308            $this->result_pids[] = $row['PID'];
309            $result[] = $resrow;
310        }
311
312        $this->sqlite->res_close($res);
313        $this->count = $cursor + 1;
314        return $result;
315    }
316
317    /**
318     * Transform the set search parameters into a statement
319     *
320     * @return array ($sql, $opts) The SQL and parameters to execute
321     */
322    public function getSQL() {
323        if(!$this->columns) throw new StructException('nocolname');
324
325        $QB = new QueryBuilder();
326
327        // basic tables
328        $first_table = '';
329        foreach($this->schemas as $schema) {
330            $datatable = 'data_' . $schema->getTable();
331            if($first_table) {
332                // follow up tables
333                $QB->addLeftJoin($first_table, $datatable, $datatable, "$first_table.pid = $datatable.pid");
334            } else {
335                // first table
336
337                if(!$schema->isLookup()) {
338                    $QB->addTable('schema_assignments');
339                    $QB->filters()->whereAnd("$datatable.pid = schema_assignments.pid");
340                    $QB->filters()->whereAnd("schema_assignments.tbl = '{$schema->getTable()}'");
341                    $QB->filters()->whereAnd("schema_assignments.assigned = 1");
342                    $QB->filters()->whereAnd("GETACCESSLEVEL($datatable.pid) > 0");
343                    $QB->filters()->whereAnd("PAGEEXISTS($datatable.pid) = 1");
344                }
345
346                $QB->addTable($datatable);
347                $QB->addSelectColumn($datatable, 'pid', 'PID');
348                $QB->addGroupByColumn($datatable, 'pid');
349
350                $first_table = $datatable;
351            }
352            $QB->filters()->whereAnd("$datatable.latest = 1");
353        }
354
355        // columns to select, handling multis
356        $sep = self::CONCAT_SEPARATOR;
357        $n = 0;
358        foreach($this->columns as $col) {
359            $CN = 'C' . $n++;
360
361            if($col->isMulti()) {
362                $datatable = "data_{$col->getTable()}";
363                $multitable = "multi_{$col->getTable()}";
364                $MN = 'M' . $col->getColref();
365
366                $QB->addLeftJoin(
367                    $datatable,
368                    $multitable,
369                    $MN,
370                    "$datatable.pid = $MN.pid AND
371                     $datatable.rev = $MN.rev AND
372                     $MN.colref = {$col->getColref()}"
373                );
374
375                $col->getType()->select($QB, $MN, 'value', $CN);
376                $sel = $QB->getSelectStatement($CN);
377                $QB->addSelectStatement("GROUP_CONCAT($sel, '$sep')", $CN);
378            } else {
379                $col->getType()->select($QB, 'data_' . $col->getTable(), $col->getColName(), $CN);
380                $QB->addGroupByStatement($CN);
381            }
382        }
383
384        // where clauses
385        foreach($this->filter as $filter) {
386            list($col, $value, $comp, $op) = $filter;
387
388            $datatable = "data_{$col->getTable()}";
389            $multitable = "multi_{$col->getTable()}";
390
391            /** @var $col Column */
392            if($col->isMulti()) {
393                $MN = 'MN' . $col->getColref(); // FIXME this joins a second time if the column was selected before
394
395                $QB->addLeftJoin(
396                    $datatable,
397                    $multitable,
398                    $MN,
399                    "$datatable.pid = $MN.pid AND
400                     $datatable.rev = $MN.rev AND
401                     $MN.colref = {$col->getColref()}"
402                );
403                $coltbl = $MN;
404                $colnam = 'value';
405            } else {
406                $coltbl = $datatable;
407                $colnam = $col->getColName();
408            }
409
410            $col->getType()->filter($QB, $coltbl, $colnam, $comp, $value, $op); // type based filter
411        }
412
413        // sorting - we always sort by the single val column
414        foreach($this->sortby as $sort) {
415            list($col, $asc) = $sort;
416            /** @var $col Column */
417            $col->getType()->sort($QB, 'data_' . $col->getTable(), $col->getColName(false), $asc ? 'ASC' : 'DESC');
418        }
419
420        return $QB->getSQL();
421    }
422
423    /**
424     * Returns all the columns that where added to the search
425     *
426     * @return Column[]
427     */
428    public function getColumns() {
429        return $this->columns;
430    }
431
432    /**
433     * Checks if the given column is a * wildcard
434     *
435     * If it's a wildcard all matching columns are added to the column list, otherwise
436     * nothing happens
437     *
438     * @param string $colname
439     * @return bool was wildcard?
440     */
441    protected function processWildcard($colname) {
442        list($colname, $table) = $this->resolveColumn($colname);
443        if($colname !== '*') return false;
444
445        // no table given? assume the first is meant
446        if($table === null) {
447            $schema_list = array_keys($this->schemas);
448            $table = $schema_list[0];
449        }
450
451        $schema = $this->schemas[$table];
452        if(!$schema) return false;
453        $this->columns = array_merge($this->columns, $schema->getColumns(false));
454        return true;
455    }
456
457    /**
458     * Split a given column name into table and column
459     *
460     * Handles Aliases. Table might be null if none given.
461     *
462     * @param $colname
463     * @return array (colname, table)
464     */
465    protected function resolveColumn($colname) {
466        if(!$this->schemas) throw new StructException('noschemas');
467
468        // resolve the alias or table name
469        list($table, $colname) = explode('.', $colname, 2);
470        if(!$colname) {
471            $colname = $table;
472            $table = null;
473        }
474        if($table && isset($this->aliases[$table])) {
475            $table = $this->aliases[$table];
476        }
477
478        if(!$colname) throw new StructException('nocolname');
479
480        return array($colname, $table);
481    }
482
483    /**
484     * Find a column to be used in the search
485     *
486     * @param string $colname may contain an alias
487     * @return bool|Column
488     */
489    public function findColumn($colname) {
490        if(!$this->schemas) throw new StructException('noschemas');
491
492        // add "fake" column for special col (unless it's a lookup)
493        if(!(reset($this->schemas)->isLookup())) {
494            $schema_list = array_keys($this->schemas);
495            if($colname == '%pageid%') {
496                return new PageColumn(0, new Page(), $schema_list[0]);
497            }
498            if($colname == '%title%') {
499                return new PageColumn(0, new Page(array('usetitles' => true)), $schema_list[0]);
500            }
501            if($colname == '%lastupdate%') {
502                return new RevisionColumn(0, new DateTime(), $schema_list[0]);
503            }
504        }
505
506        list($colname, $table) = $this->resolveColumn($colname);
507
508        // if table name given search only that, otherwise try all for matching column name
509        if($table !== null) {
510            $schemas = array($table => $this->schemas[$table]);
511        } else {
512            $schemas = $this->schemas;
513        }
514
515        // find it
516        $col = false;
517        foreach($schemas as $schema) {
518            if(empty($schema)) {
519                continue;
520            }
521            $col = $schema->findColumn($colname);
522            if($col) break;
523        }
524
525        return $col;
526    }
527
528    /**
529     * Check if the given row is empty or references our own row
530     *
531     * @param Value $value
532     * @param string $pid
533     * @return bool
534     */
535    protected function isEmptyValue(Value $value, $pid) {
536        if($value->isEmpty()) return true;
537        if(is_a($value->getColumn()->getType(), Page::class) && $value->getRawValue() == $pid) return true;
538        return false;
539    }
540}
541
542
543