xref: /plugin/struct/meta/Search.php (revision 0280da9a6b8efd1ff3fdf4a414ef44dde2ee5d87)
115929be2SAndreas Gohr<?php
215929be2SAndreas Gohr
3ba766201SAndreas Gohrnamespace dokuwiki\plugin\struct\meta;
415929be2SAndreas Gohr
5cadfc3ccSAndreas Gohruse dokuwiki\plugin\struct\types\DateTime;
6f107f479SAndreas Gohruse dokuwiki\plugin\struct\types\Decimal;
7ba766201SAndreas Gohruse dokuwiki\plugin\struct\types\Page;
86781c68dSSzymon Olewniczakuse dokuwiki\plugin\struct\types\AutoSummary;
988b58a21SSzymon Olewniczakuse dokuwiki\plugin\struct\types\Text;
102e12ac22SMichael Grosseuse dokuwiki\plugin\struct\types\User;
110561158fSAndreas Gohr
1261356325SAnna Dabrowskaclass Search
1361356325SAnna Dabrowska{
149d7a36f9SAndreas Gohr    /**
159d7a36f9SAndreas Gohr     * This separator will be used to concat multi values to flatten them in the result set
169d7a36f9SAndreas Gohr     */
179d7a36f9SAndreas Gohr    const CONCAT_SEPARATOR = "\n!_-_-_-_-_!\n";
189d7a36f9SAndreas Gohr
195511bd5bSAndreas Gohr    /**
205511bd5bSAndreas Gohr     * The list of known and allowed comparators
212e7595e7SAndreas Gohr     * (order matters)
225511bd5bSAndreas Gohr     */
2361356325SAnna Dabrowska    public static $COMPARATORS = array(
24aaa187abSSzymon Olewniczak        '<=', '>=', '=*', '=', '<', '>', '!=', '!~', '~', ' IN '
255511bd5bSAndreas Gohr    );
265511bd5bSAndreas Gohr
279d7a36f9SAndreas Gohr    /** @var  \helper_plugin_sqlite */
289d7a36f9SAndreas Gohr    protected $sqlite;
2915929be2SAndreas Gohr
3015929be2SAndreas Gohr    /** @var Schema[] list of schemas to query */
3115929be2SAndreas Gohr    protected $schemas = array();
3215929be2SAndreas Gohr
3315929be2SAndreas Gohr    /** @var Column[] list of columns to select */
3415929be2SAndreas Gohr    protected $columns = array();
3515929be2SAndreas Gohr
3615929be2SAndreas Gohr    /** @var array the sorting of the result */
3715929be2SAndreas Gohr    protected $sortby = array();
3815929be2SAndreas Gohr
399d7a36f9SAndreas Gohr    /** @var array the filters */
409d7a36f9SAndreas Gohr    protected $filter = array();
4115929be2SAndreas Gohr
4215929be2SAndreas Gohr    /** @var array list of aliases tables can be referenced by */
4315929be2SAndreas Gohr    protected $aliases = array();
4415929be2SAndreas Gohr
457f9cb794SAndreas Gohr    /** @var  int begin results from here */
467f9cb794SAndreas Gohr    protected $range_begin = 0;
477f9cb794SAndreas Gohr
487f9cb794SAndreas Gohr    /** @var  int end results here */
497f9cb794SAndreas Gohr    protected $range_end = 0;
507f9cb794SAndreas Gohr
517f9cb794SAndreas Gohr    /** @var int the number of results */
527f9cb794SAndreas Gohr    protected $count = -1;
53d4b5a17cSAndreas Gohr    /** @var  string[] the PIDs of the result rows */
54d4b5a17cSAndreas Gohr    protected $result_pids = null;
550ceefd5cSAnna Dabrowska    /** @var  array the row ids of the result rows */
560ceefd5cSAnna Dabrowska    protected $result_rids = [];
576fd73b4bSAnna Dabrowska    /** @var  array the revisions of the result rows */
586fd73b4bSAnna Dabrowska    protected $result_revs = [];
597f9cb794SAndreas Gohr
6015929be2SAndreas Gohr    /**
619d7a36f9SAndreas Gohr     * Search constructor.
629d7a36f9SAndreas Gohr     */
6361356325SAnna Dabrowska    public function __construct()
6461356325SAnna Dabrowska    {
659d7a36f9SAndreas Gohr        /** @var \helper_plugin_struct_db $plugin */
669d7a36f9SAndreas Gohr        $plugin = plugin_load('helper', 'struct_db');
679d7a36f9SAndreas Gohr        $this->sqlite = $plugin->getDB();
689d7a36f9SAndreas Gohr    }
699d7a36f9SAndreas Gohr
709d7a36f9SAndreas Gohr    /**
7115929be2SAndreas Gohr     * Add a schema to be searched
7215929be2SAndreas Gohr     *
7315929be2SAndreas Gohr     * Call multiple times for multiple schemas.
7415929be2SAndreas Gohr     *
7515929be2SAndreas Gohr     * @param string $table
7615929be2SAndreas Gohr     * @param string $alias
7715929be2SAndreas Gohr     */
7861356325SAnna Dabrowska    public function addSchema($table, $alias = '')
7961356325SAnna Dabrowska    {
802be187cdSAndreas Gohr        $schema = new Schema($table);
812be187cdSAndreas Gohr        if (!$schema->getId()) {
822be187cdSAndreas Gohr            throw new StructException('schema missing', $table);
832be187cdSAndreas Gohr        }
842be187cdSAndreas Gohr
85712c650dSAndreas Gohr        $this->schemas[$schema->getTable()] = $schema;
86712c650dSAndreas Gohr        if ($alias) $this->aliases[$alias] = $schema->getTable();
8715929be2SAndreas Gohr    }
8815929be2SAndreas Gohr
8915929be2SAndreas Gohr    /**
9015929be2SAndreas Gohr     * Add a column to be returned by the search
9115929be2SAndreas Gohr     *
9215929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
9315929be2SAndreas Gohr     * added before
9415929be2SAndreas Gohr     *
9515929be2SAndreas Gohr     * @param string $colname may contain an alias
9615929be2SAndreas Gohr     */
9761356325SAnna Dabrowska    public function addColumn($colname)
9861356325SAnna Dabrowska    {
99577b462bSAndreas Gohr        if ($this->processWildcard($colname)) return; // wildcard?
10015929be2SAndreas Gohr        $col = $this->findColumn($colname);
10115929be2SAndreas Gohr        if (!$col) return; //FIXME do we really want to ignore missing columns?
10215929be2SAndreas Gohr        $this->columns[] = $col;
10315929be2SAndreas Gohr    }
10415929be2SAndreas Gohr
10515929be2SAndreas Gohr    /**
10615929be2SAndreas Gohr     * Add sorting options
10715929be2SAndreas Gohr     *
10815929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
10915929be2SAndreas Gohr     * added before
11015929be2SAndreas Gohr     *
11115929be2SAndreas Gohr     * @param string $colname may contain an alias
11215929be2SAndreas Gohr     * @param bool $asc sort direction (ASC = true, DESC = false)
113eb55dc17SAndreas Gohr     * @param bool $nc set true for caseinsensitivity
11415929be2SAndreas Gohr     */
11561356325SAnna Dabrowska    public function addSort($colname, $asc = true, $nc = true)
11661356325SAnna Dabrowska    {
11715929be2SAndreas Gohr        $col = $this->findColumn($colname);
11815929be2SAndreas Gohr        if (!$col) return; //FIXME do we really want to ignore missing columns?
11915929be2SAndreas Gohr
120eb55dc17SAndreas Gohr        $this->sortby[$col->getFullQualifiedLabel()] = array($col, $asc, $nc);
12107993756SAndreas Gohr    }
12207993756SAndreas Gohr
12307993756SAndreas Gohr    /**
12407993756SAndreas Gohr     * Returns all set sort columns
12507993756SAndreas Gohr     *
12607993756SAndreas Gohr     * @return array
12707993756SAndreas Gohr     */
12861356325SAnna Dabrowska    public function getSorts()
12961356325SAnna Dabrowska    {
13007993756SAndreas Gohr        return $this->sortby;
13115929be2SAndreas Gohr    }
13215929be2SAndreas Gohr
13315929be2SAndreas Gohr    /**
1349d7a36f9SAndreas Gohr     * Adds a filter
13515929be2SAndreas Gohr     *
13615929be2SAndreas Gohr     * @param string $colname may contain an alias
13753528ecfSAndreas Gohr     * @param string|string[] $value
1385511bd5bSAndreas Gohr     * @param string $comp @see self::COMPARATORS
1394c13ff97SAndreas Gohr     * @param string $op either 'OR' or 'AND'
14015929be2SAndreas Gohr     */
14161356325SAnna Dabrowska    public function addFilter($colname, $value, $comp, $op = 'OR')
14261356325SAnna Dabrowska    {
1439dbc32aeSAndreas Gohr        /* Convert certain filters into others
1449dbc32aeSAndreas Gohr         * this reduces the number of supported filters to implement in types */
1459dbc32aeSAndreas Gohr        if ($comp == '*~') {
14653528ecfSAndreas Gohr            $value = $this->filterWrapAsterisks($value);
1479dbc32aeSAndreas Gohr            $comp = '~';
1489dbc32aeSAndreas Gohr        } elseif ($comp == '<>') {
1499dbc32aeSAndreas Gohr            $comp = '!=';
1509dbc32aeSAndreas Gohr        }
1519dbc32aeSAndreas Gohr
15274461852SAndreas Gohr        if (!in_array($comp, self::$COMPARATORS)) throw new StructException("Bad comperator. Use " . join(',', self::$COMPARATORS));
1534c13ff97SAndreas Gohr        if ($op != 'OR' && $op != 'AND') throw new StructException('Bad filter type . Only AND or OR allowed');
1549d7a36f9SAndreas Gohr
15515929be2SAndreas Gohr        $col = $this->findColumn($colname);
1567da1a0fdSAndreas Gohr        if (!$col) return; // ignore missing columns, filter might have been for different schema
1577da1a0fdSAndreas Gohr
1587da1a0fdSAndreas Gohr        // map filter operators to SQL syntax
1597da1a0fdSAndreas Gohr        switch ($comp) {
1607da1a0fdSAndreas Gohr            case '~':
1617da1a0fdSAndreas Gohr                $comp = 'LIKE';
1627da1a0fdSAndreas Gohr                break;
1637da1a0fdSAndreas Gohr            case '!~':
1647da1a0fdSAndreas Gohr                $comp = 'NOT LIKE';
1657da1a0fdSAndreas Gohr                break;
1667da1a0fdSAndreas Gohr            case '=*':
1677da1a0fdSAndreas Gohr                $comp = 'REGEXP';
1687da1a0fdSAndreas Gohr                break;
1697da1a0fdSAndreas Gohr        }
1707da1a0fdSAndreas Gohr
1717da1a0fdSAndreas Gohr        // we use asterisks, but SQL wants percents
1727da1a0fdSAndreas Gohr        if ($comp == 'LIKE' || $comp == 'NOT LIKE') {
17353528ecfSAndreas Gohr            $value = $this->filterChangeToLike($value);
1747da1a0fdSAndreas Gohr        }
1757da1a0fdSAndreas Gohr
176aaa187abSSzymon Olewniczak        if ($comp == ' IN ' && !is_array($value)) {
177efff5841SSzymon Olewniczak            $value = $this->parseFilterValueList($value);
178aaa187abSSzymon Olewniczak            //col IN ('a', 'b', 'c') is equal to col = 'a' OR 'col = 'b' OR col = 'c'
179aaa187abSSzymon Olewniczak            $comp = '=';
180aaa187abSSzymon Olewniczak        }
181aaa187abSSzymon Olewniczak
1827da1a0fdSAndreas Gohr        // add the filter
1834c13ff97SAndreas Gohr        $this->filter[] = array($col, $value, $comp, $op);
18415929be2SAndreas Gohr    }
18515929be2SAndreas Gohr
18615929be2SAndreas Gohr    /**
187aaa187abSSzymon Olewniczak     * Parse SQLite row value into array
188aaa187abSSzymon Olewniczak     *
189aaa187abSSzymon Olewniczak     * @param string $value
190aaa187abSSzymon Olewniczak     * @return string[]
191aaa187abSSzymon Olewniczak     */
19261356325SAnna Dabrowska    protected function parseFilterValueList($value)
19361356325SAnna Dabrowska    {
194efff5841SSzymon Olewniczak        $Handler = new FilterValueListHandler();
195670a6894SAnna Dabrowska        $LexerClass = class_exists('\Doku_Lexer') ? '\Doku_Lexer' : '\dokuwiki\Parsing\Lexer\Lexer';
196670a6894SAnna Dabrowska        $isLegacy = $LexerClass === '\Doku_Lexer';
197670a6894SAnna Dabrowska        /** @var \Doku_Lexer|\dokuwiki\Parsing\Lexer\Lexer $Lexer */
198670a6894SAnna Dabrowska        $Lexer = new $LexerClass($Handler, 'base', true);
199670a6894SAnna Dabrowska
200aaa187abSSzymon Olewniczak
201aaa187abSSzymon Olewniczak        $Lexer->addEntryPattern('\(', 'base', 'row');
202aaa187abSSzymon Olewniczak        $Lexer->addPattern('\s*,\s*', 'row');
203aaa187abSSzymon Olewniczak        $Lexer->addExitPattern('\)', 'row');
204aaa187abSSzymon Olewniczak
205aaa187abSSzymon Olewniczak        $Lexer->addEntryPattern('"', 'row', 'double_quote_string');
206dfe3ae67SAnna Dabrowska        $Lexer->addSpecialPattern('\\\\"', 'double_quote_string', 'escapeSequence');
207aaa187abSSzymon Olewniczak        $Lexer->addExitPattern('"', 'double_quote_string');
208aaa187abSSzymon Olewniczak
209dfe3ae67SAnna Dabrowska        $Lexer->addEntryPattern("'", 'row', 'singleQuoteString');
210dfe3ae67SAnna Dabrowska        $Lexer->addSpecialPattern("\\\\'", 'singleQuoteString', 'escapeSequence');
211dfe3ae67SAnna Dabrowska        $Lexer->addExitPattern("'", 'singleQuoteString');
212aaa187abSSzymon Olewniczak
213dfe3ae67SAnna Dabrowska        $Lexer->mapHandler('double_quote_string', 'singleQuoteString');
214aaa187abSSzymon Olewniczak
215aaa187abSSzymon Olewniczak        $Lexer->addSpecialPattern('[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?', 'row', 'number');
216aaa187abSSzymon Olewniczak
217aaa187abSSzymon Olewniczak        $res = $Lexer->parse($value);
218aaa187abSSzymon Olewniczak
219670a6894SAnna Dabrowska        $currentMode = $isLegacy ? $Lexer->_mode->getCurrent() : $Lexer->getModeStack()->getCurrent();
220670a6894SAnna Dabrowska        if (!$res || $currentMode != 'base') {
221aaa187abSSzymon Olewniczak            throw new StructException('invalid row value syntax');
222aaa187abSSzymon Olewniczak        }
223aaa187abSSzymon Olewniczak
224dfe3ae67SAnna Dabrowska        return $Handler->getRow();
225aaa187abSSzymon Olewniczak    }
226aaa187abSSzymon Olewniczak
227aaa187abSSzymon Olewniczak    /**
22853528ecfSAndreas Gohr     * Wrap given value in asterisks
22953528ecfSAndreas Gohr     *
23053528ecfSAndreas Gohr     * @param string|string[] $value
23153528ecfSAndreas Gohr     * @return string|string[]
23253528ecfSAndreas Gohr     */
23361356325SAnna Dabrowska    protected function filterWrapAsterisks($value)
23461356325SAnna Dabrowska    {
23553528ecfSAndreas Gohr        $map = function ($input) {
23653528ecfSAndreas Gohr            return "*$input*";
23753528ecfSAndreas Gohr        };
23853528ecfSAndreas Gohr
23953528ecfSAndreas Gohr        if (is_array($value)) {
24053528ecfSAndreas Gohr            $value = array_map($map, $value);
24153528ecfSAndreas Gohr        } else {
24253528ecfSAndreas Gohr            $value = $map($value);
24353528ecfSAndreas Gohr        }
24453528ecfSAndreas Gohr        return $value;
24553528ecfSAndreas Gohr    }
24653528ecfSAndreas Gohr
24753528ecfSAndreas Gohr    /**
24853528ecfSAndreas Gohr     * Change given string to use % instead of *
24953528ecfSAndreas Gohr     *
25053528ecfSAndreas Gohr     * @param string|string[] $value
25153528ecfSAndreas Gohr     * @return string|string[]
25253528ecfSAndreas Gohr     */
25361356325SAnna Dabrowska    protected function filterChangeToLike($value)
25461356325SAnna Dabrowska    {
25553528ecfSAndreas Gohr        $map = function ($input) {
25653528ecfSAndreas Gohr            return str_replace('*', '%', $input);
25753528ecfSAndreas Gohr        };
25853528ecfSAndreas Gohr
25953528ecfSAndreas Gohr        if (is_array($value)) {
26053528ecfSAndreas Gohr            $value = array_map($map, $value);
26153528ecfSAndreas Gohr        } else {
26253528ecfSAndreas Gohr            $value = $map($value);
26353528ecfSAndreas Gohr        }
26453528ecfSAndreas Gohr        return $value;
26553528ecfSAndreas Gohr    }
26653528ecfSAndreas Gohr
26753528ecfSAndreas Gohr    /**
2687f9cb794SAndreas Gohr     * Set offset for the results
2697f9cb794SAndreas Gohr     *
2707f9cb794SAndreas Gohr     * @param int $offset
2717f9cb794SAndreas Gohr     */
27261356325SAnna Dabrowska    public function setOffset($offset)
27361356325SAnna Dabrowska    {
2747f9cb794SAndreas Gohr        $limit = 0;
2757f9cb794SAndreas Gohr        if ($this->range_end) {
2767f9cb794SAndreas Gohr            // if there was a limit set previously, the range_end needs to be recalculated
2777f9cb794SAndreas Gohr            $limit = $this->range_end - $this->range_begin;
2787f9cb794SAndreas Gohr        }
2797f9cb794SAndreas Gohr        $this->range_begin = $offset;
2807f9cb794SAndreas Gohr        if ($limit) $this->setLimit($limit);
2817f9cb794SAndreas Gohr    }
2827f9cb794SAndreas Gohr
2837f9cb794SAndreas Gohr    /**
2847f9cb794SAndreas Gohr     * Limit results to this number
2857f9cb794SAndreas Gohr     *
2867f9cb794SAndreas Gohr     * @param int $limit Set to 0 to disable limit again
2877f9cb794SAndreas Gohr     */
28861356325SAnna Dabrowska    public function setLimit($limit)
28961356325SAnna Dabrowska    {
2907f9cb794SAndreas Gohr        if ($limit) {
2917f9cb794SAndreas Gohr            $this->range_end = $this->range_begin + $limit;
2927f9cb794SAndreas Gohr        } else {
2937f9cb794SAndreas Gohr            $this->range_end = 0;
2947f9cb794SAndreas Gohr        }
2957f9cb794SAndreas Gohr    }
2967f9cb794SAndreas Gohr
2977f9cb794SAndreas Gohr    /**
2987f9cb794SAndreas Gohr     * Return the number of results (regardless of limit and offset settings)
2997f9cb794SAndreas Gohr     *
3007f9cb794SAndreas Gohr     * Use this to implement paging. Important: this may only be called after running @see execute()
3017f9cb794SAndreas Gohr     *
3027f9cb794SAndreas Gohr     * @return int
3037f9cb794SAndreas Gohr     */
30461356325SAnna Dabrowska    public function getCount()
30561356325SAnna Dabrowska    {
3067f9cb794SAndreas Gohr        if ($this->count < 0) throw new StructException('Count is only accessible after executing the search');
3077f9cb794SAndreas Gohr        return $this->count;
3087f9cb794SAndreas Gohr    }
3097f9cb794SAndreas Gohr
310c46f5fb1SAndreas Gohr    /**
311c46f5fb1SAndreas Gohr     * Returns the PID associated with each result row
312c46f5fb1SAndreas Gohr     *
313c46f5fb1SAndreas Gohr     * Important: this may only be called after running @see execute()
314c46f5fb1SAndreas Gohr     *
315c46f5fb1SAndreas Gohr     * @return \string[]
316c46f5fb1SAndreas Gohr     */
31761356325SAnna Dabrowska    public function getPids()
31861356325SAnna Dabrowska    {
319d4b5a17cSAndreas Gohr        if ($this->result_pids === null) throw new StructException('PIDs are only accessible after executing the search');
320d4b5a17cSAndreas Gohr        return $this->result_pids;
321d4b5a17cSAndreas Gohr    }
322d4b5a17cSAndreas Gohr
3237f9cb794SAndreas Gohr    /**
3240ceefd5cSAnna Dabrowska     * Returns the rid associated with each result row
3250ceefd5cSAnna Dabrowska     *
3260ceefd5cSAnna Dabrowska     * Important: this may only be called after running @see execute()
3270ceefd5cSAnna Dabrowska     *
3280ceefd5cSAnna Dabrowska     * @return array
3290ceefd5cSAnna Dabrowska     */
33061356325SAnna Dabrowska    public function getRids()
33161356325SAnna Dabrowska    {
3320ceefd5cSAnna Dabrowska        if ($this->result_rids === null) throw new StructException('rids are only accessible after executing the search');
3330ceefd5cSAnna Dabrowska        return $this->result_rids;
3340ceefd5cSAnna Dabrowska    }
3350ceefd5cSAnna Dabrowska
3360ceefd5cSAnna Dabrowska    /**
3376fd73b4bSAnna Dabrowska     * Returns the rid associated with each result row
3386fd73b4bSAnna Dabrowska     *
3396fd73b4bSAnna Dabrowska     * Important: this may only be called after running @see execute()
3406fd73b4bSAnna Dabrowska     *
3416fd73b4bSAnna Dabrowska     * @return array
3426fd73b4bSAnna Dabrowska     */
34361356325SAnna Dabrowska    public function getRevs()
34461356325SAnna Dabrowska    {
3456fd73b4bSAnna Dabrowska        if ($this->result_revs === null) throw new StructException('revs are only accessible after executing the search');
3466fd73b4bSAnna Dabrowska        return $this->result_revs;
3476fd73b4bSAnna Dabrowska    }
3486fd73b4bSAnna Dabrowska
3496fd73b4bSAnna Dabrowska    /**
350b2ed727aSAndreas Gohr     * Execute this search and return the result
351b2ed727aSAndreas Gohr     *
35238fa36fbSAndreas Gohr     * The result is a two dimensional array of Value()s.
3537f9cb794SAndreas Gohr     *
3547f9cb794SAndreas Gohr     * This will always query for the full result (not using offset and limit) and then
3557f9cb794SAndreas Gohr     * return the wanted range, setting the count (@see getCount) to the whole result number
35638fa36fbSAndreas Gohr     *
35738fa36fbSAndreas Gohr     * @return Value[][]
358b2ed727aSAndreas Gohr     */
3598ce43f5aSAnna Dabrowska    public function execute()
36061356325SAnna Dabrowska    {
3618ce43f5aSAnna Dabrowska        list($sql, $opts) = $this->getSQL();
362b2ed727aSAndreas Gohr
3637f9cb794SAndreas Gohr        /** @var \PDOStatement $res */
364b2ed727aSAndreas Gohr        $res = $this->sqlite->query($sql, $opts);
36559b668aaSAndreas Gohr        if ($res === false) throw new StructException("SQL execution failed for\n\n$sql");
366b2ed727aSAndreas Gohr
367d4b5a17cSAndreas Gohr        $this->result_pids = array();
368b2ed727aSAndreas Gohr        $result = array();
3697f9cb794SAndreas Gohr        $cursor = -1;
3705e4bfdb0SMichael Grosse        $pageidAndRevOnly = array_reduce($this->columns, function ($pageidAndRevOnly, Column $col) {
3715e4bfdb0SMichael Grosse            return $pageidAndRevOnly && ($col->getTid() == 0);
3725e4bfdb0SMichael Grosse        }, true);
3737f9cb794SAndreas Gohr        while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
3747f9cb794SAndreas Gohr            $cursor++;
3757f9cb794SAndreas Gohr            if ($cursor < $this->range_begin) continue;
3767f9cb794SAndreas Gohr            if ($this->range_end && $cursor >= $this->range_end) continue;
3777f9cb794SAndreas Gohr
378b2ed727aSAndreas Gohr            $C = 0;
379b2ed727aSAndreas Gohr            $resrow = array();
38099a70f28SAndreas Gohr            $isempty = true;
381b2ed727aSAndreas Gohr            foreach ($this->columns as $col) {
38238fa36fbSAndreas Gohr                $val = $row["C$C"];
383b2ed727aSAndreas Gohr                if ($col->isMulti()) {
38438fa36fbSAndreas Gohr                    $val = explode(self::CONCAT_SEPARATOR, $val);
385b2ed727aSAndreas Gohr                }
38699a70f28SAndreas Gohr                $value = new Value($col, $val);
3878cba7aa0SMichael Grosse                $isempty &= $this->isEmptyValue($value);
38899a70f28SAndreas Gohr                $resrow[] = $value;
389b2ed727aSAndreas Gohr                $C++;
390b2ed727aSAndreas Gohr            }
39199a70f28SAndreas Gohr
39299a70f28SAndreas Gohr            // skip empty rows
3938cba7aa0SMichael Grosse            if ($isempty && !$pageidAndRevOnly) {
39499a70f28SAndreas Gohr                $cursor--;
39599a70f28SAndreas Gohr                continue;
39699a70f28SAndreas Gohr            }
39799a70f28SAndreas Gohr
39899a70f28SAndreas Gohr            $this->result_pids[] = $row['PID'];
3990ceefd5cSAnna Dabrowska            $this->result_rids[] = $row['rid'];
4006fd73b4bSAnna Dabrowska            $this->result_revs[] = $row['rev'];
401b2ed727aSAndreas Gohr            $result[] = $resrow;
402b2ed727aSAndreas Gohr        }
4037f9cb794SAndreas Gohr
4047f9cb794SAndreas Gohr        $this->sqlite->res_close($res);
4057f9cb794SAndreas Gohr        $this->count = $cursor + 1;
406b2ed727aSAndreas Gohr        return $result;
407b2ed727aSAndreas Gohr    }
408b2ed727aSAndreas Gohr
409b2ed727aSAndreas Gohr    /**
41015929be2SAndreas Gohr     * Transform the set search parameters into a statement
41115929be2SAndreas Gohr     *
412b2ed727aSAndreas Gohr     * @return array ($sql, $opts) The SQL and parameters to execute
41315929be2SAndreas Gohr     */
4148ce43f5aSAnna Dabrowska    public function getSQL()
41561356325SAnna Dabrowska    {
4165511bd5bSAndreas Gohr        if (!$this->columns) throw new StructException('nocolname');
41715929be2SAndreas Gohr
4182f68434dSAndreas Gohr        $QB = new QueryBuilder();
41915929be2SAndreas Gohr
4209d7a36f9SAndreas Gohr        // basic tables
421b2d67e7dSAndreas Gohr        $first_table = '';
4229d7a36f9SAndreas Gohr        foreach ($this->schemas as $schema) {
4232f68434dSAndreas Gohr            $datatable = 'data_' . $schema->getTable();
424b2d67e7dSAndreas Gohr            if ($first_table) {
4259d7a36f9SAndreas Gohr                // follow up tables
4268ce43f5aSAnna Dabrowska                $QB->addLeftJoin($first_table, $datatable, $datatable, "$first_table.pid = $datatable.pid");
4279d7a36f9SAndreas Gohr            } else {
4289d7a36f9SAndreas Gohr                // first table
42913c321dbSAndreas Gohr                $QB->addTable($datatable);
4308ce43f5aSAnna Dabrowska
4318ce43f5aSAnna Dabrowska                // add conditional page clauses if pid has a value
4328ce43f5aSAnna Dabrowska                $subAnd = $QB->filters()->whereSubAnd();
4338ce43f5aSAnna Dabrowska                $subAnd->whereAnd("$datatable.pid = ''");
4348ce43f5aSAnna Dabrowska                $subOr = $subAnd->whereSubOr();
4358ce43f5aSAnna Dabrowska                $subOr->whereAnd("GETACCESSLEVEL($datatable.pid) > 0");
4368ce43f5aSAnna Dabrowska                $subOr->whereAnd("PAGEEXISTS($datatable.pid) = 1");
43754efd03eSAnna Dabrowska                $subOr->whereAnd('(ASSIGNED = 1 OR ASSIGNED IS NULL)');
4388ce43f5aSAnna Dabrowska
4398ce43f5aSAnna Dabrowska                // add conditional schema assignment check
440f183bf6eSAnna Dabrowska                $QB->addLeftJoin(
441f183bf6eSAnna Dabrowska                    $datatable,
442f183bf6eSAnna Dabrowska                    'schema_assignments',
443f183bf6eSAnna Dabrowska                    '',
4448ce43f5aSAnna Dabrowska                    "$datatable.pid != ''
4458ce43f5aSAnna Dabrowska                    AND $datatable.pid = schema_assignments.pid
44638e29673SAnna Dabrowska                    AND schema_assignments.tbl = '{$schema->getTable()}'"
4478ce43f5aSAnna Dabrowska                );
4488ce43f5aSAnna Dabrowska
4490ceefd5cSAnna Dabrowska                $QB->addSelectColumn($datatable, 'rid');
45013c321dbSAndreas Gohr                $QB->addSelectColumn($datatable, 'pid', 'PID');
4516fd73b4bSAnna Dabrowska                $QB->addSelectColumn($datatable, 'rev');
45238e29673SAnna Dabrowska                $QB->addSelectColumn('schema_assignments', 'assigned', 'ASSIGNED');
45313c321dbSAndreas Gohr                $QB->addGroupByColumn($datatable, 'pid');
454e3104939SAnna Dabrowska                $QB->addGroupByColumn($datatable, 'rid');
455b2d67e7dSAndreas Gohr
4562f68434dSAndreas Gohr                $first_table = $datatable;
45715929be2SAndreas Gohr            }
4582f68434dSAndreas Gohr            $QB->filters()->whereAnd("$datatable.latest = 1");
4599d7a36f9SAndreas Gohr        }
46015929be2SAndreas Gohr
46115929be2SAndreas Gohr        // columns to select, handling multis
4629d7a36f9SAndreas Gohr        $sep = self::CONCAT_SEPARATOR;
46315929be2SAndreas Gohr        $n = 0;
46415929be2SAndreas Gohr        foreach ($this->columns as $col) {
46515929be2SAndreas Gohr            $CN = 'C' . $n++;
46615929be2SAndreas Gohr
467d1b04e89SAndreas Gohr            if ($col->isMulti()) {
4682f68434dSAndreas Gohr                $datatable = "data_{$col->getTable()}";
4692f68434dSAndreas Gohr                $multitable = "multi_{$col->getTable()}";
470db7970caSAndreas Gohr                $MN = $QB->generateTableAlias('M');
4712f68434dSAndreas Gohr
4722f68434dSAndreas Gohr                $QB->addLeftJoin(
4732f68434dSAndreas Gohr                    $datatable,
4742f68434dSAndreas Gohr                    $multitable,
4752f68434dSAndreas Gohr                    $MN,
4768ce43f5aSAnna Dabrowska                    "$datatable.pid = $MN.pid AND $datatable.rid = $MN.rid AND
4772f68434dSAndreas Gohr                     $datatable.rev = $MN.rev AND
4782f68434dSAndreas Gohr                     $MN.colref = {$col->getColref()}"
4792f68434dSAndreas Gohr                );
480578407b2SAndreas Gohr
481578407b2SAndreas Gohr                $col->getType()->select($QB, $MN, 'value', $CN);
482578407b2SAndreas Gohr                $sel = $QB->getSelectStatement($CN);
483578407b2SAndreas Gohr                $QB->addSelectStatement("GROUP_CONCAT($sel, '$sep')", $CN);
48415929be2SAndreas Gohr            } else {
485578407b2SAndreas Gohr                $col->getType()->select($QB, 'data_' . $col->getTable(), $col->getColName(), $CN);
4860dbe7bf6SAndreas Gohr                $QB->addGroupByStatement($CN);
48715929be2SAndreas Gohr            }
48815929be2SAndreas Gohr        }
48915929be2SAndreas Gohr
4909d7a36f9SAndreas Gohr        // where clauses
491af993d55SMichael Grosse        if (!empty($this->filter)) {
492af993d55SMichael Grosse            $userWHERE = $QB->filters()->where('AND');
493af993d55SMichael Grosse        }
494b8fe6730SAndreas Gohr        foreach ($this->filter as $filter) {
4959ebd2ed6SAndreas Gohr            /** @var Column $col */
4964c13ff97SAndreas Gohr            list($col, $value, $comp, $op) = $filter;
497b8fe6730SAndreas Gohr
4982f68434dSAndreas Gohr            $datatable = "data_{$col->getTable()}";
4992f68434dSAndreas Gohr            $multitable = "multi_{$col->getTable()}";
5009d7a36f9SAndreas Gohr
5019d7a36f9SAndreas Gohr            /** @var $col Column */
5029d7a36f9SAndreas Gohr            if ($col->isMulti()) {
503db7970caSAndreas Gohr                $MN = $QB->generateTableAlias('MN');
50415929be2SAndreas Gohr
5052f68434dSAndreas Gohr                $QB->addLeftJoin(
5062f68434dSAndreas Gohr                    $datatable,
5072f68434dSAndreas Gohr                    $multitable,
5082f68434dSAndreas Gohr                    $MN,
5098ce43f5aSAnna Dabrowska                    "$datatable.pid = $MN.pid AND $datatable.rid = $MN.rid AND
5102f68434dSAndreas Gohr                     $datatable.rev = $MN.rev AND
5112f68434dSAndreas Gohr                     $MN.colref = {$col->getColref()}"
5122f68434dSAndreas Gohr                );
513690e4ebaSAndreas Gohr                $coltbl = $MN;
514690e4ebaSAndreas Gohr                $colnam = 'value';
5159d7a36f9SAndreas Gohr            } else {
516690e4ebaSAndreas Gohr                $coltbl = $datatable;
517690e4ebaSAndreas Gohr                $colnam = $col->getColName();
5189d7a36f9SAndreas Gohr            }
51953528ecfSAndreas Gohr
520af993d55SMichael Grosse            $col->getType()->filter($userWHERE, $coltbl, $colnam, $comp, $value, $op); // type based filter
5219d7a36f9SAndreas Gohr        }
5229d7a36f9SAndreas Gohr
52329394e6cSAndreas Gohr        // sorting - we always sort by the single val column
524b8fe6730SAndreas Gohr        foreach ($this->sortby as $sort) {
525eb55dc17SAndreas Gohr            list($col, $asc, $nc) = $sort;
5269d7a36f9SAndreas Gohr            /** @var $col Column */
527eb55dc17SAndreas Gohr            $colname = $col->getColName(false);
528eb55dc17SAndreas Gohr            if ($nc) $colname .= ' COLLATE NOCASE';
529eb55dc17SAndreas Gohr            $col->getType()->sort($QB, 'data_' . $col->getTable(), $colname, $asc ? 'ASC' : 'DESC');
5309e07bdbfSAndreas Gohr        }
5319e07bdbfSAndreas Gohr
5322f68434dSAndreas Gohr        return $QB->getSQL();
53315929be2SAndreas Gohr    }
53415929be2SAndreas Gohr
53515929be2SAndreas Gohr    /**
53601dd90deSAndreas Gohr     * Returns all the columns that where added to the search
53701dd90deSAndreas Gohr     *
53801dd90deSAndreas Gohr     * @return Column[]
53901dd90deSAndreas Gohr     */
54061356325SAnna Dabrowska    public function getColumns()
54161356325SAnna Dabrowska    {
54201dd90deSAndreas Gohr        return $this->columns;
54301dd90deSAndreas Gohr    }
54401dd90deSAndreas Gohr
545577b462bSAndreas Gohr    /**
5465a4df70dSAndreas Gohr     * All the schemas currently added
5475a4df70dSAndreas Gohr     *
5485a4df70dSAndreas Gohr     * @return Schema[]
5495a4df70dSAndreas Gohr     */
55061356325SAnna Dabrowska    public function getSchemas()
55161356325SAnna Dabrowska    {
5525a4df70dSAndreas Gohr        return array_values($this->schemas);
5535a4df70dSAndreas Gohr    }
5545a4df70dSAndreas Gohr
5555a4df70dSAndreas Gohr    /**
556577b462bSAndreas Gohr     * Checks if the given column is a * wildcard
557577b462bSAndreas Gohr     *
558577b462bSAndreas Gohr     * If it's a wildcard all matching columns are added to the column list, otherwise
559577b462bSAndreas Gohr     * nothing happens
560577b462bSAndreas Gohr     *
561577b462bSAndreas Gohr     * @param string $colname
562577b462bSAndreas Gohr     * @return bool was wildcard?
563577b462bSAndreas Gohr     */
56461356325SAnna Dabrowska    protected function processWildcard($colname)
56561356325SAnna Dabrowska    {
566636a5173SAndreas Gohr        list($colname, $table) = $this->resolveColumn($colname);
567577b462bSAndreas Gohr        if ($colname !== '*') return false;
568577b462bSAndreas Gohr
569577b462bSAndreas Gohr        // no table given? assume the first is meant
570577b462bSAndreas Gohr        if ($table === null) {
571577b462bSAndreas Gohr            $schema_list = array_keys($this->schemas);
572577b462bSAndreas Gohr            $table = $schema_list[0];
573577b462bSAndreas Gohr        }
574577b462bSAndreas Gohr
575577b462bSAndreas Gohr        $schema = $this->schemas[$table];
576577b462bSAndreas Gohr        if (!$schema) return false;
577577b462bSAndreas Gohr        $this->columns = array_merge($this->columns, $schema->getColumns(false));
578577b462bSAndreas Gohr        return true;
579577b462bSAndreas Gohr    }
580577b462bSAndreas Gohr
581577b462bSAndreas Gohr    /**
582577b462bSAndreas Gohr     * Split a given column name into table and column
583577b462bSAndreas Gohr     *
584577b462bSAndreas Gohr     * Handles Aliases. Table might be null if none given.
585577b462bSAndreas Gohr     *
586577b462bSAndreas Gohr     * @param $colname
587636a5173SAndreas Gohr     * @return array (colname, table)
588577b462bSAndreas Gohr     */
58961356325SAnna Dabrowska    protected function resolveColumn($colname)
59061356325SAnna Dabrowska    {
591577b462bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
592577b462bSAndreas Gohr
593577b462bSAndreas Gohr        // resolve the alias or table name
5949007da58SMichael Große        @list($table, $colname) = explode('.', $colname, 2);
595577b462bSAndreas Gohr        if (!$colname) {
596577b462bSAndreas Gohr            $colname = $table;
597577b462bSAndreas Gohr            $table = null;
598577b462bSAndreas Gohr        }
599577b462bSAndreas Gohr        if ($table && isset($this->aliases[$table])) {
600577b462bSAndreas Gohr            $table = $this->aliases[$table];
601577b462bSAndreas Gohr        }
602577b462bSAndreas Gohr
603577b462bSAndreas Gohr        if (!$colname) throw new StructException('nocolname');
604577b462bSAndreas Gohr
605577b462bSAndreas Gohr        return array($colname, $table);
606577b462bSAndreas Gohr    }
60701dd90deSAndreas Gohr
60801dd90deSAndreas Gohr    /**
60915929be2SAndreas Gohr     * Find a column to be used in the search
61015929be2SAndreas Gohr     *
61115929be2SAndreas Gohr     * @param string $colname may contain an alias
61215929be2SAndreas Gohr     * @return bool|Column
61315929be2SAndreas Gohr     */
614*0280da9aSFrieder Schrempf    public function findColumn($colname, $strict = false)
61561356325SAnna Dabrowska    {
6165511bd5bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
617df02ffe6SMichael Große        $schema_list = array_keys($this->schemas);
618f107f479SAndreas Gohr
619f107f479SAndreas Gohr        // add "fake" column for special col
620128d4e83SAndreas Gohr        if ($colname == '%pageid%') {
621128d4e83SAndreas Gohr            return new PageColumn(0, new Page(), $schema_list[0]);
622d1b04e89SAndreas Gohr        }
623128d4e83SAndreas Gohr        if ($colname == '%title%') {
624128d4e83SAndreas Gohr            return new PageColumn(0, new Page(array('usetitles' => true)), $schema_list[0]);
625128d4e83SAndreas Gohr        }
626cadfc3ccSAndreas Gohr        if ($colname == '%lastupdate%') {
627cadfc3ccSAndreas Gohr            return new RevisionColumn(0, new DateTime(), $schema_list[0]);
628cadfc3ccSAndreas Gohr        }
6292e12ac22SMichael Grosse        if ($colname == '%lasteditor%') {
6302e12ac22SMichael Grosse            return new UserColumn(0, new User(), $schema_list[0]);
6312e12ac22SMichael Grosse        }
63288b58a21SSzymon Olewniczak        if ($colname == '%lastsummary%') {
6336781c68dSSzymon Olewniczak            return new SummaryColumn(0, new AutoSummary(), $schema_list[0]);
63488b58a21SSzymon Olewniczak        }
635f107f479SAndreas Gohr        if ($colname == '%rowid%') {
636f107f479SAndreas Gohr            return new RowColumn(0, new Decimal(), $schema_list[0]);
637f107f479SAndreas Gohr        }
638d1b04e89SAndreas Gohr
639636a5173SAndreas Gohr        list($colname, $table) = $this->resolveColumn($colname);
64015929be2SAndreas Gohr
641*0280da9aSFrieder Schrempf        /*
642*0280da9aSFrieder Schrempf         * If table name is given search only that, otherwise if no strict behavior
643*0280da9aSFrieder Schrempf         * is requested by the caller, try all assigned schemas for matching the
644*0280da9aSFrieder Schrempf         * column name.
645*0280da9aSFrieder Schrempf         */
64634ea6e10SAnna Dabrowska        if ($table !== null && isset($this->schemas[$table])) {
64715929be2SAndreas Gohr            $schemas = array($table => $this->schemas[$table]);
648*0280da9aSFrieder Schrempf        } else if ($table === null || !$strict) {
64915929be2SAndreas Gohr            $schemas = $this->schemas;
650*0280da9aSFrieder Schrempf        } else {
651*0280da9aSFrieder Schrempf            return false;
65215929be2SAndreas Gohr        }
65315929be2SAndreas Gohr
65415929be2SAndreas Gohr        // find it
65515929be2SAndreas Gohr        $col = false;
65615929be2SAndreas Gohr        foreach ($schemas as $schema) {
6574ac44d1cSMichael Grosse            if (empty($schema)) {
6584ac44d1cSMichael Grosse                continue;
6594ac44d1cSMichael Grosse            }
66015929be2SAndreas Gohr            $col = $schema->findColumn($colname);
66115929be2SAndreas Gohr            if ($col) break;
66215929be2SAndreas Gohr        }
66315929be2SAndreas Gohr
66415929be2SAndreas Gohr        return $col;
66515929be2SAndreas Gohr    }
66615929be2SAndreas Gohr
6679dbc8ec0SMichael Grosse    /**
66899a70f28SAndreas Gohr     * Check if the given row is empty or references our own row
6699dbc8ec0SMichael Grosse     *
67099a70f28SAndreas Gohr     * @param Value $value
6719dbc8ec0SMichael Grosse     * @return bool
6729dbc8ec0SMichael Grosse     */
67361356325SAnna Dabrowska    protected function isEmptyValue(Value $value)
67461356325SAnna Dabrowska    {
67599a70f28SAndreas Gohr        if ($value->isEmpty()) return true;
6768cba7aa0SMichael Grosse        if ($value->getColumn()->getTid() == 0) return true;
6779dbc8ec0SMichael Grosse        return false;
6789dbc8ec0SMichael Grosse    }
67915929be2SAndreas Gohr}
680