xref: /plugin/struct/meta/Search.php (revision da62ec9ce14a5d1d6c3f7b01481bc0e431a087e0)
115929be2SAndreas Gohr<?php
215929be2SAndreas Gohr
3ba766201SAndreas Gohrnamespace dokuwiki\plugin\struct\meta;
415929be2SAndreas Gohr
50549dcc5SAndreas Gohruse dokuwiki\plugin\struct\types\AutoSummary;
6cadfc3ccSAndreas Gohruse dokuwiki\plugin\struct\types\DateTime;
7f107f479SAndreas Gohruse dokuwiki\plugin\struct\types\Decimal;
8ba766201SAndreas Gohruse dokuwiki\plugin\struct\types\Page;
92e12ac22SMichael Grosseuse dokuwiki\plugin\struct\types\User;
100561158fSAndreas Gohr
1161356325SAnna Dabrowskaclass Search
1261356325SAnna Dabrowska{
139d7a36f9SAndreas Gohr    /**
149d7a36f9SAndreas Gohr     * This separator will be used to concat multi values to flatten them in the result set
159d7a36f9SAndreas Gohr     */
1617a3a578SAndreas Gohr    public const CONCAT_SEPARATOR = "\n!_-_-_-_-_!\n";
179d7a36f9SAndreas Gohr
185511bd5bSAndreas Gohr    /**
195511bd5bSAndreas Gohr     * The list of known and allowed comparators
202e7595e7SAndreas Gohr     * (order matters)
215511bd5bSAndreas Gohr     */
2261356325SAnna Dabrowska    public static $COMPARATORS = array(
23aaa187abSSzymon Olewniczak        '<=', '>=', '=*', '=', '<', '>', '!=', '!~', '~', ' IN '
245511bd5bSAndreas Gohr    );
255511bd5bSAndreas Gohr
269d7a36f9SAndreas Gohr    /** @var  \helper_plugin_sqlite */
279d7a36f9SAndreas Gohr    protected $sqlite;
2815929be2SAndreas Gohr
2915929be2SAndreas Gohr    /** @var Schema[] list of schemas to query */
3015929be2SAndreas Gohr    protected $schemas = array();
3115929be2SAndreas Gohr
3215929be2SAndreas Gohr    /** @var Column[] list of columns to select */
3315929be2SAndreas Gohr    protected $columns = array();
3415929be2SAndreas Gohr
3515929be2SAndreas Gohr    /** @var array the sorting of the result */
3615929be2SAndreas Gohr    protected $sortby = array();
3715929be2SAndreas Gohr
389d7a36f9SAndreas Gohr    /** @var array the filters */
399d7a36f9SAndreas Gohr    protected $filter = array();
4015929be2SAndreas Gohr
4115929be2SAndreas Gohr    /** @var array list of aliases tables can be referenced by */
4215929be2SAndreas Gohr    protected $aliases = array();
4315929be2SAndreas Gohr
447f9cb794SAndreas Gohr    /** @var  int begin results from here */
457f9cb794SAndreas Gohr    protected $range_begin = 0;
467f9cb794SAndreas Gohr
477f9cb794SAndreas Gohr    /** @var  int end results here */
487f9cb794SAndreas Gohr    protected $range_end = 0;
497f9cb794SAndreas Gohr
507f9cb794SAndreas Gohr    /** @var int the number of results */
517f9cb794SAndreas Gohr    protected $count = -1;
52d4b5a17cSAndreas Gohr    /** @var  string[] the PIDs of the result rows */
53d4b5a17cSAndreas Gohr    protected $result_pids = null;
540ceefd5cSAnna Dabrowska    /** @var  array the row ids of the result rows */
550ceefd5cSAnna Dabrowska    protected $result_rids = [];
566fd73b4bSAnna Dabrowska    /** @var  array the revisions of the result rows */
576fd73b4bSAnna Dabrowska    protected $result_revs = [];
587f9cb794SAndreas Gohr
5915929be2SAndreas Gohr    /**
609d7a36f9SAndreas Gohr     * Search constructor.
619d7a36f9SAndreas Gohr     */
6261356325SAnna Dabrowska    public function __construct()
6361356325SAnna Dabrowska    {
649d7a36f9SAndreas Gohr        /** @var \helper_plugin_struct_db $plugin */
659d7a36f9SAndreas Gohr        $plugin = plugin_load('helper', 'struct_db');
669d7a36f9SAndreas Gohr        $this->sqlite = $plugin->getDB();
679d7a36f9SAndreas Gohr    }
689d7a36f9SAndreas Gohr
699d7a36f9SAndreas Gohr    /**
7015929be2SAndreas Gohr     * Add a schema to be searched
7115929be2SAndreas Gohr     *
7215929be2SAndreas Gohr     * Call multiple times for multiple schemas.
7315929be2SAndreas Gohr     *
7415929be2SAndreas Gohr     * @param string $table
7515929be2SAndreas Gohr     * @param string $alias
7615929be2SAndreas Gohr     */
7761356325SAnna Dabrowska    public function addSchema($table, $alias = '')
7861356325SAnna Dabrowska    {
792be187cdSAndreas Gohr        $schema = new Schema($table);
802be187cdSAndreas Gohr        if (!$schema->getId()) {
812be187cdSAndreas Gohr            throw new StructException('schema missing', $table);
822be187cdSAndreas Gohr        }
832be187cdSAndreas Gohr
84712c650dSAndreas Gohr        $this->schemas[$schema->getTable()] = $schema;
85712c650dSAndreas Gohr        if ($alias) $this->aliases[$alias] = $schema->getTable();
8615929be2SAndreas Gohr    }
8715929be2SAndreas Gohr
8815929be2SAndreas Gohr    /**
8915929be2SAndreas Gohr     * Add a column to be returned by the search
9015929be2SAndreas Gohr     *
9115929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
9215929be2SAndreas Gohr     * added before
9315929be2SAndreas Gohr     *
9415929be2SAndreas Gohr     * @param string $colname may contain an alias
9515929be2SAndreas Gohr     */
9661356325SAnna Dabrowska    public function addColumn($colname)
9761356325SAnna Dabrowska    {
98577b462bSAndreas Gohr        if ($this->processWildcard($colname)) return; // wildcard?
99b26126edSAndreas Hubel        if ($colname[0] == '-') { // remove column from previous wildcard lookup
100b26126edSAndreas Hubel            $colname = substr($colname, 1);
101b26126edSAndreas Hubel            foreach ($this->columns as $key => $col) {
102b26126edSAndreas Hubel                if ($col->getLabel() == $colname) unset($this->columns[$key]);
103b26126edSAndreas Hubel            }
104b26126edSAndreas Hubel            return;
105b26126edSAndreas Hubel        }
106b26126edSAndreas Hubel
10715929be2SAndreas Gohr        $col = $this->findColumn($colname);
10815929be2SAndreas Gohr        if (!$col) return; //FIXME do we really want to ignore missing columns?
10915929be2SAndreas Gohr        $this->columns[] = $col;
11015929be2SAndreas Gohr    }
11115929be2SAndreas Gohr
11215929be2SAndreas Gohr    /**
11315929be2SAndreas Gohr     * Add sorting options
11415929be2SAndreas Gohr     *
11515929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
11615929be2SAndreas Gohr     * added before
11715929be2SAndreas Gohr     *
11815929be2SAndreas Gohr     * @param string $colname may contain an alias
11915929be2SAndreas Gohr     * @param bool $asc sort direction (ASC = true, DESC = false)
120eb55dc17SAndreas Gohr     * @param bool $nc set true for caseinsensitivity
12115929be2SAndreas Gohr     */
12261356325SAnna Dabrowska    public function addSort($colname, $asc = true, $nc = true)
12361356325SAnna Dabrowska    {
12415929be2SAndreas Gohr        $col = $this->findColumn($colname);
12515929be2SAndreas Gohr        if (!$col) return; //FIXME do we really want to ignore missing columns?
12615929be2SAndreas Gohr
127eb55dc17SAndreas Gohr        $this->sortby[$col->getFullQualifiedLabel()] = array($col, $asc, $nc);
12807993756SAndreas Gohr    }
12907993756SAndreas Gohr
13007993756SAndreas Gohr    /**
13107993756SAndreas Gohr     * Returns all set sort columns
13207993756SAndreas Gohr     *
13307993756SAndreas Gohr     * @return array
13407993756SAndreas Gohr     */
13561356325SAnna Dabrowska    public function getSorts()
13661356325SAnna Dabrowska    {
13707993756SAndreas Gohr        return $this->sortby;
13815929be2SAndreas Gohr    }
13915929be2SAndreas Gohr
14015929be2SAndreas Gohr    /**
1419d7a36f9SAndreas Gohr     * Adds a filter
14215929be2SAndreas Gohr     *
14315929be2SAndreas Gohr     * @param string $colname may contain an alias
14453528ecfSAndreas Gohr     * @param string|string[] $value
1455511bd5bSAndreas Gohr     * @param string $comp @see self::COMPARATORS
1464c13ff97SAndreas Gohr     * @param string $op either 'OR' or 'AND'
14715929be2SAndreas Gohr     */
14861356325SAnna Dabrowska    public function addFilter($colname, $value, $comp, $op = 'OR')
14961356325SAnna Dabrowska    {
1509dbc32aeSAndreas Gohr        /* Convert certain filters into others
1519dbc32aeSAndreas Gohr         * this reduces the number of supported filters to implement in types */
1529dbc32aeSAndreas Gohr        if ($comp == '*~') {
15353528ecfSAndreas Gohr            $value = $this->filterWrapAsterisks($value);
1549dbc32aeSAndreas Gohr            $comp = '~';
1559dbc32aeSAndreas Gohr        } elseif ($comp == '<>') {
1569dbc32aeSAndreas Gohr            $comp = '!=';
1579dbc32aeSAndreas Gohr        }
1589dbc32aeSAndreas Gohr
15917a3a578SAndreas Gohr        if (!in_array($comp, self::$COMPARATORS))
16017a3a578SAndreas Gohr            throw new StructException("Bad comperator. Use " . join(',', self::$COMPARATORS));
16117a3a578SAndreas Gohr        if ($op != 'OR' && $op != 'AND')
16217a3a578SAndreas Gohr            throw new StructException('Bad filter type . Only AND or OR allowed');
1639d7a36f9SAndreas Gohr
16415929be2SAndreas Gohr        $col = $this->findColumn($colname);
1657da1a0fdSAndreas Gohr        if (!$col) return; // ignore missing columns, filter might have been for different schema
1667da1a0fdSAndreas Gohr
1677da1a0fdSAndreas Gohr        // map filter operators to SQL syntax
1687da1a0fdSAndreas Gohr        switch ($comp) {
1697da1a0fdSAndreas Gohr            case '~':
1707da1a0fdSAndreas Gohr                $comp = 'LIKE';
1717da1a0fdSAndreas Gohr                break;
1727da1a0fdSAndreas Gohr            case '!~':
1737da1a0fdSAndreas Gohr                $comp = 'NOT LIKE';
1747da1a0fdSAndreas Gohr                break;
1757da1a0fdSAndreas Gohr            case '=*':
1767da1a0fdSAndreas Gohr                $comp = 'REGEXP';
1777da1a0fdSAndreas Gohr                break;
1787da1a0fdSAndreas Gohr        }
1797da1a0fdSAndreas Gohr
1807da1a0fdSAndreas Gohr        // we use asterisks, but SQL wants percents
1817da1a0fdSAndreas Gohr        if ($comp == 'LIKE' || $comp == 'NOT LIKE') {
18253528ecfSAndreas Gohr            $value = $this->filterChangeToLike($value);
1837da1a0fdSAndreas Gohr        }
1847da1a0fdSAndreas Gohr
185aaa187abSSzymon Olewniczak        if ($comp == ' IN ' && !is_array($value)) {
186efff5841SSzymon Olewniczak            $value = $this->parseFilterValueList($value);
187aaa187abSSzymon Olewniczak            //col IN ('a', 'b', 'c') is equal to col = 'a' OR 'col = 'b' OR col = 'c'
188aaa187abSSzymon Olewniczak            $comp = '=';
189aaa187abSSzymon Olewniczak        }
190aaa187abSSzymon Olewniczak
1917da1a0fdSAndreas Gohr        // add the filter
1924c13ff97SAndreas Gohr        $this->filter[] = array($col, $value, $comp, $op);
19315929be2SAndreas Gohr    }
19415929be2SAndreas Gohr
19515929be2SAndreas Gohr    /**
196aaa187abSSzymon Olewniczak     * Parse SQLite row value into array
197aaa187abSSzymon Olewniczak     *
198aaa187abSSzymon Olewniczak     * @param string $value
199aaa187abSSzymon Olewniczak     * @return string[]
200aaa187abSSzymon Olewniczak     */
20161356325SAnna Dabrowska    protected function parseFilterValueList($value)
20261356325SAnna Dabrowska    {
203efff5841SSzymon Olewniczak        $Handler = new FilterValueListHandler();
204670a6894SAnna Dabrowska        $LexerClass = class_exists('\Doku_Lexer') ? '\Doku_Lexer' : '\dokuwiki\Parsing\Lexer\Lexer';
205670a6894SAnna Dabrowska        $isLegacy = $LexerClass === '\Doku_Lexer';
206670a6894SAnna Dabrowska        /** @var \Doku_Lexer|\dokuwiki\Parsing\Lexer\Lexer $Lexer */
207670a6894SAnna Dabrowska        $Lexer = new $LexerClass($Handler, 'base', true);
208670a6894SAnna Dabrowska
209aaa187abSSzymon Olewniczak
210aaa187abSSzymon Olewniczak        $Lexer->addEntryPattern('\(', 'base', 'row');
211aaa187abSSzymon Olewniczak        $Lexer->addPattern('\s*,\s*', 'row');
212aaa187abSSzymon Olewniczak        $Lexer->addExitPattern('\)', 'row');
213aaa187abSSzymon Olewniczak
214aaa187abSSzymon Olewniczak        $Lexer->addEntryPattern('"', 'row', 'double_quote_string');
215dfe3ae67SAnna Dabrowska        $Lexer->addSpecialPattern('\\\\"', 'double_quote_string', 'escapeSequence');
216aaa187abSSzymon Olewniczak        $Lexer->addExitPattern('"', 'double_quote_string');
217aaa187abSSzymon Olewniczak
218dfe3ae67SAnna Dabrowska        $Lexer->addEntryPattern("'", 'row', 'singleQuoteString');
219dfe3ae67SAnna Dabrowska        $Lexer->addSpecialPattern("\\\\'", 'singleQuoteString', 'escapeSequence');
220dfe3ae67SAnna Dabrowska        $Lexer->addExitPattern("'", 'singleQuoteString');
221aaa187abSSzymon Olewniczak
222dfe3ae67SAnna Dabrowska        $Lexer->mapHandler('double_quote_string', 'singleQuoteString');
223aaa187abSSzymon Olewniczak
224aaa187abSSzymon Olewniczak        $Lexer->addSpecialPattern('[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?', 'row', 'number');
225aaa187abSSzymon Olewniczak
226aaa187abSSzymon Olewniczak        $res = $Lexer->parse($value);
227aaa187abSSzymon Olewniczak
228670a6894SAnna Dabrowska        $currentMode = $isLegacy ? $Lexer->_mode->getCurrent() : $Lexer->getModeStack()->getCurrent();
229670a6894SAnna Dabrowska        if (!$res || $currentMode != 'base') {
230aaa187abSSzymon Olewniczak            throw new StructException('invalid row value syntax');
231aaa187abSSzymon Olewniczak        }
232aaa187abSSzymon Olewniczak
233dfe3ae67SAnna Dabrowska        return $Handler->getRow();
234aaa187abSSzymon Olewniczak    }
235aaa187abSSzymon Olewniczak
236aaa187abSSzymon Olewniczak    /**
23753528ecfSAndreas Gohr     * Wrap given value in asterisks
23853528ecfSAndreas Gohr     *
23953528ecfSAndreas Gohr     * @param string|string[] $value
24053528ecfSAndreas Gohr     * @return string|string[]
24153528ecfSAndreas Gohr     */
24261356325SAnna Dabrowska    protected function filterWrapAsterisks($value)
24361356325SAnna Dabrowska    {
24453528ecfSAndreas Gohr        $map = function ($input) {
24553528ecfSAndreas Gohr            return "*$input*";
24653528ecfSAndreas Gohr        };
24753528ecfSAndreas Gohr
24853528ecfSAndreas Gohr        if (is_array($value)) {
24953528ecfSAndreas Gohr            $value = array_map($map, $value);
25053528ecfSAndreas Gohr        } else {
25153528ecfSAndreas Gohr            $value = $map($value);
25253528ecfSAndreas Gohr        }
25353528ecfSAndreas Gohr        return $value;
25453528ecfSAndreas Gohr    }
25553528ecfSAndreas Gohr
25653528ecfSAndreas Gohr    /**
25753528ecfSAndreas Gohr     * Change given string to use % instead of *
25853528ecfSAndreas Gohr     *
25953528ecfSAndreas Gohr     * @param string|string[] $value
26053528ecfSAndreas Gohr     * @return string|string[]
26153528ecfSAndreas Gohr     */
26261356325SAnna Dabrowska    protected function filterChangeToLike($value)
26361356325SAnna Dabrowska    {
26453528ecfSAndreas Gohr        $map = function ($input) {
26553528ecfSAndreas Gohr            return str_replace('*', '%', $input);
26653528ecfSAndreas Gohr        };
26753528ecfSAndreas Gohr
26853528ecfSAndreas Gohr        if (is_array($value)) {
26953528ecfSAndreas Gohr            $value = array_map($map, $value);
27053528ecfSAndreas Gohr        } else {
27153528ecfSAndreas Gohr            $value = $map($value);
27253528ecfSAndreas Gohr        }
27353528ecfSAndreas Gohr        return $value;
27453528ecfSAndreas Gohr    }
27553528ecfSAndreas Gohr
27653528ecfSAndreas Gohr    /**
2777f9cb794SAndreas Gohr     * Set offset for the results
2787f9cb794SAndreas Gohr     *
2797f9cb794SAndreas Gohr     * @param int $offset
2807f9cb794SAndreas Gohr     */
28161356325SAnna Dabrowska    public function setOffset($offset)
28261356325SAnna Dabrowska    {
2837f9cb794SAndreas Gohr        $limit = 0;
2847f9cb794SAndreas Gohr        if ($this->range_end) {
2857f9cb794SAndreas Gohr            // if there was a limit set previously, the range_end needs to be recalculated
2867f9cb794SAndreas Gohr            $limit = $this->range_end - $this->range_begin;
2877f9cb794SAndreas Gohr        }
2887f9cb794SAndreas Gohr        $this->range_begin = $offset;
2897f9cb794SAndreas Gohr        if ($limit) $this->setLimit($limit);
2907f9cb794SAndreas Gohr    }
2917f9cb794SAndreas Gohr
2927f9cb794SAndreas Gohr    /**
2937f9cb794SAndreas Gohr     * Limit results to this number
2947f9cb794SAndreas Gohr     *
2957f9cb794SAndreas Gohr     * @param int $limit Set to 0 to disable limit again
2967f9cb794SAndreas Gohr     */
29761356325SAnna Dabrowska    public function setLimit($limit)
29861356325SAnna Dabrowska    {
2997f9cb794SAndreas Gohr        if ($limit) {
3007f9cb794SAndreas Gohr            $this->range_end = $this->range_begin + $limit;
3017f9cb794SAndreas Gohr        } else {
3027f9cb794SAndreas Gohr            $this->range_end = 0;
3037f9cb794SAndreas Gohr        }
3047f9cb794SAndreas Gohr    }
3057f9cb794SAndreas Gohr
3067f9cb794SAndreas Gohr    /**
3077f9cb794SAndreas Gohr     * Return the number of results (regardless of limit and offset settings)
3087f9cb794SAndreas Gohr     *
3090549dcc5SAndreas Gohr     * Use this to implement paging. Important: this may only be called after running @return int
3100549dcc5SAndreas Gohr     * @see execute()
3117f9cb794SAndreas Gohr     *
3127f9cb794SAndreas Gohr     */
31361356325SAnna Dabrowska    public function getCount()
31461356325SAnna Dabrowska    {
3157f9cb794SAndreas Gohr        if ($this->count < 0) throw new StructException('Count is only accessible after executing the search');
3167f9cb794SAndreas Gohr        return $this->count;
3177f9cb794SAndreas Gohr    }
3187f9cb794SAndreas Gohr
319c46f5fb1SAndreas Gohr    /**
320c46f5fb1SAndreas Gohr     * Returns the PID associated with each result row
321c46f5fb1SAndreas Gohr     *
3220549dcc5SAndreas Gohr     * Important: this may only be called after running @return \string[]
3230549dcc5SAndreas Gohr     * @see execute()
324c46f5fb1SAndreas Gohr     *
325c46f5fb1SAndreas Gohr     */
32661356325SAnna Dabrowska    public function getPids()
32761356325SAnna Dabrowska    {
32817a3a578SAndreas Gohr        if ($this->result_pids === null)
32917a3a578SAndreas Gohr            throw new StructException('PIDs are only accessible after executing the search');
330d4b5a17cSAndreas Gohr        return $this->result_pids;
331d4b5a17cSAndreas Gohr    }
332d4b5a17cSAndreas Gohr
3337f9cb794SAndreas Gohr    /**
3340ceefd5cSAnna Dabrowska     * Returns the rid associated with each result row
3350ceefd5cSAnna Dabrowska     *
3360549dcc5SAndreas Gohr     * Important: this may only be called after running @return array
3370549dcc5SAndreas Gohr     * @see execute()
3380ceefd5cSAnna Dabrowska     *
3390ceefd5cSAnna Dabrowska     */
34061356325SAnna Dabrowska    public function getRids()
34161356325SAnna Dabrowska    {
34217a3a578SAndreas Gohr        if ($this->result_rids === null)
34317a3a578SAndreas Gohr            throw new StructException('rids are only accessible after executing the search');
3440ceefd5cSAnna Dabrowska        return $this->result_rids;
3450ceefd5cSAnna Dabrowska    }
3460ceefd5cSAnna Dabrowska
3470ceefd5cSAnna Dabrowska    /**
3486fd73b4bSAnna Dabrowska     * Returns the rid associated with each result row
3496fd73b4bSAnna Dabrowska     *
3500549dcc5SAndreas Gohr     * Important: this may only be called after running @return array
3510549dcc5SAndreas Gohr     * @see execute()
3526fd73b4bSAnna Dabrowska     *
3536fd73b4bSAnna Dabrowska     */
35461356325SAnna Dabrowska    public function getRevs()
35561356325SAnna Dabrowska    {
35617a3a578SAndreas Gohr        if ($this->result_revs === null)
35717a3a578SAndreas Gohr            throw new StructException('revs are only accessible after executing the search');
3586fd73b4bSAnna Dabrowska        return $this->result_revs;
3596fd73b4bSAnna Dabrowska    }
3606fd73b4bSAnna Dabrowska
3616fd73b4bSAnna Dabrowska    /**
362b2ed727aSAndreas Gohr     * Execute this search and return the result
363b2ed727aSAndreas Gohr     *
36438fa36fbSAndreas Gohr     * The result is a two dimensional array of Value()s.
3657f9cb794SAndreas Gohr     *
3667f9cb794SAndreas Gohr     * This will always query for the full result (not using offset and limit) and then
3670549dcc5SAndreas Gohr     * return the wanted range, setting the count (@return Value[][]
3680549dcc5SAndreas Gohr     * @see getCount) to the whole result number
36938fa36fbSAndreas Gohr     *
370b2ed727aSAndreas Gohr     */
3718ce43f5aSAnna Dabrowska    public function execute()
37261356325SAnna Dabrowska    {
3738ce43f5aSAnna Dabrowska        list($sql, $opts) = $this->getSQL();
374b2ed727aSAndreas Gohr
3757f9cb794SAndreas Gohr        /** @var \PDOStatement $res */
376b2ed727aSAndreas Gohr        $res = $this->sqlite->query($sql, $opts);
37759b668aaSAndreas Gohr        if ($res === false) throw new StructException("SQL execution failed for\n\n$sql");
378b2ed727aSAndreas Gohr
379d4b5a17cSAndreas Gohr        $this->result_pids = array();
380b2ed727aSAndreas Gohr        $result = array();
3817f9cb794SAndreas Gohr        $cursor = -1;
3825e4bfdb0SMichael Grosse        $pageidAndRevOnly = array_reduce($this->columns, function ($pageidAndRevOnly, Column $col) {
3835e4bfdb0SMichael Grosse            return $pageidAndRevOnly && ($col->getTid() == 0);
3845e4bfdb0SMichael Grosse        }, true);
3857f9cb794SAndreas Gohr        while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
3867f9cb794SAndreas Gohr            $cursor++;
3877f9cb794SAndreas Gohr            if ($cursor < $this->range_begin) continue;
3887f9cb794SAndreas Gohr            if ($this->range_end && $cursor >= $this->range_end) continue;
3897f9cb794SAndreas Gohr
390b2ed727aSAndreas Gohr            $C = 0;
391b2ed727aSAndreas Gohr            $resrow = array();
39299a70f28SAndreas Gohr            $isempty = true;
393b2ed727aSAndreas Gohr            foreach ($this->columns as $col) {
39438fa36fbSAndreas Gohr                $val = $row["C$C"];
395b2ed727aSAndreas Gohr                if ($col->isMulti()) {
39638fa36fbSAndreas Gohr                    $val = explode(self::CONCAT_SEPARATOR, $val);
397b2ed727aSAndreas Gohr                }
39899a70f28SAndreas Gohr                $value = new Value($col, $val);
3998cba7aa0SMichael Grosse                $isempty &= $this->isEmptyValue($value);
40099a70f28SAndreas Gohr                $resrow[] = $value;
401b2ed727aSAndreas Gohr                $C++;
402b2ed727aSAndreas Gohr            }
40399a70f28SAndreas Gohr
40499a70f28SAndreas Gohr            // skip empty rows
4058cba7aa0SMichael Grosse            if ($isempty && !$pageidAndRevOnly) {
40699a70f28SAndreas Gohr                $cursor--;
40799a70f28SAndreas Gohr                continue;
40899a70f28SAndreas Gohr            }
40999a70f28SAndreas Gohr
41099a70f28SAndreas Gohr            $this->result_pids[] = $row['PID'];
4110ceefd5cSAnna Dabrowska            $this->result_rids[] = $row['rid'];
4126fd73b4bSAnna Dabrowska            $this->result_revs[] = $row['rev'];
413b2ed727aSAndreas Gohr            $result[] = $resrow;
414b2ed727aSAndreas Gohr        }
4157f9cb794SAndreas Gohr
4167f9cb794SAndreas Gohr        $this->sqlite->res_close($res);
4177f9cb794SAndreas Gohr        $this->count = $cursor + 1;
418b2ed727aSAndreas Gohr        return $result;
419b2ed727aSAndreas Gohr    }
420b2ed727aSAndreas Gohr
421b2ed727aSAndreas Gohr    /**
42215929be2SAndreas Gohr     * Transform the set search parameters into a statement
42315929be2SAndreas Gohr     *
424b2ed727aSAndreas Gohr     * @return array ($sql, $opts) The SQL and parameters to execute
42515929be2SAndreas Gohr     */
4268ce43f5aSAnna Dabrowska    public function getSQL()
42761356325SAnna Dabrowska    {
4285511bd5bSAndreas Gohr        if (!$this->columns) throw new StructException('nocolname');
42915929be2SAndreas Gohr
4302f68434dSAndreas Gohr        $QB = new QueryBuilder();
43115929be2SAndreas Gohr
4329d7a36f9SAndreas Gohr        // basic tables
433b2d67e7dSAndreas Gohr        $first_table = '';
4349d7a36f9SAndreas Gohr        foreach ($this->schemas as $schema) {
4352f68434dSAndreas Gohr            $datatable = 'data_' . $schema->getTable();
436b2d67e7dSAndreas Gohr            if ($first_table) {
4379d7a36f9SAndreas Gohr                // follow up tables
4388ce43f5aSAnna Dabrowska                $QB->addLeftJoin($first_table, $datatable, $datatable, "$first_table.pid = $datatable.pid");
4399d7a36f9SAndreas Gohr            } else {
4409d7a36f9SAndreas Gohr                // first table
44113c321dbSAndreas Gohr                $QB->addTable($datatable);
4428ce43f5aSAnna Dabrowska
4438ce43f5aSAnna Dabrowska                // add conditional page clauses if pid has a value
4448ce43f5aSAnna Dabrowska                $subAnd = $QB->filters()->whereSubAnd();
4458ce43f5aSAnna Dabrowska                $subAnd->whereAnd("$datatable.pid = ''");
4468ce43f5aSAnna Dabrowska                $subOr = $subAnd->whereSubOr();
4478ce43f5aSAnna Dabrowska                $subOr->whereAnd("GETACCESSLEVEL($datatable.pid) > 0");
4488ce43f5aSAnna Dabrowska                $subOr->whereAnd("PAGEEXISTS($datatable.pid) = 1");
44954efd03eSAnna Dabrowska                $subOr->whereAnd('(ASSIGNED = 1 OR ASSIGNED IS NULL)');
4508ce43f5aSAnna Dabrowska
4518ce43f5aSAnna Dabrowska                // add conditional schema assignment check
452f183bf6eSAnna Dabrowska                $QB->addLeftJoin(
453f183bf6eSAnna Dabrowska                    $datatable,
454f183bf6eSAnna Dabrowska                    'schema_assignments',
455f183bf6eSAnna Dabrowska                    '',
4568ce43f5aSAnna Dabrowska                    "$datatable.pid != ''
4578ce43f5aSAnna Dabrowska                    AND $datatable.pid = schema_assignments.pid
45838e29673SAnna Dabrowska                    AND schema_assignments.tbl = '{$schema->getTable()}'"
4598ce43f5aSAnna Dabrowska                );
4608ce43f5aSAnna Dabrowska
4610ceefd5cSAnna Dabrowska                $QB->addSelectColumn($datatable, 'rid');
46213c321dbSAndreas Gohr                $QB->addSelectColumn($datatable, 'pid', 'PID');
4636fd73b4bSAnna Dabrowska                $QB->addSelectColumn($datatable, 'rev');
46438e29673SAnna Dabrowska                $QB->addSelectColumn('schema_assignments', 'assigned', 'ASSIGNED');
46513c321dbSAndreas Gohr                $QB->addGroupByColumn($datatable, 'pid');
466e3104939SAnna Dabrowska                $QB->addGroupByColumn($datatable, 'rid');
467b2d67e7dSAndreas Gohr
4682f68434dSAndreas Gohr                $first_table = $datatable;
46915929be2SAndreas Gohr            }
4702f68434dSAndreas Gohr            $QB->filters()->whereAnd("$datatable.latest = 1");
4719d7a36f9SAndreas Gohr        }
47215929be2SAndreas Gohr
47315929be2SAndreas Gohr        // columns to select, handling multis
4749d7a36f9SAndreas Gohr        $sep = self::CONCAT_SEPARATOR;
47515929be2SAndreas Gohr        $n = 0;
47615929be2SAndreas Gohr        foreach ($this->columns as $col) {
47715929be2SAndreas Gohr            $CN = 'C' . $n++;
47815929be2SAndreas Gohr
479d1b04e89SAndreas Gohr            if ($col->isMulti()) {
4802f68434dSAndreas Gohr                $datatable = "data_{$col->getTable()}";
4812f68434dSAndreas Gohr                $multitable = "multi_{$col->getTable()}";
482db7970caSAndreas Gohr                $MN = $QB->generateTableAlias('M');
4832f68434dSAndreas Gohr
4842f68434dSAndreas Gohr                $QB->addLeftJoin(
4852f68434dSAndreas Gohr                    $datatable,
4862f68434dSAndreas Gohr                    $multitable,
4872f68434dSAndreas Gohr                    $MN,
4888ce43f5aSAnna Dabrowska                    "$datatable.pid = $MN.pid AND $datatable.rid = $MN.rid AND
4892f68434dSAndreas Gohr                     $datatable.rev = $MN.rev AND
4902f68434dSAndreas Gohr                     $MN.colref = {$col->getColref()}"
4912f68434dSAndreas Gohr                );
492578407b2SAndreas Gohr
493578407b2SAndreas Gohr                $col->getType()->select($QB, $MN, 'value', $CN);
494578407b2SAndreas Gohr                $sel = $QB->getSelectStatement($CN);
495578407b2SAndreas Gohr                $QB->addSelectStatement("GROUP_CONCAT($sel, '$sep')", $CN);
49615929be2SAndreas Gohr            } else {
497578407b2SAndreas Gohr                $col->getType()->select($QB, 'data_' . $col->getTable(), $col->getColName(), $CN);
4980dbe7bf6SAndreas Gohr                $QB->addGroupByStatement($CN);
49915929be2SAndreas Gohr            }
50015929be2SAndreas Gohr        }
50115929be2SAndreas Gohr
5029d7a36f9SAndreas Gohr        // where clauses
503af993d55SMichael Grosse        if (!empty($this->filter)) {
504af993d55SMichael Grosse            $userWHERE = $QB->filters()->where('AND');
505af993d55SMichael Grosse        }
506b8fe6730SAndreas Gohr        foreach ($this->filter as $filter) {
5079ebd2ed6SAndreas Gohr            /** @var Column $col */
5084c13ff97SAndreas Gohr            list($col, $value, $comp, $op) = $filter;
509b8fe6730SAndreas Gohr
5102f68434dSAndreas Gohr            $datatable = "data_{$col->getTable()}";
5112f68434dSAndreas Gohr            $multitable = "multi_{$col->getTable()}";
5129d7a36f9SAndreas Gohr
5139d7a36f9SAndreas Gohr            /** @var $col Column */
5149d7a36f9SAndreas Gohr            if ($col->isMulti()) {
515db7970caSAndreas Gohr                $MN = $QB->generateTableAlias('MN');
51615929be2SAndreas Gohr
5172f68434dSAndreas Gohr                $QB->addLeftJoin(
5182f68434dSAndreas Gohr                    $datatable,
5192f68434dSAndreas Gohr                    $multitable,
5202f68434dSAndreas Gohr                    $MN,
5218ce43f5aSAnna Dabrowska                    "$datatable.pid = $MN.pid AND $datatable.rid = $MN.rid AND
5222f68434dSAndreas Gohr                     $datatable.rev = $MN.rev AND
5232f68434dSAndreas Gohr                     $MN.colref = {$col->getColref()}"
5242f68434dSAndreas Gohr                );
525690e4ebaSAndreas Gohr                $coltbl = $MN;
526690e4ebaSAndreas Gohr                $colnam = 'value';
5279d7a36f9SAndreas Gohr            } else {
528690e4ebaSAndreas Gohr                $coltbl = $datatable;
529690e4ebaSAndreas Gohr                $colnam = $col->getColName();
5309d7a36f9SAndreas Gohr            }
53153528ecfSAndreas Gohr
532af993d55SMichael Grosse            $col->getType()->filter($userWHERE, $coltbl, $colnam, $comp, $value, $op); // type based filter
5339d7a36f9SAndreas Gohr        }
5349d7a36f9SAndreas Gohr
53529394e6cSAndreas Gohr        // sorting - we always sort by the single val column
536b8fe6730SAndreas Gohr        foreach ($this->sortby as $sort) {
537eb55dc17SAndreas Gohr            list($col, $asc, $nc) = $sort;
5389d7a36f9SAndreas Gohr            /** @var $col Column */
539eb55dc17SAndreas Gohr            $colname = $col->getColName(false);
540eb55dc17SAndreas Gohr            if ($nc) $colname .= ' COLLATE NOCASE';
541eb55dc17SAndreas Gohr            $col->getType()->sort($QB, 'data_' . $col->getTable(), $colname, $asc ? 'ASC' : 'DESC');
5429e07bdbfSAndreas Gohr        }
5439e07bdbfSAndreas Gohr
5442f68434dSAndreas Gohr        return $QB->getSQL();
54515929be2SAndreas Gohr    }
54615929be2SAndreas Gohr
54715929be2SAndreas Gohr    /**
54801dd90deSAndreas Gohr     * Returns all the columns that where added to the search
54901dd90deSAndreas Gohr     *
55001dd90deSAndreas Gohr     * @return Column[]
55101dd90deSAndreas Gohr     */
55261356325SAnna Dabrowska    public function getColumns()
55361356325SAnna Dabrowska    {
55401dd90deSAndreas Gohr        return $this->columns;
55501dd90deSAndreas Gohr    }
55601dd90deSAndreas Gohr
557577b462bSAndreas Gohr    /**
5585a4df70dSAndreas Gohr     * All the schemas currently added
5595a4df70dSAndreas Gohr     *
5605a4df70dSAndreas Gohr     * @return Schema[]
5615a4df70dSAndreas Gohr     */
56261356325SAnna Dabrowska    public function getSchemas()
56361356325SAnna Dabrowska    {
5645a4df70dSAndreas Gohr        return array_values($this->schemas);
5655a4df70dSAndreas Gohr    }
5665a4df70dSAndreas Gohr
5675a4df70dSAndreas Gohr    /**
568577b462bSAndreas Gohr     * Checks if the given column is a * wildcard
569577b462bSAndreas Gohr     *
570577b462bSAndreas Gohr     * If it's a wildcard all matching columns are added to the column list, otherwise
571577b462bSAndreas Gohr     * nothing happens
572577b462bSAndreas Gohr     *
573577b462bSAndreas Gohr     * @param string $colname
574577b462bSAndreas Gohr     * @return bool was wildcard?
575577b462bSAndreas Gohr     */
57661356325SAnna Dabrowska    protected function processWildcard($colname)
57761356325SAnna Dabrowska    {
578636a5173SAndreas Gohr        list($colname, $table) = $this->resolveColumn($colname);
579577b462bSAndreas Gohr        if ($colname !== '*') return false;
580577b462bSAndreas Gohr
581577b462bSAndreas Gohr        // no table given? assume the first is meant
582577b462bSAndreas Gohr        if ($table === null) {
583577b462bSAndreas Gohr            $schema_list = array_keys($this->schemas);
584577b462bSAndreas Gohr            $table = $schema_list[0];
585577b462bSAndreas Gohr        }
586577b462bSAndreas Gohr
5871ca21e17SAnna Dabrowska        $schema = $this->schemas[$table] ?? null;
588577b462bSAndreas Gohr        if (!$schema) return false;
589577b462bSAndreas Gohr        $this->columns = array_merge($this->columns, $schema->getColumns(false));
590577b462bSAndreas Gohr        return true;
591577b462bSAndreas Gohr    }
592577b462bSAndreas Gohr
593577b462bSAndreas Gohr    /**
594577b462bSAndreas Gohr     * Split a given column name into table and column
595577b462bSAndreas Gohr     *
596577b462bSAndreas Gohr     * Handles Aliases. Table might be null if none given.
597577b462bSAndreas Gohr     *
598577b462bSAndreas Gohr     * @param $colname
599636a5173SAndreas Gohr     * @return array (colname, table)
600577b462bSAndreas Gohr     */
60161356325SAnna Dabrowska    protected function resolveColumn($colname)
60261356325SAnna Dabrowska    {
603577b462bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
604577b462bSAndreas Gohr
605577b462bSAndreas Gohr        // resolve the alias or table name
6069007da58SMichael Große        @list($table, $colname) = explode('.', $colname, 2);
607577b462bSAndreas Gohr        if (!$colname) {
608577b462bSAndreas Gohr            $colname = $table;
609577b462bSAndreas Gohr            $table = null;
610577b462bSAndreas Gohr        }
611577b462bSAndreas Gohr        if ($table && isset($this->aliases[$table])) {
612577b462bSAndreas Gohr            $table = $this->aliases[$table];
613577b462bSAndreas Gohr        }
614577b462bSAndreas Gohr
615577b462bSAndreas Gohr        if (!$colname) throw new StructException('nocolname');
616577b462bSAndreas Gohr
617577b462bSAndreas Gohr        return array($colname, $table);
618577b462bSAndreas Gohr    }
61901dd90deSAndreas Gohr
62001dd90deSAndreas Gohr    /**
62115929be2SAndreas Gohr     * Find a column to be used in the search
62215929be2SAndreas Gohr     *
62315929be2SAndreas Gohr     * @param string $colname may contain an alias
62415929be2SAndreas Gohr     * @return bool|Column
62515929be2SAndreas Gohr     */
6260280da9aSFrieder Schrempf    public function findColumn($colname, $strict = false)
62761356325SAnna Dabrowska    {
6285511bd5bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
629df02ffe6SMichael Große        $schema_list = array_keys($this->schemas);
630f107f479SAndreas Gohr
631f107f479SAndreas Gohr        // add "fake" column for special col
632128d4e83SAndreas Gohr        if ($colname == '%pageid%') {
633128d4e83SAndreas Gohr            return new PageColumn(0, new Page(), $schema_list[0]);
634d1b04e89SAndreas Gohr        }
635128d4e83SAndreas Gohr        if ($colname == '%title%') {
636128d4e83SAndreas Gohr            return new PageColumn(0, new Page(array('usetitles' => true)), $schema_list[0]);
637128d4e83SAndreas Gohr        }
638cadfc3ccSAndreas Gohr        if ($colname == '%lastupdate%') {
639cadfc3ccSAndreas Gohr            return new RevisionColumn(0, new DateTime(), $schema_list[0]);
640cadfc3ccSAndreas Gohr        }
6412e12ac22SMichael Grosse        if ($colname == '%lasteditor%') {
6422e12ac22SMichael Grosse            return new UserColumn(0, new User(), $schema_list[0]);
6432e12ac22SMichael Grosse        }
64488b58a21SSzymon Olewniczak        if ($colname == '%lastsummary%') {
6456781c68dSSzymon Olewniczak            return new SummaryColumn(0, new AutoSummary(), $schema_list[0]);
64688b58a21SSzymon Olewniczak        }
647f107f479SAndreas Gohr        if ($colname == '%rowid%') {
648f107f479SAndreas Gohr            return new RowColumn(0, new Decimal(), $schema_list[0]);
649f107f479SAndreas Gohr        }
650*da62ec9cSAnna Dabrowska        if ($colname == '%published%') {
651*da62ec9cSAnna Dabrowska            return new PublishedColumn(0, new Decimal(), $schema_list[0]);
652*da62ec9cSAnna Dabrowska        }
653d1b04e89SAndreas Gohr
654636a5173SAndreas Gohr        list($colname, $table) = $this->resolveColumn($colname);
65515929be2SAndreas Gohr
6560280da9aSFrieder Schrempf        /*
6570280da9aSFrieder Schrempf         * If table name is given search only that, otherwise if no strict behavior
6580280da9aSFrieder Schrempf         * is requested by the caller, try all assigned schemas for matching the
6590280da9aSFrieder Schrempf         * column name.
6600280da9aSFrieder Schrempf         */
66134ea6e10SAnna Dabrowska        if ($table !== null && isset($this->schemas[$table])) {
66215929be2SAndreas Gohr            $schemas = array($table => $this->schemas[$table]);
6630280da9aSFrieder Schrempf        } elseif ($table === null || !$strict) {
66415929be2SAndreas Gohr            $schemas = $this->schemas;
6650280da9aSFrieder Schrempf        } else {
6660280da9aSFrieder Schrempf            return false;
66715929be2SAndreas Gohr        }
66815929be2SAndreas Gohr
66915929be2SAndreas Gohr        // find it
67015929be2SAndreas Gohr        $col = false;
67115929be2SAndreas Gohr        foreach ($schemas as $schema) {
6724ac44d1cSMichael Grosse            if (empty($schema)) {
6734ac44d1cSMichael Grosse                continue;
6744ac44d1cSMichael Grosse            }
67515929be2SAndreas Gohr            $col = $schema->findColumn($colname);
67615929be2SAndreas Gohr            if ($col) break;
67715929be2SAndreas Gohr        }
67815929be2SAndreas Gohr
67915929be2SAndreas Gohr        return $col;
68015929be2SAndreas Gohr    }
68115929be2SAndreas Gohr
6829dbc8ec0SMichael Grosse    /**
68399a70f28SAndreas Gohr     * Check if the given row is empty or references our own row
6849dbc8ec0SMichael Grosse     *
68599a70f28SAndreas Gohr     * @param Value $value
6869dbc8ec0SMichael Grosse     * @return bool
6879dbc8ec0SMichael Grosse     */
68861356325SAnna Dabrowska    protected function isEmptyValue(Value $value)
68961356325SAnna Dabrowska    {
69099a70f28SAndreas Gohr        if ($value->isEmpty()) return true;
6918cba7aa0SMichael Grosse        if ($value->getColumn()->getTid() == 0) return true;
6929dbc8ec0SMichael Grosse        return false;
6939dbc8ec0SMichael Grosse    }
69415929be2SAndreas Gohr}
695