xref: /plugin/struct/meta/Search.php (revision cadfc3ccf1b35ae86ec3981128859fe566cac29e)
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        $col = $this->findColumn($colname);
82        if(!$col) return; //FIXME do we really want to ignore missing columns?
83        $this->columns[] = $col;
84    }
85
86    /**
87     * Add sorting options
88     *
89     * Call multiple times for multiple columns. Be sure the referenced tables have been
90     * added before
91     *
92     * @param string $colname may contain an alias
93     * @param bool $asc sort direction (ASC = true, DESC = false)
94     */
95    public function addSort($colname, $asc = true) {
96        $col = $this->findColumn($colname);
97        if(!$col) return; //FIXME do we really want to ignore missing columns?
98
99        $this->sortby[$col->getFullQualifiedLabel()] = array($col, $asc);
100    }
101
102    /**
103     * Returns all set sort columns
104     *
105     * @return array
106     */
107    public function getSorts() {
108        return $this->sortby;
109    }
110
111    /**
112     * Adds a filter
113     *
114     * @param string $colname may contain an alias
115     * @param string $value
116     * @param string $comp @see self::COMPARATORS
117     * @param string $op either 'OR' or 'AND'
118     */
119    public function addFilter($colname, $value, $comp, $op = 'OR') {
120        /* Convert certain filters into others
121         * this reduces the number of supported filters to implement in types */
122        if ($comp == '*~') {
123            $value = '*' . $value . '*';
124            $comp = '~';
125        } elseif ($comp == '<>') {
126            $comp = '!=';
127        }
128
129        if(!in_array($comp, self::$COMPARATORS)) throw new StructException("Bad comperator. Use " . join(',', self::$COMPARATORS));
130        if($op != 'OR' && $op != 'AND') throw new StructException('Bad filter type . Only AND or OR allowed');
131
132        $col = $this->findColumn($colname);
133        if(!$col) return; // ignore missing columns, filter might have been for different schema
134
135        // map filter operators to SQL syntax
136        switch($comp) {
137            case '~':
138                $comp = 'LIKE';
139                break;
140            case '!~':
141                $comp = 'NOT LIKE';
142                break;
143            case '=*':
144                $comp = 'REGEXP';
145                break;
146        }
147
148        // we use asterisks, but SQL wants percents
149        if($comp == 'LIKE' || $comp == 'NOT LIKE') {
150            $value = str_replace('*','%',$value);
151        }
152
153        // add the filter
154        $this->filter[] = array($col, $value, $comp, $op);
155    }
156
157    /**
158     * Set offset for the results
159     *
160     * @param int $offset
161     */
162    public function setOffset($offset) {
163        $limit = 0;
164        if($this->range_end) {
165            // if there was a limit set previously, the range_end needs to be recalculated
166            $limit = $this->range_end - $this->range_begin;
167        }
168        $this->range_begin = $offset;
169        if($limit) $this->setLimit($limit);
170    }
171
172    /**
173     * Limit results to this number
174     *
175     * @param int $limit Set to 0 to disable limit again
176     */
177    public function setLimit($limit) {
178        if($limit) {
179            $this->range_end = $this->range_begin + $limit;
180        } else {
181            $this->range_end = 0;
182        }
183    }
184
185    /**
186     * Return the number of results (regardless of limit and offset settings)
187     *
188     * Use this to implement paging. Important: this may only be called after running @see execute()
189     *
190     * @return int
191     */
192    public function getCount() {
193        if($this->count < 0) throw new StructException('Count is only accessible after executing the search');
194        return $this->count;
195    }
196
197    /**
198     * Execute this search and return the result
199     *
200     * The result is a two dimensional array of Value()s.
201     *
202     * This will always query for the full result (not using offset and limit) and then
203     * return the wanted range, setting the count (@see getCount) to the whole result number
204     *
205     * @return Value[][]
206     */
207    public function execute() {
208        list($sql, $opts) = $this->getSQL();
209
210        /** @var \PDOStatement $res */
211        $res = $this->sqlite->query($sql, $opts);
212        if($res === false) throw new StructException("SQL execution failed for\n\n$sql");
213
214        $result = array();
215        $cursor = -1;
216        while($row = $res->fetch(\PDO::FETCH_ASSOC)) {
217            if ($this->isRowEmpty($row)) {
218                continue;
219            }
220            $cursor++;
221            if($cursor < $this->range_begin) continue;
222            if($this->range_end && $cursor >= $this->range_end) continue;
223
224            $C = 0;
225            $resrow = array();
226            foreach($this->columns as $col) {
227                $val = $row["C$C"];
228                if($col->isMulti()) {
229                    $val = explode(self::CONCAT_SEPARATOR, $val);
230                }
231                $resrow[] = new Value($col, $val);
232                $C++;
233            }
234            $result[] = $resrow;
235        }
236
237        $this->sqlite->res_close($res);
238        $this->count = $cursor + 1;
239        return $result;
240    }
241
242    /**
243     * Transform the set search parameters into a statement
244     *
245     * @return array ($sql, $opts) The SQL and parameters to execute
246     */
247    public function getSQL() {
248        if(!$this->columns) throw new StructException('nocolname');
249
250        $QB = new QueryBuilder();
251
252        // basic tables
253        $first_table = '';
254        foreach($this->schemas as $schema) {
255            $datatable = 'data_'.$schema->getTable();
256            if($first_table) {
257                // follow up tables
258                $QB->addLeftJoin($first_table, $datatable, $datatable, "$first_table.pid = $datatable.pid");
259            } else {
260                // first table
261                $QB->addTable('schema_assignments');
262                $QB->addTable($datatable);
263                $QB->addSelectColumn($datatable, 'pid', 'PID');
264                $QB->addGroupByColumn($datatable, 'pid');
265
266                $QB->filters()->whereAnd("$datatable.pid = schema_assignments.pid");
267                $QB->filters()->whereAnd("schema_assignments.tbl = '{$schema->getTable()}'");
268                $QB->filters()->whereAnd("schema_assignments.assigned = 1");
269                $QB->filters()->whereAnd("GETACCESSLEVEL($datatable.pid) > 0");
270                $QB->filters()->whereAnd("PAGEEXISTS($datatable.pid) = 1");
271
272                $first_table = $datatable;
273            }
274            $QB->filters()->whereAnd("$datatable.latest = 1");
275        }
276
277        // columns to select, handling multis
278        $sep = self::CONCAT_SEPARATOR;
279        $n = 0;
280        foreach($this->columns as $col) {
281            $CN = 'C' . $n++;
282
283            if($col->isMulti()) {
284                $datatable = "data_{$col->getTable()}";
285                $multitable = "multi_{$col->getTable()}";
286                $MN = 'M' . $col->getColref();
287
288                $QB->addLeftJoin(
289                    $datatable,
290                    $multitable,
291                    $MN,
292                    "$datatable.pid = $MN.pid AND
293                     $datatable.rev = $MN.rev AND
294                     $MN.colref = {$col->getColref()}"
295                );
296
297                $col->getType()->select($QB, $MN, 'value' , $CN);
298                $sel = $QB->getSelectStatement($CN);
299                $QB->addSelectStatement("GROUP_CONCAT($sel, '$sep')", $CN);
300            } else {
301                $col->getType()->select($QB, 'data_'.$col->getTable(), $col->getColName() , $CN);
302
303                // the %lastupdate% column needs datetime mangling
304                if(is_a($col, 'dokuwiki\\plugin\\struct\\meta\\RevisionColumn')) {
305                    $sel = $QB->getSelectStatement($CN);
306                    $QB->addSelectStatement("DATETIME($sel, 'unixepoch')", $CN);
307                }
308
309                $QB->addGroupByStatement($CN);
310            }
311        }
312
313        // where clauses
314        foreach($this->filter as $filter) {
315            list($col, $value, $comp, $op) = $filter;
316
317            $datatable = "data_{$col->getTable()}";
318            $multitable = "multi_{$col->getTable()}";
319
320            /** @var $col Column */
321            if($col->isMulti()) {
322                $MN = 'MN' . $col->getColref(); // FIXME this joins a second time if the column was selected before
323
324                $QB->addLeftJoin(
325                    $datatable,
326                    $multitable,
327                    $MN,
328                    "$datatable.pid = $MN.pid AND
329                     $datatable.rev = $MN.rev AND
330                     $MN.colref = {$col->getColref()}"
331                );
332                $coltbl = $MN;
333                $colnam = 'value';
334            } else {
335                $coltbl = $datatable;
336                $colnam = $col->getColName();
337            }
338            $col->getType()->filter($QB, $coltbl, $colnam, $comp, $value, $op); // type based filter
339        }
340
341        // sorting - we always sort by the single val column
342        foreach($this->sortby as $sort) {
343            list($col, $asc) = $sort;
344            /** @var $col Column */
345            $QB->addOrderBy($col->getFullColName(false) . ' '.(($asc) ? 'ASC' : 'DESC'));
346        }
347
348        return $QB->getSQL();
349    }
350
351    /**
352     * Returns all the columns that where added to the search
353     *
354     * @return Column[]
355     */
356    public function getColumns() {
357        return $this->columns;
358    }
359
360
361    /**
362     * Find a column to be used in the search
363     *
364     * @param string $colname may contain an alias
365     * @return bool|Column
366     */
367    public function findColumn($colname) {
368        if(!$this->schemas) throw new StructException('noschemas');
369
370        // handling of page and title column is special - we add a "fake" column
371        $schema_list = array_keys($this->schemas);
372        if($colname == '%pageid%') {
373            return new PageColumn(0, new Page(), $schema_list[0]);
374        }
375        if($colname == '%title%') {
376            return new PageColumn(0, new Page(array('usetitles' => true)),  $schema_list[0]);
377        }
378        if($colname == '%lastupdate%') {
379            return new RevisionColumn(0, new DateTime(),  $schema_list[0]);
380        }
381
382        // resolve the alias or table name
383        list($table, $colname) = explode('.', $colname, 2);
384        if(!$colname) {
385            $colname = $table;
386            $table = '';
387        }
388        if($table && isset($this->aliases[$table])) {
389            $table = $this->aliases[$table];
390        }
391
392        if(!$colname) throw new StructException('nocolname');
393
394        // if table name given search only that, otherwise try all for matching column name
395        if($table) {
396            $schemas = array($table => $this->schemas[$table]);
397        } else {
398            $schemas = $this->schemas;
399        }
400
401        // find it
402        $col = false;
403        foreach($schemas as $schema) {
404            if(empty($schema)) {
405                continue;
406            }
407            $col = $schema->findColumn($colname);
408            if($col) break;
409        }
410
411        return $col;
412    }
413
414    /**
415     * Check if a row is empty / only contains a reference to itself
416     *
417     * @param array $rowColumns an array as returned from the database
418     * @return bool
419     */
420    private function isRowEmpty($rowColumns) {
421        $C = 0;
422        foreach($this->columns as $col) {
423            $val = $rowColumns["C$C"];
424            $C += 1;
425            if (blank($val) || is_a($col->getType(),'dokuwiki\plugin\struct\types\Page') && $val == $rowColumns["PID"]) {
426                continue;
427            }
428            return false;
429        }
430        return true;
431    }
432
433}
434
435
436