xref: /plugin/struct/meta/Search.php (revision b8d3247dc56feb4b81d8c7df61a4214dd02a662f)
115929be2SAndreas Gohr<?php
215929be2SAndreas Gohr
3ba766201SAndreas Gohrnamespace dokuwiki\plugin\struct\meta;
415929be2SAndreas Gohr
57234bfb1Ssplitbrainuse dokuwiki\Parsing\Lexer\Lexer;
60549dcc5SAndreas Gohruse dokuwiki\plugin\struct\types\AutoSummary;
7cadfc3ccSAndreas Gohruse dokuwiki\plugin\struct\types\DateTime;
8f107f479SAndreas Gohruse dokuwiki\plugin\struct\types\Decimal;
9ba766201SAndreas Gohruse dokuwiki\plugin\struct\types\Page;
102e12ac22SMichael Grosseuse dokuwiki\plugin\struct\types\User;
110561158fSAndreas Gohr
1261356325SAnna Dabrowskaclass Search
1361356325SAnna Dabrowska{
149d7a36f9SAndreas Gohr    /**
159d7a36f9SAndreas Gohr     * This separator will be used to concat multi values to flatten them in the result set
169d7a36f9SAndreas Gohr     */
1717a3a578SAndreas Gohr    public const CONCAT_SEPARATOR = "\n!_-_-_-_-_!\n";
189d7a36f9SAndreas Gohr
195511bd5bSAndreas Gohr    /**
205511bd5bSAndreas Gohr     * The list of known and allowed comparators
212e7595e7SAndreas Gohr     * (order matters)
225511bd5bSAndreas Gohr     */
237234bfb1Ssplitbrain    public static $COMPARATORS = ['<=', '>=', '=*', '=', '<', '>', '!=', '!~', '~', ' IN '];
245511bd5bSAndreas Gohr
25bb8d98c4SAnna Dabrowska    /** @var \helper_plugin_struct_db */
26bb8d98c4SAnna Dabrowska    protected $dbHelper;
27bb8d98c4SAnna Dabrowska
289d7a36f9SAndreas Gohr    /** @var  \helper_plugin_sqlite */
299d7a36f9SAndreas Gohr    protected $sqlite;
3015929be2SAndreas Gohr
3115929be2SAndreas Gohr    /** @var Schema[] list of schemas to query */
327234bfb1Ssplitbrain    protected $schemas = [];
3315929be2SAndreas Gohr
3415929be2SAndreas Gohr    /** @var Column[] list of columns to select */
357234bfb1Ssplitbrain    protected $columns = [];
3615929be2SAndreas Gohr
3715929be2SAndreas Gohr    /** @var array the sorting of the result */
387234bfb1Ssplitbrain    protected $sortby = [];
3915929be2SAndreas Gohr
409d7a36f9SAndreas Gohr    /** @var array the filters */
417234bfb1Ssplitbrain    protected $filter = [];
4215929be2SAndreas Gohr
431057ed14SAndreas Gohr    /** @var array the filters */
447234bfb1Ssplitbrain    protected $dynamicFilter = [];
451057ed14SAndreas Gohr
4615929be2SAndreas Gohr    /** @var array list of aliases tables can be referenced by */
477234bfb1Ssplitbrain    protected $aliases = [];
4815929be2SAndreas Gohr
497f9cb794SAndreas Gohr    /** @var  int begin results from here */
507f9cb794SAndreas Gohr    protected $range_begin = 0;
517f9cb794SAndreas Gohr
527f9cb794SAndreas Gohr    /** @var  int end results here */
537f9cb794SAndreas Gohr    protected $range_end = 0;
547f9cb794SAndreas Gohr
557f9cb794SAndreas Gohr    /** @var int the number of results */
567f9cb794SAndreas Gohr    protected $count = -1;
57d4b5a17cSAndreas Gohr    /** @var  string[] the PIDs of the result rows */
587234bfb1Ssplitbrain    protected $result_pids;
590ceefd5cSAnna Dabrowska    /** @var  array the row ids of the result rows */
600ceefd5cSAnna Dabrowska    protected $result_rids = [];
616fd73b4bSAnna Dabrowska    /** @var  array the revisions of the result rows */
626fd73b4bSAnna Dabrowska    protected $result_revs = [];
637f9cb794SAndreas Gohr
64eff6062eSAnna Dabrowska    /** @var bool Include latest = 1 in select query */
65eff6062eSAnna Dabrowska    protected $selectLatest = true;
66eff6062eSAnna Dabrowska
6715929be2SAndreas Gohr    /**
689d7a36f9SAndreas Gohr     * Search constructor.
699d7a36f9SAndreas Gohr     */
7061356325SAnna Dabrowska    public function __construct()
7161356325SAnna Dabrowska    {
72837e87e2SAnna Dabrowska        /** @var  $dbHelper */
73837e87e2SAnna Dabrowska        $this->dbHelper = plugin_load('helper', 'struct_db');
74837e87e2SAnna Dabrowska        $this->sqlite = $this->dbHelper->getDB();
75bb8d98c4SAnna Dabrowska    }
76837e87e2SAnna Dabrowska
77837e87e2SAnna Dabrowska    public function getDb()
78837e87e2SAnna Dabrowska    {
79837e87e2SAnna Dabrowska        return $this->sqlite;
809d7a36f9SAndreas Gohr    }
819d7a36f9SAndreas Gohr
829d7a36f9SAndreas Gohr    /**
8315929be2SAndreas Gohr     * Add a schema to be searched
8415929be2SAndreas Gohr     *
8515929be2SAndreas Gohr     * Call multiple times for multiple schemas.
8615929be2SAndreas Gohr     *
8715929be2SAndreas Gohr     * @param string $table
8815929be2SAndreas Gohr     * @param string $alias
8915929be2SAndreas Gohr     */
9061356325SAnna Dabrowska    public function addSchema($table, $alias = '')
9161356325SAnna Dabrowska    {
922be187cdSAndreas Gohr        $schema = new Schema($table);
932be187cdSAndreas Gohr        if (!$schema->getId()) {
942be187cdSAndreas Gohr            throw new StructException('schema missing', $table);
952be187cdSAndreas Gohr        }
962be187cdSAndreas Gohr
97712c650dSAndreas Gohr        $this->schemas[$schema->getTable()] = $schema;
98712c650dSAndreas Gohr        if ($alias) $this->aliases[$alias] = $schema->getTable();
9915929be2SAndreas Gohr    }
10015929be2SAndreas Gohr
10115929be2SAndreas Gohr    /**
10215929be2SAndreas Gohr     * Add a column to be returned by the search
10315929be2SAndreas Gohr     *
10415929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
10515929be2SAndreas Gohr     * added before
10615929be2SAndreas Gohr     *
10715929be2SAndreas Gohr     * @param string $colname may contain an alias
10815929be2SAndreas Gohr     */
10961356325SAnna Dabrowska    public function addColumn($colname)
11061356325SAnna Dabrowska    {
111577b462bSAndreas Gohr        if ($this->processWildcard($colname)) return; // wildcard?
112b26126edSAndreas Hubel        if ($colname[0] == '-') { // remove column from previous wildcard lookup
113b26126edSAndreas Hubel            $colname = substr($colname, 1);
114b26126edSAndreas Hubel            foreach ($this->columns as $key => $col) {
1157234bfb1Ssplitbrain                if ($col->getLabel() === $colname) unset($this->columns[$key]);
116b26126edSAndreas Hubel            }
117b26126edSAndreas Hubel            return;
118b26126edSAndreas Hubel        }
119b26126edSAndreas Hubel
12015929be2SAndreas Gohr        $col = $this->findColumn($colname);
12115929be2SAndreas Gohr        if (!$col) return; //FIXME do we really want to ignore missing columns?
12215929be2SAndreas Gohr        $this->columns[] = $col;
12315929be2SAndreas Gohr    }
12415929be2SAndreas Gohr
12515929be2SAndreas Gohr    /**
12615929be2SAndreas Gohr     * Add sorting options
12715929be2SAndreas Gohr     *
12815929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
12915929be2SAndreas Gohr     * added before
13015929be2SAndreas Gohr     *
13115929be2SAndreas Gohr     * @param string $colname may contain an alias
13215929be2SAndreas Gohr     * @param bool $asc sort direction (ASC = true, DESC = false)
133eb55dc17SAndreas Gohr     * @param bool $nc set true for caseinsensitivity
13415929be2SAndreas Gohr     */
13561356325SAnna Dabrowska    public function addSort($colname, $asc = true, $nc = true)
13661356325SAnna Dabrowska    {
13715929be2SAndreas Gohr        $col = $this->findColumn($colname);
13815929be2SAndreas Gohr        if (!$col) return; //FIXME do we really want to ignore missing columns?
13915929be2SAndreas Gohr
1407234bfb1Ssplitbrain        $this->sortby[$col->getFullQualifiedLabel()] = [$col, $asc, $nc];
14107993756SAndreas Gohr    }
14207993756SAndreas Gohr
14307993756SAndreas Gohr    /**
144b3a9db22SAndreas Gohr     * Clear all sorting options
145b3a9db22SAndreas Gohr     *
146b3a9db22SAndreas Gohr     * @return void
147b3a9db22SAndreas Gohr     */
148b3a9db22SAndreas Gohr    public function clearSort()
149b3a9db22SAndreas Gohr    {
150b3a9db22SAndreas Gohr        $this->sortby = [];
151b3a9db22SAndreas Gohr    }
152b3a9db22SAndreas Gohr
153b3a9db22SAndreas Gohr    /**
15407993756SAndreas Gohr     * Returns all set sort columns
15507993756SAndreas Gohr     *
15607993756SAndreas Gohr     * @return array
15707993756SAndreas Gohr     */
15861356325SAnna Dabrowska    public function getSorts()
15961356325SAnna Dabrowska    {
16007993756SAndreas Gohr        return $this->sortby;
16115929be2SAndreas Gohr    }
16215929be2SAndreas Gohr
16315929be2SAndreas Gohr    /**
1649d7a36f9SAndreas Gohr     * Adds a filter
16515929be2SAndreas Gohr     *
16615929be2SAndreas Gohr     * @param string $colname may contain an alias
16753528ecfSAndreas Gohr     * @param string|string[] $value
1685511bd5bSAndreas Gohr     * @param string $comp @see self::COMPARATORS
1694c13ff97SAndreas Gohr     * @param string $op either 'OR' or 'AND'
17015929be2SAndreas Gohr     */
17161356325SAnna Dabrowska    public function addFilter($colname, $value, $comp, $op = 'OR')
17261356325SAnna Dabrowska    {
1731057ed14SAndreas Gohr        $filter = $this->createFilter($colname, $value, $comp, $op);
1741057ed14SAndreas Gohr        if ($filter) $this->filter[] = $filter;
1751057ed14SAndreas Gohr    }
1761057ed14SAndreas Gohr
1771057ed14SAndreas Gohr    /**
1781057ed14SAndreas Gohr     * Adds a dynamic filter
1791057ed14SAndreas Gohr     *
1801057ed14SAndreas Gohr     * @param string $colname may contain an alias
1811057ed14SAndreas Gohr     * @param string|string[] $value
1821057ed14SAndreas Gohr     * @param string $comp @see self::COMPARATORS
1831057ed14SAndreas Gohr     * @param string $op either 'OR' or 'AND'
1841057ed14SAndreas Gohr     */
1851057ed14SAndreas Gohr    public function addDynamicFilter($colname, $value, $comp, $op = 'OR')
1861057ed14SAndreas Gohr    {
1871057ed14SAndreas Gohr        $filter = $this->createFilter($colname, $value, $comp, $op);
1881057ed14SAndreas Gohr        if ($filter) $this->dynamicFilter[] = $filter;
1891057ed14SAndreas Gohr    }
1901057ed14SAndreas Gohr
1911057ed14SAndreas Gohr    /**
1921057ed14SAndreas Gohr     * Create a filter definition
1931057ed14SAndreas Gohr     *
1941057ed14SAndreas Gohr     * @param string $colname may contain an alias
1951057ed14SAndreas Gohr     * @param string|string[] $value
1961057ed14SAndreas Gohr     * @param string $comp @see self::COMPARATORS
1971057ed14SAndreas Gohr     * @param string $op either 'OR' or 'AND'
1981057ed14SAndreas Gohr     * @return array|null [Column col, string|string[] value, string comp, string op]
1991057ed14SAndreas Gohr     */
2001057ed14SAndreas Gohr    protected function createFilter($colname, $value, $comp, $op = 'OR')
2011057ed14SAndreas Gohr    {
2029dbc32aeSAndreas Gohr        /* Convert certain filters into others
2039dbc32aeSAndreas Gohr         * this reduces the number of supported filters to implement in types */
2049dbc32aeSAndreas Gohr        if ($comp == '*~') {
20553528ecfSAndreas Gohr            $value = $this->filterWrapAsterisks($value);
2069dbc32aeSAndreas Gohr            $comp = '~';
2079dbc32aeSAndreas Gohr        } elseif ($comp == '<>') {
2089dbc32aeSAndreas Gohr            $comp = '!=';
2099dbc32aeSAndreas Gohr        }
2109dbc32aeSAndreas Gohr
21117a3a578SAndreas Gohr        if (!in_array($comp, self::$COMPARATORS))
2127234bfb1Ssplitbrain            throw new StructException("Bad comperator. Use " . implode(',', self::$COMPARATORS));
21317a3a578SAndreas Gohr        if ($op != 'OR' && $op != 'AND')
21417a3a578SAndreas Gohr            throw new StructException('Bad filter type . Only AND or OR allowed');
2159d7a36f9SAndreas Gohr
21615929be2SAndreas Gohr        $col = $this->findColumn($colname);
2171057ed14SAndreas Gohr        if (!$col) return null; // ignore missing columns, filter might have been for different schema
2187da1a0fdSAndreas Gohr
2197da1a0fdSAndreas Gohr        // map filter operators to SQL syntax
2207da1a0fdSAndreas Gohr        switch ($comp) {
2217da1a0fdSAndreas Gohr            case '~':
2227da1a0fdSAndreas Gohr                $comp = 'LIKE';
2237da1a0fdSAndreas Gohr                break;
2247da1a0fdSAndreas Gohr            case '!~':
2257da1a0fdSAndreas Gohr                $comp = 'NOT LIKE';
2267da1a0fdSAndreas Gohr                break;
2277da1a0fdSAndreas Gohr            case '=*':
2287da1a0fdSAndreas Gohr                $comp = 'REGEXP';
2297da1a0fdSAndreas Gohr                break;
2307da1a0fdSAndreas Gohr        }
2317da1a0fdSAndreas Gohr
2327da1a0fdSAndreas Gohr        // we use asterisks, but SQL wants percents
2337da1a0fdSAndreas Gohr        if ($comp == 'LIKE' || $comp == 'NOT LIKE') {
23453528ecfSAndreas Gohr            $value = $this->filterChangeToLike($value);
2357da1a0fdSAndreas Gohr        }
2367da1a0fdSAndreas Gohr
237aaa187abSSzymon Olewniczak        if ($comp == ' IN ' && !is_array($value)) {
238efff5841SSzymon Olewniczak            $value = $this->parseFilterValueList($value);
239aaa187abSSzymon Olewniczak            //col IN ('a', 'b', 'c') is equal to col = 'a' OR 'col = 'b' OR col = 'c'
240aaa187abSSzymon Olewniczak            $comp = '=';
241aaa187abSSzymon Olewniczak        }
242aaa187abSSzymon Olewniczak
2437da1a0fdSAndreas Gohr        // add the filter
2447234bfb1Ssplitbrain        return [$col, $value, $comp, $op];
24515929be2SAndreas Gohr    }
24615929be2SAndreas Gohr
24715929be2SAndreas Gohr    /**
248aaa187abSSzymon Olewniczak     * Parse SQLite row value into array
249aaa187abSSzymon Olewniczak     *
250aaa187abSSzymon Olewniczak     * @param string $value
251aaa187abSSzymon Olewniczak     * @return string[]
252aaa187abSSzymon Olewniczak     */
25361356325SAnna Dabrowska    protected function parseFilterValueList($value)
25461356325SAnna Dabrowska    {
255efff5841SSzymon Olewniczak        $Handler = new FilterValueListHandler();
256670a6894SAnna Dabrowska        $LexerClass = class_exists('\Doku_Lexer') ? '\Doku_Lexer' : '\dokuwiki\Parsing\Lexer\Lexer';
257670a6894SAnna Dabrowska        $isLegacy = $LexerClass === '\Doku_Lexer';
2587234bfb1Ssplitbrain        /** @var \Doku_Lexer|Lexer $Lexer */
259670a6894SAnna Dabrowska        $Lexer = new $LexerClass($Handler, 'base', true);
260670a6894SAnna Dabrowska
261aaa187abSSzymon Olewniczak
262aaa187abSSzymon Olewniczak        $Lexer->addEntryPattern('\(', 'base', 'row');
263aaa187abSSzymon Olewniczak        $Lexer->addPattern('\s*,\s*', 'row');
264aaa187abSSzymon Olewniczak        $Lexer->addExitPattern('\)', 'row');
265aaa187abSSzymon Olewniczak
266aaa187abSSzymon Olewniczak        $Lexer->addEntryPattern('"', 'row', 'double_quote_string');
267dfe3ae67SAnna Dabrowska        $Lexer->addSpecialPattern('\\\\"', 'double_quote_string', 'escapeSequence');
268aaa187abSSzymon Olewniczak        $Lexer->addExitPattern('"', 'double_quote_string');
269aaa187abSSzymon Olewniczak
270dfe3ae67SAnna Dabrowska        $Lexer->addEntryPattern("'", 'row', 'singleQuoteString');
271dfe3ae67SAnna Dabrowska        $Lexer->addSpecialPattern("\\\\'", 'singleQuoteString', 'escapeSequence');
272dfe3ae67SAnna Dabrowska        $Lexer->addExitPattern("'", 'singleQuoteString');
273aaa187abSSzymon Olewniczak
274dfe3ae67SAnna Dabrowska        $Lexer->mapHandler('double_quote_string', 'singleQuoteString');
275aaa187abSSzymon Olewniczak
276aaa187abSSzymon Olewniczak        $Lexer->addSpecialPattern('[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?', 'row', 'number');
277aaa187abSSzymon Olewniczak
278aaa187abSSzymon Olewniczak        $res = $Lexer->parse($value);
279aaa187abSSzymon Olewniczak
280670a6894SAnna Dabrowska        $currentMode = $isLegacy ? $Lexer->_mode->getCurrent() : $Lexer->getModeStack()->getCurrent();
281670a6894SAnna Dabrowska        if (!$res || $currentMode != 'base') {
282aaa187abSSzymon Olewniczak            throw new StructException('invalid row value syntax');
283aaa187abSSzymon Olewniczak        }
284aaa187abSSzymon Olewniczak
285dfe3ae67SAnna Dabrowska        return $Handler->getRow();
286aaa187abSSzymon Olewniczak    }
287aaa187abSSzymon Olewniczak
288aaa187abSSzymon Olewniczak    /**
28953528ecfSAndreas Gohr     * Wrap given value in asterisks
29053528ecfSAndreas Gohr     *
29153528ecfSAndreas Gohr     * @param string|string[] $value
29253528ecfSAndreas Gohr     * @return string|string[]
29353528ecfSAndreas Gohr     */
29461356325SAnna Dabrowska    protected function filterWrapAsterisks($value)
29561356325SAnna Dabrowska    {
2965e29103aSannda        $map = static fn($input) => "*$input*";
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    {
3145e29103aSannda        $map = static fn($input) => str_replace('*', '%', $input);
31553528ecfSAndreas Gohr
31653528ecfSAndreas Gohr        if (is_array($value)) {
31753528ecfSAndreas Gohr            $value = array_map($map, $value);
31853528ecfSAndreas Gohr        } else {
31953528ecfSAndreas Gohr            $value = $map($value);
32053528ecfSAndreas Gohr        }
32153528ecfSAndreas Gohr        return $value;
32253528ecfSAndreas Gohr    }
32353528ecfSAndreas Gohr
32453528ecfSAndreas Gohr    /**
3257f9cb794SAndreas Gohr     * Set offset for the results
3267f9cb794SAndreas Gohr     *
3277f9cb794SAndreas Gohr     * @param int $offset
3287f9cb794SAndreas Gohr     */
32961356325SAnna Dabrowska    public function setOffset($offset)
33061356325SAnna Dabrowska    {
3317f9cb794SAndreas Gohr        $limit = 0;
3327f9cb794SAndreas Gohr        if ($this->range_end) {
3337f9cb794SAndreas Gohr            // if there was a limit set previously, the range_end needs to be recalculated
3347f9cb794SAndreas Gohr            $limit = $this->range_end - $this->range_begin;
3357f9cb794SAndreas Gohr        }
3367f9cb794SAndreas Gohr        $this->range_begin = $offset;
3377f9cb794SAndreas Gohr        if ($limit) $this->setLimit($limit);
3387f9cb794SAndreas Gohr    }
3397f9cb794SAndreas Gohr
3407f9cb794SAndreas Gohr    /**
341fdf37115SAndreas Gohr     * Get the current offset for the results
342fdf37115SAndreas Gohr     *
343fdf37115SAndreas Gohr     * @return int
344fdf37115SAndreas Gohr     */
345fdf37115SAndreas Gohr    public function getOffset()
346fdf37115SAndreas Gohr    {
347fdf37115SAndreas Gohr        return $this->range_begin;
348fdf37115SAndreas Gohr    }
349fdf37115SAndreas Gohr
350fdf37115SAndreas Gohr    /**
3517f9cb794SAndreas Gohr     * Limit results to this number
3527f9cb794SAndreas Gohr     *
3537f9cb794SAndreas Gohr     * @param int $limit Set to 0 to disable limit again
3547f9cb794SAndreas Gohr     */
35561356325SAnna Dabrowska    public function setLimit($limit)
35661356325SAnna Dabrowska    {
3577f9cb794SAndreas Gohr        if ($limit) {
3587f9cb794SAndreas Gohr            $this->range_end = $this->range_begin + $limit;
3597f9cb794SAndreas Gohr        } else {
3607f9cb794SAndreas Gohr            $this->range_end = 0;
3617f9cb794SAndreas Gohr        }
3627f9cb794SAndreas Gohr    }
3637f9cb794SAndreas Gohr
3647f9cb794SAndreas Gohr    /**
365fdf37115SAndreas Gohr     * Get the current limit for the results
366fdf37115SAndreas Gohr     *
367fdf37115SAndreas Gohr     * @return int
368fdf37115SAndreas Gohr     */
369fdf37115SAndreas Gohr    public function getLimit()
370fdf37115SAndreas Gohr    {
371fdf37115SAndreas Gohr        if ($this->range_end) {
372fdf37115SAndreas Gohr            return $this->range_end - $this->range_begin;
373fdf37115SAndreas Gohr        }
374fdf37115SAndreas Gohr        return 0;
375fdf37115SAndreas Gohr    }
376fdf37115SAndreas Gohr
377fdf37115SAndreas Gohr    /**
378eff6062eSAnna Dabrowska     * Allows disabling default 'latest = 1' clause in select statement
379eff6062eSAnna Dabrowska     *
380eff6062eSAnna Dabrowska     * @param bool $selectLatest
381eff6062eSAnna Dabrowska     */
382eff6062eSAnna Dabrowska    public function setSelectLatest($selectLatest): void
383eff6062eSAnna Dabrowska    {
384eff6062eSAnna Dabrowska        $this->selectLatest = $selectLatest;
385eff6062eSAnna Dabrowska    }
386eff6062eSAnna Dabrowska
387eff6062eSAnna Dabrowska    /**
3887f9cb794SAndreas Gohr     * Return the number of results (regardless of limit and offset settings)
3897f9cb794SAndreas Gohr     *
3900549dcc5SAndreas Gohr     * Use this to implement paging. Important: this may only be called after running @return int
3910549dcc5SAndreas Gohr     * @see execute()
3927f9cb794SAndreas Gohr     *
3937f9cb794SAndreas Gohr     */
39461356325SAnna Dabrowska    public function getCount()
39561356325SAnna Dabrowska    {
3967f9cb794SAndreas Gohr        if ($this->count < 0) throw new StructException('Count is only accessible after executing the search');
3977f9cb794SAndreas Gohr        return $this->count;
3987f9cb794SAndreas Gohr    }
3997f9cb794SAndreas Gohr
400c46f5fb1SAndreas Gohr    /**
401c46f5fb1SAndreas Gohr     * Returns the PID associated with each result row
402c46f5fb1SAndreas Gohr     *
4030549dcc5SAndreas Gohr     * Important: this may only be called after running @return \string[]
4040549dcc5SAndreas Gohr     * @see execute()
405c46f5fb1SAndreas Gohr     *
406c46f5fb1SAndreas Gohr     */
40761356325SAnna Dabrowska    public function getPids()
40861356325SAnna Dabrowska    {
40917a3a578SAndreas Gohr        if ($this->result_pids === null)
41017a3a578SAndreas Gohr            throw new StructException('PIDs are only accessible after executing the search');
411d4b5a17cSAndreas Gohr        return $this->result_pids;
412d4b5a17cSAndreas Gohr    }
413d4b5a17cSAndreas Gohr
4147f9cb794SAndreas Gohr    /**
4150ceefd5cSAnna Dabrowska     * Returns the rid associated with each result row
4160ceefd5cSAnna Dabrowska     *
4170549dcc5SAndreas Gohr     * Important: this may only be called after running @return array
4180549dcc5SAndreas Gohr     * @see execute()
4190ceefd5cSAnna Dabrowska     *
4200ceefd5cSAnna Dabrowska     */
42161356325SAnna Dabrowska    public function getRids()
42261356325SAnna Dabrowska    {
42317a3a578SAndreas Gohr        if ($this->result_rids === null)
42417a3a578SAndreas Gohr            throw new StructException('rids are only accessible after executing the search');
4250ceefd5cSAnna Dabrowska        return $this->result_rids;
4260ceefd5cSAnna Dabrowska    }
4270ceefd5cSAnna Dabrowska
4280ceefd5cSAnna Dabrowska    /**
4296fd73b4bSAnna Dabrowska     * Returns the rid associated with each result row
4306fd73b4bSAnna Dabrowska     *
4310549dcc5SAndreas Gohr     * Important: this may only be called after running @return array
4320549dcc5SAndreas Gohr     * @see execute()
4336fd73b4bSAnna Dabrowska     *
4346fd73b4bSAnna Dabrowska     */
43561356325SAnna Dabrowska    public function getRevs()
43661356325SAnna Dabrowska    {
43717a3a578SAndreas Gohr        if ($this->result_revs === null)
43817a3a578SAndreas Gohr            throw new StructException('revs are only accessible after executing the search');
4396fd73b4bSAnna Dabrowska        return $this->result_revs;
4406fd73b4bSAnna Dabrowska    }
4416fd73b4bSAnna Dabrowska
4426fd73b4bSAnna Dabrowska    /**
443b2ed727aSAndreas Gohr     * Execute this search and return the result
444b2ed727aSAndreas Gohr     *
44538fa36fbSAndreas Gohr     * The result is a two dimensional array of Value()s.
4467f9cb794SAndreas Gohr     *
4477f9cb794SAndreas Gohr     * This will always query for the full result (not using offset and limit) and then
4480549dcc5SAndreas Gohr     * return the wanted range, setting the count (@return Value[][]
4490549dcc5SAndreas Gohr     * @see getCount) to the whole result number
45038fa36fbSAndreas Gohr     *
451b2ed727aSAndreas Gohr     */
4528ce43f5aSAnna Dabrowska    public function execute()
45361356325SAnna Dabrowska    {
4547234bfb1Ssplitbrain        [$sql, $opts] = $this->getSQL();
455b2ed727aSAndreas Gohr
4567f9cb794SAndreas Gohr        /** @var \PDOStatement $res */
457b2ed727aSAndreas Gohr        $res = $this->sqlite->query($sql, $opts);
45859b668aaSAndreas Gohr        if ($res === false) throw new StructException("SQL execution failed for\n\n$sql");
459b2ed727aSAndreas Gohr
4607234bfb1Ssplitbrain        $this->result_pids = [];
4617234bfb1Ssplitbrain        $result = [];
4627f9cb794SAndreas Gohr        $cursor = -1;
463*b8d3247dSAnna Dabrowska        $pageidAndRevOnly = array_reduce(
464*b8d3247dSAnna Dabrowska            $this->columns,
465*b8d3247dSAnna Dabrowska            static fn($pageidAndRevOnly, Column $col) => $pageidAndRevOnly && ($col->getTid() == 0),
466*b8d3247dSAnna Dabrowska            true
467*b8d3247dSAnna Dabrowska        );
4687f9cb794SAndreas Gohr        while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
4697f9cb794SAndreas Gohr            $cursor++;
4707f9cb794SAndreas Gohr            if ($cursor < $this->range_begin) continue;
4717f9cb794SAndreas Gohr            if ($this->range_end && $cursor >= $this->range_end) continue;
4727f9cb794SAndreas Gohr
473b2ed727aSAndreas Gohr            $C = 0;
4747234bfb1Ssplitbrain            $resrow = [];
47599a70f28SAndreas Gohr            $isempty = true;
476b2ed727aSAndreas Gohr            foreach ($this->columns as $col) {
47738fa36fbSAndreas Gohr                $val = $row["C$C"];
478b2ed727aSAndreas Gohr                if ($col->isMulti()) {
47938fa36fbSAndreas Gohr                    $val = explode(self::CONCAT_SEPARATOR, $val);
480b2ed727aSAndreas Gohr                }
48199a70f28SAndreas Gohr                $value = new Value($col, $val);
4828cba7aa0SMichael Grosse                $isempty &= $this->isEmptyValue($value);
48399a70f28SAndreas Gohr                $resrow[] = $value;
484b2ed727aSAndreas Gohr                $C++;
485b2ed727aSAndreas Gohr            }
48699a70f28SAndreas Gohr
48799a70f28SAndreas Gohr            // skip empty rows
4888cba7aa0SMichael Grosse            if ($isempty && !$pageidAndRevOnly) {
48999a70f28SAndreas Gohr                $cursor--;
49099a70f28SAndreas Gohr                continue;
49199a70f28SAndreas Gohr            }
49299a70f28SAndreas Gohr
49399a70f28SAndreas Gohr            $this->result_pids[] = $row['PID'];
4940ceefd5cSAnna Dabrowska            $this->result_rids[] = $row['rid'];
4956fd73b4bSAnna Dabrowska            $this->result_revs[] = $row['rev'];
496b2ed727aSAndreas Gohr            $result[] = $resrow;
497b2ed727aSAndreas Gohr        }
4987f9cb794SAndreas Gohr
49979b29326SAnna Dabrowska        $res->closeCursor();
5007f9cb794SAndreas Gohr        $this->count = $cursor + 1;
501b2ed727aSAndreas Gohr        return $result;
502b2ed727aSAndreas Gohr    }
503b2ed727aSAndreas Gohr
504b2ed727aSAndreas Gohr    /**
50515929be2SAndreas Gohr     * Transform the set search parameters into a statement
50615929be2SAndreas Gohr     *
507299ca8ccSAndreas Gohr     * Calls runSQLBuilder()
508299ca8ccSAndreas Gohr     *
509b2ed727aSAndreas Gohr     * @return array ($sql, $opts) The SQL and parameters to execute
51015929be2SAndreas Gohr     */
5118ce43f5aSAnna Dabrowska    public function getSQL()
51261356325SAnna Dabrowska    {
5135511bd5bSAndreas Gohr        if (!$this->columns) throw new StructException('nocolname');
514299ca8ccSAndreas Gohr        return $this->runSQLBuilder()->getSQL();
515299ca8ccSAndreas Gohr    }
51615929be2SAndreas Gohr
517299ca8ccSAndreas Gohr    /**
518299ca8ccSAndreas Gohr     * Initialize and execute the SQLBuilder
519299ca8ccSAndreas Gohr     *
520299ca8ccSAndreas Gohr     * Called from getSQL(). Can be overwritten to extend the query using the query builder
521299ca8ccSAndreas Gohr     *
522299ca8ccSAndreas Gohr     * @return SearchSQLBuilder
523299ca8ccSAndreas Gohr     */
524299ca8ccSAndreas Gohr    protected function runSQLBuilder()
525299ca8ccSAndreas Gohr    {
526fd9c77d3SAndreas Gohr        $sqlBuilder = new SearchSQLBuilder();
527b37d1c8bSAnna Dabrowska        $sqlBuilder->setSelectLatest($this->selectLatest);
528fd9c77d3SAndreas Gohr        $sqlBuilder->addSchemas($this->schemas);
529fd9c77d3SAndreas Gohr        $sqlBuilder->addColumns($this->columns);
530fd9c77d3SAndreas Gohr        $sqlBuilder->addFilters($this->filter);
531fd9c77d3SAndreas Gohr        $sqlBuilder->addFilters($this->dynamicFilter);
532fd9c77d3SAndreas Gohr        $sqlBuilder->addSorts($this->sortby);
533299ca8ccSAndreas Gohr        return $sqlBuilder;
53415929be2SAndreas Gohr    }
53515929be2SAndreas Gohr
53615929be2SAndreas Gohr    /**
53701dd90deSAndreas Gohr     * Returns all the columns that where added to the search
53801dd90deSAndreas Gohr     *
53901dd90deSAndreas Gohr     * @return Column[]
54001dd90deSAndreas Gohr     */
54161356325SAnna Dabrowska    public function getColumns()
54261356325SAnna Dabrowska    {
54301dd90deSAndreas Gohr        return $this->columns;
54401dd90deSAndreas Gohr    }
54501dd90deSAndreas Gohr
546577b462bSAndreas Gohr    /**
5475a4df70dSAndreas Gohr     * All the schemas currently added
5485a4df70dSAndreas Gohr     *
5495a4df70dSAndreas Gohr     * @return Schema[]
5505a4df70dSAndreas Gohr     */
55161356325SAnna Dabrowska    public function getSchemas()
55261356325SAnna Dabrowska    {
5535a4df70dSAndreas Gohr        return array_values($this->schemas);
5545a4df70dSAndreas Gohr    }
5555a4df70dSAndreas Gohr
5565a4df70dSAndreas Gohr    /**
557577b462bSAndreas Gohr     * Checks if the given column is a * wildcard
558577b462bSAndreas Gohr     *
559577b462bSAndreas Gohr     * If it's a wildcard all matching columns are added to the column list, otherwise
560577b462bSAndreas Gohr     * nothing happens
561577b462bSAndreas Gohr     *
562577b462bSAndreas Gohr     * @param string $colname
563577b462bSAndreas Gohr     * @return bool was wildcard?
564577b462bSAndreas Gohr     */
56561356325SAnna Dabrowska    protected function processWildcard($colname)
56661356325SAnna Dabrowska    {
5677234bfb1Ssplitbrain        [$colname, $table] = $this->resolveColumn($colname);
568577b462bSAndreas Gohr        if ($colname !== '*') return false;
569577b462bSAndreas Gohr
570577b462bSAndreas Gohr        // no table given? assume the first is meant
571577b462bSAndreas Gohr        if ($table === null) {
572577b462bSAndreas Gohr            $schema_list = array_keys($this->schemas);
573577b462bSAndreas Gohr            $table = $schema_list[0];
574577b462bSAndreas Gohr        }
575577b462bSAndreas Gohr
5761ca21e17SAnna Dabrowska        $schema = $this->schemas[$table] ?? null;
5777234bfb1Ssplitbrain        if (!$schema instanceof Schema) return false;
578577b462bSAndreas Gohr        $this->columns = array_merge($this->columns, $schema->getColumns(false));
579577b462bSAndreas Gohr        return true;
580577b462bSAndreas Gohr    }
581577b462bSAndreas Gohr
582577b462bSAndreas Gohr    /**
583577b462bSAndreas Gohr     * Split a given column name into table and column
584577b462bSAndreas Gohr     *
585577b462bSAndreas Gohr     * Handles Aliases. Table might be null if none given.
586577b462bSAndreas Gohr     *
587577b462bSAndreas Gohr     * @param $colname
588636a5173SAndreas Gohr     * @return array (colname, table)
589577b462bSAndreas Gohr     */
59061356325SAnna Dabrowska    protected function resolveColumn($colname)
59161356325SAnna Dabrowska    {
592577b462bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
593577b462bSAndreas Gohr
594577b462bSAndreas Gohr        // resolve the alias or table name
5957fe2cdf2SAndreas Gohr        [$table, $colname] = sexplode('.', $colname, 2, '');
596577b462bSAndreas Gohr        if (!$colname) {
597577b462bSAndreas Gohr            $colname = $table;
598577b462bSAndreas Gohr            $table = null;
599577b462bSAndreas Gohr        }
600577b462bSAndreas Gohr        if ($table && isset($this->aliases[$table])) {
601577b462bSAndreas Gohr            $table = $this->aliases[$table];
602577b462bSAndreas Gohr        }
603577b462bSAndreas Gohr
604577b462bSAndreas Gohr        if (!$colname) throw new StructException('nocolname');
605577b462bSAndreas Gohr
6067234bfb1Ssplitbrain        return [$colname, $table];
607577b462bSAndreas Gohr    }
60801dd90deSAndreas Gohr
60901dd90deSAndreas Gohr    /**
61015929be2SAndreas Gohr     * Find a column to be used in the search
61115929be2SAndreas Gohr     *
61215929be2SAndreas Gohr     * @param string $colname may contain an alias
61315929be2SAndreas Gohr     * @return bool|Column
61415929be2SAndreas Gohr     */
6150280da9aSFrieder Schrempf    public function findColumn($colname, $strict = false)
61661356325SAnna Dabrowska    {
6175511bd5bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
618df02ffe6SMichael Große        $schema_list = array_keys($this->schemas);
619f107f479SAndreas Gohr
620f107f479SAndreas Gohr        // add "fake" column for special col
621128d4e83SAndreas Gohr        if ($colname == '%pageid%') {
622128d4e83SAndreas Gohr            return new PageColumn(0, new Page(), $schema_list[0]);
623d1b04e89SAndreas Gohr        }
624128d4e83SAndreas Gohr        if ($colname == '%title%') {
6257234bfb1Ssplitbrain            return new PageColumn(0, new Page(['usetitles' => true]), $schema_list[0]);
626128d4e83SAndreas Gohr        }
627cadfc3ccSAndreas Gohr        if ($colname == '%lastupdate%') {
628cadfc3ccSAndreas Gohr            return new RevisionColumn(0, new DateTime(), $schema_list[0]);
629cadfc3ccSAndreas Gohr        }
6302e12ac22SMichael Grosse        if ($colname == '%lasteditor%') {
6312e12ac22SMichael Grosse            return new UserColumn(0, new User(), $schema_list[0]);
6322e12ac22SMichael Grosse        }
63388b58a21SSzymon Olewniczak        if ($colname == '%lastsummary%') {
6346781c68dSSzymon Olewniczak            return new SummaryColumn(0, new AutoSummary(), $schema_list[0]);
63588b58a21SSzymon Olewniczak        }
636f107f479SAndreas Gohr        if ($colname == '%rowid%') {
637f107f479SAndreas Gohr            return new RowColumn(0, new Decimal(), $schema_list[0]);
638f107f479SAndreas Gohr        }
639da62ec9cSAnna Dabrowska        if ($colname == '%published%') {
640da62ec9cSAnna Dabrowska            return new PublishedColumn(0, new Decimal(), $schema_list[0]);
641da62ec9cSAnna Dabrowska        }
642d1b04e89SAndreas Gohr
6437234bfb1Ssplitbrain        [$colname, $table] = $this->resolveColumn($colname);
64415929be2SAndreas Gohr
6450280da9aSFrieder Schrempf        /*
6460280da9aSFrieder Schrempf         * If table name is given search only that, otherwise if no strict behavior
6470280da9aSFrieder Schrempf         * is requested by the caller, try all assigned schemas for matching the
6480280da9aSFrieder Schrempf         * column name.
6490280da9aSFrieder Schrempf         */
65034ea6e10SAnna Dabrowska        if ($table !== null && isset($this->schemas[$table])) {
6517234bfb1Ssplitbrain            $schemas = [$table => $this->schemas[$table]];
6520280da9aSFrieder Schrempf        } elseif ($table === null || !$strict) {
65315929be2SAndreas Gohr            $schemas = $this->schemas;
6540280da9aSFrieder Schrempf        } else {
6550280da9aSFrieder Schrempf            return false;
65615929be2SAndreas Gohr        }
65715929be2SAndreas Gohr
65815929be2SAndreas Gohr        // find it
65915929be2SAndreas Gohr        $col = false;
66015929be2SAndreas Gohr        foreach ($schemas as $schema) {
6614ac44d1cSMichael Grosse            if (empty($schema)) {
6624ac44d1cSMichael Grosse                continue;
6634ac44d1cSMichael Grosse            }
66415929be2SAndreas Gohr            $col = $schema->findColumn($colname);
66515929be2SAndreas Gohr            if ($col) break;
66615929be2SAndreas Gohr        }
66715929be2SAndreas Gohr
66815929be2SAndreas Gohr        return $col;
66915929be2SAndreas Gohr    }
67015929be2SAndreas Gohr
6719dbc8ec0SMichael Grosse    /**
67299a70f28SAndreas Gohr     * Check if the given row is empty or references our own row
6739dbc8ec0SMichael Grosse     *
67499a70f28SAndreas Gohr     * @param Value $value
6759dbc8ec0SMichael Grosse     * @return bool
6769dbc8ec0SMichael Grosse     */
67761356325SAnna Dabrowska    protected function isEmptyValue(Value $value)
67861356325SAnna Dabrowska    {
67999a70f28SAndreas Gohr        if ($value->isEmpty()) return true;
6808cba7aa0SMichael Grosse        if ($value->getColumn()->getTid() == 0) return true;
6819dbc8ec0SMichael Grosse        return false;
6829dbc8ec0SMichael Grosse    }
68315929be2SAndreas Gohr}
684