xref: /plugin/struct/meta/Search.php (revision b37d1c8b1c9b7955c33a25761820e4ae23ee7369)
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
441057ed14SAndreas Gohr    /** @var array the filters */
451057ed14SAndreas Gohr    protected $dynamicFilter = array();
461057ed14SAndreas 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
65eff6062eSAnna Dabrowska    /** @var bool Include latest = 1 in select query */
66eff6062eSAnna Dabrowska    protected $selectLatest = true;
67eff6062eSAnna Dabrowska
6815929be2SAndreas Gohr    /**
699d7a36f9SAndreas Gohr     * Search constructor.
709d7a36f9SAndreas Gohr     */
7161356325SAnna Dabrowska    public function __construct()
7261356325SAnna Dabrowska    {
73837e87e2SAnna Dabrowska        /** @var  $dbHelper */
74837e87e2SAnna Dabrowska        $this->dbHelper = plugin_load('helper', 'struct_db');
75837e87e2SAnna Dabrowska        $this->sqlite = $this->dbHelper->getDB();
76bb8d98c4SAnna Dabrowska    }
77837e87e2SAnna Dabrowska
78837e87e2SAnna Dabrowska    public function getDb()
79837e87e2SAnna Dabrowska    {
80837e87e2SAnna Dabrowska        return $this->sqlite;
819d7a36f9SAndreas Gohr    }
829d7a36f9SAndreas Gohr
839d7a36f9SAndreas Gohr    /**
8415929be2SAndreas Gohr     * Add a schema to be searched
8515929be2SAndreas Gohr     *
8615929be2SAndreas Gohr     * Call multiple times for multiple schemas.
8715929be2SAndreas Gohr     *
8815929be2SAndreas Gohr     * @param string $table
8915929be2SAndreas Gohr     * @param string $alias
9015929be2SAndreas Gohr     */
9161356325SAnna Dabrowska    public function addSchema($table, $alias = '')
9261356325SAnna Dabrowska    {
932be187cdSAndreas Gohr        $schema = new Schema($table);
942be187cdSAndreas Gohr        if (!$schema->getId()) {
952be187cdSAndreas Gohr            throw new StructException('schema missing', $table);
962be187cdSAndreas Gohr        }
972be187cdSAndreas Gohr
98712c650dSAndreas Gohr        $this->schemas[$schema->getTable()] = $schema;
99712c650dSAndreas Gohr        if ($alias) $this->aliases[$alias] = $schema->getTable();
10015929be2SAndreas Gohr    }
10115929be2SAndreas Gohr
10215929be2SAndreas Gohr    /**
10315929be2SAndreas Gohr     * Add a column to be returned by the search
10415929be2SAndreas Gohr     *
10515929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
10615929be2SAndreas Gohr     * added before
10715929be2SAndreas Gohr     *
10815929be2SAndreas Gohr     * @param string $colname may contain an alias
10915929be2SAndreas Gohr     */
11061356325SAnna Dabrowska    public function addColumn($colname)
11161356325SAnna Dabrowska    {
112577b462bSAndreas Gohr        if ($this->processWildcard($colname)) return; // wildcard?
113b26126edSAndreas Hubel        if ($colname[0] == '-') { // remove column from previous wildcard lookup
114b26126edSAndreas Hubel            $colname = substr($colname, 1);
115b26126edSAndreas Hubel            foreach ($this->columns as $key => $col) {
116b26126edSAndreas Hubel                if ($col->getLabel() == $colname) unset($this->columns[$key]);
117b26126edSAndreas Hubel            }
118b26126edSAndreas Hubel            return;
119b26126edSAndreas Hubel        }
120b26126edSAndreas Hubel
12115929be2SAndreas Gohr        $col = $this->findColumn($colname);
12215929be2SAndreas Gohr        if (!$col) return; //FIXME do we really want to ignore missing columns?
12315929be2SAndreas Gohr        $this->columns[] = $col;
12415929be2SAndreas Gohr    }
12515929be2SAndreas Gohr
12615929be2SAndreas Gohr    /**
12715929be2SAndreas Gohr     * Add sorting options
12815929be2SAndreas Gohr     *
12915929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
13015929be2SAndreas Gohr     * added before
13115929be2SAndreas Gohr     *
13215929be2SAndreas Gohr     * @param string $colname may contain an alias
13315929be2SAndreas Gohr     * @param bool $asc sort direction (ASC = true, DESC = false)
134eb55dc17SAndreas Gohr     * @param bool $nc set true for caseinsensitivity
13515929be2SAndreas Gohr     */
13661356325SAnna Dabrowska    public function addSort($colname, $asc = true, $nc = true)
13761356325SAnna Dabrowska    {
13815929be2SAndreas Gohr        $col = $this->findColumn($colname);
13915929be2SAndreas Gohr        if (!$col) return; //FIXME do we really want to ignore missing columns?
14015929be2SAndreas Gohr
141eb55dc17SAndreas Gohr        $this->sortby[$col->getFullQualifiedLabel()] = array($col, $asc, $nc);
14207993756SAndreas Gohr    }
14307993756SAndreas Gohr
14407993756SAndreas Gohr    /**
145b3a9db22SAndreas Gohr     * Clear all sorting options
146b3a9db22SAndreas Gohr     *
147b3a9db22SAndreas Gohr     * @return void
148b3a9db22SAndreas Gohr     */
149b3a9db22SAndreas Gohr    public function clearSort()
150b3a9db22SAndreas Gohr    {
151b3a9db22SAndreas Gohr        $this->sortby = [];
152b3a9db22SAndreas Gohr    }
153b3a9db22SAndreas Gohr
154b3a9db22SAndreas Gohr    /**
15507993756SAndreas Gohr     * Returns all set sort columns
15607993756SAndreas Gohr     *
15707993756SAndreas Gohr     * @return array
15807993756SAndreas Gohr     */
15961356325SAnna Dabrowska    public function getSorts()
16061356325SAnna Dabrowska    {
16107993756SAndreas Gohr        return $this->sortby;
16215929be2SAndreas Gohr    }
16315929be2SAndreas Gohr
16415929be2SAndreas Gohr    /**
1659d7a36f9SAndreas Gohr     * Adds a filter
16615929be2SAndreas Gohr     *
16715929be2SAndreas Gohr     * @param string $colname may contain an alias
16853528ecfSAndreas Gohr     * @param string|string[] $value
1695511bd5bSAndreas Gohr     * @param string $comp @see self::COMPARATORS
1704c13ff97SAndreas Gohr     * @param string $op either 'OR' or 'AND'
17115929be2SAndreas Gohr     */
17261356325SAnna Dabrowska    public function addFilter($colname, $value, $comp, $op = 'OR')
17361356325SAnna Dabrowska    {
1741057ed14SAndreas Gohr        $filter = $this->createFilter($colname, $value, $comp, $op);
1751057ed14SAndreas Gohr        if ($filter) $this->filter[] = $filter;
1761057ed14SAndreas Gohr    }
1771057ed14SAndreas Gohr
1781057ed14SAndreas Gohr    /**
1791057ed14SAndreas Gohr     * Adds a dynamic filter
1801057ed14SAndreas Gohr     *
1811057ed14SAndreas Gohr     * @param string $colname may contain an alias
1821057ed14SAndreas Gohr     * @param string|string[] $value
1831057ed14SAndreas Gohr     * @param string $comp @see self::COMPARATORS
1841057ed14SAndreas Gohr     * @param string $op either 'OR' or 'AND'
1851057ed14SAndreas Gohr     */
1861057ed14SAndreas Gohr    public function addDynamicFilter($colname, $value, $comp, $op = 'OR')
1871057ed14SAndreas Gohr    {
1881057ed14SAndreas Gohr        $filter = $this->createFilter($colname, $value, $comp, $op);
1891057ed14SAndreas Gohr        if ($filter) $this->dynamicFilter[] = $filter;
1901057ed14SAndreas Gohr    }
1911057ed14SAndreas Gohr
1921057ed14SAndreas Gohr    /**
1931057ed14SAndreas Gohr     * Create a filter definition
1941057ed14SAndreas Gohr     *
1951057ed14SAndreas Gohr     * @param string $colname may contain an alias
1961057ed14SAndreas Gohr     * @param string|string[] $value
1971057ed14SAndreas Gohr     * @param string $comp @see self::COMPARATORS
1981057ed14SAndreas Gohr     * @param string $op either 'OR' or 'AND'
1991057ed14SAndreas Gohr     * @return array|null [Column col, string|string[] value, string comp, string op]
2001057ed14SAndreas Gohr     */
2011057ed14SAndreas Gohr    protected function createFilter($colname, $value, $comp, $op = 'OR')
2021057ed14SAndreas Gohr    {
2039dbc32aeSAndreas Gohr        /* Convert certain filters into others
2049dbc32aeSAndreas Gohr         * this reduces the number of supported filters to implement in types */
2059dbc32aeSAndreas Gohr        if ($comp == '*~') {
20653528ecfSAndreas Gohr            $value = $this->filterWrapAsterisks($value);
2079dbc32aeSAndreas Gohr            $comp = '~';
2089dbc32aeSAndreas Gohr        } elseif ($comp == '<>') {
2099dbc32aeSAndreas Gohr            $comp = '!=';
2109dbc32aeSAndreas Gohr        }
2119dbc32aeSAndreas Gohr
21217a3a578SAndreas Gohr        if (!in_array($comp, self::$COMPARATORS))
21317a3a578SAndreas Gohr            throw new StructException("Bad comperator. Use " . join(',', self::$COMPARATORS));
21417a3a578SAndreas Gohr        if ($op != 'OR' && $op != 'AND')
21517a3a578SAndreas Gohr            throw new StructException('Bad filter type . Only AND or OR allowed');
2169d7a36f9SAndreas Gohr
21715929be2SAndreas Gohr        $col = $this->findColumn($colname);
2181057ed14SAndreas Gohr        if (!$col) return null; // ignore missing columns, filter might have been for different schema
2197da1a0fdSAndreas Gohr
2207da1a0fdSAndreas Gohr        // map filter operators to SQL syntax
2217da1a0fdSAndreas Gohr        switch ($comp) {
2227da1a0fdSAndreas Gohr            case '~':
2237da1a0fdSAndreas Gohr                $comp = 'LIKE';
2247da1a0fdSAndreas Gohr                break;
2257da1a0fdSAndreas Gohr            case '!~':
2267da1a0fdSAndreas Gohr                $comp = 'NOT LIKE';
2277da1a0fdSAndreas Gohr                break;
2287da1a0fdSAndreas Gohr            case '=*':
2297da1a0fdSAndreas Gohr                $comp = 'REGEXP';
2307da1a0fdSAndreas Gohr                break;
2317da1a0fdSAndreas Gohr        }
2327da1a0fdSAndreas Gohr
2337da1a0fdSAndreas Gohr        // we use asterisks, but SQL wants percents
2347da1a0fdSAndreas Gohr        if ($comp == 'LIKE' || $comp == 'NOT LIKE') {
23553528ecfSAndreas Gohr            $value = $this->filterChangeToLike($value);
2367da1a0fdSAndreas Gohr        }
2377da1a0fdSAndreas Gohr
238aaa187abSSzymon Olewniczak        if ($comp == ' IN ' && !is_array($value)) {
239efff5841SSzymon Olewniczak            $value = $this->parseFilterValueList($value);
240aaa187abSSzymon Olewniczak            //col IN ('a', 'b', 'c') is equal to col = 'a' OR 'col = 'b' OR col = 'c'
241aaa187abSSzymon Olewniczak            $comp = '=';
242aaa187abSSzymon Olewniczak        }
243aaa187abSSzymon Olewniczak
2447da1a0fdSAndreas Gohr        // add the filter
2451057ed14SAndreas Gohr        return array($col, $value, $comp, $op);
24615929be2SAndreas Gohr    }
24715929be2SAndreas Gohr
24815929be2SAndreas Gohr    /**
249aaa187abSSzymon Olewniczak     * Parse SQLite row value into array
250aaa187abSSzymon Olewniczak     *
251aaa187abSSzymon Olewniczak     * @param string $value
252aaa187abSSzymon Olewniczak     * @return string[]
253aaa187abSSzymon Olewniczak     */
25461356325SAnna Dabrowska    protected function parseFilterValueList($value)
25561356325SAnna Dabrowska    {
256efff5841SSzymon Olewniczak        $Handler = new FilterValueListHandler();
257670a6894SAnna Dabrowska        $LexerClass = class_exists('\Doku_Lexer') ? '\Doku_Lexer' : '\dokuwiki\Parsing\Lexer\Lexer';
258670a6894SAnna Dabrowska        $isLegacy = $LexerClass === '\Doku_Lexer';
259670a6894SAnna Dabrowska        /** @var \Doku_Lexer|\dokuwiki\Parsing\Lexer\Lexer $Lexer */
260670a6894SAnna Dabrowska        $Lexer = new $LexerClass($Handler, 'base', true);
261670a6894SAnna Dabrowska
262aaa187abSSzymon Olewniczak
263aaa187abSSzymon Olewniczak        $Lexer->addEntryPattern('\(', 'base', 'row');
264aaa187abSSzymon Olewniczak        $Lexer->addPattern('\s*,\s*', 'row');
265aaa187abSSzymon Olewniczak        $Lexer->addExitPattern('\)', 'row');
266aaa187abSSzymon Olewniczak
267aaa187abSSzymon Olewniczak        $Lexer->addEntryPattern('"', 'row', 'double_quote_string');
268dfe3ae67SAnna Dabrowska        $Lexer->addSpecialPattern('\\\\"', 'double_quote_string', 'escapeSequence');
269aaa187abSSzymon Olewniczak        $Lexer->addExitPattern('"', 'double_quote_string');
270aaa187abSSzymon Olewniczak
271dfe3ae67SAnna Dabrowska        $Lexer->addEntryPattern("'", 'row', 'singleQuoteString');
272dfe3ae67SAnna Dabrowska        $Lexer->addSpecialPattern("\\\\'", 'singleQuoteString', 'escapeSequence');
273dfe3ae67SAnna Dabrowska        $Lexer->addExitPattern("'", 'singleQuoteString');
274aaa187abSSzymon Olewniczak
275dfe3ae67SAnna Dabrowska        $Lexer->mapHandler('double_quote_string', 'singleQuoteString');
276aaa187abSSzymon Olewniczak
277aaa187abSSzymon Olewniczak        $Lexer->addSpecialPattern('[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?', 'row', 'number');
278aaa187abSSzymon Olewniczak
279aaa187abSSzymon Olewniczak        $res = $Lexer->parse($value);
280aaa187abSSzymon Olewniczak
281670a6894SAnna Dabrowska        $currentMode = $isLegacy ? $Lexer->_mode->getCurrent() : $Lexer->getModeStack()->getCurrent();
282670a6894SAnna Dabrowska        if (!$res || $currentMode != 'base') {
283aaa187abSSzymon Olewniczak            throw new StructException('invalid row value syntax');
284aaa187abSSzymon Olewniczak        }
285aaa187abSSzymon Olewniczak
286dfe3ae67SAnna Dabrowska        return $Handler->getRow();
287aaa187abSSzymon Olewniczak    }
288aaa187abSSzymon Olewniczak
289aaa187abSSzymon Olewniczak    /**
29053528ecfSAndreas Gohr     * Wrap given value in asterisks
29153528ecfSAndreas Gohr     *
29253528ecfSAndreas Gohr     * @param string|string[] $value
29353528ecfSAndreas Gohr     * @return string|string[]
29453528ecfSAndreas Gohr     */
29561356325SAnna Dabrowska    protected function filterWrapAsterisks($value)
29661356325SAnna Dabrowska    {
29753528ecfSAndreas Gohr        $map = function ($input) {
29853528ecfSAndreas Gohr            return "*$input*";
29953528ecfSAndreas Gohr        };
30053528ecfSAndreas Gohr
30153528ecfSAndreas Gohr        if (is_array($value)) {
30253528ecfSAndreas Gohr            $value = array_map($map, $value);
30353528ecfSAndreas Gohr        } else {
30453528ecfSAndreas Gohr            $value = $map($value);
30553528ecfSAndreas Gohr        }
30653528ecfSAndreas Gohr        return $value;
30753528ecfSAndreas Gohr    }
30853528ecfSAndreas Gohr
30953528ecfSAndreas Gohr    /**
31053528ecfSAndreas Gohr     * Change given string to use % instead of *
31153528ecfSAndreas Gohr     *
31253528ecfSAndreas Gohr     * @param string|string[] $value
31353528ecfSAndreas Gohr     * @return string|string[]
31453528ecfSAndreas Gohr     */
31561356325SAnna Dabrowska    protected function filterChangeToLike($value)
31661356325SAnna Dabrowska    {
31753528ecfSAndreas Gohr        $map = function ($input) {
31853528ecfSAndreas Gohr            return str_replace('*', '%', $input);
31953528ecfSAndreas Gohr        };
32053528ecfSAndreas Gohr
32153528ecfSAndreas Gohr        if (is_array($value)) {
32253528ecfSAndreas Gohr            $value = array_map($map, $value);
32353528ecfSAndreas Gohr        } else {
32453528ecfSAndreas Gohr            $value = $map($value);
32553528ecfSAndreas Gohr        }
32653528ecfSAndreas Gohr        return $value;
32753528ecfSAndreas Gohr    }
32853528ecfSAndreas Gohr
32953528ecfSAndreas Gohr    /**
3307f9cb794SAndreas Gohr     * Set offset for the results
3317f9cb794SAndreas Gohr     *
3327f9cb794SAndreas Gohr     * @param int $offset
3337f9cb794SAndreas Gohr     */
33461356325SAnna Dabrowska    public function setOffset($offset)
33561356325SAnna Dabrowska    {
3367f9cb794SAndreas Gohr        $limit = 0;
3377f9cb794SAndreas Gohr        if ($this->range_end) {
3387f9cb794SAndreas Gohr            // if there was a limit set previously, the range_end needs to be recalculated
3397f9cb794SAndreas Gohr            $limit = $this->range_end - $this->range_begin;
3407f9cb794SAndreas Gohr        }
3417f9cb794SAndreas Gohr        $this->range_begin = $offset;
3427f9cb794SAndreas Gohr        if ($limit) $this->setLimit($limit);
3437f9cb794SAndreas Gohr    }
3447f9cb794SAndreas Gohr
3457f9cb794SAndreas Gohr    /**
346fdf37115SAndreas Gohr     * Get the current offset for the results
347fdf37115SAndreas Gohr     *
348fdf37115SAndreas Gohr     * @return int
349fdf37115SAndreas Gohr     */
350fdf37115SAndreas Gohr    public function getOffset()
351fdf37115SAndreas Gohr    {
352fdf37115SAndreas Gohr        return $this->range_begin;
353fdf37115SAndreas Gohr    }
354fdf37115SAndreas Gohr
355fdf37115SAndreas Gohr    /**
3567f9cb794SAndreas Gohr     * Limit results to this number
3577f9cb794SAndreas Gohr     *
3587f9cb794SAndreas Gohr     * @param int $limit Set to 0 to disable limit again
3597f9cb794SAndreas Gohr     */
36061356325SAnna Dabrowska    public function setLimit($limit)
36161356325SAnna Dabrowska    {
3627f9cb794SAndreas Gohr        if ($limit) {
3637f9cb794SAndreas Gohr            $this->range_end = $this->range_begin + $limit;
3647f9cb794SAndreas Gohr        } else {
3657f9cb794SAndreas Gohr            $this->range_end = 0;
3667f9cb794SAndreas Gohr        }
3677f9cb794SAndreas Gohr    }
3687f9cb794SAndreas Gohr
3697f9cb794SAndreas Gohr    /**
370fdf37115SAndreas Gohr     * Get the current limit for the results
371fdf37115SAndreas Gohr     *
372fdf37115SAndreas Gohr     * @return int
373fdf37115SAndreas Gohr     */
374fdf37115SAndreas Gohr    public function getLimit()
375fdf37115SAndreas Gohr    {
376fdf37115SAndreas Gohr        if ($this->range_end) {
377fdf37115SAndreas Gohr            return $this->range_end - $this->range_begin;
378fdf37115SAndreas Gohr        }
379fdf37115SAndreas Gohr        return 0;
380fdf37115SAndreas Gohr    }
381fdf37115SAndreas Gohr
382fdf37115SAndreas Gohr    /**
383eff6062eSAnna Dabrowska     * Allows disabling default 'latest = 1' clause in select statement
384eff6062eSAnna Dabrowska     *
385eff6062eSAnna Dabrowska     * @param bool $selectLatest
386eff6062eSAnna Dabrowska     */
387eff6062eSAnna Dabrowska    public function setSelectLatest($selectLatest): void
388eff6062eSAnna Dabrowska    {
389eff6062eSAnna Dabrowska        $this->selectLatest = $selectLatest;
390eff6062eSAnna Dabrowska    }
391eff6062eSAnna Dabrowska
392eff6062eSAnna Dabrowska    /**
3937f9cb794SAndreas Gohr     * Return the number of results (regardless of limit and offset settings)
3947f9cb794SAndreas Gohr     *
3950549dcc5SAndreas Gohr     * Use this to implement paging. Important: this may only be called after running @return int
3960549dcc5SAndreas Gohr     * @see execute()
3977f9cb794SAndreas Gohr     *
3987f9cb794SAndreas Gohr     */
39961356325SAnna Dabrowska    public function getCount()
40061356325SAnna Dabrowska    {
4017f9cb794SAndreas Gohr        if ($this->count < 0) throw new StructException('Count is only accessible after executing the search');
4027f9cb794SAndreas Gohr        return $this->count;
4037f9cb794SAndreas Gohr    }
4047f9cb794SAndreas Gohr
405c46f5fb1SAndreas Gohr    /**
406c46f5fb1SAndreas Gohr     * Returns the PID associated with each result row
407c46f5fb1SAndreas Gohr     *
4080549dcc5SAndreas Gohr     * Important: this may only be called after running @return \string[]
4090549dcc5SAndreas Gohr     * @see execute()
410c46f5fb1SAndreas Gohr     *
411c46f5fb1SAndreas Gohr     */
41261356325SAnna Dabrowska    public function getPids()
41361356325SAnna Dabrowska    {
41417a3a578SAndreas Gohr        if ($this->result_pids === null)
41517a3a578SAndreas Gohr            throw new StructException('PIDs are only accessible after executing the search');
416d4b5a17cSAndreas Gohr        return $this->result_pids;
417d4b5a17cSAndreas Gohr    }
418d4b5a17cSAndreas Gohr
4197f9cb794SAndreas Gohr    /**
4200ceefd5cSAnna Dabrowska     * Returns the rid associated with each result row
4210ceefd5cSAnna Dabrowska     *
4220549dcc5SAndreas Gohr     * Important: this may only be called after running @return array
4230549dcc5SAndreas Gohr     * @see execute()
4240ceefd5cSAnna Dabrowska     *
4250ceefd5cSAnna Dabrowska     */
42661356325SAnna Dabrowska    public function getRids()
42761356325SAnna Dabrowska    {
42817a3a578SAndreas Gohr        if ($this->result_rids === null)
42917a3a578SAndreas Gohr            throw new StructException('rids are only accessible after executing the search');
4300ceefd5cSAnna Dabrowska        return $this->result_rids;
4310ceefd5cSAnna Dabrowska    }
4320ceefd5cSAnna Dabrowska
4330ceefd5cSAnna Dabrowska    /**
4346fd73b4bSAnna Dabrowska     * Returns the rid associated with each result row
4356fd73b4bSAnna Dabrowska     *
4360549dcc5SAndreas Gohr     * Important: this may only be called after running @return array
4370549dcc5SAndreas Gohr     * @see execute()
4386fd73b4bSAnna Dabrowska     *
4396fd73b4bSAnna Dabrowska     */
44061356325SAnna Dabrowska    public function getRevs()
44161356325SAnna Dabrowska    {
44217a3a578SAndreas Gohr        if ($this->result_revs === null)
44317a3a578SAndreas Gohr            throw new StructException('revs are only accessible after executing the search');
4446fd73b4bSAnna Dabrowska        return $this->result_revs;
4456fd73b4bSAnna Dabrowska    }
4466fd73b4bSAnna Dabrowska
4476fd73b4bSAnna Dabrowska    /**
448b2ed727aSAndreas Gohr     * Execute this search and return the result
449b2ed727aSAndreas Gohr     *
45038fa36fbSAndreas Gohr     * The result is a two dimensional array of Value()s.
4517f9cb794SAndreas Gohr     *
4527f9cb794SAndreas Gohr     * This will always query for the full result (not using offset and limit) and then
4530549dcc5SAndreas Gohr     * return the wanted range, setting the count (@return Value[][]
4540549dcc5SAndreas Gohr     * @see getCount) to the whole result number
45538fa36fbSAndreas Gohr     *
456b2ed727aSAndreas Gohr     */
4578ce43f5aSAnna Dabrowska    public function execute()
45861356325SAnna Dabrowska    {
4598ce43f5aSAnna Dabrowska        list($sql, $opts) = $this->getSQL();
460b2ed727aSAndreas Gohr
4617f9cb794SAndreas Gohr        /** @var \PDOStatement $res */
462b2ed727aSAndreas Gohr        $res = $this->sqlite->query($sql, $opts);
46359b668aaSAndreas Gohr        if ($res === false) throw new StructException("SQL execution failed for\n\n$sql");
464b2ed727aSAndreas Gohr
465d4b5a17cSAndreas Gohr        $this->result_pids = array();
466b2ed727aSAndreas Gohr        $result = array();
4677f9cb794SAndreas Gohr        $cursor = -1;
4685e4bfdb0SMichael Grosse        $pageidAndRevOnly = array_reduce($this->columns, function ($pageidAndRevOnly, Column $col) {
4695e4bfdb0SMichael Grosse            return $pageidAndRevOnly && ($col->getTid() == 0);
4705e4bfdb0SMichael Grosse        }, true);
4717f9cb794SAndreas Gohr        while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
4727f9cb794SAndreas Gohr            $cursor++;
4737f9cb794SAndreas Gohr            if ($cursor < $this->range_begin) continue;
4747f9cb794SAndreas Gohr            if ($this->range_end && $cursor >= $this->range_end) continue;
4757f9cb794SAndreas Gohr
476b2ed727aSAndreas Gohr            $C = 0;
477b2ed727aSAndreas Gohr            $resrow = array();
47899a70f28SAndreas Gohr            $isempty = true;
479b2ed727aSAndreas Gohr            foreach ($this->columns as $col) {
48038fa36fbSAndreas Gohr                $val = $row["C$C"];
481b2ed727aSAndreas Gohr                if ($col->isMulti()) {
48238fa36fbSAndreas Gohr                    $val = explode(self::CONCAT_SEPARATOR, $val);
483b2ed727aSAndreas Gohr                }
48499a70f28SAndreas Gohr                $value = new Value($col, $val);
4858cba7aa0SMichael Grosse                $isempty &= $this->isEmptyValue($value);
48699a70f28SAndreas Gohr                $resrow[] = $value;
487b2ed727aSAndreas Gohr                $C++;
488b2ed727aSAndreas Gohr            }
48999a70f28SAndreas Gohr
49099a70f28SAndreas Gohr            // skip empty rows
4918cba7aa0SMichael Grosse            if ($isempty && !$pageidAndRevOnly) {
49299a70f28SAndreas Gohr                $cursor--;
49399a70f28SAndreas Gohr                continue;
49499a70f28SAndreas Gohr            }
49599a70f28SAndreas Gohr
49699a70f28SAndreas Gohr            $this->result_pids[] = $row['PID'];
4970ceefd5cSAnna Dabrowska            $this->result_rids[] = $row['rid'];
4986fd73b4bSAnna Dabrowska            $this->result_revs[] = $row['rev'];
499b2ed727aSAndreas Gohr            $result[] = $resrow;
500b2ed727aSAndreas Gohr        }
5017f9cb794SAndreas Gohr
50279b29326SAnna Dabrowska        $res->closeCursor();
5037f9cb794SAndreas Gohr        $this->count = $cursor + 1;
504b2ed727aSAndreas Gohr        return $result;
505b2ed727aSAndreas Gohr    }
506b2ed727aSAndreas Gohr
507b2ed727aSAndreas Gohr    /**
50815929be2SAndreas Gohr     * Transform the set search parameters into a statement
50915929be2SAndreas Gohr     *
510299ca8ccSAndreas Gohr     * Calls runSQLBuilder()
511299ca8ccSAndreas Gohr     *
512b2ed727aSAndreas Gohr     * @return array ($sql, $opts) The SQL and parameters to execute
51315929be2SAndreas Gohr     */
5148ce43f5aSAnna Dabrowska    public function getSQL()
51561356325SAnna Dabrowska    {
5165511bd5bSAndreas Gohr        if (!$this->columns) throw new StructException('nocolname');
517299ca8ccSAndreas Gohr        return $this->runSQLBuilder()->getSQL();
518299ca8ccSAndreas Gohr    }
51915929be2SAndreas Gohr
520299ca8ccSAndreas Gohr    /**
521299ca8ccSAndreas Gohr     * Initialize and execute the SQLBuilder
522299ca8ccSAndreas Gohr     *
523299ca8ccSAndreas Gohr     * Called from getSQL(). Can be overwritten to extend the query using the query builder
524299ca8ccSAndreas Gohr     *
525299ca8ccSAndreas Gohr     * @return SearchSQLBuilder
526299ca8ccSAndreas Gohr     */
527299ca8ccSAndreas Gohr    protected function runSQLBuilder()
528299ca8ccSAndreas Gohr    {
529fd9c77d3SAndreas Gohr        $sqlBuilder = new SearchSQLBuilder();
530*b37d1c8bSAnna Dabrowska        $sqlBuilder->setSelectLatest($this->selectLatest);
531fd9c77d3SAndreas Gohr        $sqlBuilder->addSchemas($this->schemas);
532fd9c77d3SAndreas Gohr        $sqlBuilder->addColumns($this->columns);
533fd9c77d3SAndreas Gohr        $sqlBuilder->addFilters($this->filter);
534fd9c77d3SAndreas Gohr        $sqlBuilder->addFilters($this->dynamicFilter);
535fd9c77d3SAndreas Gohr        $sqlBuilder->addSorts($this->sortby);
536299ca8ccSAndreas Gohr        return $sqlBuilder;
53715929be2SAndreas Gohr    }
53815929be2SAndreas Gohr
53915929be2SAndreas Gohr    /**
54001dd90deSAndreas Gohr     * Returns all the columns that where added to the search
54101dd90deSAndreas Gohr     *
54201dd90deSAndreas Gohr     * @return Column[]
54301dd90deSAndreas Gohr     */
54461356325SAnna Dabrowska    public function getColumns()
54561356325SAnna Dabrowska    {
54601dd90deSAndreas Gohr        return $this->columns;
54701dd90deSAndreas Gohr    }
54801dd90deSAndreas Gohr
549577b462bSAndreas Gohr    /**
5505a4df70dSAndreas Gohr     * All the schemas currently added
5515a4df70dSAndreas Gohr     *
5525a4df70dSAndreas Gohr     * @return Schema[]
5535a4df70dSAndreas Gohr     */
55461356325SAnna Dabrowska    public function getSchemas()
55561356325SAnna Dabrowska    {
5565a4df70dSAndreas Gohr        return array_values($this->schemas);
5575a4df70dSAndreas Gohr    }
5585a4df70dSAndreas Gohr
5595a4df70dSAndreas Gohr    /**
560577b462bSAndreas Gohr     * Checks if the given column is a * wildcard
561577b462bSAndreas Gohr     *
562577b462bSAndreas Gohr     * If it's a wildcard all matching columns are added to the column list, otherwise
563577b462bSAndreas Gohr     * nothing happens
564577b462bSAndreas Gohr     *
565577b462bSAndreas Gohr     * @param string $colname
566577b462bSAndreas Gohr     * @return bool was wildcard?
567577b462bSAndreas Gohr     */
56861356325SAnna Dabrowska    protected function processWildcard($colname)
56961356325SAnna Dabrowska    {
570636a5173SAndreas Gohr        list($colname, $table) = $this->resolveColumn($colname);
571577b462bSAndreas Gohr        if ($colname !== '*') return false;
572577b462bSAndreas Gohr
573577b462bSAndreas Gohr        // no table given? assume the first is meant
574577b462bSAndreas Gohr        if ($table === null) {
575577b462bSAndreas Gohr            $schema_list = array_keys($this->schemas);
576577b462bSAndreas Gohr            $table = $schema_list[0];
577577b462bSAndreas Gohr        }
578577b462bSAndreas Gohr
5791ca21e17SAnna Dabrowska        $schema = $this->schemas[$table] ?? null;
580577b462bSAndreas Gohr        if (!$schema) return false;
581577b462bSAndreas Gohr        $this->columns = array_merge($this->columns, $schema->getColumns(false));
582577b462bSAndreas Gohr        return true;
583577b462bSAndreas Gohr    }
584577b462bSAndreas Gohr
585577b462bSAndreas Gohr    /**
586577b462bSAndreas Gohr     * Split a given column name into table and column
587577b462bSAndreas Gohr     *
588577b462bSAndreas Gohr     * Handles Aliases. Table might be null if none given.
589577b462bSAndreas Gohr     *
590577b462bSAndreas Gohr     * @param $colname
591636a5173SAndreas Gohr     * @return array (colname, table)
592577b462bSAndreas Gohr     */
59361356325SAnna Dabrowska    protected function resolveColumn($colname)
59461356325SAnna Dabrowska    {
595577b462bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
596577b462bSAndreas Gohr
597577b462bSAndreas Gohr        // resolve the alias or table name
59825ed0c0dSAndreas Gohr        @list($table, $colname) = array_pad(explode('.', $colname, 2), 2, '');
599577b462bSAndreas Gohr        if (!$colname) {
600577b462bSAndreas Gohr            $colname = $table;
601577b462bSAndreas Gohr            $table = null;
602577b462bSAndreas Gohr        }
603577b462bSAndreas Gohr        if ($table && isset($this->aliases[$table])) {
604577b462bSAndreas Gohr            $table = $this->aliases[$table];
605577b462bSAndreas Gohr        }
606577b462bSAndreas Gohr
607577b462bSAndreas Gohr        if (!$colname) throw new StructException('nocolname');
608577b462bSAndreas Gohr
609577b462bSAndreas Gohr        return array($colname, $table);
610577b462bSAndreas Gohr    }
61101dd90deSAndreas Gohr
61201dd90deSAndreas Gohr    /**
61315929be2SAndreas Gohr     * Find a column to be used in the search
61415929be2SAndreas Gohr     *
61515929be2SAndreas Gohr     * @param string $colname may contain an alias
61615929be2SAndreas Gohr     * @return bool|Column
61715929be2SAndreas Gohr     */
6180280da9aSFrieder Schrempf    public function findColumn($colname, $strict = false)
61961356325SAnna Dabrowska    {
6205511bd5bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
621df02ffe6SMichael Große        $schema_list = array_keys($this->schemas);
622f107f479SAndreas Gohr
623f107f479SAndreas Gohr        // add "fake" column for special col
624128d4e83SAndreas Gohr        if ($colname == '%pageid%') {
625128d4e83SAndreas Gohr            return new PageColumn(0, new Page(), $schema_list[0]);
626d1b04e89SAndreas Gohr        }
627128d4e83SAndreas Gohr        if ($colname == '%title%') {
628128d4e83SAndreas Gohr            return new PageColumn(0, new Page(array('usetitles' => true)), $schema_list[0]);
629128d4e83SAndreas Gohr        }
630cadfc3ccSAndreas Gohr        if ($colname == '%lastupdate%') {
631cadfc3ccSAndreas Gohr            return new RevisionColumn(0, new DateTime(), $schema_list[0]);
632cadfc3ccSAndreas Gohr        }
6332e12ac22SMichael Grosse        if ($colname == '%lasteditor%') {
6342e12ac22SMichael Grosse            return new UserColumn(0, new User(), $schema_list[0]);
6352e12ac22SMichael Grosse        }
63688b58a21SSzymon Olewniczak        if ($colname == '%lastsummary%') {
6376781c68dSSzymon Olewniczak            return new SummaryColumn(0, new AutoSummary(), $schema_list[0]);
63888b58a21SSzymon Olewniczak        }
639f107f479SAndreas Gohr        if ($colname == '%rowid%') {
640f107f479SAndreas Gohr            return new RowColumn(0, new Decimal(), $schema_list[0]);
641f107f479SAndreas Gohr        }
642da62ec9cSAnna Dabrowska        if ($colname == '%published%') {
643da62ec9cSAnna Dabrowska            return new PublishedColumn(0, new Decimal(), $schema_list[0]);
644da62ec9cSAnna Dabrowska        }
645d1b04e89SAndreas Gohr
646636a5173SAndreas Gohr        list($colname, $table) = $this->resolveColumn($colname);
64715929be2SAndreas Gohr
6480280da9aSFrieder Schrempf        /*
6490280da9aSFrieder Schrempf         * If table name is given search only that, otherwise if no strict behavior
6500280da9aSFrieder Schrempf         * is requested by the caller, try all assigned schemas for matching the
6510280da9aSFrieder Schrempf         * column name.
6520280da9aSFrieder Schrempf         */
65334ea6e10SAnna Dabrowska        if ($table !== null && isset($this->schemas[$table])) {
65415929be2SAndreas Gohr            $schemas = array($table => $this->schemas[$table]);
6550280da9aSFrieder Schrempf        } elseif ($table === null || !$strict) {
65615929be2SAndreas Gohr            $schemas = $this->schemas;
6570280da9aSFrieder Schrempf        } else {
6580280da9aSFrieder Schrempf            return false;
65915929be2SAndreas Gohr        }
66015929be2SAndreas Gohr
66115929be2SAndreas Gohr        // find it
66215929be2SAndreas Gohr        $col = false;
66315929be2SAndreas Gohr        foreach ($schemas as $schema) {
6644ac44d1cSMichael Grosse            if (empty($schema)) {
6654ac44d1cSMichael Grosse                continue;
6664ac44d1cSMichael Grosse            }
66715929be2SAndreas Gohr            $col = $schema->findColumn($colname);
66815929be2SAndreas Gohr            if ($col) break;
66915929be2SAndreas Gohr        }
67015929be2SAndreas Gohr
67115929be2SAndreas Gohr        return $col;
67215929be2SAndreas Gohr    }
67315929be2SAndreas Gohr
6749dbc8ec0SMichael Grosse    /**
67599a70f28SAndreas Gohr     * Check if the given row is empty or references our own row
6769dbc8ec0SMichael Grosse     *
67799a70f28SAndreas Gohr     * @param Value $value
6789dbc8ec0SMichael Grosse     * @return bool
6799dbc8ec0SMichael Grosse     */
68061356325SAnna Dabrowska    protected function isEmptyValue(Value $value)
68161356325SAnna Dabrowska    {
68299a70f28SAndreas Gohr        if ($value->isEmpty()) return true;
6838cba7aa0SMichael Grosse        if ($value->getColumn()->getTid() == 0) return true;
6849dbc8ec0SMichael Grosse        return false;
6859dbc8ec0SMichael Grosse    }
68615929be2SAndreas Gohr}
687