xref: /plugin/struct/meta/Search.php (revision 0561158f2815d6f30d3c4038684e6b6918bbfd86)
115929be2SAndreas Gohr<?php
215929be2SAndreas Gohr
315929be2SAndreas Gohrnamespace plugin\struct\meta;
415929be2SAndreas Gohr
5*0561158fSAndreas Gohruse plugin\struct\types\Text;
6*0561158fSAndreas Gohr
715929be2SAndreas Gohrclass Search {
89d7a36f9SAndreas Gohr    /**
99d7a36f9SAndreas Gohr     * This separator will be used to concat multi values to flatten them in the result set
109d7a36f9SAndreas Gohr     */
119d7a36f9SAndreas Gohr    const CONCAT_SEPARATOR = "\n!_-_-_-_-_!\n";
129d7a36f9SAndreas Gohr
135511bd5bSAndreas Gohr    /**
145511bd5bSAndreas Gohr     * The list of known and allowed comparators
155511bd5bSAndreas Gohr     */
1674461852SAndreas Gohr    static public $COMPARATORS = array(
175511bd5bSAndreas Gohr        '<', '>', '<=', '>=', '!=', '!~', '~'
185511bd5bSAndreas Gohr    );
195511bd5bSAndreas Gohr
209d7a36f9SAndreas Gohr    /** @var  \helper_plugin_sqlite */
219d7a36f9SAndreas Gohr    protected $sqlite;
2215929be2SAndreas Gohr
2315929be2SAndreas Gohr    /** @var Schema[] list of schemas to query */
2415929be2SAndreas Gohr    protected $schemas = array();
2515929be2SAndreas Gohr
2615929be2SAndreas Gohr    /** @var Column[] list of columns to select */
2715929be2SAndreas Gohr    protected $columns = array();
2815929be2SAndreas Gohr
2915929be2SAndreas Gohr    /** @var array the sorting of the result */
3015929be2SAndreas Gohr    protected $sortby = array();
3115929be2SAndreas Gohr
329d7a36f9SAndreas Gohr    /** @var array the filters */
339d7a36f9SAndreas Gohr    protected $filter = array();
3415929be2SAndreas Gohr
3515929be2SAndreas Gohr    /** @var array list of aliases tables can be referenced by */
3615929be2SAndreas Gohr    protected $aliases = array();
3715929be2SAndreas Gohr
3815929be2SAndreas Gohr    /**
399d7a36f9SAndreas Gohr     * Search constructor.
409d7a36f9SAndreas Gohr     */
419d7a36f9SAndreas Gohr    public function __construct() {
429d7a36f9SAndreas Gohr        /** @var \helper_plugin_struct_db $plugin */
439d7a36f9SAndreas Gohr        $plugin = plugin_load('helper', 'struct_db');
449d7a36f9SAndreas Gohr        $this->sqlite = $plugin->getDB();
459d7a36f9SAndreas Gohr    }
469d7a36f9SAndreas Gohr
479d7a36f9SAndreas Gohr    /**
4815929be2SAndreas Gohr     * Add a schema to be searched
4915929be2SAndreas Gohr     *
5015929be2SAndreas Gohr     * Call multiple times for multiple schemas.
5115929be2SAndreas Gohr     *
5215929be2SAndreas Gohr     * @param string $table
5315929be2SAndreas Gohr     * @param string $alias
5415929be2SAndreas Gohr     */
5515929be2SAndreas Gohr    public function addSchema($table, $alias = '') {
5615929be2SAndreas Gohr        $this->schemas[$table] = new Schema($table);
5715929be2SAndreas Gohr        if($alias) $this->aliases[$alias] = $table;
5815929be2SAndreas Gohr    }
5915929be2SAndreas Gohr
6015929be2SAndreas Gohr    /**
6115929be2SAndreas Gohr     * Add a column to be returned by the search
6215929be2SAndreas Gohr     *
6315929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
6415929be2SAndreas Gohr     * added before
6515929be2SAndreas Gohr     *
6615929be2SAndreas Gohr     * @param string $colname may contain an alias
6715929be2SAndreas Gohr     */
6815929be2SAndreas Gohr    public function addColumn($colname) {
69*0561158fSAndreas Gohr        if(!$this->schemas) throw new StructException('noschemas');
70*0561158fSAndreas Gohr        if($colname == '%pid%') { // Special column
71*0561158fSAndreas Gohr            $col = new PageColumn(0, new Text(), array_shift(array_keys($this->schemas))); //FIXME the type should be Page
72*0561158fSAndreas Gohr        // FIXME %title% needs to be handled here, too (later)
73*0561158fSAndreas Gohr        } else {
7415929be2SAndreas Gohr            $col = $this->findColumn($colname);
75*0561158fSAndreas Gohr        }
7615929be2SAndreas Gohr        if(!$col) return; //FIXME do we really want to ignore missing columns?
7715929be2SAndreas Gohr        $this->columns[] = $col;
7815929be2SAndreas Gohr    }
7915929be2SAndreas Gohr
8015929be2SAndreas Gohr    /**
8115929be2SAndreas Gohr     * Add sorting options
8215929be2SAndreas Gohr     *
8315929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
8415929be2SAndreas Gohr     * added before
8515929be2SAndreas Gohr     *
8615929be2SAndreas Gohr     * @param string $colname may contain an alias
8715929be2SAndreas Gohr     * @param bool $asc sort direction (ASC = true, DESC = false)
8815929be2SAndreas Gohr     */
8915929be2SAndreas Gohr    public function addSort($colname, $asc = true) {
9015929be2SAndreas Gohr        $col = $this->findColumn($colname);
9115929be2SAndreas Gohr        if(!$col) return; //FIXME do we really want to ignore missing columns?
9215929be2SAndreas Gohr
9315929be2SAndreas Gohr        $this->sortby[] = array($col, $asc);
9415929be2SAndreas Gohr    }
9515929be2SAndreas Gohr
9615929be2SAndreas Gohr    /**
979d7a36f9SAndreas Gohr     * Adds a filter
9815929be2SAndreas Gohr     *
9915929be2SAndreas Gohr     * @param string $colname may contain an alias
10015929be2SAndreas Gohr     * @param string $value
1015511bd5bSAndreas Gohr     * @param string $comp @see self::COMPARATORS
1029d7a36f9SAndreas Gohr     * @param string $type either 'OR' or 'AND'
10315929be2SAndreas Gohr     */
1049d7a36f9SAndreas Gohr    public function addFilter($colname, $value, $comp, $type = 'OR') {
10574461852SAndreas Gohr        if(!in_array($comp, self::$COMPARATORS)) throw new StructException("Bad comperator. Use " . join(',', self::$COMPARATORS));
1065511bd5bSAndreas Gohr        if($type != 'OR' && $type != 'AND') throw new StructException('Bad filter type . Only AND or OR allowed');
1079d7a36f9SAndreas Gohr
10815929be2SAndreas Gohr        $col = $this->findColumn($colname);
10915929be2SAndreas Gohr        if(!$col) return; //FIXME do we really want to ignore missing columns?
11015929be2SAndreas Gohr
1119d7a36f9SAndreas Gohr        $this->filter[] = array($col, $value, $comp, $type);
11215929be2SAndreas Gohr    }
11315929be2SAndreas Gohr
11415929be2SAndreas Gohr    /**
115b2ed727aSAndreas Gohr     * Execute this search and return the result
116b2ed727aSAndreas Gohr     *
117b2ed727aSAndreas Gohr     * The result is a two dimensional array of array. Each cell contains an array with
118b2ed727aSAndreas Gohr     * the keys 'col' (containing a Column object) and 'val' containing the value(s)
119b2ed727aSAndreas Gohr     */
120b2ed727aSAndreas Gohr    public function execute() {
121b2ed727aSAndreas Gohr        list($sql, $opts) = $this->getSQL();
122b2ed727aSAndreas Gohr
123b2ed727aSAndreas Gohr        $res = $this->sqlite->query($sql, $opts);
124b2ed727aSAndreas Gohr        $data = $this->sqlite->res2arr($res);
125b2ed727aSAndreas Gohr        $this->sqlite->res_close($res);
126b2ed727aSAndreas Gohr
127b2ed727aSAndreas Gohr        $result = array();
128b2ed727aSAndreas Gohr        foreach($data as $row) {
129b2ed727aSAndreas Gohr            $C = 0;
130b2ed727aSAndreas Gohr            $resrow = array();
131b2ed727aSAndreas Gohr            foreach($this->columns as $col) {
132b2ed727aSAndreas Gohr                $rescol = array();
133b2ed727aSAndreas Gohr                $rescol['col'] = $col;
134b2ed727aSAndreas Gohr                $rescol['val'] = $row["C$C"];
135b2ed727aSAndreas Gohr                if($col->isMulti()) {
136b2ed727aSAndreas Gohr                    $rescol['val'] = explode(self::CONCAT_SEPARATOR,$rescol['val']);
137b2ed727aSAndreas Gohr                }
138b2ed727aSAndreas Gohr                $resrow[] = $rescol;
139b2ed727aSAndreas Gohr                $C++;
140b2ed727aSAndreas Gohr            }
141b2ed727aSAndreas Gohr            $result[] = $resrow;
142b2ed727aSAndreas Gohr        }
143b2ed727aSAndreas Gohr        return $result;
144b2ed727aSAndreas Gohr    }
145b2ed727aSAndreas Gohr
146b2ed727aSAndreas Gohr    /**
14715929be2SAndreas Gohr     * Transform the set search parameters into a statement
14815929be2SAndreas Gohr     *
149b2ed727aSAndreas Gohr     * @return array ($sql, $opts) The SQL and parameters to execute
15015929be2SAndreas Gohr     */
15115929be2SAndreas Gohr    public function getSQL() {
1525511bd5bSAndreas Gohr        if(!$this->columns) throw new StructException('nocolname');
15315929be2SAndreas Gohr
15415929be2SAndreas Gohr        $from = '';
1559d7a36f9SAndreas Gohr        $select = '';
1569d7a36f9SAndreas Gohr        $order = '';
1579d7a36f9SAndreas Gohr        $grouping = array();
1589d7a36f9SAndreas Gohr        $opts = array();
1599d7a36f9SAndreas Gohr        $where = '1 = 1';
16015929be2SAndreas Gohr
1619d7a36f9SAndreas Gohr        // basic tables
1629d7a36f9SAndreas Gohr        $first = '';
1639d7a36f9SAndreas Gohr        foreach($this->schemas as $schema) {
1649d7a36f9SAndreas Gohr            if($first) {
1659d7a36f9SAndreas Gohr                // follow up tables
1669d7a36f9SAndreas Gohr                $from .= "\nLEFT OUTER JOIN data_{$schema->getTable()} ON data_$first.pid = data_{$schema->getTable()}.pid";
1679d7a36f9SAndreas Gohr            } else {
1689d7a36f9SAndreas Gohr                // first table
1699d7a36f9SAndreas Gohr                $select .= "data_{$schema->getTable()}.pid as PID, ";
1709d7a36f9SAndreas Gohr                $from .= "data_{$schema->getTable()}";
1719d7a36f9SAndreas Gohr                $first = $schema->getTable();
17215929be2SAndreas Gohr            }
1737059e7e1SAndreas Gohr
1747059e7e1SAndreas Gohr            $where .= "\nAND data_{$schema->getTable()}.latest = 1";
1759d7a36f9SAndreas Gohr        }
17615929be2SAndreas Gohr
17715929be2SAndreas Gohr        // columns to select, handling multis
1789d7a36f9SAndreas Gohr        $sep = self::CONCAT_SEPARATOR;
17915929be2SAndreas Gohr        $n = 0;
18015929be2SAndreas Gohr        foreach($this->columns as $col) {
18115929be2SAndreas Gohr            $CN = 'C' . $n++;
18215929be2SAndreas Gohr
183*0561158fSAndreas Gohr            if(is_a($col, 'plugin\struct\meta\PageColumn')) {
184*0561158fSAndreas Gohr                $select .= 'data_' . $col->getTable() . ".pid AS $CN, ";
185*0561158fSAndreas Gohr                $grouping[] = $CN;
186*0561158fSAndreas Gohr            } else if($col->isMulti()) {
18715929be2SAndreas Gohr                $tn = 'M' . $col->getColref();
1889d7a36f9SAndreas Gohr                $select .= "GROUP_CONCAT($tn.value, '$sep') AS $CN, ";
1890fe33e72SAndreas Gohr                $from .= "\nLEFT OUTER JOIN multi_{$col->getTable()} AS $tn";
1909d7a36f9SAndreas Gohr                $from .= " ON data_{$col->getTable()}.pid = $tn.pid AND data_{$col->getTable()}.rev = $tn.rev";
1910fe33e72SAndreas Gohr                $from .= " AND $tn.colref = {$col->getColref()}\n";
19215929be2SAndreas Gohr            } else {
19315929be2SAndreas Gohr                $select .= 'data_' . $col->getTable() . '.col' . $col->getColref() . " AS $CN, ";
1949d7a36f9SAndreas Gohr                $grouping[] = $CN;
19515929be2SAndreas Gohr            }
19615929be2SAndreas Gohr        }
19715929be2SAndreas Gohr        $select = rtrim($select, ', ');
19815929be2SAndreas Gohr
1999d7a36f9SAndreas Gohr        // where clauses
200b8fe6730SAndreas Gohr        foreach($this->filter as $filter) {
201b8fe6730SAndreas Gohr            list($col, $value, $comp, $type) = $filter;
202b8fe6730SAndreas Gohr
2039d7a36f9SAndreas Gohr            /** @var $col Column */
2049d7a36f9SAndreas Gohr            if($col->isMulti()) {
2059d7a36f9SAndreas Gohr                $tn = 'MN' . $col->getColref(); // FIXME this joins a second time if the column was selected before
2060fe33e72SAndreas Gohr                $from .= "\nLEFT OUTER JOIN multi_{$col->getTable()} AS $tn";
2079d7a36f9SAndreas Gohr                $from .= " ON data_{$col->getTable()}.pid = $tn.pid AND data_{$col->getTable()}.rev = $tn.rev";
2080fe33e72SAndreas Gohr                $from .= " AND $tn.colref = {$col->getColref()}\n";
20915929be2SAndreas Gohr
2109d7a36f9SAndreas Gohr                $column = "$tn.value";
2119d7a36f9SAndreas Gohr            } else {
2129d7a36f9SAndreas Gohr                $column = "data_{$col->getTable()}.col{$col->getColref()}";
2139d7a36f9SAndreas Gohr            }
2149d7a36f9SAndreas Gohr
2159d7a36f9SAndreas Gohr            list($wsql, $wopt) = $col->getType()->compare($column, $comp, $value);
2169d7a36f9SAndreas Gohr            $opts = array_merge($opts, $wopt);
2179d7a36f9SAndreas Gohr
2189d7a36f9SAndreas Gohr            $where .= " $type $wsql";
2199d7a36f9SAndreas Gohr        }
2209d7a36f9SAndreas Gohr
2219d7a36f9SAndreas Gohr        // sorting
222b8fe6730SAndreas Gohr        foreach($this->sortby as $sort) {
223b8fe6730SAndreas Gohr            list($col, $asc) = $sort;
224b8fe6730SAndreas Gohr
2259d7a36f9SAndreas Gohr            /** @var $col Column */
2269d7a36f9SAndreas Gohr            if($col->isMulti()) {
2279d7a36f9SAndreas Gohr                // FIXME how to sort by multival?
2289d7a36f9SAndreas Gohr                // FIXME what if sort by non merged multival?
2299d7a36f9SAndreas Gohr            } else {
2309d7a36f9SAndreas Gohr                $order .= "data_{$col->getTable()}.col{$col->getColref()} ";
2319d7a36f9SAndreas Gohr                $order .= ($asc) ? 'ASC' : 'DESC';
2329d7a36f9SAndreas Gohr                $order .= ', ';
2339d7a36f9SAndreas Gohr            }
2349d7a36f9SAndreas Gohr        }
2359d7a36f9SAndreas Gohr        $order = rtrim($order, ', ');
2369d7a36f9SAndreas Gohr
2379d7a36f9SAndreas Gohr        $sql = "SELECT $select\n  FROM $from\nWHERE $where\nGROUP BY " . join(', ', $grouping);
2389d7a36f9SAndreas Gohr        if($order) $sql .= "\nORDER BY $order";
2399d7a36f9SAndreas Gohr
240b2ed727aSAndreas Gohr        return array($sql, $opts);
24115929be2SAndreas Gohr    }
24215929be2SAndreas Gohr
24315929be2SAndreas Gohr    /**
24415929be2SAndreas Gohr     * Find a column to be used in the search
24515929be2SAndreas Gohr     *
24615929be2SAndreas Gohr     * @param string $colname may contain an alias
24715929be2SAndreas Gohr     * @return bool|Column
24815929be2SAndreas Gohr     */
24915929be2SAndreas Gohr    protected function findColumn($colname) {
2505511bd5bSAndreas Gohr        if(!$this->schemas) throw new StructException('noschemas');
25115929be2SAndreas Gohr
25215929be2SAndreas Gohr        // resolve the alias or table name
25315929be2SAndreas Gohr        list($table, $colname) = explode('.', $colname, 2);
25415929be2SAndreas Gohr        if(!$colname) {
25515929be2SAndreas Gohr            $colname = $table;
25615929be2SAndreas Gohr            $table = '';
25715929be2SAndreas Gohr        }
25815929be2SAndreas Gohr        if($table && isset($this->aliases[$table])) {
25915929be2SAndreas Gohr            $table = $this->aliases[$table];
26015929be2SAndreas Gohr        }
26115929be2SAndreas Gohr
2625511bd5bSAndreas Gohr        if(!$colname) throw new StructException('nocolname');
26315929be2SAndreas Gohr
26415929be2SAndreas Gohr        // if table name given search only that, otherwiese try all for matching column name
26515929be2SAndreas Gohr        if($table) {
26615929be2SAndreas Gohr            $schemas = array($table => $this->schemas[$table]);
26715929be2SAndreas Gohr        } else {
26815929be2SAndreas Gohr            $schemas = $this->schemas;
26915929be2SAndreas Gohr        }
27015929be2SAndreas Gohr
27115929be2SAndreas Gohr        // find it
27215929be2SAndreas Gohr        $col = false;
27315929be2SAndreas Gohr        foreach($schemas as $schema) {
27415929be2SAndreas Gohr            $col = $schema->findColumn($colname);
27515929be2SAndreas Gohr            if($col) break;
27615929be2SAndreas Gohr        }
27715929be2SAndreas Gohr
27815929be2SAndreas Gohr        return $col;
27915929be2SAndreas Gohr    }
28015929be2SAndreas Gohr
28115929be2SAndreas Gohr}
28215929be2SAndreas Gohr
2835511bd5bSAndreas Gohr
284