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