xref: /plugin/struct/meta/Search.php (revision 01a8eccd70603dd29d644f62afedc0fd6a69bdc6)
115929be2SAndreas Gohr<?php
215929be2SAndreas Gohr
315929be2SAndreas Gohrnamespace plugin\struct\meta;
415929be2SAndreas Gohr
50234787dSAndreas Gohruse plugin\struct\types\Page;
60561158fSAndreas Gohruse plugin\struct\types\Text;
70561158fSAndreas Gohr
815929be2SAndreas Gohrclass Search {
99d7a36f9SAndreas Gohr    /**
109d7a36f9SAndreas Gohr     * This separator will be used to concat multi values to flatten them in the result set
119d7a36f9SAndreas Gohr     */
129d7a36f9SAndreas Gohr    const CONCAT_SEPARATOR = "\n!_-_-_-_-_!\n";
139d7a36f9SAndreas Gohr
145511bd5bSAndreas Gohr    /**
155511bd5bSAndreas Gohr     * The list of known and allowed comparators
165511bd5bSAndreas Gohr     */
1774461852SAndreas Gohr    static public $COMPARATORS = array(
18*01a8eccdSMichael Große        '<=', '>=', '=', '<', '>', '!=', '!~', '~'
195511bd5bSAndreas Gohr    );
205511bd5bSAndreas Gohr
219d7a36f9SAndreas Gohr    /** @var  \helper_plugin_sqlite */
229d7a36f9SAndreas Gohr    protected $sqlite;
2315929be2SAndreas Gohr
2415929be2SAndreas Gohr    /** @var Schema[] list of schemas to query */
2515929be2SAndreas Gohr    protected $schemas = array();
2615929be2SAndreas Gohr
2715929be2SAndreas Gohr    /** @var Column[] list of columns to select */
2815929be2SAndreas Gohr    protected $columns = array();
2915929be2SAndreas Gohr
3015929be2SAndreas Gohr    /** @var array the sorting of the result */
3115929be2SAndreas Gohr    protected $sortby = array();
3215929be2SAndreas Gohr
339d7a36f9SAndreas Gohr    /** @var array the filters */
349d7a36f9SAndreas Gohr    protected $filter = array();
3515929be2SAndreas Gohr
3615929be2SAndreas Gohr    /** @var array list of aliases tables can be referenced by */
3715929be2SAndreas Gohr    protected $aliases = array();
3815929be2SAndreas Gohr
397f9cb794SAndreas Gohr    /** @var  int begin results from here */
407f9cb794SAndreas Gohr    protected $range_begin = 0;
417f9cb794SAndreas Gohr
427f9cb794SAndreas Gohr    /** @var  int end results here */
437f9cb794SAndreas Gohr    protected $range_end = 0;
447f9cb794SAndreas Gohr
457f9cb794SAndreas Gohr    /** @var int the number of results */
467f9cb794SAndreas Gohr    protected $count = -1;
477f9cb794SAndreas Gohr
4815929be2SAndreas Gohr    /**
499d7a36f9SAndreas Gohr     * Search constructor.
509d7a36f9SAndreas Gohr     */
519d7a36f9SAndreas Gohr    public function __construct() {
529d7a36f9SAndreas Gohr        /** @var \helper_plugin_struct_db $plugin */
539d7a36f9SAndreas Gohr        $plugin = plugin_load('helper', 'struct_db');
549d7a36f9SAndreas Gohr        $this->sqlite = $plugin->getDB();
559d7a36f9SAndreas Gohr    }
569d7a36f9SAndreas Gohr
579d7a36f9SAndreas Gohr    /**
5815929be2SAndreas Gohr     * Add a schema to be searched
5915929be2SAndreas Gohr     *
6015929be2SAndreas Gohr     * Call multiple times for multiple schemas.
6115929be2SAndreas Gohr     *
6215929be2SAndreas Gohr     * @param string $table
6315929be2SAndreas Gohr     * @param string $alias
6415929be2SAndreas Gohr     */
6515929be2SAndreas Gohr    public function addSchema($table, $alias = '') {
6615929be2SAndreas Gohr        $this->schemas[$table] = new Schema($table);
6715929be2SAndreas Gohr        if($alias) $this->aliases[$alias] = $table;
6815929be2SAndreas Gohr    }
6915929be2SAndreas Gohr
7015929be2SAndreas Gohr    /**
7115929be2SAndreas Gohr     * Add a column to be returned by the search
7215929be2SAndreas Gohr     *
7315929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
7415929be2SAndreas Gohr     * added before
7515929be2SAndreas Gohr     *
7615929be2SAndreas Gohr     * @param string $colname may contain an alias
7715929be2SAndreas Gohr     */
7815929be2SAndreas Gohr    public function addColumn($colname) {
7915929be2SAndreas Gohr        $col = $this->findColumn($colname);
8015929be2SAndreas Gohr        if(!$col) return; //FIXME do we really want to ignore missing columns?
8115929be2SAndreas Gohr        $this->columns[] = $col;
8215929be2SAndreas Gohr    }
8315929be2SAndreas Gohr
8415929be2SAndreas Gohr    /**
8515929be2SAndreas Gohr     * Add sorting options
8615929be2SAndreas Gohr     *
8715929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
8815929be2SAndreas Gohr     * added before
8915929be2SAndreas Gohr     *
9015929be2SAndreas Gohr     * @param string $colname may contain an alias
9115929be2SAndreas Gohr     * @param bool $asc sort direction (ASC = true, DESC = false)
9215929be2SAndreas Gohr     */
9315929be2SAndreas Gohr    public function addSort($colname, $asc = true) {
9415929be2SAndreas Gohr        $col = $this->findColumn($colname);
9515929be2SAndreas Gohr        if(!$col) return; //FIXME do we really want to ignore missing columns?
9615929be2SAndreas Gohr
9715929be2SAndreas Gohr        $this->sortby[] = array($col, $asc);
9815929be2SAndreas Gohr    }
9915929be2SAndreas Gohr
10015929be2SAndreas Gohr    /**
1019d7a36f9SAndreas Gohr     * Adds a filter
10215929be2SAndreas Gohr     *
10315929be2SAndreas Gohr     * @param string $colname may contain an alias
10415929be2SAndreas Gohr     * @param string $value
1055511bd5bSAndreas Gohr     * @param string $comp @see self::COMPARATORS
1069d7a36f9SAndreas Gohr     * @param string $type either 'OR' or 'AND'
10715929be2SAndreas Gohr     */
1089d7a36f9SAndreas Gohr    public function addFilter($colname, $value, $comp, $type = 'OR') {
10974461852SAndreas Gohr        if(!in_array($comp, self::$COMPARATORS)) throw new StructException("Bad comperator. Use " . join(',', self::$COMPARATORS));
1105511bd5bSAndreas Gohr        if($type != 'OR' && $type != 'AND') throw new StructException('Bad filter type . Only AND or OR allowed');
1119d7a36f9SAndreas Gohr
11215929be2SAndreas Gohr        $col = $this->findColumn($colname);
11315929be2SAndreas Gohr        if(!$col) return; //FIXME do we really want to ignore missing columns?
11415929be2SAndreas Gohr
1159d7a36f9SAndreas Gohr        $this->filter[] = array($col, $value, $comp, $type);
11615929be2SAndreas Gohr    }
11715929be2SAndreas Gohr
11815929be2SAndreas Gohr    /**
1197f9cb794SAndreas Gohr     * Set offset for the results
1207f9cb794SAndreas Gohr     *
1217f9cb794SAndreas Gohr     * @param int $offset
1227f9cb794SAndreas Gohr     */
1237f9cb794SAndreas Gohr    public function setOffset($offset) {
1247f9cb794SAndreas Gohr        $limit = 0;
1257f9cb794SAndreas Gohr        if($this->range_end) {
1267f9cb794SAndreas Gohr            // if there was a limit set previously, the range_end needs to be recalculated
1277f9cb794SAndreas Gohr            $limit = $this->range_end - $this->range_begin;
1287f9cb794SAndreas Gohr        }
1297f9cb794SAndreas Gohr        $this->range_begin = $offset;
1307f9cb794SAndreas Gohr        if($limit) $this->setLimit($limit);
1317f9cb794SAndreas Gohr    }
1327f9cb794SAndreas Gohr
1337f9cb794SAndreas Gohr    /**
1347f9cb794SAndreas Gohr     * Limit results to this number
1357f9cb794SAndreas Gohr     *
1367f9cb794SAndreas Gohr     * @param int $limit Set to 0 to disable limit again
1377f9cb794SAndreas Gohr     */
1387f9cb794SAndreas Gohr    public function setLimit($limit) {
1397f9cb794SAndreas Gohr        if($limit) {
1407f9cb794SAndreas Gohr            $this->range_end = $this->range_begin + $limit;
1417f9cb794SAndreas Gohr        } else {
1427f9cb794SAndreas Gohr            $this->range_end = 0;
1437f9cb794SAndreas Gohr        }
1447f9cb794SAndreas Gohr    }
1457f9cb794SAndreas Gohr
1467f9cb794SAndreas Gohr    /**
1477f9cb794SAndreas Gohr     * Return the number of results (regardless of limit and offset settings)
1487f9cb794SAndreas Gohr     *
1497f9cb794SAndreas Gohr     * Use this to implement paging. Important: this may only be called after running @see execute()
1507f9cb794SAndreas Gohr     *
1517f9cb794SAndreas Gohr     * @return int
1527f9cb794SAndreas Gohr     */
1537f9cb794SAndreas Gohr    public function getCount() {
1547f9cb794SAndreas Gohr        if($this->count < 0) throw new StructException('Count is only accessible after executing the search');
1557f9cb794SAndreas Gohr        return $this->count;
1567f9cb794SAndreas Gohr    }
1577f9cb794SAndreas Gohr
1587f9cb794SAndreas Gohr    /**
159b2ed727aSAndreas Gohr     * Execute this search and return the result
160b2ed727aSAndreas Gohr     *
16138fa36fbSAndreas Gohr     * The result is a two dimensional array of Value()s.
1627f9cb794SAndreas Gohr     *
1637f9cb794SAndreas Gohr     * This will always query for the full result (not using offset and limit) and then
1647f9cb794SAndreas Gohr     * return the wanted range, setting the count (@see getCount) to the whole result number
16538fa36fbSAndreas Gohr     *
16638fa36fbSAndreas Gohr     * @return Value[][]
167b2ed727aSAndreas Gohr     */
168b2ed727aSAndreas Gohr    public function execute() {
169b2ed727aSAndreas Gohr        list($sql, $opts) = $this->getSQL();
170b2ed727aSAndreas Gohr
1717f9cb794SAndreas Gohr        /** @var \PDOStatement $res */
172b2ed727aSAndreas Gohr        $res = $this->sqlite->query($sql, $opts);
173b2ed727aSAndreas Gohr
174b2ed727aSAndreas Gohr        $result = array();
1757f9cb794SAndreas Gohr        $cursor = -1;
1767f9cb794SAndreas Gohr        while($row = $res->fetch(\PDO::FETCH_ASSOC)) {
1777f9cb794SAndreas Gohr            $cursor++;
1787f9cb794SAndreas Gohr            if($cursor < $this->range_begin) continue;
1797f9cb794SAndreas Gohr            if($this->range_end && $cursor >= $this->range_end) continue;
1807f9cb794SAndreas Gohr
181b2ed727aSAndreas Gohr            $C = 0;
182b2ed727aSAndreas Gohr            $resrow = array();
183b2ed727aSAndreas Gohr            foreach($this->columns as $col) {
18438fa36fbSAndreas Gohr                $val = $row["C$C"];
185b2ed727aSAndreas Gohr                if($col->isMulti()) {
18638fa36fbSAndreas Gohr                    $val = explode(self::CONCAT_SEPARATOR, $val);
187b2ed727aSAndreas Gohr                }
18838fa36fbSAndreas Gohr                $resrow[] = new Value($col, $val);
189b2ed727aSAndreas Gohr                $C++;
190b2ed727aSAndreas Gohr            }
191b2ed727aSAndreas Gohr            $result[] = $resrow;
192b2ed727aSAndreas Gohr        }
1937f9cb794SAndreas Gohr
1947f9cb794SAndreas Gohr        $this->sqlite->res_close($res);
1957f9cb794SAndreas Gohr        $this->count = $cursor + 1;
196b2ed727aSAndreas Gohr        return $result;
197b2ed727aSAndreas Gohr    }
198b2ed727aSAndreas Gohr
199b2ed727aSAndreas Gohr    /**
20015929be2SAndreas Gohr     * Transform the set search parameters into a statement
20115929be2SAndreas Gohr     *
202b2ed727aSAndreas Gohr     * @return array ($sql, $opts) The SQL and parameters to execute
20315929be2SAndreas Gohr     */
20415929be2SAndreas Gohr    public function getSQL() {
2055511bd5bSAndreas Gohr        if(!$this->columns) throw new StructException('nocolname');
20615929be2SAndreas Gohr
20715929be2SAndreas Gohr        $from = '';
2089d7a36f9SAndreas Gohr        $select = '';
2099d7a36f9SAndreas Gohr        $order = '';
2109d7a36f9SAndreas Gohr        $grouping = array();
2119d7a36f9SAndreas Gohr        $opts = array();
2129d7a36f9SAndreas Gohr        $where = '1 = 1';
21315929be2SAndreas Gohr
2149d7a36f9SAndreas Gohr        // basic tables
2159d7a36f9SAndreas Gohr        $first = '';
2169d7a36f9SAndreas Gohr        foreach($this->schemas as $schema) {
2179d7a36f9SAndreas Gohr            if($first) {
2189d7a36f9SAndreas Gohr                // follow up tables
2199d7a36f9SAndreas Gohr                $from .= "\nLEFT OUTER JOIN data_{$schema->getTable()} ON data_$first.pid = data_{$schema->getTable()}.pid";
2209d7a36f9SAndreas Gohr            } else {
2219d7a36f9SAndreas Gohr                // first table
2229d7a36f9SAndreas Gohr                $select .= "data_{$schema->getTable()}.pid as PID, ";
2239d7a36f9SAndreas Gohr                $from .= "data_{$schema->getTable()}";
2249d7a36f9SAndreas Gohr                $first = $schema->getTable();
22515929be2SAndreas Gohr            }
2267059e7e1SAndreas Gohr
2277059e7e1SAndreas Gohr            $where .= "\nAND data_{$schema->getTable()}.latest = 1";
2289d7a36f9SAndreas Gohr        }
22915929be2SAndreas Gohr
23015929be2SAndreas Gohr        // columns to select, handling multis
2319d7a36f9SAndreas Gohr        $sep = self::CONCAT_SEPARATOR;
23215929be2SAndreas Gohr        $n = 0;
23315929be2SAndreas Gohr        foreach($this->columns as $col) {
23415929be2SAndreas Gohr            $CN = 'C' . $n++;
23515929be2SAndreas Gohr
236d1b04e89SAndreas Gohr            if($col->isMulti()) {
23715929be2SAndreas Gohr                $tn = 'M' . $col->getColref();
2389d7a36f9SAndreas Gohr                $select .= "GROUP_CONCAT($tn.value, '$sep') AS $CN, ";
2390fe33e72SAndreas Gohr                $from .= "\nLEFT OUTER JOIN multi_{$col->getTable()} AS $tn";
2409d7a36f9SAndreas Gohr                $from .= " ON data_{$col->getTable()}.pid = $tn.pid AND data_{$col->getTable()}.rev = $tn.rev";
2410fe33e72SAndreas Gohr                $from .= " AND $tn.colref = {$col->getColref()}\n";
24215929be2SAndreas Gohr            } else {
2435b2d2a8cSAndreas Gohr                $select .= "{$col->getColName()} AS $CN, ";
2449d7a36f9SAndreas Gohr                $grouping[] = $CN;
24515929be2SAndreas Gohr            }
24615929be2SAndreas Gohr        }
24715929be2SAndreas Gohr        $select = rtrim($select, ', ');
24815929be2SAndreas Gohr
2499d7a36f9SAndreas Gohr        // where clauses
250b8fe6730SAndreas Gohr        foreach($this->filter as $filter) {
251b8fe6730SAndreas Gohr            list($col, $value, $comp, $type) = $filter;
252b8fe6730SAndreas Gohr
2539d7a36f9SAndreas Gohr            /** @var $col Column */
2549d7a36f9SAndreas Gohr            if($col->isMulti()) {
2559d7a36f9SAndreas Gohr                $tn = 'MN' . $col->getColref(); // FIXME this joins a second time if the column was selected before
2560fe33e72SAndreas Gohr                $from .= "\nLEFT OUTER JOIN multi_{$col->getTable()} AS $tn";
2579d7a36f9SAndreas Gohr                $from .= " ON data_{$col->getTable()}.pid = $tn.pid AND data_{$col->getTable()}.rev = $tn.rev";
2580fe33e72SAndreas Gohr                $from .= " AND $tn.colref = {$col->getColref()}\n";
25915929be2SAndreas Gohr
2609d7a36f9SAndreas Gohr                $column = "$tn.value";
2619d7a36f9SAndreas Gohr            } else {
262d1b04e89SAndreas Gohr                $column = $col->getColName();
2639d7a36f9SAndreas Gohr            }
2649d7a36f9SAndreas Gohr
2659d7a36f9SAndreas Gohr            list($wsql, $wopt) = $col->getType()->compare($column, $comp, $value);
2669d7a36f9SAndreas Gohr            $opts = array_merge($opts, $wopt);
2679d7a36f9SAndreas Gohr
268d1b04e89SAndreas Gohr            $where .= "\n$type $wsql";
2699d7a36f9SAndreas Gohr        }
2709d7a36f9SAndreas Gohr
2719d7a36f9SAndreas Gohr        // sorting
272b8fe6730SAndreas Gohr        foreach($this->sortby as $sort) {
273b8fe6730SAndreas Gohr            list($col, $asc) = $sort;
274b8fe6730SAndreas Gohr
2759d7a36f9SAndreas Gohr            /** @var $col Column */
2769d7a36f9SAndreas Gohr            if($col->isMulti()) {
2779d7a36f9SAndreas Gohr                // FIXME how to sort by multival?
2789d7a36f9SAndreas Gohr                // FIXME what if sort by non merged multival?
2799d7a36f9SAndreas Gohr            } else {
280d1b04e89SAndreas Gohr                $order .= $col->getColName() . ' ';
2819d7a36f9SAndreas Gohr                $order .= ($asc) ? 'ASC' : 'DESC';
2829d7a36f9SAndreas Gohr                $order .= ', ';
2839d7a36f9SAndreas Gohr            }
2849d7a36f9SAndreas Gohr        }
2859d7a36f9SAndreas Gohr        $order = rtrim($order, ', ');
2869d7a36f9SAndreas Gohr
2879d7a36f9SAndreas Gohr        $sql = "SELECT $select\n  FROM $from\nWHERE $where\nGROUP BY " . join(', ', $grouping);
2889d7a36f9SAndreas Gohr        if($order) $sql .= "\nORDER BY $order";
2899d7a36f9SAndreas Gohr
290b2ed727aSAndreas Gohr        return array($sql, $opts);
29115929be2SAndreas Gohr    }
29215929be2SAndreas Gohr
29315929be2SAndreas Gohr    /**
29415929be2SAndreas Gohr     * Find a column to be used in the search
29515929be2SAndreas Gohr     *
29615929be2SAndreas Gohr     * @param string $colname may contain an alias
29715929be2SAndreas Gohr     * @return bool|Column
29815929be2SAndreas Gohr     */
29915929be2SAndreas Gohr    protected function findColumn($colname) {
3005511bd5bSAndreas Gohr        if(!$this->schemas) throw new StructException('noschemas');
30115929be2SAndreas Gohr
302d1b04e89SAndreas Gohr        // handling of page column is special
303d3f94fb7SAndreas Gohr        if($colname == '%pageid%') {
3040234787dSAndreas Gohr            return new PageColumn(0, new Page(), array_shift(array_keys($this->schemas)));
305d1b04e89SAndreas Gohr        }
306d1b04e89SAndreas Gohr        // FIXME %title% needs to be handled here, too (later)
307d1b04e89SAndreas Gohr
30815929be2SAndreas Gohr        // resolve the alias or table name
30915929be2SAndreas Gohr        list($table, $colname) = explode('.', $colname, 2);
31015929be2SAndreas Gohr        if(!$colname) {
31115929be2SAndreas Gohr            $colname = $table;
31215929be2SAndreas Gohr            $table = '';
31315929be2SAndreas Gohr        }
31415929be2SAndreas Gohr        if($table && isset($this->aliases[$table])) {
31515929be2SAndreas Gohr            $table = $this->aliases[$table];
31615929be2SAndreas Gohr        }
31715929be2SAndreas Gohr
3185511bd5bSAndreas Gohr        if(!$colname) throw new StructException('nocolname');
31915929be2SAndreas Gohr
32015929be2SAndreas Gohr        // if table name given search only that, otherwiese try all for matching column name
32115929be2SAndreas Gohr        if($table) {
32215929be2SAndreas Gohr            $schemas = array($table => $this->schemas[$table]);
32315929be2SAndreas Gohr        } else {
32415929be2SAndreas Gohr            $schemas = $this->schemas;
32515929be2SAndreas Gohr        }
32615929be2SAndreas Gohr
32715929be2SAndreas Gohr        // find it
32815929be2SAndreas Gohr        $col = false;
32915929be2SAndreas Gohr        foreach($schemas as $schema) {
33015929be2SAndreas Gohr            $col = $schema->findColumn($colname);
33115929be2SAndreas Gohr            if($col) break;
33215929be2SAndreas Gohr        }
33315929be2SAndreas Gohr
33415929be2SAndreas Gohr        return $col;
33515929be2SAndreas Gohr    }
33615929be2SAndreas Gohr
33715929be2SAndreas Gohr}
33815929be2SAndreas Gohr
3395511bd5bSAndreas Gohr
340