xref: /plugin/struct/meta/Search.php (revision 1057ed145ebe196623f851365e7cea64a25415b6)
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
44*1057ed14SAndreas Gohr    /** @var array the filters */
45*1057ed14SAndreas Gohr    protected $dynamicFilter = array();
46*1057ed14SAndreas Gohr
4715929be2SAndreas Gohr    /** @var array list of aliases tables can be referenced by */
4815929be2SAndreas Gohr    protected $aliases = array();
4915929be2SAndreas Gohr
507f9cb794SAndreas Gohr    /** @var  int begin results from here */
517f9cb794SAndreas Gohr    protected $range_begin = 0;
527f9cb794SAndreas Gohr
537f9cb794SAndreas Gohr    /** @var  int end results here */
547f9cb794SAndreas Gohr    protected $range_end = 0;
557f9cb794SAndreas Gohr
567f9cb794SAndreas Gohr    /** @var int the number of results */
577f9cb794SAndreas Gohr    protected $count = -1;
58d4b5a17cSAndreas Gohr    /** @var  string[] the PIDs of the result rows */
59d4b5a17cSAndreas Gohr    protected $result_pids = null;
600ceefd5cSAnna Dabrowska    /** @var  array the row ids of the result rows */
610ceefd5cSAnna Dabrowska    protected $result_rids = [];
626fd73b4bSAnna Dabrowska    /** @var  array the revisions of the result rows */
636fd73b4bSAnna Dabrowska    protected $result_revs = [];
647f9cb794SAndreas Gohr
6515929be2SAndreas Gohr    /**
669d7a36f9SAndreas Gohr     * Search constructor.
679d7a36f9SAndreas Gohr     */
6861356325SAnna Dabrowska    public function __construct()
6961356325SAnna Dabrowska    {
70837e87e2SAnna Dabrowska        /** @var  $dbHelper */
71837e87e2SAnna Dabrowska        $this->dbHelper = plugin_load('helper', 'struct_db');
72837e87e2SAnna Dabrowska        $this->sqlite = $this->dbHelper->getDB();
73bb8d98c4SAnna Dabrowska    }
74837e87e2SAnna Dabrowska
75837e87e2SAnna Dabrowska    public function getDb()
76837e87e2SAnna Dabrowska    {
77837e87e2SAnna Dabrowska        return $this->sqlite;
789d7a36f9SAndreas Gohr    }
799d7a36f9SAndreas Gohr
809d7a36f9SAndreas Gohr    /**
8115929be2SAndreas Gohr     * Add a schema to be searched
8215929be2SAndreas Gohr     *
8315929be2SAndreas Gohr     * Call multiple times for multiple schemas.
8415929be2SAndreas Gohr     *
8515929be2SAndreas Gohr     * @param string $table
8615929be2SAndreas Gohr     * @param string $alias
8715929be2SAndreas Gohr     */
8861356325SAnna Dabrowska    public function addSchema($table, $alias = '')
8961356325SAnna Dabrowska    {
902be187cdSAndreas Gohr        $schema = new Schema($table);
912be187cdSAndreas Gohr        if (!$schema->getId()) {
922be187cdSAndreas Gohr            throw new StructException('schema missing', $table);
932be187cdSAndreas Gohr        }
942be187cdSAndreas Gohr
95712c650dSAndreas Gohr        $this->schemas[$schema->getTable()] = $schema;
96712c650dSAndreas Gohr        if ($alias) $this->aliases[$alias] = $schema->getTable();
9715929be2SAndreas Gohr    }
9815929be2SAndreas Gohr
9915929be2SAndreas Gohr    /**
10015929be2SAndreas Gohr     * Add a column to be returned by the search
10115929be2SAndreas Gohr     *
10215929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
10315929be2SAndreas Gohr     * added before
10415929be2SAndreas Gohr     *
10515929be2SAndreas Gohr     * @param string $colname may contain an alias
10615929be2SAndreas Gohr     */
10761356325SAnna Dabrowska    public function addColumn($colname)
10861356325SAnna Dabrowska    {
109577b462bSAndreas Gohr        if ($this->processWildcard($colname)) return; // wildcard?
110b26126edSAndreas Hubel        if ($colname[0] == '-') { // remove column from previous wildcard lookup
111b26126edSAndreas Hubel            $colname = substr($colname, 1);
112b26126edSAndreas Hubel            foreach ($this->columns as $key => $col) {
113b26126edSAndreas Hubel                if ($col->getLabel() == $colname) unset($this->columns[$key]);
114b26126edSAndreas Hubel            }
115b26126edSAndreas Hubel            return;
116b26126edSAndreas Hubel        }
117b26126edSAndreas Hubel
11815929be2SAndreas Gohr        $col = $this->findColumn($colname);
11915929be2SAndreas Gohr        if (!$col) return; //FIXME do we really want to ignore missing columns?
12015929be2SAndreas Gohr        $this->columns[] = $col;
12115929be2SAndreas Gohr    }
12215929be2SAndreas Gohr
12315929be2SAndreas Gohr    /**
12415929be2SAndreas Gohr     * Add sorting options
12515929be2SAndreas Gohr     *
12615929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
12715929be2SAndreas Gohr     * added before
12815929be2SAndreas Gohr     *
12915929be2SAndreas Gohr     * @param string $colname may contain an alias
13015929be2SAndreas Gohr     * @param bool $asc sort direction (ASC = true, DESC = false)
131eb55dc17SAndreas Gohr     * @param bool $nc set true for caseinsensitivity
13215929be2SAndreas Gohr     */
13361356325SAnna Dabrowska    public function addSort($colname, $asc = true, $nc = true)
13461356325SAnna Dabrowska    {
13515929be2SAndreas Gohr        $col = $this->findColumn($colname);
13615929be2SAndreas Gohr        if (!$col) return; //FIXME do we really want to ignore missing columns?
13715929be2SAndreas Gohr
138eb55dc17SAndreas Gohr        $this->sortby[$col->getFullQualifiedLabel()] = array($col, $asc, $nc);
13907993756SAndreas Gohr    }
14007993756SAndreas Gohr
14107993756SAndreas Gohr    /**
142b3a9db22SAndreas Gohr     * Clear all sorting options
143b3a9db22SAndreas Gohr     *
144b3a9db22SAndreas Gohr     * @return void
145b3a9db22SAndreas Gohr     */
146b3a9db22SAndreas Gohr    public function clearSort()
147b3a9db22SAndreas Gohr    {
148b3a9db22SAndreas Gohr        $this->sortby = [];
149b3a9db22SAndreas Gohr    }
150b3a9db22SAndreas Gohr
151b3a9db22SAndreas Gohr    /**
15207993756SAndreas Gohr     * Returns all set sort columns
15307993756SAndreas Gohr     *
15407993756SAndreas Gohr     * @return array
15507993756SAndreas Gohr     */
15661356325SAnna Dabrowska    public function getSorts()
15761356325SAnna Dabrowska    {
15807993756SAndreas Gohr        return $this->sortby;
15915929be2SAndreas Gohr    }
16015929be2SAndreas Gohr
16115929be2SAndreas Gohr    /**
1629d7a36f9SAndreas Gohr     * Adds a filter
16315929be2SAndreas Gohr     *
16415929be2SAndreas Gohr     * @param string $colname may contain an alias
16553528ecfSAndreas Gohr     * @param string|string[] $value
1665511bd5bSAndreas Gohr     * @param string $comp @see self::COMPARATORS
1674c13ff97SAndreas Gohr     * @param string $op either 'OR' or 'AND'
16815929be2SAndreas Gohr     */
16961356325SAnna Dabrowska    public function addFilter($colname, $value, $comp, $op = 'OR')
17061356325SAnna Dabrowska    {
171*1057ed14SAndreas Gohr        $filter = $this->createFilter($colname, $value, $comp, $op);
172*1057ed14SAndreas Gohr        if ($filter) $this->filter[] = $filter;
173*1057ed14SAndreas Gohr    }
174*1057ed14SAndreas Gohr
175*1057ed14SAndreas Gohr    /**
176*1057ed14SAndreas Gohr     * Adds a dynamic filter
177*1057ed14SAndreas Gohr     *
178*1057ed14SAndreas Gohr     * @param string $colname may contain an alias
179*1057ed14SAndreas Gohr     * @param string|string[] $value
180*1057ed14SAndreas Gohr     * @param string $comp @see self::COMPARATORS
181*1057ed14SAndreas Gohr     * @param string $op either 'OR' or 'AND'
182*1057ed14SAndreas Gohr     */
183*1057ed14SAndreas Gohr    public function addDynamicFilter($colname, $value, $comp, $op = 'OR')
184*1057ed14SAndreas Gohr    {
185*1057ed14SAndreas Gohr        $filter = $this->createFilter($colname, $value, $comp, $op);
186*1057ed14SAndreas Gohr        if ($filter) $this->dynamicFilter[] = $filter;
187*1057ed14SAndreas Gohr    }
188*1057ed14SAndreas Gohr
189*1057ed14SAndreas Gohr    /**
190*1057ed14SAndreas Gohr     * Create a filter definition
191*1057ed14SAndreas Gohr     *
192*1057ed14SAndreas Gohr     * @param string $colname may contain an alias
193*1057ed14SAndreas Gohr     * @param string|string[] $value
194*1057ed14SAndreas Gohr     * @param string $comp @see self::COMPARATORS
195*1057ed14SAndreas Gohr     * @param string $op either 'OR' or 'AND'
196*1057ed14SAndreas Gohr     * @return array|null [Column col, string|string[] value, string comp, string op]
197*1057ed14SAndreas Gohr     */
198*1057ed14SAndreas Gohr    protected function createFilter($colname, $value, $comp, $op = 'OR')
199*1057ed14SAndreas Gohr    {
2009dbc32aeSAndreas Gohr        /* Convert certain filters into others
2019dbc32aeSAndreas Gohr         * this reduces the number of supported filters to implement in types */
2029dbc32aeSAndreas Gohr        if ($comp == '*~') {
20353528ecfSAndreas Gohr            $value = $this->filterWrapAsterisks($value);
2049dbc32aeSAndreas Gohr            $comp = '~';
2059dbc32aeSAndreas Gohr        } elseif ($comp == '<>') {
2069dbc32aeSAndreas Gohr            $comp = '!=';
2079dbc32aeSAndreas Gohr        }
2089dbc32aeSAndreas Gohr
20917a3a578SAndreas Gohr        if (!in_array($comp, self::$COMPARATORS))
21017a3a578SAndreas Gohr            throw new StructException("Bad comperator. Use " . join(',', self::$COMPARATORS));
21117a3a578SAndreas Gohr        if ($op != 'OR' && $op != 'AND')
21217a3a578SAndreas Gohr            throw new StructException('Bad filter type . Only AND or OR allowed');
2139d7a36f9SAndreas Gohr
21415929be2SAndreas Gohr        $col = $this->findColumn($colname);
215*1057ed14SAndreas Gohr        if (!$col) return null; // ignore missing columns, filter might have been for different schema
2167da1a0fdSAndreas Gohr
2177da1a0fdSAndreas Gohr        // map filter operators to SQL syntax
2187da1a0fdSAndreas Gohr        switch ($comp) {
2197da1a0fdSAndreas Gohr            case '~':
2207da1a0fdSAndreas Gohr                $comp = 'LIKE';
2217da1a0fdSAndreas Gohr                break;
2227da1a0fdSAndreas Gohr            case '!~':
2237da1a0fdSAndreas Gohr                $comp = 'NOT LIKE';
2247da1a0fdSAndreas Gohr                break;
2257da1a0fdSAndreas Gohr            case '=*':
2267da1a0fdSAndreas Gohr                $comp = 'REGEXP';
2277da1a0fdSAndreas Gohr                break;
2287da1a0fdSAndreas Gohr        }
2297da1a0fdSAndreas Gohr
2307da1a0fdSAndreas Gohr        // we use asterisks, but SQL wants percents
2317da1a0fdSAndreas Gohr        if ($comp == 'LIKE' || $comp == 'NOT LIKE') {
23253528ecfSAndreas Gohr            $value = $this->filterChangeToLike($value);
2337da1a0fdSAndreas Gohr        }
2347da1a0fdSAndreas Gohr
235aaa187abSSzymon Olewniczak        if ($comp == ' IN ' && !is_array($value)) {
236efff5841SSzymon Olewniczak            $value = $this->parseFilterValueList($value);
237aaa187abSSzymon Olewniczak            //col IN ('a', 'b', 'c') is equal to col = 'a' OR 'col = 'b' OR col = 'c'
238aaa187abSSzymon Olewniczak            $comp = '=';
239aaa187abSSzymon Olewniczak        }
240aaa187abSSzymon Olewniczak
2417da1a0fdSAndreas Gohr        // add the filter
242*1057ed14SAndreas Gohr        return array($col, $value, $comp, $op);
24315929be2SAndreas Gohr    }
24415929be2SAndreas Gohr
24515929be2SAndreas Gohr    /**
246aaa187abSSzymon Olewniczak     * Parse SQLite row value into array
247aaa187abSSzymon Olewniczak     *
248aaa187abSSzymon Olewniczak     * @param string $value
249aaa187abSSzymon Olewniczak     * @return string[]
250aaa187abSSzymon Olewniczak     */
25161356325SAnna Dabrowska    protected function parseFilterValueList($value)
25261356325SAnna Dabrowska    {
253efff5841SSzymon Olewniczak        $Handler = new FilterValueListHandler();
254670a6894SAnna Dabrowska        $LexerClass = class_exists('\Doku_Lexer') ? '\Doku_Lexer' : '\dokuwiki\Parsing\Lexer\Lexer';
255670a6894SAnna Dabrowska        $isLegacy = $LexerClass === '\Doku_Lexer';
256670a6894SAnna Dabrowska        /** @var \Doku_Lexer|\dokuwiki\Parsing\Lexer\Lexer $Lexer */
257670a6894SAnna Dabrowska        $Lexer = new $LexerClass($Handler, 'base', true);
258670a6894SAnna Dabrowska
259aaa187abSSzymon Olewniczak
260aaa187abSSzymon Olewniczak        $Lexer->addEntryPattern('\(', 'base', 'row');
261aaa187abSSzymon Olewniczak        $Lexer->addPattern('\s*,\s*', 'row');
262aaa187abSSzymon Olewniczak        $Lexer->addExitPattern('\)', 'row');
263aaa187abSSzymon Olewniczak
264aaa187abSSzymon Olewniczak        $Lexer->addEntryPattern('"', 'row', 'double_quote_string');
265dfe3ae67SAnna Dabrowska        $Lexer->addSpecialPattern('\\\\"', 'double_quote_string', 'escapeSequence');
266aaa187abSSzymon Olewniczak        $Lexer->addExitPattern('"', 'double_quote_string');
267aaa187abSSzymon Olewniczak
268dfe3ae67SAnna Dabrowska        $Lexer->addEntryPattern("'", 'row', 'singleQuoteString');
269dfe3ae67SAnna Dabrowska        $Lexer->addSpecialPattern("\\\\'", 'singleQuoteString', 'escapeSequence');
270dfe3ae67SAnna Dabrowska        $Lexer->addExitPattern("'", 'singleQuoteString');
271aaa187abSSzymon Olewniczak
272dfe3ae67SAnna Dabrowska        $Lexer->mapHandler('double_quote_string', 'singleQuoteString');
273aaa187abSSzymon Olewniczak
274aaa187abSSzymon Olewniczak        $Lexer->addSpecialPattern('[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?', 'row', 'number');
275aaa187abSSzymon Olewniczak
276aaa187abSSzymon Olewniczak        $res = $Lexer->parse($value);
277aaa187abSSzymon Olewniczak
278670a6894SAnna Dabrowska        $currentMode = $isLegacy ? $Lexer->_mode->getCurrent() : $Lexer->getModeStack()->getCurrent();
279670a6894SAnna Dabrowska        if (!$res || $currentMode != 'base') {
280aaa187abSSzymon Olewniczak            throw new StructException('invalid row value syntax');
281aaa187abSSzymon Olewniczak        }
282aaa187abSSzymon Olewniczak
283dfe3ae67SAnna Dabrowska        return $Handler->getRow();
284aaa187abSSzymon Olewniczak    }
285aaa187abSSzymon Olewniczak
286aaa187abSSzymon Olewniczak    /**
28753528ecfSAndreas Gohr     * Wrap given value in asterisks
28853528ecfSAndreas Gohr     *
28953528ecfSAndreas Gohr     * @param string|string[] $value
29053528ecfSAndreas Gohr     * @return string|string[]
29153528ecfSAndreas Gohr     */
29261356325SAnna Dabrowska    protected function filterWrapAsterisks($value)
29361356325SAnna Dabrowska    {
29453528ecfSAndreas Gohr        $map = function ($input) {
29553528ecfSAndreas Gohr            return "*$input*";
29653528ecfSAndreas Gohr        };
29753528ecfSAndreas Gohr
29853528ecfSAndreas Gohr        if (is_array($value)) {
29953528ecfSAndreas Gohr            $value = array_map($map, $value);
30053528ecfSAndreas Gohr        } else {
30153528ecfSAndreas Gohr            $value = $map($value);
30253528ecfSAndreas Gohr        }
30353528ecfSAndreas Gohr        return $value;
30453528ecfSAndreas Gohr    }
30553528ecfSAndreas Gohr
30653528ecfSAndreas Gohr    /**
30753528ecfSAndreas Gohr     * Change given string to use % instead of *
30853528ecfSAndreas Gohr     *
30953528ecfSAndreas Gohr     * @param string|string[] $value
31053528ecfSAndreas Gohr     * @return string|string[]
31153528ecfSAndreas Gohr     */
31261356325SAnna Dabrowska    protected function filterChangeToLike($value)
31361356325SAnna Dabrowska    {
31453528ecfSAndreas Gohr        $map = function ($input) {
31553528ecfSAndreas Gohr            return str_replace('*', '%', $input);
31653528ecfSAndreas Gohr        };
31753528ecfSAndreas Gohr
31853528ecfSAndreas Gohr        if (is_array($value)) {
31953528ecfSAndreas Gohr            $value = array_map($map, $value);
32053528ecfSAndreas Gohr        } else {
32153528ecfSAndreas Gohr            $value = $map($value);
32253528ecfSAndreas Gohr        }
32353528ecfSAndreas Gohr        return $value;
32453528ecfSAndreas Gohr    }
32553528ecfSAndreas Gohr
32653528ecfSAndreas Gohr    /**
3277f9cb794SAndreas Gohr     * Set offset for the results
3287f9cb794SAndreas Gohr     *
3297f9cb794SAndreas Gohr     * @param int $offset
3307f9cb794SAndreas Gohr     */
33161356325SAnna Dabrowska    public function setOffset($offset)
33261356325SAnna Dabrowska    {
3337f9cb794SAndreas Gohr        $limit = 0;
3347f9cb794SAndreas Gohr        if ($this->range_end) {
3357f9cb794SAndreas Gohr            // if there was a limit set previously, the range_end needs to be recalculated
3367f9cb794SAndreas Gohr            $limit = $this->range_end - $this->range_begin;
3377f9cb794SAndreas Gohr        }
3387f9cb794SAndreas Gohr        $this->range_begin = $offset;
3397f9cb794SAndreas Gohr        if ($limit) $this->setLimit($limit);
3407f9cb794SAndreas Gohr    }
3417f9cb794SAndreas Gohr
3427f9cb794SAndreas Gohr    /**
3437f9cb794SAndreas Gohr     * Limit results to this number
3447f9cb794SAndreas Gohr     *
3457f9cb794SAndreas Gohr     * @param int $limit Set to 0 to disable limit again
3467f9cb794SAndreas Gohr     */
34761356325SAnna Dabrowska    public function setLimit($limit)
34861356325SAnna Dabrowska    {
3497f9cb794SAndreas Gohr        if ($limit) {
3507f9cb794SAndreas Gohr            $this->range_end = $this->range_begin + $limit;
3517f9cb794SAndreas Gohr        } else {
3527f9cb794SAndreas Gohr            $this->range_end = 0;
3537f9cb794SAndreas Gohr        }
3547f9cb794SAndreas Gohr    }
3557f9cb794SAndreas Gohr
3567f9cb794SAndreas Gohr    /**
3577f9cb794SAndreas Gohr     * Return the number of results (regardless of limit and offset settings)
3587f9cb794SAndreas Gohr     *
3590549dcc5SAndreas Gohr     * Use this to implement paging. Important: this may only be called after running @return int
3600549dcc5SAndreas Gohr     * @see execute()
3617f9cb794SAndreas Gohr     *
3627f9cb794SAndreas Gohr     */
36361356325SAnna Dabrowska    public function getCount()
36461356325SAnna Dabrowska    {
3657f9cb794SAndreas Gohr        if ($this->count < 0) throw new StructException('Count is only accessible after executing the search');
3667f9cb794SAndreas Gohr        return $this->count;
3677f9cb794SAndreas Gohr    }
3687f9cb794SAndreas Gohr
369c46f5fb1SAndreas Gohr    /**
370c46f5fb1SAndreas Gohr     * Returns the PID associated with each result row
371c46f5fb1SAndreas Gohr     *
3720549dcc5SAndreas Gohr     * Important: this may only be called after running @return \string[]
3730549dcc5SAndreas Gohr     * @see execute()
374c46f5fb1SAndreas Gohr     *
375c46f5fb1SAndreas Gohr     */
37661356325SAnna Dabrowska    public function getPids()
37761356325SAnna Dabrowska    {
37817a3a578SAndreas Gohr        if ($this->result_pids === null)
37917a3a578SAndreas Gohr            throw new StructException('PIDs are only accessible after executing the search');
380d4b5a17cSAndreas Gohr        return $this->result_pids;
381d4b5a17cSAndreas Gohr    }
382d4b5a17cSAndreas Gohr
3837f9cb794SAndreas Gohr    /**
3840ceefd5cSAnna Dabrowska     * Returns the rid associated with each result row
3850ceefd5cSAnna Dabrowska     *
3860549dcc5SAndreas Gohr     * Important: this may only be called after running @return array
3870549dcc5SAndreas Gohr     * @see execute()
3880ceefd5cSAnna Dabrowska     *
3890ceefd5cSAnna Dabrowska     */
39061356325SAnna Dabrowska    public function getRids()
39161356325SAnna Dabrowska    {
39217a3a578SAndreas Gohr        if ($this->result_rids === null)
39317a3a578SAndreas Gohr            throw new StructException('rids are only accessible after executing the search');
3940ceefd5cSAnna Dabrowska        return $this->result_rids;
3950ceefd5cSAnna Dabrowska    }
3960ceefd5cSAnna Dabrowska
3970ceefd5cSAnna Dabrowska    /**
3986fd73b4bSAnna Dabrowska     * Returns the rid associated with each result row
3996fd73b4bSAnna Dabrowska     *
4000549dcc5SAndreas Gohr     * Important: this may only be called after running @return array
4010549dcc5SAndreas Gohr     * @see execute()
4026fd73b4bSAnna Dabrowska     *
4036fd73b4bSAnna Dabrowska     */
40461356325SAnna Dabrowska    public function getRevs()
40561356325SAnna Dabrowska    {
40617a3a578SAndreas Gohr        if ($this->result_revs === null)
40717a3a578SAndreas Gohr            throw new StructException('revs are only accessible after executing the search');
4086fd73b4bSAnna Dabrowska        return $this->result_revs;
4096fd73b4bSAnna Dabrowska    }
4106fd73b4bSAnna Dabrowska
4116fd73b4bSAnna Dabrowska    /**
412b2ed727aSAndreas Gohr     * Execute this search and return the result
413b2ed727aSAndreas Gohr     *
41438fa36fbSAndreas Gohr     * The result is a two dimensional array of Value()s.
4157f9cb794SAndreas Gohr     *
4167f9cb794SAndreas Gohr     * This will always query for the full result (not using offset and limit) and then
4170549dcc5SAndreas Gohr     * return the wanted range, setting the count (@return Value[][]
4180549dcc5SAndreas Gohr     * @see getCount) to the whole result number
41938fa36fbSAndreas Gohr     *
420b2ed727aSAndreas Gohr     */
4218ce43f5aSAnna Dabrowska    public function execute()
42261356325SAnna Dabrowska    {
4238ce43f5aSAnna Dabrowska        list($sql, $opts) = $this->getSQL();
424b2ed727aSAndreas Gohr
4257f9cb794SAndreas Gohr        /** @var \PDOStatement $res */
426b2ed727aSAndreas Gohr        $res = $this->sqlite->query($sql, $opts);
42759b668aaSAndreas Gohr        if ($res === false) throw new StructException("SQL execution failed for\n\n$sql");
428b2ed727aSAndreas Gohr
429d4b5a17cSAndreas Gohr        $this->result_pids = array();
430b2ed727aSAndreas Gohr        $result = array();
4317f9cb794SAndreas Gohr        $cursor = -1;
4325e4bfdb0SMichael Grosse        $pageidAndRevOnly = array_reduce($this->columns, function ($pageidAndRevOnly, Column $col) {
4335e4bfdb0SMichael Grosse            return $pageidAndRevOnly && ($col->getTid() == 0);
4345e4bfdb0SMichael Grosse        }, true);
4357f9cb794SAndreas Gohr        while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
4367f9cb794SAndreas Gohr            $cursor++;
4377f9cb794SAndreas Gohr            if ($cursor < $this->range_begin) continue;
4387f9cb794SAndreas Gohr            if ($this->range_end && $cursor >= $this->range_end) continue;
4397f9cb794SAndreas Gohr
440b2ed727aSAndreas Gohr            $C = 0;
441b2ed727aSAndreas Gohr            $resrow = array();
44299a70f28SAndreas Gohr            $isempty = true;
443b2ed727aSAndreas Gohr            foreach ($this->columns as $col) {
44438fa36fbSAndreas Gohr                $val = $row["C$C"];
445b2ed727aSAndreas Gohr                if ($col->isMulti()) {
44638fa36fbSAndreas Gohr                    $val = explode(self::CONCAT_SEPARATOR, $val);
447b2ed727aSAndreas Gohr                }
44899a70f28SAndreas Gohr                $value = new Value($col, $val);
4498cba7aa0SMichael Grosse                $isempty &= $this->isEmptyValue($value);
45099a70f28SAndreas Gohr                $resrow[] = $value;
451b2ed727aSAndreas Gohr                $C++;
452b2ed727aSAndreas Gohr            }
45399a70f28SAndreas Gohr
45499a70f28SAndreas Gohr            // skip empty rows
4558cba7aa0SMichael Grosse            if ($isempty && !$pageidAndRevOnly) {
45699a70f28SAndreas Gohr                $cursor--;
45799a70f28SAndreas Gohr                continue;
45899a70f28SAndreas Gohr            }
45999a70f28SAndreas Gohr
46099a70f28SAndreas Gohr            $this->result_pids[] = $row['PID'];
4610ceefd5cSAnna Dabrowska            $this->result_rids[] = $row['rid'];
4626fd73b4bSAnna Dabrowska            $this->result_revs[] = $row['rev'];
463b2ed727aSAndreas Gohr            $result[] = $resrow;
464b2ed727aSAndreas Gohr        }
4657f9cb794SAndreas Gohr
46679b29326SAnna Dabrowska        $res->closeCursor();
4677f9cb794SAndreas Gohr        $this->count = $cursor + 1;
468b2ed727aSAndreas Gohr        return $result;
469b2ed727aSAndreas Gohr    }
470b2ed727aSAndreas Gohr
471b2ed727aSAndreas Gohr    /**
47215929be2SAndreas Gohr     * Transform the set search parameters into a statement
47315929be2SAndreas Gohr     *
474b2ed727aSAndreas Gohr     * @return array ($sql, $opts) The SQL and parameters to execute
47515929be2SAndreas Gohr     */
4768ce43f5aSAnna Dabrowska    public function getSQL()
47761356325SAnna Dabrowska    {
4785511bd5bSAndreas Gohr        if (!$this->columns) throw new StructException('nocolname');
47915929be2SAndreas Gohr
4802f68434dSAndreas Gohr        $QB = new QueryBuilder();
48115929be2SAndreas Gohr
4829d7a36f9SAndreas Gohr        // basic tables
483b2d67e7dSAndreas Gohr        $first_table = '';
4849d7a36f9SAndreas Gohr        foreach ($this->schemas as $schema) {
4852f68434dSAndreas Gohr            $datatable = 'data_' . $schema->getTable();
486b2d67e7dSAndreas Gohr            if ($first_table) {
4879d7a36f9SAndreas Gohr                // follow up tables
4888ce43f5aSAnna Dabrowska                $QB->addLeftJoin($first_table, $datatable, $datatable, "$first_table.pid = $datatable.pid");
4899d7a36f9SAndreas Gohr            } else {
4909d7a36f9SAndreas Gohr                // first table
49113c321dbSAndreas Gohr                $QB->addTable($datatable);
4928ce43f5aSAnna Dabrowska
4938ce43f5aSAnna Dabrowska                // add conditional page clauses if pid has a value
4948ce43f5aSAnna Dabrowska                $subAnd = $QB->filters()->whereSubAnd();
4958ce43f5aSAnna Dabrowska                $subAnd->whereAnd("$datatable.pid = ''");
4968ce43f5aSAnna Dabrowska                $subOr = $subAnd->whereSubOr();
4978ce43f5aSAnna Dabrowska                $subOr->whereAnd("GETACCESSLEVEL($datatable.pid) > 0");
4988ce43f5aSAnna Dabrowska                $subOr->whereAnd("PAGEEXISTS($datatable.pid) = 1");
49954efd03eSAnna Dabrowska                $subOr->whereAnd('(ASSIGNED = 1 OR ASSIGNED IS NULL)');
5008ce43f5aSAnna Dabrowska
5018ce43f5aSAnna Dabrowska                // add conditional schema assignment check
502f183bf6eSAnna Dabrowska                $QB->addLeftJoin(
503f183bf6eSAnna Dabrowska                    $datatable,
504f183bf6eSAnna Dabrowska                    'schema_assignments',
505f183bf6eSAnna Dabrowska                    '',
5068ce43f5aSAnna Dabrowska                    "$datatable.pid != ''
5078ce43f5aSAnna Dabrowska                    AND $datatable.pid = schema_assignments.pid
50838e29673SAnna Dabrowska                    AND schema_assignments.tbl = '{$schema->getTable()}'"
5098ce43f5aSAnna Dabrowska                );
5108ce43f5aSAnna Dabrowska
5110ceefd5cSAnna Dabrowska                $QB->addSelectColumn($datatable, 'rid');
51213c321dbSAndreas Gohr                $QB->addSelectColumn($datatable, 'pid', 'PID');
5136fd73b4bSAnna Dabrowska                $QB->addSelectColumn($datatable, 'rev');
51438e29673SAnna Dabrowska                $QB->addSelectColumn('schema_assignments', 'assigned', 'ASSIGNED');
51513c321dbSAndreas Gohr                $QB->addGroupByColumn($datatable, 'pid');
516e3104939SAnna Dabrowska                $QB->addGroupByColumn($datatable, 'rid');
517b2d67e7dSAndreas Gohr
5182f68434dSAndreas Gohr                $first_table = $datatable;
51915929be2SAndreas Gohr            }
520bb8d98c4SAnna Dabrowska            // phpcs:ignore
52100624072SAnna Dabrowska            $QB->filters()->whereAnd("( (IS_PUBLISHER($datatable.pid) AND $datatable.latest = 1) OR (IS_PUBLISHER($datatable.pid) !=1 AND $datatable.published = 1) )");
5229d7a36f9SAndreas Gohr        }
52315929be2SAndreas Gohr
52415929be2SAndreas Gohr        // columns to select, handling multis
5259d7a36f9SAndreas Gohr        $sep = self::CONCAT_SEPARATOR;
52615929be2SAndreas Gohr        $n = 0;
52715929be2SAndreas Gohr        foreach ($this->columns as $col) {
52815929be2SAndreas Gohr            $CN = 'C' . $n++;
52915929be2SAndreas Gohr
530d1b04e89SAndreas Gohr            if ($col->isMulti()) {
5312f68434dSAndreas Gohr                $datatable = "data_{$col->getTable()}";
5322f68434dSAndreas Gohr                $multitable = "multi_{$col->getTable()}";
533db7970caSAndreas Gohr                $MN = $QB->generateTableAlias('M');
5342f68434dSAndreas Gohr
5352f68434dSAndreas Gohr                $QB->addLeftJoin(
5362f68434dSAndreas Gohr                    $datatable,
5372f68434dSAndreas Gohr                    $multitable,
5382f68434dSAndreas Gohr                    $MN,
5398ce43f5aSAnna Dabrowska                    "$datatable.pid = $MN.pid AND $datatable.rid = $MN.rid AND
5402f68434dSAndreas Gohr                     $datatable.rev = $MN.rev AND
5412f68434dSAndreas Gohr                     $MN.colref = {$col->getColref()}"
5422f68434dSAndreas Gohr                );
543578407b2SAndreas Gohr
544578407b2SAndreas Gohr                $col->getType()->select($QB, $MN, 'value', $CN);
545578407b2SAndreas Gohr                $sel = $QB->getSelectStatement($CN);
546acc82d60SAndreas Gohr                $QB->addSelectStatement("GROUP_CONCAT_DISTINCT($sel, '$sep')", $CN);
54715929be2SAndreas Gohr            } else {
548578407b2SAndreas Gohr                $col->getType()->select($QB, 'data_' . $col->getTable(), $col->getColName(), $CN);
5490dbe7bf6SAndreas Gohr                $QB->addGroupByStatement($CN);
55015929be2SAndreas Gohr            }
55115929be2SAndreas Gohr        }
55215929be2SAndreas Gohr
5539d7a36f9SAndreas Gohr        // where clauses
554af993d55SMichael Grosse        if (!empty($this->filter)) {
555af993d55SMichael Grosse            $userWHERE = $QB->filters()->where('AND');
556af993d55SMichael Grosse        }
557b8fe6730SAndreas Gohr        foreach ($this->filter as $filter) {
5589ebd2ed6SAndreas Gohr            /** @var Column $col */
5594c13ff97SAndreas Gohr            list($col, $value, $comp, $op) = $filter;
560b8fe6730SAndreas Gohr
5612f68434dSAndreas Gohr            $datatable = "data_{$col->getTable()}";
5622f68434dSAndreas Gohr            $multitable = "multi_{$col->getTable()}";
5639d7a36f9SAndreas Gohr
5649d7a36f9SAndreas Gohr            /** @var $col Column */
5659d7a36f9SAndreas Gohr            if ($col->isMulti()) {
566db7970caSAndreas Gohr                $MN = $QB->generateTableAlias('MN');
56715929be2SAndreas Gohr
5682f68434dSAndreas Gohr                $QB->addLeftJoin(
5692f68434dSAndreas Gohr                    $datatable,
5702f68434dSAndreas Gohr                    $multitable,
5712f68434dSAndreas Gohr                    $MN,
5728ce43f5aSAnna Dabrowska                    "$datatable.pid = $MN.pid AND $datatable.rid = $MN.rid AND
5732f68434dSAndreas Gohr                     $datatable.rev = $MN.rev AND
5742f68434dSAndreas Gohr                     $MN.colref = {$col->getColref()}"
5752f68434dSAndreas Gohr                );
576690e4ebaSAndreas Gohr                $coltbl = $MN;
577690e4ebaSAndreas Gohr                $colnam = 'value';
5789d7a36f9SAndreas Gohr            } else {
579690e4ebaSAndreas Gohr                $coltbl = $datatable;
580690e4ebaSAndreas Gohr                $colnam = $col->getColName();
5819d7a36f9SAndreas Gohr            }
58253528ecfSAndreas Gohr
583af993d55SMichael Grosse            $col->getType()->filter($userWHERE, $coltbl, $colnam, $comp, $value, $op); // type based filter
5849d7a36f9SAndreas Gohr        }
5859d7a36f9SAndreas Gohr
58629394e6cSAndreas Gohr        // sorting - we always sort by the single val column
587b8fe6730SAndreas Gohr        foreach ($this->sortby as $sort) {
588eb55dc17SAndreas Gohr            list($col, $asc, $nc) = $sort;
5899d7a36f9SAndreas Gohr            /** @var $col Column */
590eb55dc17SAndreas Gohr            $colname = $col->getColName(false);
591eb55dc17SAndreas Gohr            if ($nc) $colname .= ' COLLATE NOCASE';
592eb55dc17SAndreas Gohr            $col->getType()->sort($QB, 'data_' . $col->getTable(), $colname, $asc ? 'ASC' : 'DESC');
5939e07bdbfSAndreas Gohr        }
5949e07bdbfSAndreas Gohr
5952f68434dSAndreas Gohr        return $QB->getSQL();
59615929be2SAndreas Gohr    }
59715929be2SAndreas Gohr
59815929be2SAndreas Gohr    /**
59901dd90deSAndreas Gohr     * Returns all the columns that where added to the search
60001dd90deSAndreas Gohr     *
60101dd90deSAndreas Gohr     * @return Column[]
60201dd90deSAndreas Gohr     */
60361356325SAnna Dabrowska    public function getColumns()
60461356325SAnna Dabrowska    {
60501dd90deSAndreas Gohr        return $this->columns;
60601dd90deSAndreas Gohr    }
60701dd90deSAndreas Gohr
608577b462bSAndreas Gohr    /**
6095a4df70dSAndreas Gohr     * All the schemas currently added
6105a4df70dSAndreas Gohr     *
6115a4df70dSAndreas Gohr     * @return Schema[]
6125a4df70dSAndreas Gohr     */
61361356325SAnna Dabrowska    public function getSchemas()
61461356325SAnna Dabrowska    {
6155a4df70dSAndreas Gohr        return array_values($this->schemas);
6165a4df70dSAndreas Gohr    }
6175a4df70dSAndreas Gohr
6185a4df70dSAndreas Gohr    /**
619577b462bSAndreas Gohr     * Checks if the given column is a * wildcard
620577b462bSAndreas Gohr     *
621577b462bSAndreas Gohr     * If it's a wildcard all matching columns are added to the column list, otherwise
622577b462bSAndreas Gohr     * nothing happens
623577b462bSAndreas Gohr     *
624577b462bSAndreas Gohr     * @param string $colname
625577b462bSAndreas Gohr     * @return bool was wildcard?
626577b462bSAndreas Gohr     */
62761356325SAnna Dabrowska    protected function processWildcard($colname)
62861356325SAnna Dabrowska    {
629636a5173SAndreas Gohr        list($colname, $table) = $this->resolveColumn($colname);
630577b462bSAndreas Gohr        if ($colname !== '*') return false;
631577b462bSAndreas Gohr
632577b462bSAndreas Gohr        // no table given? assume the first is meant
633577b462bSAndreas Gohr        if ($table === null) {
634577b462bSAndreas Gohr            $schema_list = array_keys($this->schemas);
635577b462bSAndreas Gohr            $table = $schema_list[0];
636577b462bSAndreas Gohr        }
637577b462bSAndreas Gohr
6381ca21e17SAnna Dabrowska        $schema = $this->schemas[$table] ?? null;
639577b462bSAndreas Gohr        if (!$schema) return false;
640577b462bSAndreas Gohr        $this->columns = array_merge($this->columns, $schema->getColumns(false));
641577b462bSAndreas Gohr        return true;
642577b462bSAndreas Gohr    }
643577b462bSAndreas Gohr
644577b462bSAndreas Gohr    /**
645577b462bSAndreas Gohr     * Split a given column name into table and column
646577b462bSAndreas Gohr     *
647577b462bSAndreas Gohr     * Handles Aliases. Table might be null if none given.
648577b462bSAndreas Gohr     *
649577b462bSAndreas Gohr     * @param $colname
650636a5173SAndreas Gohr     * @return array (colname, table)
651577b462bSAndreas Gohr     */
65261356325SAnna Dabrowska    protected function resolveColumn($colname)
65361356325SAnna Dabrowska    {
654577b462bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
655577b462bSAndreas Gohr
656577b462bSAndreas Gohr        // resolve the alias or table name
65725ed0c0dSAndreas Gohr        @list($table, $colname) = array_pad(explode('.', $colname, 2), 2, '');
658577b462bSAndreas Gohr        if (!$colname) {
659577b462bSAndreas Gohr            $colname = $table;
660577b462bSAndreas Gohr            $table = null;
661577b462bSAndreas Gohr        }
662577b462bSAndreas Gohr        if ($table && isset($this->aliases[$table])) {
663577b462bSAndreas Gohr            $table = $this->aliases[$table];
664577b462bSAndreas Gohr        }
665577b462bSAndreas Gohr
666577b462bSAndreas Gohr        if (!$colname) throw new StructException('nocolname');
667577b462bSAndreas Gohr
668577b462bSAndreas Gohr        return array($colname, $table);
669577b462bSAndreas Gohr    }
67001dd90deSAndreas Gohr
67101dd90deSAndreas Gohr    /**
67215929be2SAndreas Gohr     * Find a column to be used in the search
67315929be2SAndreas Gohr     *
67415929be2SAndreas Gohr     * @param string $colname may contain an alias
67515929be2SAndreas Gohr     * @return bool|Column
67615929be2SAndreas Gohr     */
6770280da9aSFrieder Schrempf    public function findColumn($colname, $strict = false)
67861356325SAnna Dabrowska    {
6795511bd5bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
680df02ffe6SMichael Große        $schema_list = array_keys($this->schemas);
681f107f479SAndreas Gohr
682f107f479SAndreas Gohr        // add "fake" column for special col
683128d4e83SAndreas Gohr        if ($colname == '%pageid%') {
684128d4e83SAndreas Gohr            return new PageColumn(0, new Page(), $schema_list[0]);
685d1b04e89SAndreas Gohr        }
686128d4e83SAndreas Gohr        if ($colname == '%title%') {
687128d4e83SAndreas Gohr            return new PageColumn(0, new Page(array('usetitles' => true)), $schema_list[0]);
688128d4e83SAndreas Gohr        }
689cadfc3ccSAndreas Gohr        if ($colname == '%lastupdate%') {
690cadfc3ccSAndreas Gohr            return new RevisionColumn(0, new DateTime(), $schema_list[0]);
691cadfc3ccSAndreas Gohr        }
6922e12ac22SMichael Grosse        if ($colname == '%lasteditor%') {
6932e12ac22SMichael Grosse            return new UserColumn(0, new User(), $schema_list[0]);
6942e12ac22SMichael Grosse        }
69588b58a21SSzymon Olewniczak        if ($colname == '%lastsummary%') {
6966781c68dSSzymon Olewniczak            return new SummaryColumn(0, new AutoSummary(), $schema_list[0]);
69788b58a21SSzymon Olewniczak        }
698f107f479SAndreas Gohr        if ($colname == '%rowid%') {
699f107f479SAndreas Gohr            return new RowColumn(0, new Decimal(), $schema_list[0]);
700f107f479SAndreas Gohr        }
701da62ec9cSAnna Dabrowska        if ($colname == '%published%') {
702da62ec9cSAnna Dabrowska            return new PublishedColumn(0, new Decimal(), $schema_list[0]);
703da62ec9cSAnna Dabrowska        }
704d1b04e89SAndreas Gohr
705636a5173SAndreas Gohr        list($colname, $table) = $this->resolveColumn($colname);
70615929be2SAndreas Gohr
7070280da9aSFrieder Schrempf        /*
7080280da9aSFrieder Schrempf         * If table name is given search only that, otherwise if no strict behavior
7090280da9aSFrieder Schrempf         * is requested by the caller, try all assigned schemas for matching the
7100280da9aSFrieder Schrempf         * column name.
7110280da9aSFrieder Schrempf         */
71234ea6e10SAnna Dabrowska        if ($table !== null && isset($this->schemas[$table])) {
71315929be2SAndreas Gohr            $schemas = array($table => $this->schemas[$table]);
7140280da9aSFrieder Schrempf        } elseif ($table === null || !$strict) {
71515929be2SAndreas Gohr            $schemas = $this->schemas;
7160280da9aSFrieder Schrempf        } else {
7170280da9aSFrieder Schrempf            return false;
71815929be2SAndreas Gohr        }
71915929be2SAndreas Gohr
72015929be2SAndreas Gohr        // find it
72115929be2SAndreas Gohr        $col = false;
72215929be2SAndreas Gohr        foreach ($schemas as $schema) {
7234ac44d1cSMichael Grosse            if (empty($schema)) {
7244ac44d1cSMichael Grosse                continue;
7254ac44d1cSMichael Grosse            }
72615929be2SAndreas Gohr            $col = $schema->findColumn($colname);
72715929be2SAndreas Gohr            if ($col) break;
72815929be2SAndreas Gohr        }
72915929be2SAndreas Gohr
73015929be2SAndreas Gohr        return $col;
73115929be2SAndreas Gohr    }
73215929be2SAndreas Gohr
7339dbc8ec0SMichael Grosse    /**
73499a70f28SAndreas Gohr     * Check if the given row is empty or references our own row
7359dbc8ec0SMichael Grosse     *
73699a70f28SAndreas Gohr     * @param Value $value
7379dbc8ec0SMichael Grosse     * @return bool
7389dbc8ec0SMichael Grosse     */
73961356325SAnna Dabrowska    protected function isEmptyValue(Value $value)
74061356325SAnna Dabrowska    {
74199a70f28SAndreas Gohr        if ($value->isEmpty()) return true;
7428cba7aa0SMichael Grosse        if ($value->getColumn()->getTid() == 0) return true;
7439dbc8ec0SMichael Grosse        return false;
7449dbc8ec0SMichael Grosse    }
74515929be2SAndreas Gohr}
746