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