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