xref: /plugin/struct/meta/Search.php (revision bb8d98c4da8c9e71a9a1d62a6b706af3a628e17a)
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
26*bb8d98c4SAnna Dabrowska    /** @var \helper_plugin_struct_db */
27*bb8d98c4SAnna Dabrowska    protected $dbHelper;
28*bb8d98c4SAnna Dabrowska
299d7a36f9SAndreas Gohr    /** @var  \helper_plugin_sqlite */
309d7a36f9SAndreas Gohr    protected $sqlite;
3115929be2SAndreas Gohr
3215929be2SAndreas Gohr    /** @var Schema[] list of schemas to query */
3315929be2SAndreas Gohr    protected $schemas = array();
3415929be2SAndreas Gohr
3515929be2SAndreas Gohr    /** @var Column[] list of columns to select */
3615929be2SAndreas Gohr    protected $columns = array();
3715929be2SAndreas Gohr
3815929be2SAndreas Gohr    /** @var array the sorting of the result */
3915929be2SAndreas Gohr    protected $sortby = array();
4015929be2SAndreas Gohr
419d7a36f9SAndreas Gohr    /** @var array the filters */
429d7a36f9SAndreas Gohr    protected $filter = array();
4315929be2SAndreas Gohr
4415929be2SAndreas Gohr    /** @var array list of aliases tables can be referenced by */
4515929be2SAndreas Gohr    protected $aliases = array();
4615929be2SAndreas Gohr
477f9cb794SAndreas Gohr    /** @var  int begin results from here */
487f9cb794SAndreas Gohr    protected $range_begin = 0;
497f9cb794SAndreas Gohr
507f9cb794SAndreas Gohr    /** @var  int end results here */
517f9cb794SAndreas Gohr    protected $range_end = 0;
527f9cb794SAndreas Gohr
537f9cb794SAndreas Gohr    /** @var int the number of results */
547f9cb794SAndreas Gohr    protected $count = -1;
55d4b5a17cSAndreas Gohr    /** @var  string[] the PIDs of the result rows */
56d4b5a17cSAndreas Gohr    protected $result_pids = null;
570ceefd5cSAnna Dabrowska    /** @var  array the row ids of the result rows */
580ceefd5cSAnna Dabrowska    protected $result_rids = [];
596fd73b4bSAnna Dabrowska    /** @var  array the revisions of the result rows */
606fd73b4bSAnna Dabrowska    protected $result_revs = [];
617f9cb794SAndreas Gohr
6215929be2SAndreas Gohr    /**
639d7a36f9SAndreas Gohr     * Search constructor.
649d7a36f9SAndreas Gohr     */
6561356325SAnna Dabrowska    public function __construct()
6661356325SAnna Dabrowska    {
67*bb8d98c4SAnna Dabrowska        /** @var  $dbHelper */
68*bb8d98c4SAnna Dabrowska        $this->dbHelper = plugin_load('helper', 'struct_db');
69*bb8d98c4SAnna Dabrowska        $this->sqlite = $this->dbHelper->getDB();
70*bb8d98c4SAnna Dabrowska    }
71*bb8d98c4SAnna Dabrowska
72*bb8d98c4SAnna Dabrowska    public function getDb()
73*bb8d98c4SAnna Dabrowska    {
74*bb8d98c4SAnna Dabrowska        return $this->sqlite;
759d7a36f9SAndreas Gohr    }
769d7a36f9SAndreas Gohr
779d7a36f9SAndreas Gohr    /**
7815929be2SAndreas Gohr     * Add a schema to be searched
7915929be2SAndreas Gohr     *
8015929be2SAndreas Gohr     * Call multiple times for multiple schemas.
8115929be2SAndreas Gohr     *
8215929be2SAndreas Gohr     * @param string $table
8315929be2SAndreas Gohr     * @param string $alias
8415929be2SAndreas Gohr     */
8561356325SAnna Dabrowska    public function addSchema($table, $alias = '')
8661356325SAnna Dabrowska    {
872be187cdSAndreas Gohr        $schema = new Schema($table);
882be187cdSAndreas Gohr        if (!$schema->getId()) {
892be187cdSAndreas Gohr            throw new StructException('schema missing', $table);
902be187cdSAndreas Gohr        }
912be187cdSAndreas Gohr
92712c650dSAndreas Gohr        $this->schemas[$schema->getTable()] = $schema;
93712c650dSAndreas Gohr        if ($alias) $this->aliases[$alias] = $schema->getTable();
9415929be2SAndreas Gohr    }
9515929be2SAndreas Gohr
9615929be2SAndreas Gohr    /**
9715929be2SAndreas Gohr     * Add a column to be returned by the search
9815929be2SAndreas Gohr     *
9915929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
10015929be2SAndreas Gohr     * added before
10115929be2SAndreas Gohr     *
10215929be2SAndreas Gohr     * @param string $colname may contain an alias
10315929be2SAndreas Gohr     */
10461356325SAnna Dabrowska    public function addColumn($colname)
10561356325SAnna Dabrowska    {
106577b462bSAndreas Gohr        if ($this->processWildcard($colname)) return; // wildcard?
107b26126edSAndreas Hubel        if ($colname[0] == '-') { // remove column from previous wildcard lookup
108b26126edSAndreas Hubel            $colname = substr($colname, 1);
109b26126edSAndreas Hubel            foreach ($this->columns as $key => $col) {
110b26126edSAndreas Hubel                if ($col->getLabel() == $colname) unset($this->columns[$key]);
111b26126edSAndreas Hubel            }
112b26126edSAndreas Hubel            return;
113b26126edSAndreas Hubel        }
114b26126edSAndreas Hubel
11515929be2SAndreas Gohr        $col = $this->findColumn($colname);
11615929be2SAndreas Gohr        if (!$col) return; //FIXME do we really want to ignore missing columns?
11715929be2SAndreas Gohr        $this->columns[] = $col;
11815929be2SAndreas Gohr    }
11915929be2SAndreas Gohr
12015929be2SAndreas Gohr    /**
12115929be2SAndreas Gohr     * Add sorting options
12215929be2SAndreas Gohr     *
12315929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
12415929be2SAndreas Gohr     * added before
12515929be2SAndreas Gohr     *
12615929be2SAndreas Gohr     * @param string $colname may contain an alias
12715929be2SAndreas Gohr     * @param bool $asc sort direction (ASC = true, DESC = false)
128eb55dc17SAndreas Gohr     * @param bool $nc set true for caseinsensitivity
12915929be2SAndreas Gohr     */
13061356325SAnna Dabrowska    public function addSort($colname, $asc = true, $nc = true)
13161356325SAnna Dabrowska    {
13215929be2SAndreas Gohr        $col = $this->findColumn($colname);
13315929be2SAndreas Gohr        if (!$col) return; //FIXME do we really want to ignore missing columns?
13415929be2SAndreas Gohr
135eb55dc17SAndreas Gohr        $this->sortby[$col->getFullQualifiedLabel()] = array($col, $asc, $nc);
13607993756SAndreas Gohr    }
13707993756SAndreas Gohr
13807993756SAndreas Gohr    /**
13907993756SAndreas Gohr     * Returns all set sort columns
14007993756SAndreas Gohr     *
14107993756SAndreas Gohr     * @return array
14207993756SAndreas Gohr     */
14361356325SAnna Dabrowska    public function getSorts()
14461356325SAnna Dabrowska    {
14507993756SAndreas Gohr        return $this->sortby;
14615929be2SAndreas Gohr    }
14715929be2SAndreas Gohr
14815929be2SAndreas Gohr    /**
1499d7a36f9SAndreas Gohr     * Adds a filter
15015929be2SAndreas Gohr     *
15115929be2SAndreas Gohr     * @param string $colname may contain an alias
15253528ecfSAndreas Gohr     * @param string|string[] $value
1535511bd5bSAndreas Gohr     * @param string $comp @see self::COMPARATORS
1544c13ff97SAndreas Gohr     * @param string $op either 'OR' or 'AND'
15515929be2SAndreas Gohr     */
15661356325SAnna Dabrowska    public function addFilter($colname, $value, $comp, $op = 'OR')
15761356325SAnna Dabrowska    {
1589dbc32aeSAndreas Gohr        /* Convert certain filters into others
1599dbc32aeSAndreas Gohr         * this reduces the number of supported filters to implement in types */
1609dbc32aeSAndreas Gohr        if ($comp == '*~') {
16153528ecfSAndreas Gohr            $value = $this->filterWrapAsterisks($value);
1629dbc32aeSAndreas Gohr            $comp = '~';
1639dbc32aeSAndreas Gohr        } elseif ($comp == '<>') {
1649dbc32aeSAndreas Gohr            $comp = '!=';
1659dbc32aeSAndreas Gohr        }
1669dbc32aeSAndreas Gohr
16717a3a578SAndreas Gohr        if (!in_array($comp, self::$COMPARATORS))
16817a3a578SAndreas Gohr            throw new StructException("Bad comperator. Use " . join(',', self::$COMPARATORS));
16917a3a578SAndreas Gohr        if ($op != 'OR' && $op != 'AND')
17017a3a578SAndreas Gohr            throw new StructException('Bad filter type . Only AND or OR allowed');
1719d7a36f9SAndreas Gohr
17215929be2SAndreas Gohr        $col = $this->findColumn($colname);
1737da1a0fdSAndreas Gohr        if (!$col) return; // ignore missing columns, filter might have been for different schema
1747da1a0fdSAndreas Gohr
1757da1a0fdSAndreas Gohr        // map filter operators to SQL syntax
1767da1a0fdSAndreas Gohr        switch ($comp) {
1777da1a0fdSAndreas Gohr            case '~':
1787da1a0fdSAndreas Gohr                $comp = 'LIKE';
1797da1a0fdSAndreas Gohr                break;
1807da1a0fdSAndreas Gohr            case '!~':
1817da1a0fdSAndreas Gohr                $comp = 'NOT LIKE';
1827da1a0fdSAndreas Gohr                break;
1837da1a0fdSAndreas Gohr            case '=*':
1847da1a0fdSAndreas Gohr                $comp = 'REGEXP';
1857da1a0fdSAndreas Gohr                break;
1867da1a0fdSAndreas Gohr        }
1877da1a0fdSAndreas Gohr
1887da1a0fdSAndreas Gohr        // we use asterisks, but SQL wants percents
1897da1a0fdSAndreas Gohr        if ($comp == 'LIKE' || $comp == 'NOT LIKE') {
19053528ecfSAndreas Gohr            $value = $this->filterChangeToLike($value);
1917da1a0fdSAndreas Gohr        }
1927da1a0fdSAndreas Gohr
193aaa187abSSzymon Olewniczak        if ($comp == ' IN ' && !is_array($value)) {
194efff5841SSzymon Olewniczak            $value = $this->parseFilterValueList($value);
195aaa187abSSzymon Olewniczak            //col IN ('a', 'b', 'c') is equal to col = 'a' OR 'col = 'b' OR col = 'c'
196aaa187abSSzymon Olewniczak            $comp = '=';
197aaa187abSSzymon Olewniczak        }
198aaa187abSSzymon Olewniczak
1997da1a0fdSAndreas Gohr        // add the filter
2004c13ff97SAndreas Gohr        $this->filter[] = array($col, $value, $comp, $op);
20115929be2SAndreas Gohr    }
20215929be2SAndreas Gohr
20315929be2SAndreas Gohr    /**
204aaa187abSSzymon Olewniczak     * Parse SQLite row value into array
205aaa187abSSzymon Olewniczak     *
206aaa187abSSzymon Olewniczak     * @param string $value
207aaa187abSSzymon Olewniczak     * @return string[]
208aaa187abSSzymon Olewniczak     */
20961356325SAnna Dabrowska    protected function parseFilterValueList($value)
21061356325SAnna Dabrowska    {
211efff5841SSzymon Olewniczak        $Handler = new FilterValueListHandler();
212670a6894SAnna Dabrowska        $LexerClass = class_exists('\Doku_Lexer') ? '\Doku_Lexer' : '\dokuwiki\Parsing\Lexer\Lexer';
213670a6894SAnna Dabrowska        $isLegacy = $LexerClass === '\Doku_Lexer';
214670a6894SAnna Dabrowska        /** @var \Doku_Lexer|\dokuwiki\Parsing\Lexer\Lexer $Lexer */
215670a6894SAnna Dabrowska        $Lexer = new $LexerClass($Handler, 'base', true);
216670a6894SAnna Dabrowska
217aaa187abSSzymon Olewniczak
218aaa187abSSzymon Olewniczak        $Lexer->addEntryPattern('\(', 'base', 'row');
219aaa187abSSzymon Olewniczak        $Lexer->addPattern('\s*,\s*', 'row');
220aaa187abSSzymon Olewniczak        $Lexer->addExitPattern('\)', 'row');
221aaa187abSSzymon Olewniczak
222aaa187abSSzymon Olewniczak        $Lexer->addEntryPattern('"', 'row', 'double_quote_string');
223dfe3ae67SAnna Dabrowska        $Lexer->addSpecialPattern('\\\\"', 'double_quote_string', 'escapeSequence');
224aaa187abSSzymon Olewniczak        $Lexer->addExitPattern('"', 'double_quote_string');
225aaa187abSSzymon Olewniczak
226dfe3ae67SAnna Dabrowska        $Lexer->addEntryPattern("'", 'row', 'singleQuoteString');
227dfe3ae67SAnna Dabrowska        $Lexer->addSpecialPattern("\\\\'", 'singleQuoteString', 'escapeSequence');
228dfe3ae67SAnna Dabrowska        $Lexer->addExitPattern("'", 'singleQuoteString');
229aaa187abSSzymon Olewniczak
230dfe3ae67SAnna Dabrowska        $Lexer->mapHandler('double_quote_string', 'singleQuoteString');
231aaa187abSSzymon Olewniczak
232aaa187abSSzymon Olewniczak        $Lexer->addSpecialPattern('[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?', 'row', 'number');
233aaa187abSSzymon Olewniczak
234aaa187abSSzymon Olewniczak        $res = $Lexer->parse($value);
235aaa187abSSzymon Olewniczak
236670a6894SAnna Dabrowska        $currentMode = $isLegacy ? $Lexer->_mode->getCurrent() : $Lexer->getModeStack()->getCurrent();
237670a6894SAnna Dabrowska        if (!$res || $currentMode != 'base') {
238aaa187abSSzymon Olewniczak            throw new StructException('invalid row value syntax');
239aaa187abSSzymon Olewniczak        }
240aaa187abSSzymon Olewniczak
241dfe3ae67SAnna Dabrowska        return $Handler->getRow();
242aaa187abSSzymon Olewniczak    }
243aaa187abSSzymon Olewniczak
244aaa187abSSzymon Olewniczak    /**
24553528ecfSAndreas Gohr     * Wrap given value in asterisks
24653528ecfSAndreas Gohr     *
24753528ecfSAndreas Gohr     * @param string|string[] $value
24853528ecfSAndreas Gohr     * @return string|string[]
24953528ecfSAndreas Gohr     */
25061356325SAnna Dabrowska    protected function filterWrapAsterisks($value)
25161356325SAnna Dabrowska    {
25253528ecfSAndreas Gohr        $map = function ($input) {
25353528ecfSAndreas Gohr            return "*$input*";
25453528ecfSAndreas Gohr        };
25553528ecfSAndreas Gohr
25653528ecfSAndreas Gohr        if (is_array($value)) {
25753528ecfSAndreas Gohr            $value = array_map($map, $value);
25853528ecfSAndreas Gohr        } else {
25953528ecfSAndreas Gohr            $value = $map($value);
26053528ecfSAndreas Gohr        }
26153528ecfSAndreas Gohr        return $value;
26253528ecfSAndreas Gohr    }
26353528ecfSAndreas Gohr
26453528ecfSAndreas Gohr    /**
26553528ecfSAndreas Gohr     * Change given string to use % instead of *
26653528ecfSAndreas Gohr     *
26753528ecfSAndreas Gohr     * @param string|string[] $value
26853528ecfSAndreas Gohr     * @return string|string[]
26953528ecfSAndreas Gohr     */
27061356325SAnna Dabrowska    protected function filterChangeToLike($value)
27161356325SAnna Dabrowska    {
27253528ecfSAndreas Gohr        $map = function ($input) {
27353528ecfSAndreas Gohr            return str_replace('*', '%', $input);
27453528ecfSAndreas Gohr        };
27553528ecfSAndreas Gohr
27653528ecfSAndreas Gohr        if (is_array($value)) {
27753528ecfSAndreas Gohr            $value = array_map($map, $value);
27853528ecfSAndreas Gohr        } else {
27953528ecfSAndreas Gohr            $value = $map($value);
28053528ecfSAndreas Gohr        }
28153528ecfSAndreas Gohr        return $value;
28253528ecfSAndreas Gohr    }
28353528ecfSAndreas Gohr
28453528ecfSAndreas Gohr    /**
2857f9cb794SAndreas Gohr     * Set offset for the results
2867f9cb794SAndreas Gohr     *
2877f9cb794SAndreas Gohr     * @param int $offset
2887f9cb794SAndreas Gohr     */
28961356325SAnna Dabrowska    public function setOffset($offset)
29061356325SAnna Dabrowska    {
2917f9cb794SAndreas Gohr        $limit = 0;
2927f9cb794SAndreas Gohr        if ($this->range_end) {
2937f9cb794SAndreas Gohr            // if there was a limit set previously, the range_end needs to be recalculated
2947f9cb794SAndreas Gohr            $limit = $this->range_end - $this->range_begin;
2957f9cb794SAndreas Gohr        }
2967f9cb794SAndreas Gohr        $this->range_begin = $offset;
2977f9cb794SAndreas Gohr        if ($limit) $this->setLimit($limit);
2987f9cb794SAndreas Gohr    }
2997f9cb794SAndreas Gohr
3007f9cb794SAndreas Gohr    /**
3017f9cb794SAndreas Gohr     * Limit results to this number
3027f9cb794SAndreas Gohr     *
3037f9cb794SAndreas Gohr     * @param int $limit Set to 0 to disable limit again
3047f9cb794SAndreas Gohr     */
30561356325SAnna Dabrowska    public function setLimit($limit)
30661356325SAnna Dabrowska    {
3077f9cb794SAndreas Gohr        if ($limit) {
3087f9cb794SAndreas Gohr            $this->range_end = $this->range_begin + $limit;
3097f9cb794SAndreas Gohr        } else {
3107f9cb794SAndreas Gohr            $this->range_end = 0;
3117f9cb794SAndreas Gohr        }
3127f9cb794SAndreas Gohr    }
3137f9cb794SAndreas Gohr
3147f9cb794SAndreas Gohr    /**
3157f9cb794SAndreas Gohr     * Return the number of results (regardless of limit and offset settings)
3167f9cb794SAndreas Gohr     *
3170549dcc5SAndreas Gohr     * Use this to implement paging. Important: this may only be called after running @return int
3180549dcc5SAndreas Gohr     * @see execute()
3197f9cb794SAndreas Gohr     *
3207f9cb794SAndreas Gohr     */
32161356325SAnna Dabrowska    public function getCount()
32261356325SAnna Dabrowska    {
3237f9cb794SAndreas Gohr        if ($this->count < 0) throw new StructException('Count is only accessible after executing the search');
3247f9cb794SAndreas Gohr        return $this->count;
3257f9cb794SAndreas Gohr    }
3267f9cb794SAndreas Gohr
327c46f5fb1SAndreas Gohr    /**
328c46f5fb1SAndreas Gohr     * Returns the PID associated with each result row
329c46f5fb1SAndreas Gohr     *
3300549dcc5SAndreas Gohr     * Important: this may only be called after running @return \string[]
3310549dcc5SAndreas Gohr     * @see execute()
332c46f5fb1SAndreas Gohr     *
333c46f5fb1SAndreas Gohr     */
33461356325SAnna Dabrowska    public function getPids()
33561356325SAnna Dabrowska    {
33617a3a578SAndreas Gohr        if ($this->result_pids === null)
33717a3a578SAndreas Gohr            throw new StructException('PIDs are only accessible after executing the search');
338d4b5a17cSAndreas Gohr        return $this->result_pids;
339d4b5a17cSAndreas Gohr    }
340d4b5a17cSAndreas Gohr
3417f9cb794SAndreas Gohr    /**
3420ceefd5cSAnna Dabrowska     * Returns the rid associated with each result row
3430ceefd5cSAnna Dabrowska     *
3440549dcc5SAndreas Gohr     * Important: this may only be called after running @return array
3450549dcc5SAndreas Gohr     * @see execute()
3460ceefd5cSAnna Dabrowska     *
3470ceefd5cSAnna Dabrowska     */
34861356325SAnna Dabrowska    public function getRids()
34961356325SAnna Dabrowska    {
35017a3a578SAndreas Gohr        if ($this->result_rids === null)
35117a3a578SAndreas Gohr            throw new StructException('rids are only accessible after executing the search');
3520ceefd5cSAnna Dabrowska        return $this->result_rids;
3530ceefd5cSAnna Dabrowska    }
3540ceefd5cSAnna Dabrowska
3550ceefd5cSAnna Dabrowska    /**
3566fd73b4bSAnna Dabrowska     * Returns the rid associated with each result row
3576fd73b4bSAnna Dabrowska     *
3580549dcc5SAndreas Gohr     * Important: this may only be called after running @return array
3590549dcc5SAndreas Gohr     * @see execute()
3606fd73b4bSAnna Dabrowska     *
3616fd73b4bSAnna Dabrowska     */
36261356325SAnna Dabrowska    public function getRevs()
36361356325SAnna Dabrowska    {
36417a3a578SAndreas Gohr        if ($this->result_revs === null)
36517a3a578SAndreas Gohr            throw new StructException('revs are only accessible after executing the search');
3666fd73b4bSAnna Dabrowska        return $this->result_revs;
3676fd73b4bSAnna Dabrowska    }
3686fd73b4bSAnna Dabrowska
3696fd73b4bSAnna Dabrowska    /**
370b2ed727aSAndreas Gohr     * Execute this search and return the result
371b2ed727aSAndreas Gohr     *
37238fa36fbSAndreas Gohr     * The result is a two dimensional array of Value()s.
3737f9cb794SAndreas Gohr     *
3747f9cb794SAndreas Gohr     * This will always query for the full result (not using offset and limit) and then
3750549dcc5SAndreas Gohr     * return the wanted range, setting the count (@return Value[][]
3760549dcc5SAndreas Gohr     * @see getCount) to the whole result number
37738fa36fbSAndreas Gohr     *
378b2ed727aSAndreas Gohr     */
3798ce43f5aSAnna Dabrowska    public function execute()
38061356325SAnna Dabrowska    {
3818ce43f5aSAnna Dabrowska        list($sql, $opts) = $this->getSQL();
382b2ed727aSAndreas Gohr
3837f9cb794SAndreas Gohr        /** @var \PDOStatement $res */
384b2ed727aSAndreas Gohr        $res = $this->sqlite->query($sql, $opts);
38559b668aaSAndreas Gohr        if ($res === false) throw new StructException("SQL execution failed for\n\n$sql");
386b2ed727aSAndreas Gohr
387d4b5a17cSAndreas Gohr        $this->result_pids = array();
388b2ed727aSAndreas Gohr        $result = array();
3897f9cb794SAndreas Gohr        $cursor = -1;
3905e4bfdb0SMichael Grosse        $pageidAndRevOnly = array_reduce($this->columns, function ($pageidAndRevOnly, Column $col) {
3915e4bfdb0SMichael Grosse            return $pageidAndRevOnly && ($col->getTid() == 0);
3925e4bfdb0SMichael Grosse        }, true);
3937f9cb794SAndreas Gohr        while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
3947f9cb794SAndreas Gohr            $cursor++;
3957f9cb794SAndreas Gohr            if ($cursor < $this->range_begin) continue;
3967f9cb794SAndreas Gohr            if ($this->range_end && $cursor >= $this->range_end) continue;
3977f9cb794SAndreas Gohr
398b2ed727aSAndreas Gohr            $C = 0;
399b2ed727aSAndreas Gohr            $resrow = array();
40099a70f28SAndreas Gohr            $isempty = true;
401b2ed727aSAndreas Gohr            foreach ($this->columns as $col) {
40238fa36fbSAndreas Gohr                $val = $row["C$C"];
403b2ed727aSAndreas Gohr                if ($col->isMulti()) {
40438fa36fbSAndreas Gohr                    $val = explode(self::CONCAT_SEPARATOR, $val);
405b2ed727aSAndreas Gohr                }
40699a70f28SAndreas Gohr                $value = new Value($col, $val);
4078cba7aa0SMichael Grosse                $isempty &= $this->isEmptyValue($value);
40899a70f28SAndreas Gohr                $resrow[] = $value;
409b2ed727aSAndreas Gohr                $C++;
410b2ed727aSAndreas Gohr            }
41199a70f28SAndreas Gohr
41299a70f28SAndreas Gohr            // skip empty rows
4138cba7aa0SMichael Grosse            if ($isempty && !$pageidAndRevOnly) {
41499a70f28SAndreas Gohr                $cursor--;
41599a70f28SAndreas Gohr                continue;
41699a70f28SAndreas Gohr            }
41799a70f28SAndreas Gohr
41899a70f28SAndreas Gohr            $this->result_pids[] = $row['PID'];
4190ceefd5cSAnna Dabrowska            $this->result_rids[] = $row['rid'];
4206fd73b4bSAnna Dabrowska            $this->result_revs[] = $row['rev'];
421b2ed727aSAndreas Gohr            $result[] = $resrow;
422b2ed727aSAndreas Gohr        }
4237f9cb794SAndreas Gohr
4247f9cb794SAndreas Gohr        $this->sqlite->res_close($res);
4257f9cb794SAndreas Gohr        $this->count = $cursor + 1;
426b2ed727aSAndreas Gohr        return $result;
427b2ed727aSAndreas Gohr    }
428b2ed727aSAndreas Gohr
429b2ed727aSAndreas Gohr    /**
43015929be2SAndreas Gohr     * Transform the set search parameters into a statement
43115929be2SAndreas Gohr     *
432b2ed727aSAndreas Gohr     * @return array ($sql, $opts) The SQL and parameters to execute
43315929be2SAndreas Gohr     */
4348ce43f5aSAnna Dabrowska    public function getSQL()
43561356325SAnna Dabrowska    {
4365511bd5bSAndreas Gohr        if (!$this->columns) throw new StructException('nocolname');
43715929be2SAndreas Gohr
4382f68434dSAndreas Gohr        $QB = new QueryBuilder();
43915929be2SAndreas Gohr
4409d7a36f9SAndreas Gohr        // basic tables
441b2d67e7dSAndreas Gohr        $first_table = '';
4429d7a36f9SAndreas Gohr        foreach ($this->schemas as $schema) {
4432f68434dSAndreas Gohr            $datatable = 'data_' . $schema->getTable();
444b2d67e7dSAndreas Gohr            if ($first_table) {
4459d7a36f9SAndreas Gohr                // follow up tables
4468ce43f5aSAnna Dabrowska                $QB->addLeftJoin($first_table, $datatable, $datatable, "$first_table.pid = $datatable.pid");
4479d7a36f9SAndreas Gohr            } else {
4489d7a36f9SAndreas Gohr                // first table
44913c321dbSAndreas Gohr                $QB->addTable($datatable);
4508ce43f5aSAnna Dabrowska
4518ce43f5aSAnna Dabrowska                // add conditional page clauses if pid has a value
4528ce43f5aSAnna Dabrowska                $subAnd = $QB->filters()->whereSubAnd();
4538ce43f5aSAnna Dabrowska                $subAnd->whereAnd("$datatable.pid = ''");
4548ce43f5aSAnna Dabrowska                $subOr = $subAnd->whereSubOr();
4558ce43f5aSAnna Dabrowska                $subOr->whereAnd("GETACCESSLEVEL($datatable.pid) > 0");
4568ce43f5aSAnna Dabrowska                $subOr->whereAnd("PAGEEXISTS($datatable.pid) = 1");
45754efd03eSAnna Dabrowska                $subOr->whereAnd('(ASSIGNED = 1 OR ASSIGNED IS NULL)');
4588ce43f5aSAnna Dabrowska
4598ce43f5aSAnna Dabrowska                // add conditional schema assignment check
460f183bf6eSAnna Dabrowska                $QB->addLeftJoin(
461f183bf6eSAnna Dabrowska                    $datatable,
462f183bf6eSAnna Dabrowska                    'schema_assignments',
463f183bf6eSAnna Dabrowska                    '',
4648ce43f5aSAnna Dabrowska                    "$datatable.pid != ''
4658ce43f5aSAnna Dabrowska                    AND $datatable.pid = schema_assignments.pid
46638e29673SAnna Dabrowska                    AND schema_assignments.tbl = '{$schema->getTable()}'"
4678ce43f5aSAnna Dabrowska                );
4688ce43f5aSAnna Dabrowska
4690ceefd5cSAnna Dabrowska                $QB->addSelectColumn($datatable, 'rid');
47013c321dbSAndreas Gohr                $QB->addSelectColumn($datatable, 'pid', 'PID');
4716fd73b4bSAnna Dabrowska                $QB->addSelectColumn($datatable, 'rev');
47238e29673SAnna Dabrowska                $QB->addSelectColumn('schema_assignments', 'assigned', 'ASSIGNED');
47313c321dbSAndreas Gohr                $QB->addGroupByColumn($datatable, 'pid');
474e3104939SAnna Dabrowska                $QB->addGroupByColumn($datatable, 'rid');
475b2d67e7dSAndreas Gohr
4762f68434dSAndreas Gohr                $first_table = $datatable;
47715929be2SAndreas Gohr            }
478*bb8d98c4SAnna Dabrowska            // phpcs:ignore
479*bb8d98c4SAnna Dabrowska            $QB->filters()->whereAnd("( (IS_PUBLISHER($datatable.pid) AND $datatable.latest = 1) OR (IS_PUBLISHER($datatable.pid) IS FALSE AND $datatable.published = 1) )");
4809d7a36f9SAndreas Gohr        }
48115929be2SAndreas Gohr
48215929be2SAndreas Gohr        // columns to select, handling multis
4839d7a36f9SAndreas Gohr        $sep = self::CONCAT_SEPARATOR;
48415929be2SAndreas Gohr        $n = 0;
48515929be2SAndreas Gohr        foreach ($this->columns as $col) {
48615929be2SAndreas Gohr            $CN = 'C' . $n++;
48715929be2SAndreas Gohr
488d1b04e89SAndreas Gohr            if ($col->isMulti()) {
4892f68434dSAndreas Gohr                $datatable = "data_{$col->getTable()}";
4902f68434dSAndreas Gohr                $multitable = "multi_{$col->getTable()}";
491db7970caSAndreas Gohr                $MN = $QB->generateTableAlias('M');
4922f68434dSAndreas Gohr
4932f68434dSAndreas Gohr                $QB->addLeftJoin(
4942f68434dSAndreas Gohr                    $datatable,
4952f68434dSAndreas Gohr                    $multitable,
4962f68434dSAndreas Gohr                    $MN,
4978ce43f5aSAnna Dabrowska                    "$datatable.pid = $MN.pid AND $datatable.rid = $MN.rid AND
4982f68434dSAndreas Gohr                     $datatable.rev = $MN.rev AND
4992f68434dSAndreas Gohr                     $MN.colref = {$col->getColref()}"
5002f68434dSAndreas Gohr                );
501578407b2SAndreas Gohr
502578407b2SAndreas Gohr                $col->getType()->select($QB, $MN, 'value', $CN);
503578407b2SAndreas Gohr                $sel = $QB->getSelectStatement($CN);
504578407b2SAndreas Gohr                $QB->addSelectStatement("GROUP_CONCAT($sel, '$sep')", $CN);
50515929be2SAndreas Gohr            } else {
506578407b2SAndreas Gohr                $col->getType()->select($QB, 'data_' . $col->getTable(), $col->getColName(), $CN);
5070dbe7bf6SAndreas Gohr                $QB->addGroupByStatement($CN);
50815929be2SAndreas Gohr            }
50915929be2SAndreas Gohr        }
51015929be2SAndreas Gohr
5119d7a36f9SAndreas Gohr        // where clauses
512af993d55SMichael Grosse        if (!empty($this->filter)) {
513af993d55SMichael Grosse            $userWHERE = $QB->filters()->where('AND');
514af993d55SMichael Grosse        }
515b8fe6730SAndreas Gohr        foreach ($this->filter as $filter) {
5169ebd2ed6SAndreas Gohr            /** @var Column $col */
5174c13ff97SAndreas Gohr            list($col, $value, $comp, $op) = $filter;
518b8fe6730SAndreas Gohr
5192f68434dSAndreas Gohr            $datatable = "data_{$col->getTable()}";
5202f68434dSAndreas Gohr            $multitable = "multi_{$col->getTable()}";
5219d7a36f9SAndreas Gohr
5229d7a36f9SAndreas Gohr            /** @var $col Column */
5239d7a36f9SAndreas Gohr            if ($col->isMulti()) {
524db7970caSAndreas Gohr                $MN = $QB->generateTableAlias('MN');
52515929be2SAndreas Gohr
5262f68434dSAndreas Gohr                $QB->addLeftJoin(
5272f68434dSAndreas Gohr                    $datatable,
5282f68434dSAndreas Gohr                    $multitable,
5292f68434dSAndreas Gohr                    $MN,
5308ce43f5aSAnna Dabrowska                    "$datatable.pid = $MN.pid AND $datatable.rid = $MN.rid AND
5312f68434dSAndreas Gohr                     $datatable.rev = $MN.rev AND
5322f68434dSAndreas Gohr                     $MN.colref = {$col->getColref()}"
5332f68434dSAndreas Gohr                );
534690e4ebaSAndreas Gohr                $coltbl = $MN;
535690e4ebaSAndreas Gohr                $colnam = 'value';
5369d7a36f9SAndreas Gohr            } else {
537690e4ebaSAndreas Gohr                $coltbl = $datatable;
538690e4ebaSAndreas Gohr                $colnam = $col->getColName();
5399d7a36f9SAndreas Gohr            }
54053528ecfSAndreas Gohr
541af993d55SMichael Grosse            $col->getType()->filter($userWHERE, $coltbl, $colnam, $comp, $value, $op); // type based filter
5429d7a36f9SAndreas Gohr        }
5439d7a36f9SAndreas Gohr
54429394e6cSAndreas Gohr        // sorting - we always sort by the single val column
545b8fe6730SAndreas Gohr        foreach ($this->sortby as $sort) {
546eb55dc17SAndreas Gohr            list($col, $asc, $nc) = $sort;
5479d7a36f9SAndreas Gohr            /** @var $col Column */
548eb55dc17SAndreas Gohr            $colname = $col->getColName(false);
549eb55dc17SAndreas Gohr            if ($nc) $colname .= ' COLLATE NOCASE';
550eb55dc17SAndreas Gohr            $col->getType()->sort($QB, 'data_' . $col->getTable(), $colname, $asc ? 'ASC' : 'DESC');
5519e07bdbfSAndreas Gohr        }
5529e07bdbfSAndreas Gohr
5532f68434dSAndreas Gohr        return $QB->getSQL();
55415929be2SAndreas Gohr    }
55515929be2SAndreas Gohr
55615929be2SAndreas Gohr    /**
55701dd90deSAndreas Gohr     * Returns all the columns that where added to the search
55801dd90deSAndreas Gohr     *
55901dd90deSAndreas Gohr     * @return Column[]
56001dd90deSAndreas Gohr     */
56161356325SAnna Dabrowska    public function getColumns()
56261356325SAnna Dabrowska    {
56301dd90deSAndreas Gohr        return $this->columns;
56401dd90deSAndreas Gohr    }
56501dd90deSAndreas Gohr
566577b462bSAndreas Gohr    /**
5675a4df70dSAndreas Gohr     * All the schemas currently added
5685a4df70dSAndreas Gohr     *
5695a4df70dSAndreas Gohr     * @return Schema[]
5705a4df70dSAndreas Gohr     */
57161356325SAnna Dabrowska    public function getSchemas()
57261356325SAnna Dabrowska    {
5735a4df70dSAndreas Gohr        return array_values($this->schemas);
5745a4df70dSAndreas Gohr    }
5755a4df70dSAndreas Gohr
5765a4df70dSAndreas Gohr    /**
577577b462bSAndreas Gohr     * Checks if the given column is a * wildcard
578577b462bSAndreas Gohr     *
579577b462bSAndreas Gohr     * If it's a wildcard all matching columns are added to the column list, otherwise
580577b462bSAndreas Gohr     * nothing happens
581577b462bSAndreas Gohr     *
582577b462bSAndreas Gohr     * @param string $colname
583577b462bSAndreas Gohr     * @return bool was wildcard?
584577b462bSAndreas Gohr     */
58561356325SAnna Dabrowska    protected function processWildcard($colname)
58661356325SAnna Dabrowska    {
587636a5173SAndreas Gohr        list($colname, $table) = $this->resolveColumn($colname);
588577b462bSAndreas Gohr        if ($colname !== '*') return false;
589577b462bSAndreas Gohr
590577b462bSAndreas Gohr        // no table given? assume the first is meant
591577b462bSAndreas Gohr        if ($table === null) {
592577b462bSAndreas Gohr            $schema_list = array_keys($this->schemas);
593577b462bSAndreas Gohr            $table = $schema_list[0];
594577b462bSAndreas Gohr        }
595577b462bSAndreas Gohr
5961ca21e17SAnna Dabrowska        $schema = $this->schemas[$table] ?? null;
597577b462bSAndreas Gohr        if (!$schema) return false;
598577b462bSAndreas Gohr        $this->columns = array_merge($this->columns, $schema->getColumns(false));
599577b462bSAndreas Gohr        return true;
600577b462bSAndreas Gohr    }
601577b462bSAndreas Gohr
602577b462bSAndreas Gohr    /**
603577b462bSAndreas Gohr     * Split a given column name into table and column
604577b462bSAndreas Gohr     *
605577b462bSAndreas Gohr     * Handles Aliases. Table might be null if none given.
606577b462bSAndreas Gohr     *
607577b462bSAndreas Gohr     * @param $colname
608636a5173SAndreas Gohr     * @return array (colname, table)
609577b462bSAndreas Gohr     */
61061356325SAnna Dabrowska    protected function resolveColumn($colname)
61161356325SAnna Dabrowska    {
612577b462bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
613577b462bSAndreas Gohr
614577b462bSAndreas Gohr        // resolve the alias or table name
6159007da58SMichael Große        @list($table, $colname) = explode('.', $colname, 2);
616577b462bSAndreas Gohr        if (!$colname) {
617577b462bSAndreas Gohr            $colname = $table;
618577b462bSAndreas Gohr            $table = null;
619577b462bSAndreas Gohr        }
620577b462bSAndreas Gohr        if ($table && isset($this->aliases[$table])) {
621577b462bSAndreas Gohr            $table = $this->aliases[$table];
622577b462bSAndreas Gohr        }
623577b462bSAndreas Gohr
624577b462bSAndreas Gohr        if (!$colname) throw new StructException('nocolname');
625577b462bSAndreas Gohr
626577b462bSAndreas Gohr        return array($colname, $table);
627577b462bSAndreas Gohr    }
62801dd90deSAndreas Gohr
62901dd90deSAndreas Gohr    /**
63015929be2SAndreas Gohr     * Find a column to be used in the search
63115929be2SAndreas Gohr     *
63215929be2SAndreas Gohr     * @param string $colname may contain an alias
63315929be2SAndreas Gohr     * @return bool|Column
63415929be2SAndreas Gohr     */
6350280da9aSFrieder Schrempf    public function findColumn($colname, $strict = false)
63661356325SAnna Dabrowska    {
6375511bd5bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
638df02ffe6SMichael Große        $schema_list = array_keys($this->schemas);
639f107f479SAndreas Gohr
640f107f479SAndreas Gohr        // add "fake" column for special col
641128d4e83SAndreas Gohr        if ($colname == '%pageid%') {
642128d4e83SAndreas Gohr            return new PageColumn(0, new Page(), $schema_list[0]);
643d1b04e89SAndreas Gohr        }
644128d4e83SAndreas Gohr        if ($colname == '%title%') {
645128d4e83SAndreas Gohr            return new PageColumn(0, new Page(array('usetitles' => true)), $schema_list[0]);
646128d4e83SAndreas Gohr        }
647cadfc3ccSAndreas Gohr        if ($colname == '%lastupdate%') {
648cadfc3ccSAndreas Gohr            return new RevisionColumn(0, new DateTime(), $schema_list[0]);
649cadfc3ccSAndreas Gohr        }
6502e12ac22SMichael Grosse        if ($colname == '%lasteditor%') {
6512e12ac22SMichael Grosse            return new UserColumn(0, new User(), $schema_list[0]);
6522e12ac22SMichael Grosse        }
65388b58a21SSzymon Olewniczak        if ($colname == '%lastsummary%') {
6546781c68dSSzymon Olewniczak            return new SummaryColumn(0, new AutoSummary(), $schema_list[0]);
65588b58a21SSzymon Olewniczak        }
656f107f479SAndreas Gohr        if ($colname == '%rowid%') {
657f107f479SAndreas Gohr            return new RowColumn(0, new Decimal(), $schema_list[0]);
658f107f479SAndreas Gohr        }
659da62ec9cSAnna Dabrowska        if ($colname == '%published%') {
660da62ec9cSAnna Dabrowska            return new PublishedColumn(0, new Decimal(), $schema_list[0]);
661da62ec9cSAnna Dabrowska        }
662d1b04e89SAndreas Gohr
663636a5173SAndreas Gohr        list($colname, $table) = $this->resolveColumn($colname);
66415929be2SAndreas Gohr
6650280da9aSFrieder Schrempf        /*
6660280da9aSFrieder Schrempf         * If table name is given search only that, otherwise if no strict behavior
6670280da9aSFrieder Schrempf         * is requested by the caller, try all assigned schemas for matching the
6680280da9aSFrieder Schrempf         * column name.
6690280da9aSFrieder Schrempf         */
67034ea6e10SAnna Dabrowska        if ($table !== null && isset($this->schemas[$table])) {
67115929be2SAndreas Gohr            $schemas = array($table => $this->schemas[$table]);
6720280da9aSFrieder Schrempf        } elseif ($table === null || !$strict) {
67315929be2SAndreas Gohr            $schemas = $this->schemas;
6740280da9aSFrieder Schrempf        } else {
6750280da9aSFrieder Schrempf            return false;
67615929be2SAndreas Gohr        }
67715929be2SAndreas Gohr
67815929be2SAndreas Gohr        // find it
67915929be2SAndreas Gohr        $col = false;
68015929be2SAndreas Gohr        foreach ($schemas as $schema) {
6814ac44d1cSMichael Grosse            if (empty($schema)) {
6824ac44d1cSMichael Grosse                continue;
6834ac44d1cSMichael Grosse            }
68415929be2SAndreas Gohr            $col = $schema->findColumn($colname);
68515929be2SAndreas Gohr            if ($col) break;
68615929be2SAndreas Gohr        }
68715929be2SAndreas Gohr
68815929be2SAndreas Gohr        return $col;
68915929be2SAndreas Gohr    }
69015929be2SAndreas Gohr
6919dbc8ec0SMichael Grosse    /**
69299a70f28SAndreas Gohr     * Check if the given row is empty or references our own row
6939dbc8ec0SMichael Grosse     *
69499a70f28SAndreas Gohr     * @param Value $value
6959dbc8ec0SMichael Grosse     * @return bool
6969dbc8ec0SMichael Grosse     */
69761356325SAnna Dabrowska    protected function isEmptyValue(Value $value)
69861356325SAnna Dabrowska    {
69999a70f28SAndreas Gohr        if ($value->isEmpty()) return true;
7008cba7aa0SMichael Grosse        if ($value->getColumn()->getTid() == 0) return true;
7019dbc8ec0SMichael Grosse        return false;
7029dbc8ec0SMichael Grosse    }
70315929be2SAndreas Gohr}
704