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