xref: /plugin/struct/meta/Search.php (revision b3a9db2269e6f282a06527b6ba5f5122bdbc5b9d)
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
26bb8d98c4SAnna Dabrowska    /** @var \helper_plugin_struct_db */
27bb8d98c4SAnna Dabrowska    protected $dbHelper;
28bb8d98c4SAnna 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    {
67837e87e2SAnna Dabrowska        /** @var  $dbHelper */
68837e87e2SAnna Dabrowska        $this->dbHelper = plugin_load('helper', 'struct_db');
69837e87e2SAnna Dabrowska        $this->sqlite = $this->dbHelper->getDB();
70bb8d98c4SAnna Dabrowska    }
71837e87e2SAnna Dabrowska
72837e87e2SAnna Dabrowska    public function getDb()
73837e87e2SAnna Dabrowska    {
74837e87e2SAnna 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    /**
139*b3a9db22SAndreas Gohr     * Clear all sorting options
140*b3a9db22SAndreas Gohr     *
141*b3a9db22SAndreas Gohr     * @return void
142*b3a9db22SAndreas Gohr     */
143*b3a9db22SAndreas Gohr    public function clearSort()
144*b3a9db22SAndreas Gohr    {
145*b3a9db22SAndreas Gohr        $this->sortby = [];
146*b3a9db22SAndreas Gohr    }
147*b3a9db22SAndreas Gohr
148*b3a9db22SAndreas Gohr    /**
14907993756SAndreas Gohr     * Returns all set sort columns
15007993756SAndreas Gohr     *
15107993756SAndreas Gohr     * @return array
15207993756SAndreas Gohr     */
15361356325SAnna Dabrowska    public function getSorts()
15461356325SAnna Dabrowska    {
15507993756SAndreas Gohr        return $this->sortby;
15615929be2SAndreas Gohr    }
15715929be2SAndreas Gohr
15815929be2SAndreas Gohr    /**
1599d7a36f9SAndreas Gohr     * Adds a filter
16015929be2SAndreas Gohr     *
16115929be2SAndreas Gohr     * @param string $colname may contain an alias
16253528ecfSAndreas Gohr     * @param string|string[] $value
1635511bd5bSAndreas Gohr     * @param string $comp @see self::COMPARATORS
1644c13ff97SAndreas Gohr     * @param string $op either 'OR' or 'AND'
16515929be2SAndreas Gohr     */
16661356325SAnna Dabrowska    public function addFilter($colname, $value, $comp, $op = 'OR')
16761356325SAnna Dabrowska    {
1689dbc32aeSAndreas Gohr        /* Convert certain filters into others
1699dbc32aeSAndreas Gohr         * this reduces the number of supported filters to implement in types */
1709dbc32aeSAndreas Gohr        if ($comp == '*~') {
17153528ecfSAndreas Gohr            $value = $this->filterWrapAsterisks($value);
1729dbc32aeSAndreas Gohr            $comp = '~';
1739dbc32aeSAndreas Gohr        } elseif ($comp == '<>') {
1749dbc32aeSAndreas Gohr            $comp = '!=';
1759dbc32aeSAndreas Gohr        }
1769dbc32aeSAndreas Gohr
17717a3a578SAndreas Gohr        if (!in_array($comp, self::$COMPARATORS))
17817a3a578SAndreas Gohr            throw new StructException("Bad comperator. Use " . join(',', self::$COMPARATORS));
17917a3a578SAndreas Gohr        if ($op != 'OR' && $op != 'AND')
18017a3a578SAndreas Gohr            throw new StructException('Bad filter type . Only AND or OR allowed');
1819d7a36f9SAndreas Gohr
18215929be2SAndreas Gohr        $col = $this->findColumn($colname);
1837da1a0fdSAndreas Gohr        if (!$col) return; // ignore missing columns, filter might have been for different schema
1847da1a0fdSAndreas Gohr
1857da1a0fdSAndreas Gohr        // map filter operators to SQL syntax
1867da1a0fdSAndreas Gohr        switch ($comp) {
1877da1a0fdSAndreas Gohr            case '~':
1887da1a0fdSAndreas Gohr                $comp = 'LIKE';
1897da1a0fdSAndreas Gohr                break;
1907da1a0fdSAndreas Gohr            case '!~':
1917da1a0fdSAndreas Gohr                $comp = 'NOT LIKE';
1927da1a0fdSAndreas Gohr                break;
1937da1a0fdSAndreas Gohr            case '=*':
1947da1a0fdSAndreas Gohr                $comp = 'REGEXP';
1957da1a0fdSAndreas Gohr                break;
1967da1a0fdSAndreas Gohr        }
1977da1a0fdSAndreas Gohr
1987da1a0fdSAndreas Gohr        // we use asterisks, but SQL wants percents
1997da1a0fdSAndreas Gohr        if ($comp == 'LIKE' || $comp == 'NOT LIKE') {
20053528ecfSAndreas Gohr            $value = $this->filterChangeToLike($value);
2017da1a0fdSAndreas Gohr        }
2027da1a0fdSAndreas Gohr
203aaa187abSSzymon Olewniczak        if ($comp == ' IN ' && !is_array($value)) {
204efff5841SSzymon Olewniczak            $value = $this->parseFilterValueList($value);
205aaa187abSSzymon Olewniczak            //col IN ('a', 'b', 'c') is equal to col = 'a' OR 'col = 'b' OR col = 'c'
206aaa187abSSzymon Olewniczak            $comp = '=';
207aaa187abSSzymon Olewniczak        }
208aaa187abSSzymon Olewniczak
2097da1a0fdSAndreas Gohr        // add the filter
2104c13ff97SAndreas Gohr        $this->filter[] = array($col, $value, $comp, $op);
21115929be2SAndreas Gohr    }
21215929be2SAndreas Gohr
21315929be2SAndreas Gohr    /**
214aaa187abSSzymon Olewniczak     * Parse SQLite row value into array
215aaa187abSSzymon Olewniczak     *
216aaa187abSSzymon Olewniczak     * @param string $value
217aaa187abSSzymon Olewniczak     * @return string[]
218aaa187abSSzymon Olewniczak     */
21961356325SAnna Dabrowska    protected function parseFilterValueList($value)
22061356325SAnna Dabrowska    {
221efff5841SSzymon Olewniczak        $Handler = new FilterValueListHandler();
222670a6894SAnna Dabrowska        $LexerClass = class_exists('\Doku_Lexer') ? '\Doku_Lexer' : '\dokuwiki\Parsing\Lexer\Lexer';
223670a6894SAnna Dabrowska        $isLegacy = $LexerClass === '\Doku_Lexer';
224670a6894SAnna Dabrowska        /** @var \Doku_Lexer|\dokuwiki\Parsing\Lexer\Lexer $Lexer */
225670a6894SAnna Dabrowska        $Lexer = new $LexerClass($Handler, 'base', true);
226670a6894SAnna Dabrowska
227aaa187abSSzymon Olewniczak
228aaa187abSSzymon Olewniczak        $Lexer->addEntryPattern('\(', 'base', 'row');
229aaa187abSSzymon Olewniczak        $Lexer->addPattern('\s*,\s*', 'row');
230aaa187abSSzymon Olewniczak        $Lexer->addExitPattern('\)', 'row');
231aaa187abSSzymon Olewniczak
232aaa187abSSzymon Olewniczak        $Lexer->addEntryPattern('"', 'row', 'double_quote_string');
233dfe3ae67SAnna Dabrowska        $Lexer->addSpecialPattern('\\\\"', 'double_quote_string', 'escapeSequence');
234aaa187abSSzymon Olewniczak        $Lexer->addExitPattern('"', 'double_quote_string');
235aaa187abSSzymon Olewniczak
236dfe3ae67SAnna Dabrowska        $Lexer->addEntryPattern("'", 'row', 'singleQuoteString');
237dfe3ae67SAnna Dabrowska        $Lexer->addSpecialPattern("\\\\'", 'singleQuoteString', 'escapeSequence');
238dfe3ae67SAnna Dabrowska        $Lexer->addExitPattern("'", 'singleQuoteString');
239aaa187abSSzymon Olewniczak
240dfe3ae67SAnna Dabrowska        $Lexer->mapHandler('double_quote_string', 'singleQuoteString');
241aaa187abSSzymon Olewniczak
242aaa187abSSzymon Olewniczak        $Lexer->addSpecialPattern('[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?', 'row', 'number');
243aaa187abSSzymon Olewniczak
244aaa187abSSzymon Olewniczak        $res = $Lexer->parse($value);
245aaa187abSSzymon Olewniczak
246670a6894SAnna Dabrowska        $currentMode = $isLegacy ? $Lexer->_mode->getCurrent() : $Lexer->getModeStack()->getCurrent();
247670a6894SAnna Dabrowska        if (!$res || $currentMode != 'base') {
248aaa187abSSzymon Olewniczak            throw new StructException('invalid row value syntax');
249aaa187abSSzymon Olewniczak        }
250aaa187abSSzymon Olewniczak
251dfe3ae67SAnna Dabrowska        return $Handler->getRow();
252aaa187abSSzymon Olewniczak    }
253aaa187abSSzymon Olewniczak
254aaa187abSSzymon Olewniczak    /**
25553528ecfSAndreas Gohr     * Wrap given value in asterisks
25653528ecfSAndreas Gohr     *
25753528ecfSAndreas Gohr     * @param string|string[] $value
25853528ecfSAndreas Gohr     * @return string|string[]
25953528ecfSAndreas Gohr     */
26061356325SAnna Dabrowska    protected function filterWrapAsterisks($value)
26161356325SAnna Dabrowska    {
26253528ecfSAndreas Gohr        $map = function ($input) {
26353528ecfSAndreas Gohr            return "*$input*";
26453528ecfSAndreas Gohr        };
26553528ecfSAndreas Gohr
26653528ecfSAndreas Gohr        if (is_array($value)) {
26753528ecfSAndreas Gohr            $value = array_map($map, $value);
26853528ecfSAndreas Gohr        } else {
26953528ecfSAndreas Gohr            $value = $map($value);
27053528ecfSAndreas Gohr        }
27153528ecfSAndreas Gohr        return $value;
27253528ecfSAndreas Gohr    }
27353528ecfSAndreas Gohr
27453528ecfSAndreas Gohr    /**
27553528ecfSAndreas Gohr     * Change given string to use % instead of *
27653528ecfSAndreas Gohr     *
27753528ecfSAndreas Gohr     * @param string|string[] $value
27853528ecfSAndreas Gohr     * @return string|string[]
27953528ecfSAndreas Gohr     */
28061356325SAnna Dabrowska    protected function filterChangeToLike($value)
28161356325SAnna Dabrowska    {
28253528ecfSAndreas Gohr        $map = function ($input) {
28353528ecfSAndreas Gohr            return str_replace('*', '%', $input);
28453528ecfSAndreas Gohr        };
28553528ecfSAndreas Gohr
28653528ecfSAndreas Gohr        if (is_array($value)) {
28753528ecfSAndreas Gohr            $value = array_map($map, $value);
28853528ecfSAndreas Gohr        } else {
28953528ecfSAndreas Gohr            $value = $map($value);
29053528ecfSAndreas Gohr        }
29153528ecfSAndreas Gohr        return $value;
29253528ecfSAndreas Gohr    }
29353528ecfSAndreas Gohr
29453528ecfSAndreas Gohr    /**
2957f9cb794SAndreas Gohr     * Set offset for the results
2967f9cb794SAndreas Gohr     *
2977f9cb794SAndreas Gohr     * @param int $offset
2987f9cb794SAndreas Gohr     */
29961356325SAnna Dabrowska    public function setOffset($offset)
30061356325SAnna Dabrowska    {
3017f9cb794SAndreas Gohr        $limit = 0;
3027f9cb794SAndreas Gohr        if ($this->range_end) {
3037f9cb794SAndreas Gohr            // if there was a limit set previously, the range_end needs to be recalculated
3047f9cb794SAndreas Gohr            $limit = $this->range_end - $this->range_begin;
3057f9cb794SAndreas Gohr        }
3067f9cb794SAndreas Gohr        $this->range_begin = $offset;
3077f9cb794SAndreas Gohr        if ($limit) $this->setLimit($limit);
3087f9cb794SAndreas Gohr    }
3097f9cb794SAndreas Gohr
3107f9cb794SAndreas Gohr    /**
3117f9cb794SAndreas Gohr     * Limit results to this number
3127f9cb794SAndreas Gohr     *
3137f9cb794SAndreas Gohr     * @param int $limit Set to 0 to disable limit again
3147f9cb794SAndreas Gohr     */
31561356325SAnna Dabrowska    public function setLimit($limit)
31661356325SAnna Dabrowska    {
3177f9cb794SAndreas Gohr        if ($limit) {
3187f9cb794SAndreas Gohr            $this->range_end = $this->range_begin + $limit;
3197f9cb794SAndreas Gohr        } else {
3207f9cb794SAndreas Gohr            $this->range_end = 0;
3217f9cb794SAndreas Gohr        }
3227f9cb794SAndreas Gohr    }
3237f9cb794SAndreas Gohr
3247f9cb794SAndreas Gohr    /**
3257f9cb794SAndreas Gohr     * Return the number of results (regardless of limit and offset settings)
3267f9cb794SAndreas Gohr     *
3270549dcc5SAndreas Gohr     * Use this to implement paging. Important: this may only be called after running @return int
3280549dcc5SAndreas Gohr     * @see execute()
3297f9cb794SAndreas Gohr     *
3307f9cb794SAndreas Gohr     */
33161356325SAnna Dabrowska    public function getCount()
33261356325SAnna Dabrowska    {
3337f9cb794SAndreas Gohr        if ($this->count < 0) throw new StructException('Count is only accessible after executing the search');
3347f9cb794SAndreas Gohr        return $this->count;
3357f9cb794SAndreas Gohr    }
3367f9cb794SAndreas Gohr
337c46f5fb1SAndreas Gohr    /**
338c46f5fb1SAndreas Gohr     * Returns the PID associated with each result row
339c46f5fb1SAndreas Gohr     *
3400549dcc5SAndreas Gohr     * Important: this may only be called after running @return \string[]
3410549dcc5SAndreas Gohr     * @see execute()
342c46f5fb1SAndreas Gohr     *
343c46f5fb1SAndreas Gohr     */
34461356325SAnna Dabrowska    public function getPids()
34561356325SAnna Dabrowska    {
34617a3a578SAndreas Gohr        if ($this->result_pids === null)
34717a3a578SAndreas Gohr            throw new StructException('PIDs are only accessible after executing the search');
348d4b5a17cSAndreas Gohr        return $this->result_pids;
349d4b5a17cSAndreas Gohr    }
350d4b5a17cSAndreas Gohr
3517f9cb794SAndreas Gohr    /**
3520ceefd5cSAnna Dabrowska     * Returns the rid associated with each result row
3530ceefd5cSAnna Dabrowska     *
3540549dcc5SAndreas Gohr     * Important: this may only be called after running @return array
3550549dcc5SAndreas Gohr     * @see execute()
3560ceefd5cSAnna Dabrowska     *
3570ceefd5cSAnna Dabrowska     */
35861356325SAnna Dabrowska    public function getRids()
35961356325SAnna Dabrowska    {
36017a3a578SAndreas Gohr        if ($this->result_rids === null)
36117a3a578SAndreas Gohr            throw new StructException('rids are only accessible after executing the search');
3620ceefd5cSAnna Dabrowska        return $this->result_rids;
3630ceefd5cSAnna Dabrowska    }
3640ceefd5cSAnna Dabrowska
3650ceefd5cSAnna Dabrowska    /**
3666fd73b4bSAnna Dabrowska     * Returns the rid associated with each result row
3676fd73b4bSAnna Dabrowska     *
3680549dcc5SAndreas Gohr     * Important: this may only be called after running @return array
3690549dcc5SAndreas Gohr     * @see execute()
3706fd73b4bSAnna Dabrowska     *
3716fd73b4bSAnna Dabrowska     */
37261356325SAnna Dabrowska    public function getRevs()
37361356325SAnna Dabrowska    {
37417a3a578SAndreas Gohr        if ($this->result_revs === null)
37517a3a578SAndreas Gohr            throw new StructException('revs are only accessible after executing the search');
3766fd73b4bSAnna Dabrowska        return $this->result_revs;
3776fd73b4bSAnna Dabrowska    }
3786fd73b4bSAnna Dabrowska
3796fd73b4bSAnna Dabrowska    /**
380b2ed727aSAndreas Gohr     * Execute this search and return the result
381b2ed727aSAndreas Gohr     *
38238fa36fbSAndreas Gohr     * The result is a two dimensional array of Value()s.
3837f9cb794SAndreas Gohr     *
3847f9cb794SAndreas Gohr     * This will always query for the full result (not using offset and limit) and then
3850549dcc5SAndreas Gohr     * return the wanted range, setting the count (@return Value[][]
3860549dcc5SAndreas Gohr     * @see getCount) to the whole result number
38738fa36fbSAndreas Gohr     *
388b2ed727aSAndreas Gohr     */
3898ce43f5aSAnna Dabrowska    public function execute()
39061356325SAnna Dabrowska    {
3918ce43f5aSAnna Dabrowska        list($sql, $opts) = $this->getSQL();
392b2ed727aSAndreas Gohr
3937f9cb794SAndreas Gohr        /** @var \PDOStatement $res */
394b2ed727aSAndreas Gohr        $res = $this->sqlite->query($sql, $opts);
39559b668aaSAndreas Gohr        if ($res === false) throw new StructException("SQL execution failed for\n\n$sql");
396b2ed727aSAndreas Gohr
397d4b5a17cSAndreas Gohr        $this->result_pids = array();
398b2ed727aSAndreas Gohr        $result = array();
3997f9cb794SAndreas Gohr        $cursor = -1;
4005e4bfdb0SMichael Grosse        $pageidAndRevOnly = array_reduce($this->columns, function ($pageidAndRevOnly, Column $col) {
4015e4bfdb0SMichael Grosse            return $pageidAndRevOnly && ($col->getTid() == 0);
4025e4bfdb0SMichael Grosse        }, true);
4037f9cb794SAndreas Gohr        while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
4047f9cb794SAndreas Gohr            $cursor++;
4057f9cb794SAndreas Gohr            if ($cursor < $this->range_begin) continue;
4067f9cb794SAndreas Gohr            if ($this->range_end && $cursor >= $this->range_end) continue;
4077f9cb794SAndreas Gohr
408b2ed727aSAndreas Gohr            $C = 0;
409b2ed727aSAndreas Gohr            $resrow = array();
41099a70f28SAndreas Gohr            $isempty = true;
411b2ed727aSAndreas Gohr            foreach ($this->columns as $col) {
41238fa36fbSAndreas Gohr                $val = $row["C$C"];
413b2ed727aSAndreas Gohr                if ($col->isMulti()) {
41438fa36fbSAndreas Gohr                    $val = explode(self::CONCAT_SEPARATOR, $val);
415b2ed727aSAndreas Gohr                }
41699a70f28SAndreas Gohr                $value = new Value($col, $val);
4178cba7aa0SMichael Grosse                $isempty &= $this->isEmptyValue($value);
41899a70f28SAndreas Gohr                $resrow[] = $value;
419b2ed727aSAndreas Gohr                $C++;
420b2ed727aSAndreas Gohr            }
42199a70f28SAndreas Gohr
42299a70f28SAndreas Gohr            // skip empty rows
4238cba7aa0SMichael Grosse            if ($isempty && !$pageidAndRevOnly) {
42499a70f28SAndreas Gohr                $cursor--;
42599a70f28SAndreas Gohr                continue;
42699a70f28SAndreas Gohr            }
42799a70f28SAndreas Gohr
42899a70f28SAndreas Gohr            $this->result_pids[] = $row['PID'];
4290ceefd5cSAnna Dabrowska            $this->result_rids[] = $row['rid'];
4306fd73b4bSAnna Dabrowska            $this->result_revs[] = $row['rev'];
431b2ed727aSAndreas Gohr            $result[] = $resrow;
432b2ed727aSAndreas Gohr        }
4337f9cb794SAndreas Gohr
43479b29326SAnna Dabrowska        $res->closeCursor();
4357f9cb794SAndreas Gohr        $this->count = $cursor + 1;
436b2ed727aSAndreas Gohr        return $result;
437b2ed727aSAndreas Gohr    }
438b2ed727aSAndreas Gohr
439b2ed727aSAndreas Gohr    /**
44015929be2SAndreas Gohr     * Transform the set search parameters into a statement
44115929be2SAndreas Gohr     *
442b2ed727aSAndreas Gohr     * @return array ($sql, $opts) The SQL and parameters to execute
44315929be2SAndreas Gohr     */
4448ce43f5aSAnna Dabrowska    public function getSQL()
44561356325SAnna Dabrowska    {
4465511bd5bSAndreas Gohr        if (!$this->columns) throw new StructException('nocolname');
44715929be2SAndreas Gohr
4482f68434dSAndreas Gohr        $QB = new QueryBuilder();
44915929be2SAndreas Gohr
4509d7a36f9SAndreas Gohr        // basic tables
451b2d67e7dSAndreas Gohr        $first_table = '';
4529d7a36f9SAndreas Gohr        foreach ($this->schemas as $schema) {
4532f68434dSAndreas Gohr            $datatable = 'data_' . $schema->getTable();
454b2d67e7dSAndreas Gohr            if ($first_table) {
4559d7a36f9SAndreas Gohr                // follow up tables
4568ce43f5aSAnna Dabrowska                $QB->addLeftJoin($first_table, $datatable, $datatable, "$first_table.pid = $datatable.pid");
4579d7a36f9SAndreas Gohr            } else {
4589d7a36f9SAndreas Gohr                // first table
45913c321dbSAndreas Gohr                $QB->addTable($datatable);
4608ce43f5aSAnna Dabrowska
4618ce43f5aSAnna Dabrowska                // add conditional page clauses if pid has a value
4628ce43f5aSAnna Dabrowska                $subAnd = $QB->filters()->whereSubAnd();
4638ce43f5aSAnna Dabrowska                $subAnd->whereAnd("$datatable.pid = ''");
4648ce43f5aSAnna Dabrowska                $subOr = $subAnd->whereSubOr();
4658ce43f5aSAnna Dabrowska                $subOr->whereAnd("GETACCESSLEVEL($datatable.pid) > 0");
4668ce43f5aSAnna Dabrowska                $subOr->whereAnd("PAGEEXISTS($datatable.pid) = 1");
46754efd03eSAnna Dabrowska                $subOr->whereAnd('(ASSIGNED = 1 OR ASSIGNED IS NULL)');
4688ce43f5aSAnna Dabrowska
4698ce43f5aSAnna Dabrowska                // add conditional schema assignment check
470f183bf6eSAnna Dabrowska                $QB->addLeftJoin(
471f183bf6eSAnna Dabrowska                    $datatable,
472f183bf6eSAnna Dabrowska                    'schema_assignments',
473f183bf6eSAnna Dabrowska                    '',
4748ce43f5aSAnna Dabrowska                    "$datatable.pid != ''
4758ce43f5aSAnna Dabrowska                    AND $datatable.pid = schema_assignments.pid
47638e29673SAnna Dabrowska                    AND schema_assignments.tbl = '{$schema->getTable()}'"
4778ce43f5aSAnna Dabrowska                );
4788ce43f5aSAnna Dabrowska
4790ceefd5cSAnna Dabrowska                $QB->addSelectColumn($datatable, 'rid');
48013c321dbSAndreas Gohr                $QB->addSelectColumn($datatable, 'pid', 'PID');
4816fd73b4bSAnna Dabrowska                $QB->addSelectColumn($datatable, 'rev');
48238e29673SAnna Dabrowska                $QB->addSelectColumn('schema_assignments', 'assigned', 'ASSIGNED');
48313c321dbSAndreas Gohr                $QB->addGroupByColumn($datatable, 'pid');
484e3104939SAnna Dabrowska                $QB->addGroupByColumn($datatable, 'rid');
485b2d67e7dSAndreas Gohr
4862f68434dSAndreas Gohr                $first_table = $datatable;
48715929be2SAndreas Gohr            }
488bb8d98c4SAnna Dabrowska            // phpcs:ignore
48900624072SAnna Dabrowska            $QB->filters()->whereAnd("( (IS_PUBLISHER($datatable.pid) AND $datatable.latest = 1) OR (IS_PUBLISHER($datatable.pid) !=1 AND $datatable.published = 1) )");
4909d7a36f9SAndreas Gohr        }
49115929be2SAndreas Gohr
49215929be2SAndreas Gohr        // columns to select, handling multis
4939d7a36f9SAndreas Gohr        $sep = self::CONCAT_SEPARATOR;
49415929be2SAndreas Gohr        $n = 0;
49515929be2SAndreas Gohr        foreach ($this->columns as $col) {
49615929be2SAndreas Gohr            $CN = 'C' . $n++;
49715929be2SAndreas Gohr
498d1b04e89SAndreas Gohr            if ($col->isMulti()) {
4992f68434dSAndreas Gohr                $datatable = "data_{$col->getTable()}";
5002f68434dSAndreas Gohr                $multitable = "multi_{$col->getTable()}";
501db7970caSAndreas Gohr                $MN = $QB->generateTableAlias('M');
5022f68434dSAndreas Gohr
5032f68434dSAndreas Gohr                $QB->addLeftJoin(
5042f68434dSAndreas Gohr                    $datatable,
5052f68434dSAndreas Gohr                    $multitable,
5062f68434dSAndreas Gohr                    $MN,
5078ce43f5aSAnna Dabrowska                    "$datatable.pid = $MN.pid AND $datatable.rid = $MN.rid AND
5082f68434dSAndreas Gohr                     $datatable.rev = $MN.rev AND
5092f68434dSAndreas Gohr                     $MN.colref = {$col->getColref()}"
5102f68434dSAndreas Gohr                );
511578407b2SAndreas Gohr
512578407b2SAndreas Gohr                $col->getType()->select($QB, $MN, 'value', $CN);
513578407b2SAndreas Gohr                $sel = $QB->getSelectStatement($CN);
514acc82d60SAndreas Gohr                $QB->addSelectStatement("GROUP_CONCAT_DISTINCT($sel, '$sep')", $CN);
51515929be2SAndreas Gohr            } else {
516578407b2SAndreas Gohr                $col->getType()->select($QB, 'data_' . $col->getTable(), $col->getColName(), $CN);
5170dbe7bf6SAndreas Gohr                $QB->addGroupByStatement($CN);
51815929be2SAndreas Gohr            }
51915929be2SAndreas Gohr        }
52015929be2SAndreas Gohr
5219d7a36f9SAndreas Gohr        // where clauses
522af993d55SMichael Grosse        if (!empty($this->filter)) {
523af993d55SMichael Grosse            $userWHERE = $QB->filters()->where('AND');
524af993d55SMichael Grosse        }
525b8fe6730SAndreas Gohr        foreach ($this->filter as $filter) {
5269ebd2ed6SAndreas Gohr            /** @var Column $col */
5274c13ff97SAndreas Gohr            list($col, $value, $comp, $op) = $filter;
528b8fe6730SAndreas Gohr
5292f68434dSAndreas Gohr            $datatable = "data_{$col->getTable()}";
5302f68434dSAndreas Gohr            $multitable = "multi_{$col->getTable()}";
5319d7a36f9SAndreas Gohr
5329d7a36f9SAndreas Gohr            /** @var $col Column */
5339d7a36f9SAndreas Gohr            if ($col->isMulti()) {
534db7970caSAndreas Gohr                $MN = $QB->generateTableAlias('MN');
53515929be2SAndreas Gohr
5362f68434dSAndreas Gohr                $QB->addLeftJoin(
5372f68434dSAndreas Gohr                    $datatable,
5382f68434dSAndreas Gohr                    $multitable,
5392f68434dSAndreas Gohr                    $MN,
5408ce43f5aSAnna Dabrowska                    "$datatable.pid = $MN.pid AND $datatable.rid = $MN.rid AND
5412f68434dSAndreas Gohr                     $datatable.rev = $MN.rev AND
5422f68434dSAndreas Gohr                     $MN.colref = {$col->getColref()}"
5432f68434dSAndreas Gohr                );
544690e4ebaSAndreas Gohr                $coltbl = $MN;
545690e4ebaSAndreas Gohr                $colnam = 'value';
5469d7a36f9SAndreas Gohr            } else {
547690e4ebaSAndreas Gohr                $coltbl = $datatable;
548690e4ebaSAndreas Gohr                $colnam = $col->getColName();
5499d7a36f9SAndreas Gohr            }
55053528ecfSAndreas Gohr
551af993d55SMichael Grosse            $col->getType()->filter($userWHERE, $coltbl, $colnam, $comp, $value, $op); // type based filter
5529d7a36f9SAndreas Gohr        }
5539d7a36f9SAndreas Gohr
55429394e6cSAndreas Gohr        // sorting - we always sort by the single val column
555b8fe6730SAndreas Gohr        foreach ($this->sortby as $sort) {
556eb55dc17SAndreas Gohr            list($col, $asc, $nc) = $sort;
5579d7a36f9SAndreas Gohr            /** @var $col Column */
558eb55dc17SAndreas Gohr            $colname = $col->getColName(false);
559eb55dc17SAndreas Gohr            if ($nc) $colname .= ' COLLATE NOCASE';
560eb55dc17SAndreas Gohr            $col->getType()->sort($QB, 'data_' . $col->getTable(), $colname, $asc ? 'ASC' : 'DESC');
5619e07bdbfSAndreas Gohr        }
5629e07bdbfSAndreas Gohr
5632f68434dSAndreas Gohr        return $QB->getSQL();
56415929be2SAndreas Gohr    }
56515929be2SAndreas Gohr
56615929be2SAndreas Gohr    /**
56701dd90deSAndreas Gohr     * Returns all the columns that where added to the search
56801dd90deSAndreas Gohr     *
56901dd90deSAndreas Gohr     * @return Column[]
57001dd90deSAndreas Gohr     */
57161356325SAnna Dabrowska    public function getColumns()
57261356325SAnna Dabrowska    {
57301dd90deSAndreas Gohr        return $this->columns;
57401dd90deSAndreas Gohr    }
57501dd90deSAndreas Gohr
576577b462bSAndreas Gohr    /**
5775a4df70dSAndreas Gohr     * All the schemas currently added
5785a4df70dSAndreas Gohr     *
5795a4df70dSAndreas Gohr     * @return Schema[]
5805a4df70dSAndreas Gohr     */
58161356325SAnna Dabrowska    public function getSchemas()
58261356325SAnna Dabrowska    {
5835a4df70dSAndreas Gohr        return array_values($this->schemas);
5845a4df70dSAndreas Gohr    }
5855a4df70dSAndreas Gohr
5865a4df70dSAndreas Gohr    /**
587577b462bSAndreas Gohr     * Checks if the given column is a * wildcard
588577b462bSAndreas Gohr     *
589577b462bSAndreas Gohr     * If it's a wildcard all matching columns are added to the column list, otherwise
590577b462bSAndreas Gohr     * nothing happens
591577b462bSAndreas Gohr     *
592577b462bSAndreas Gohr     * @param string $colname
593577b462bSAndreas Gohr     * @return bool was wildcard?
594577b462bSAndreas Gohr     */
59561356325SAnna Dabrowska    protected function processWildcard($colname)
59661356325SAnna Dabrowska    {
597636a5173SAndreas Gohr        list($colname, $table) = $this->resolveColumn($colname);
598577b462bSAndreas Gohr        if ($colname !== '*') return false;
599577b462bSAndreas Gohr
600577b462bSAndreas Gohr        // no table given? assume the first is meant
601577b462bSAndreas Gohr        if ($table === null) {
602577b462bSAndreas Gohr            $schema_list = array_keys($this->schemas);
603577b462bSAndreas Gohr            $table = $schema_list[0];
604577b462bSAndreas Gohr        }
605577b462bSAndreas Gohr
6061ca21e17SAnna Dabrowska        $schema = $this->schemas[$table] ?? null;
607577b462bSAndreas Gohr        if (!$schema) return false;
608577b462bSAndreas Gohr        $this->columns = array_merge($this->columns, $schema->getColumns(false));
609577b462bSAndreas Gohr        return true;
610577b462bSAndreas Gohr    }
611577b462bSAndreas Gohr
612577b462bSAndreas Gohr    /**
613577b462bSAndreas Gohr     * Split a given column name into table and column
614577b462bSAndreas Gohr     *
615577b462bSAndreas Gohr     * Handles Aliases. Table might be null if none given.
616577b462bSAndreas Gohr     *
617577b462bSAndreas Gohr     * @param $colname
618636a5173SAndreas Gohr     * @return array (colname, table)
619577b462bSAndreas Gohr     */
62061356325SAnna Dabrowska    protected function resolveColumn($colname)
62161356325SAnna Dabrowska    {
622577b462bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
623577b462bSAndreas Gohr
624577b462bSAndreas Gohr        // resolve the alias or table name
62525ed0c0dSAndreas Gohr        @list($table, $colname) = array_pad(explode('.', $colname, 2), 2, '');
626577b462bSAndreas Gohr        if (!$colname) {
627577b462bSAndreas Gohr            $colname = $table;
628577b462bSAndreas Gohr            $table = null;
629577b462bSAndreas Gohr        }
630577b462bSAndreas Gohr        if ($table && isset($this->aliases[$table])) {
631577b462bSAndreas Gohr            $table = $this->aliases[$table];
632577b462bSAndreas Gohr        }
633577b462bSAndreas Gohr
634577b462bSAndreas Gohr        if (!$colname) throw new StructException('nocolname');
635577b462bSAndreas Gohr
636577b462bSAndreas Gohr        return array($colname, $table);
637577b462bSAndreas Gohr    }
63801dd90deSAndreas Gohr
63901dd90deSAndreas Gohr    /**
64015929be2SAndreas Gohr     * Find a column to be used in the search
64115929be2SAndreas Gohr     *
64215929be2SAndreas Gohr     * @param string $colname may contain an alias
64315929be2SAndreas Gohr     * @return bool|Column
64415929be2SAndreas Gohr     */
6450280da9aSFrieder Schrempf    public function findColumn($colname, $strict = false)
64661356325SAnna Dabrowska    {
6475511bd5bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
648df02ffe6SMichael Große        $schema_list = array_keys($this->schemas);
649f107f479SAndreas Gohr
650f107f479SAndreas Gohr        // add "fake" column for special col
651128d4e83SAndreas Gohr        if ($colname == '%pageid%') {
652128d4e83SAndreas Gohr            return new PageColumn(0, new Page(), $schema_list[0]);
653d1b04e89SAndreas Gohr        }
654128d4e83SAndreas Gohr        if ($colname == '%title%') {
655128d4e83SAndreas Gohr            return new PageColumn(0, new Page(array('usetitles' => true)), $schema_list[0]);
656128d4e83SAndreas Gohr        }
657cadfc3ccSAndreas Gohr        if ($colname == '%lastupdate%') {
658cadfc3ccSAndreas Gohr            return new RevisionColumn(0, new DateTime(), $schema_list[0]);
659cadfc3ccSAndreas Gohr        }
6602e12ac22SMichael Grosse        if ($colname == '%lasteditor%') {
6612e12ac22SMichael Grosse            return new UserColumn(0, new User(), $schema_list[0]);
6622e12ac22SMichael Grosse        }
66388b58a21SSzymon Olewniczak        if ($colname == '%lastsummary%') {
6646781c68dSSzymon Olewniczak            return new SummaryColumn(0, new AutoSummary(), $schema_list[0]);
66588b58a21SSzymon Olewniczak        }
666f107f479SAndreas Gohr        if ($colname == '%rowid%') {
667f107f479SAndreas Gohr            return new RowColumn(0, new Decimal(), $schema_list[0]);
668f107f479SAndreas Gohr        }
669da62ec9cSAnna Dabrowska        if ($colname == '%published%') {
670da62ec9cSAnna Dabrowska            return new PublishedColumn(0, new Decimal(), $schema_list[0]);
671da62ec9cSAnna Dabrowska        }
672d1b04e89SAndreas Gohr
673636a5173SAndreas Gohr        list($colname, $table) = $this->resolveColumn($colname);
67415929be2SAndreas Gohr
6750280da9aSFrieder Schrempf        /*
6760280da9aSFrieder Schrempf         * If table name is given search only that, otherwise if no strict behavior
6770280da9aSFrieder Schrempf         * is requested by the caller, try all assigned schemas for matching the
6780280da9aSFrieder Schrempf         * column name.
6790280da9aSFrieder Schrempf         */
68034ea6e10SAnna Dabrowska        if ($table !== null && isset($this->schemas[$table])) {
68115929be2SAndreas Gohr            $schemas = array($table => $this->schemas[$table]);
6820280da9aSFrieder Schrempf        } elseif ($table === null || !$strict) {
68315929be2SAndreas Gohr            $schemas = $this->schemas;
6840280da9aSFrieder Schrempf        } else {
6850280da9aSFrieder Schrempf            return false;
68615929be2SAndreas Gohr        }
68715929be2SAndreas Gohr
68815929be2SAndreas Gohr        // find it
68915929be2SAndreas Gohr        $col = false;
69015929be2SAndreas Gohr        foreach ($schemas as $schema) {
6914ac44d1cSMichael Grosse            if (empty($schema)) {
6924ac44d1cSMichael Grosse                continue;
6934ac44d1cSMichael Grosse            }
69415929be2SAndreas Gohr            $col = $schema->findColumn($colname);
69515929be2SAndreas Gohr            if ($col) break;
69615929be2SAndreas Gohr        }
69715929be2SAndreas Gohr
69815929be2SAndreas Gohr        return $col;
69915929be2SAndreas Gohr    }
70015929be2SAndreas Gohr
7019dbc8ec0SMichael Grosse    /**
70299a70f28SAndreas Gohr     * Check if the given row is empty or references our own row
7039dbc8ec0SMichael Grosse     *
70499a70f28SAndreas Gohr     * @param Value $value
7059dbc8ec0SMichael Grosse     * @return bool
7069dbc8ec0SMichael Grosse     */
70761356325SAnna Dabrowska    protected function isEmptyValue(Value $value)
70861356325SAnna Dabrowska    {
70999a70f28SAndreas Gohr        if ($value->isEmpty()) return true;
7108cba7aa0SMichael Grosse        if ($value->getColumn()->getTid() == 0) return true;
7119dbc8ec0SMichael Grosse        return false;
7129dbc8ec0SMichael Grosse    }
71315929be2SAndreas Gohr}
714