xref: /plugin/struct/meta/Search.php (revision a5cdcc0579d879e5b8fd8ac2fc03cccb40ecddbc)
1<?php
2
3namespace plugin\struct\meta;
4
5use 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    /** @var bool only distinct data? */
48    protected $distinct = false;
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 $type either 'OR' or 'AND'
118     */
119    public function addFilter($colname, $value, $comp, $type = '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($type != 'OR' && $type != 'AND') throw new StructException('Bad filter type . Only AND or OR allowed');
131
132        $col = $this->findColumn($colname);
133        if(!$col) return; //FIXME do we really want to ignore missing columns?
134        $value = str_replace('*','%',$value);
135        $this->filter[] = array($col, $value, $comp, $type);
136    }
137
138    /**
139     * Set offset for the results
140     *
141     * @param int $offset
142     */
143    public function setOffset($offset) {
144        $limit = 0;
145        if($this->range_end) {
146            // if there was a limit set previously, the range_end needs to be recalculated
147            $limit = $this->range_end - $this->range_begin;
148        }
149        $this->range_begin = $offset;
150        if($limit) $this->setLimit($limit);
151    }
152
153    /**
154     * Limit results to this number
155     *
156     * @param int $limit Set to 0 to disable limit again
157     */
158    public function setLimit($limit) {
159        if($limit) {
160            $this->range_end = $this->range_begin + $limit;
161        } else {
162            $this->range_end = 0;
163        }
164    }
165
166    /**
167     * Request distinct data only, no PID column
168     *
169     * @param boolean $distinct
170     */
171    public function setDistinct($distinct) {
172        $this->distinct = $distinct;
173    }
174
175    /**
176     * Return the number of results (regardless of limit and offset settings)
177     *
178     * Use this to implement paging. Important: this may only be called after running @see execute()
179     *
180     * @return int
181     */
182    public function getCount() {
183        if($this->count < 0) throw new StructException('Count is only accessible after executing the search');
184        return $this->count;
185    }
186
187    /**
188     * Execute this search and return the result
189     *
190     * The result is a two dimensional array of Value()s.
191     *
192     * This will always query for the full result (not using offset and limit) and then
193     * return the wanted range, setting the count (@see getCount) to the whole result number
194     *
195     * @return Value[][]
196     */
197    public function execute() {
198        list($sql, $opts) = $this->getSQL();
199
200        /** @var \PDOStatement $res */
201        $res = $this->sqlite->query($sql, $opts);
202
203        $result = array();
204        $cursor = -1;
205        while($row = $res->fetch(\PDO::FETCH_ASSOC)) {
206            $cursor++;
207            if($cursor < $this->range_begin) continue;
208            if($this->range_end && $cursor >= $this->range_end) continue;
209
210            $C = 0;
211            $resrow = array();
212            foreach($this->columns as $col) {
213                $val = $row["C$C"];
214                if($col->isMulti()) {
215                    $val = explode(self::CONCAT_SEPARATOR, $val);
216                }
217                $resrow[] = new Value($col, $val);
218                $C++;
219            }
220            $result[] = $resrow;
221        }
222
223        $this->sqlite->res_close($res);
224        $this->count = $cursor + 1;
225        return $result;
226    }
227
228    /**
229     * Transform the set search parameters into a statement
230     *
231     * @return array ($sql, $opts) The SQL and parameters to execute
232     */
233    public function getSQL() {
234        if(!$this->columns) throw new StructException('nocolname');
235
236        $from = '';
237        $select = '';
238        $order = '';
239        $grouping = array();
240        $opts = array();
241        $where = '1 = 1';
242        $fwhere = '';
243
244        // basic tables
245        $first = '';
246        foreach($this->schemas as $schema) {
247            if($first) {
248                // follow up tables
249                $from .= "\nLEFT OUTER JOIN data_{$schema->getTable()} ON data_$first.pid = data_{$schema->getTable()}.pid";
250            } else {
251                // first table
252                if($this->distinct) {
253                    $select .= 'DISTINCT ';
254                } else {
255                    $select .= "data_{$schema->getTable()}.pid as PID, ";
256                }
257
258                $from .= 'schema_assignments, ';
259                $where .= "\nAND data_{$schema->getTable()}.pid = schema_assignments.pid";
260                $where .= "\nAND schema_assignments.assigned = 1";
261
262                $from .= "data_{$schema->getTable()}";
263                $where .= "\nAND GETACCESSLEVEL(data_{$schema->getTable()}.pid) > 0";
264                $first = $schema->getTable();
265            }
266
267            $where .= "\nAND data_{$schema->getTable()}.latest = 1";
268        }
269
270        // columns to select, handling multis
271        $sep = self::CONCAT_SEPARATOR;
272        $n = 0;
273        foreach($this->columns as $col) {
274            $CN = 'C' . $n++;
275
276            if($col->isMulti()) {
277                $tn = 'M' . $col->getColref();
278                $select .= "GROUP_CONCAT($tn.value, '$sep') AS $CN, ";
279                $from .= "\nLEFT OUTER JOIN multi_{$col->getTable()} AS $tn";
280                $from .= " ON data_{$col->getTable()}.pid = $tn.pid AND data_{$col->getTable()}.rev = $tn.rev";
281                $from .= " AND $tn.colref = {$col->getColref()}\n";
282            } else {
283                $select .= "{$col->getColName()} AS $CN, ";
284                $grouping[] = $CN;
285            }
286        }
287        $select = rtrim($select, ', ');
288
289        // where clauses
290        foreach($this->filter as $filter) {
291            list($col, $value, $comp, $type) = $filter;
292
293            /** @var $col Column */
294            if($col->isMulti()) {
295                $tn = 'MN' . $col->getColref(); // FIXME this joins a second time if the column was selected before
296                $from .= "\nLEFT OUTER JOIN multi_{$col->getTable()} AS $tn";
297                $from .= " ON data_{$col->getTable()}.pid = $tn.pid AND data_{$col->getTable()}.rev = $tn.rev";
298                $from .= " AND $tn.colref = {$col->getColref()}\n";
299
300                $column = "$tn.value";
301            } else {
302                $column = $col->getColName();
303            }
304
305            list($wsql, $wopt) = $col->getType()->compare($column, $comp, $value);
306            $opts = array_merge($opts, $wopt);
307
308            if(!$fwhere) $type = ''; // no type for first filter
309            $fwhere .= "\n$type $wsql";
310        }
311
312        // sorting - we always sort by the single val column
313        foreach($this->sortby as $sort) {
314            list($col, $asc) = $sort;
315            /** @var $col Column */
316            $order .= $col->getColName() . ' ';
317            $order .= ($asc) ? 'ASC' : 'DESC';
318            $order .= ', ';
319        }
320        $order = rtrim($order, ', ');
321
322        $fwhere = trim($fwhere);
323        if($fwhere) {
324            $fwhere = "AND ($fwhere\n)";
325        }
326
327        $sql = "SELECT $select\n  FROM $from\nWHERE $where\n$fwhere\nGROUP BY " . join(', ', $grouping);
328        if($order) $sql .= "\nORDER BY $order";
329
330        return array($sql, $opts);
331    }
332
333    /**
334     * Returns all the columns that where added to the search
335     *
336     * @return Column[]
337     */
338    public function getColumns() {
339        return $this->columns;
340    }
341
342
343    /**
344     * Find a column to be used in the search
345     *
346     * @param string $colname may contain an alias
347     * @return bool|Column
348     */
349    public function findColumn($colname) {
350        if(!$this->schemas) throw new StructException('noschemas');
351
352        // handling of page column is special
353        if($colname == '%pageid%') {
354            $schema_list = array_keys($this->schemas);
355            return new PageColumn(0, new Page(), array_shift($schema_list));
356        }
357        // FIXME %title% needs to be handled here, too (later)
358
359        // resolve the alias or table name
360        list($table, $colname) = explode('.', $colname, 2);
361        if(!$colname) {
362            $colname = $table;
363            $table = '';
364        }
365        if($table && isset($this->aliases[$table])) {
366            $table = $this->aliases[$table];
367        }
368
369        if(!$colname) throw new StructException('nocolname');
370
371        // if table name given search only that, otherwiese try all for matching column name
372        if($table) {
373            $schemas = array($table => $this->schemas[$table]);
374        } else {
375            $schemas = $this->schemas;
376        }
377
378        // find it
379        $col = false;
380        foreach($schemas as $schema) {
381            $col = $schema->findColumn($colname);
382            if($col) break;
383        }
384
385        return $col;
386    }
387
388}
389
390
391