xref: /plugin/struct/meta/Search.php (revision fdf371159b3e9f57726cdb9c44df35e764a8770a)
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
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    {
1711057ed14SAndreas Gohr        $filter = $this->createFilter($colname, $value, $comp, $op);
1721057ed14SAndreas Gohr        if ($filter) $this->filter[] = $filter;
1731057ed14SAndreas Gohr    }
1741057ed14SAndreas Gohr
1751057ed14SAndreas Gohr    /**
1761057ed14SAndreas Gohr     * Adds a dynamic filter
1771057ed14SAndreas Gohr     *
1781057ed14SAndreas Gohr     * @param string $colname may contain an alias
1791057ed14SAndreas Gohr     * @param string|string[] $value
1801057ed14SAndreas Gohr     * @param string $comp @see self::COMPARATORS
1811057ed14SAndreas Gohr     * @param string $op either 'OR' or 'AND'
1821057ed14SAndreas Gohr     */
1831057ed14SAndreas Gohr    public function addDynamicFilter($colname, $value, $comp, $op = 'OR')
1841057ed14SAndreas Gohr    {
1851057ed14SAndreas Gohr        $filter = $this->createFilter($colname, $value, $comp, $op);
1861057ed14SAndreas Gohr        if ($filter) $this->dynamicFilter[] = $filter;
1871057ed14SAndreas Gohr    }
1881057ed14SAndreas Gohr
1891057ed14SAndreas Gohr    /**
1901057ed14SAndreas Gohr     * Create a filter definition
1911057ed14SAndreas Gohr     *
1921057ed14SAndreas Gohr     * @param string $colname may contain an alias
1931057ed14SAndreas Gohr     * @param string|string[] $value
1941057ed14SAndreas Gohr     * @param string $comp @see self::COMPARATORS
1951057ed14SAndreas Gohr     * @param string $op either 'OR' or 'AND'
1961057ed14SAndreas Gohr     * @return array|null [Column col, string|string[] value, string comp, string op]
1971057ed14SAndreas Gohr     */
1981057ed14SAndreas Gohr    protected function createFilter($colname, $value, $comp, $op = 'OR')
1991057ed14SAndreas 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);
2151057ed14SAndreas 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
2421057ed14SAndreas 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    /**
343*fdf37115SAndreas Gohr     * Get the current offset for the results
344*fdf37115SAndreas Gohr     *
345*fdf37115SAndreas Gohr     * @return int
346*fdf37115SAndreas Gohr     */
347*fdf37115SAndreas Gohr    public function getOffset()
348*fdf37115SAndreas Gohr    {
349*fdf37115SAndreas Gohr        return $this->range_begin;
350*fdf37115SAndreas Gohr    }
351*fdf37115SAndreas Gohr
352*fdf37115SAndreas Gohr    /**
3537f9cb794SAndreas Gohr     * Limit results to this number
3547f9cb794SAndreas Gohr     *
3557f9cb794SAndreas Gohr     * @param int $limit Set to 0 to disable limit again
3567f9cb794SAndreas Gohr     */
35761356325SAnna Dabrowska    public function setLimit($limit)
35861356325SAnna Dabrowska    {
3597f9cb794SAndreas Gohr        if ($limit) {
3607f9cb794SAndreas Gohr            $this->range_end = $this->range_begin + $limit;
3617f9cb794SAndreas Gohr        } else {
3627f9cb794SAndreas Gohr            $this->range_end = 0;
3637f9cb794SAndreas Gohr        }
3647f9cb794SAndreas Gohr    }
3657f9cb794SAndreas Gohr
3667f9cb794SAndreas Gohr    /**
367*fdf37115SAndreas Gohr     * Get the current limit for the results
368*fdf37115SAndreas Gohr     *
369*fdf37115SAndreas Gohr     * @return int
370*fdf37115SAndreas Gohr     */
371*fdf37115SAndreas Gohr    public function getLimit()
372*fdf37115SAndreas Gohr    {
373*fdf37115SAndreas Gohr        if ($this->range_end) {
374*fdf37115SAndreas Gohr            return $this->range_end - $this->range_begin;
375*fdf37115SAndreas Gohr        }
376*fdf37115SAndreas Gohr        return 0;
377*fdf37115SAndreas Gohr    }
378*fdf37115SAndreas Gohr
379*fdf37115SAndreas Gohr    /**
3807f9cb794SAndreas Gohr     * Return the number of results (regardless of limit and offset settings)
3817f9cb794SAndreas Gohr     *
3820549dcc5SAndreas Gohr     * Use this to implement paging. Important: this may only be called after running @return int
3830549dcc5SAndreas Gohr     * @see execute()
3847f9cb794SAndreas Gohr     *
3857f9cb794SAndreas Gohr     */
38661356325SAnna Dabrowska    public function getCount()
38761356325SAnna Dabrowska    {
3887f9cb794SAndreas Gohr        if ($this->count < 0) throw new StructException('Count is only accessible after executing the search');
3897f9cb794SAndreas Gohr        return $this->count;
3907f9cb794SAndreas Gohr    }
3917f9cb794SAndreas Gohr
392c46f5fb1SAndreas Gohr    /**
393c46f5fb1SAndreas Gohr     * Returns the PID associated with each result row
394c46f5fb1SAndreas Gohr     *
3950549dcc5SAndreas Gohr     * Important: this may only be called after running @return \string[]
3960549dcc5SAndreas Gohr     * @see execute()
397c46f5fb1SAndreas Gohr     *
398c46f5fb1SAndreas Gohr     */
39961356325SAnna Dabrowska    public function getPids()
40061356325SAnna Dabrowska    {
40117a3a578SAndreas Gohr        if ($this->result_pids === null)
40217a3a578SAndreas Gohr            throw new StructException('PIDs are only accessible after executing the search');
403d4b5a17cSAndreas Gohr        return $this->result_pids;
404d4b5a17cSAndreas Gohr    }
405d4b5a17cSAndreas Gohr
4067f9cb794SAndreas Gohr    /**
4070ceefd5cSAnna Dabrowska     * Returns the rid associated with each result row
4080ceefd5cSAnna Dabrowska     *
4090549dcc5SAndreas Gohr     * Important: this may only be called after running @return array
4100549dcc5SAndreas Gohr     * @see execute()
4110ceefd5cSAnna Dabrowska     *
4120ceefd5cSAnna Dabrowska     */
41361356325SAnna Dabrowska    public function getRids()
41461356325SAnna Dabrowska    {
41517a3a578SAndreas Gohr        if ($this->result_rids === null)
41617a3a578SAndreas Gohr            throw new StructException('rids are only accessible after executing the search');
4170ceefd5cSAnna Dabrowska        return $this->result_rids;
4180ceefd5cSAnna Dabrowska    }
4190ceefd5cSAnna Dabrowska
4200ceefd5cSAnna Dabrowska    /**
4216fd73b4bSAnna Dabrowska     * Returns the rid associated with each result row
4226fd73b4bSAnna Dabrowska     *
4230549dcc5SAndreas Gohr     * Important: this may only be called after running @return array
4240549dcc5SAndreas Gohr     * @see execute()
4256fd73b4bSAnna Dabrowska     *
4266fd73b4bSAnna Dabrowska     */
42761356325SAnna Dabrowska    public function getRevs()
42861356325SAnna Dabrowska    {
42917a3a578SAndreas Gohr        if ($this->result_revs === null)
43017a3a578SAndreas Gohr            throw new StructException('revs are only accessible after executing the search');
4316fd73b4bSAnna Dabrowska        return $this->result_revs;
4326fd73b4bSAnna Dabrowska    }
4336fd73b4bSAnna Dabrowska
4346fd73b4bSAnna Dabrowska    /**
435b2ed727aSAndreas Gohr     * Execute this search and return the result
436b2ed727aSAndreas Gohr     *
43738fa36fbSAndreas Gohr     * The result is a two dimensional array of Value()s.
4387f9cb794SAndreas Gohr     *
4397f9cb794SAndreas Gohr     * This will always query for the full result (not using offset and limit) and then
4400549dcc5SAndreas Gohr     * return the wanted range, setting the count (@return Value[][]
4410549dcc5SAndreas Gohr     * @see getCount) to the whole result number
44238fa36fbSAndreas Gohr     *
443b2ed727aSAndreas Gohr     */
4448ce43f5aSAnna Dabrowska    public function execute()
44561356325SAnna Dabrowska    {
4468ce43f5aSAnna Dabrowska        list($sql, $opts) = $this->getSQL();
447b2ed727aSAndreas Gohr
4487f9cb794SAndreas Gohr        /** @var \PDOStatement $res */
449b2ed727aSAndreas Gohr        $res = $this->sqlite->query($sql, $opts);
45059b668aaSAndreas Gohr        if ($res === false) throw new StructException("SQL execution failed for\n\n$sql");
451b2ed727aSAndreas Gohr
452d4b5a17cSAndreas Gohr        $this->result_pids = array();
453b2ed727aSAndreas Gohr        $result = array();
4547f9cb794SAndreas Gohr        $cursor = -1;
4555e4bfdb0SMichael Grosse        $pageidAndRevOnly = array_reduce($this->columns, function ($pageidAndRevOnly, Column $col) {
4565e4bfdb0SMichael Grosse            return $pageidAndRevOnly && ($col->getTid() == 0);
4575e4bfdb0SMichael Grosse        }, true);
4587f9cb794SAndreas Gohr        while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
4597f9cb794SAndreas Gohr            $cursor++;
4607f9cb794SAndreas Gohr            if ($cursor < $this->range_begin) continue;
4617f9cb794SAndreas Gohr            if ($this->range_end && $cursor >= $this->range_end) continue;
4627f9cb794SAndreas Gohr
463b2ed727aSAndreas Gohr            $C = 0;
464b2ed727aSAndreas Gohr            $resrow = array();
46599a70f28SAndreas Gohr            $isempty = true;
466b2ed727aSAndreas Gohr            foreach ($this->columns as $col) {
46738fa36fbSAndreas Gohr                $val = $row["C$C"];
468b2ed727aSAndreas Gohr                if ($col->isMulti()) {
46938fa36fbSAndreas Gohr                    $val = explode(self::CONCAT_SEPARATOR, $val);
470b2ed727aSAndreas Gohr                }
47199a70f28SAndreas Gohr                $value = new Value($col, $val);
4728cba7aa0SMichael Grosse                $isempty &= $this->isEmptyValue($value);
47399a70f28SAndreas Gohr                $resrow[] = $value;
474b2ed727aSAndreas Gohr                $C++;
475b2ed727aSAndreas Gohr            }
47699a70f28SAndreas Gohr
47799a70f28SAndreas Gohr            // skip empty rows
4788cba7aa0SMichael Grosse            if ($isempty && !$pageidAndRevOnly) {
47999a70f28SAndreas Gohr                $cursor--;
48099a70f28SAndreas Gohr                continue;
48199a70f28SAndreas Gohr            }
48299a70f28SAndreas Gohr
48399a70f28SAndreas Gohr            $this->result_pids[] = $row['PID'];
4840ceefd5cSAnna Dabrowska            $this->result_rids[] = $row['rid'];
4856fd73b4bSAnna Dabrowska            $this->result_revs[] = $row['rev'];
486b2ed727aSAndreas Gohr            $result[] = $resrow;
487b2ed727aSAndreas Gohr        }
4887f9cb794SAndreas Gohr
48979b29326SAnna Dabrowska        $res->closeCursor();
4907f9cb794SAndreas Gohr        $this->count = $cursor + 1;
491b2ed727aSAndreas Gohr        return $result;
492b2ed727aSAndreas Gohr    }
493b2ed727aSAndreas Gohr
494b2ed727aSAndreas Gohr    /**
49515929be2SAndreas Gohr     * Transform the set search parameters into a statement
49615929be2SAndreas Gohr     *
497b2ed727aSAndreas Gohr     * @return array ($sql, $opts) The SQL and parameters to execute
49815929be2SAndreas Gohr     */
4998ce43f5aSAnna Dabrowska    public function getSQL()
50061356325SAnna Dabrowska    {
5015511bd5bSAndreas Gohr        if (!$this->columns) throw new StructException('nocolname');
50215929be2SAndreas Gohr
503fd9c77d3SAndreas Gohr        $sqlBuilder = new SearchSQLBuilder();
504fd9c77d3SAndreas Gohr        $sqlBuilder->addSchemas($this->schemas);
505fd9c77d3SAndreas Gohr        $sqlBuilder->addColumns($this->columns);
506fd9c77d3SAndreas Gohr        $sqlBuilder->addFilters($this->filter);
507fd9c77d3SAndreas Gohr        $sqlBuilder->addFilters($this->dynamicFilter);
508fd9c77d3SAndreas Gohr        $sqlBuilder->addSorts($this->sortby);
50915929be2SAndreas Gohr
510fd9c77d3SAndreas Gohr        return $sqlBuilder->getSQL();
51115929be2SAndreas Gohr    }
51215929be2SAndreas Gohr
51315929be2SAndreas Gohr    /**
51401dd90deSAndreas Gohr     * Returns all the columns that where added to the search
51501dd90deSAndreas Gohr     *
51601dd90deSAndreas Gohr     * @return Column[]
51701dd90deSAndreas Gohr     */
51861356325SAnna Dabrowska    public function getColumns()
51961356325SAnna Dabrowska    {
52001dd90deSAndreas Gohr        return $this->columns;
52101dd90deSAndreas Gohr    }
52201dd90deSAndreas Gohr
523577b462bSAndreas Gohr    /**
5245a4df70dSAndreas Gohr     * All the schemas currently added
5255a4df70dSAndreas Gohr     *
5265a4df70dSAndreas Gohr     * @return Schema[]
5275a4df70dSAndreas Gohr     */
52861356325SAnna Dabrowska    public function getSchemas()
52961356325SAnna Dabrowska    {
5305a4df70dSAndreas Gohr        return array_values($this->schemas);
5315a4df70dSAndreas Gohr    }
5325a4df70dSAndreas Gohr
5335a4df70dSAndreas Gohr    /**
534577b462bSAndreas Gohr     * Checks if the given column is a * wildcard
535577b462bSAndreas Gohr     *
536577b462bSAndreas Gohr     * If it's a wildcard all matching columns are added to the column list, otherwise
537577b462bSAndreas Gohr     * nothing happens
538577b462bSAndreas Gohr     *
539577b462bSAndreas Gohr     * @param string $colname
540577b462bSAndreas Gohr     * @return bool was wildcard?
541577b462bSAndreas Gohr     */
54261356325SAnna Dabrowska    protected function processWildcard($colname)
54361356325SAnna Dabrowska    {
544636a5173SAndreas Gohr        list($colname, $table) = $this->resolveColumn($colname);
545577b462bSAndreas Gohr        if ($colname !== '*') return false;
546577b462bSAndreas Gohr
547577b462bSAndreas Gohr        // no table given? assume the first is meant
548577b462bSAndreas Gohr        if ($table === null) {
549577b462bSAndreas Gohr            $schema_list = array_keys($this->schemas);
550577b462bSAndreas Gohr            $table = $schema_list[0];
551577b462bSAndreas Gohr        }
552577b462bSAndreas Gohr
5531ca21e17SAnna Dabrowska        $schema = $this->schemas[$table] ?? null;
554577b462bSAndreas Gohr        if (!$schema) return false;
555577b462bSAndreas Gohr        $this->columns = array_merge($this->columns, $schema->getColumns(false));
556577b462bSAndreas Gohr        return true;
557577b462bSAndreas Gohr    }
558577b462bSAndreas Gohr
559577b462bSAndreas Gohr    /**
560577b462bSAndreas Gohr     * Split a given column name into table and column
561577b462bSAndreas Gohr     *
562577b462bSAndreas Gohr     * Handles Aliases. Table might be null if none given.
563577b462bSAndreas Gohr     *
564577b462bSAndreas Gohr     * @param $colname
565636a5173SAndreas Gohr     * @return array (colname, table)
566577b462bSAndreas Gohr     */
56761356325SAnna Dabrowska    protected function resolveColumn($colname)
56861356325SAnna Dabrowska    {
569577b462bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
570577b462bSAndreas Gohr
571577b462bSAndreas Gohr        // resolve the alias or table name
57225ed0c0dSAndreas Gohr        @list($table, $colname) = array_pad(explode('.', $colname, 2), 2, '');
573577b462bSAndreas Gohr        if (!$colname) {
574577b462bSAndreas Gohr            $colname = $table;
575577b462bSAndreas Gohr            $table = null;
576577b462bSAndreas Gohr        }
577577b462bSAndreas Gohr        if ($table && isset($this->aliases[$table])) {
578577b462bSAndreas Gohr            $table = $this->aliases[$table];
579577b462bSAndreas Gohr        }
580577b462bSAndreas Gohr
581577b462bSAndreas Gohr        if (!$colname) throw new StructException('nocolname');
582577b462bSAndreas Gohr
583577b462bSAndreas Gohr        return array($colname, $table);
584577b462bSAndreas Gohr    }
58501dd90deSAndreas Gohr
58601dd90deSAndreas Gohr    /**
58715929be2SAndreas Gohr     * Find a column to be used in the search
58815929be2SAndreas Gohr     *
58915929be2SAndreas Gohr     * @param string $colname may contain an alias
59015929be2SAndreas Gohr     * @return bool|Column
59115929be2SAndreas Gohr     */
5920280da9aSFrieder Schrempf    public function findColumn($colname, $strict = false)
59361356325SAnna Dabrowska    {
5945511bd5bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
595df02ffe6SMichael Große        $schema_list = array_keys($this->schemas);
596f107f479SAndreas Gohr
597f107f479SAndreas Gohr        // add "fake" column for special col
598128d4e83SAndreas Gohr        if ($colname == '%pageid%') {
599128d4e83SAndreas Gohr            return new PageColumn(0, new Page(), $schema_list[0]);
600d1b04e89SAndreas Gohr        }
601128d4e83SAndreas Gohr        if ($colname == '%title%') {
602128d4e83SAndreas Gohr            return new PageColumn(0, new Page(array('usetitles' => true)), $schema_list[0]);
603128d4e83SAndreas Gohr        }
604cadfc3ccSAndreas Gohr        if ($colname == '%lastupdate%') {
605cadfc3ccSAndreas Gohr            return new RevisionColumn(0, new DateTime(), $schema_list[0]);
606cadfc3ccSAndreas Gohr        }
6072e12ac22SMichael Grosse        if ($colname == '%lasteditor%') {
6082e12ac22SMichael Grosse            return new UserColumn(0, new User(), $schema_list[0]);
6092e12ac22SMichael Grosse        }
61088b58a21SSzymon Olewniczak        if ($colname == '%lastsummary%') {
6116781c68dSSzymon Olewniczak            return new SummaryColumn(0, new AutoSummary(), $schema_list[0]);
61288b58a21SSzymon Olewniczak        }
613f107f479SAndreas Gohr        if ($colname == '%rowid%') {
614f107f479SAndreas Gohr            return new RowColumn(0, new Decimal(), $schema_list[0]);
615f107f479SAndreas Gohr        }
616da62ec9cSAnna Dabrowska        if ($colname == '%published%') {
617da62ec9cSAnna Dabrowska            return new PublishedColumn(0, new Decimal(), $schema_list[0]);
618da62ec9cSAnna Dabrowska        }
619d1b04e89SAndreas Gohr
620636a5173SAndreas Gohr        list($colname, $table) = $this->resolveColumn($colname);
62115929be2SAndreas Gohr
6220280da9aSFrieder Schrempf        /*
6230280da9aSFrieder Schrempf         * If table name is given search only that, otherwise if no strict behavior
6240280da9aSFrieder Schrempf         * is requested by the caller, try all assigned schemas for matching the
6250280da9aSFrieder Schrempf         * column name.
6260280da9aSFrieder Schrempf         */
62734ea6e10SAnna Dabrowska        if ($table !== null && isset($this->schemas[$table])) {
62815929be2SAndreas Gohr            $schemas = array($table => $this->schemas[$table]);
6290280da9aSFrieder Schrempf        } elseif ($table === null || !$strict) {
63015929be2SAndreas Gohr            $schemas = $this->schemas;
6310280da9aSFrieder Schrempf        } else {
6320280da9aSFrieder Schrempf            return false;
63315929be2SAndreas Gohr        }
63415929be2SAndreas Gohr
63515929be2SAndreas Gohr        // find it
63615929be2SAndreas Gohr        $col = false;
63715929be2SAndreas Gohr        foreach ($schemas as $schema) {
6384ac44d1cSMichael Grosse            if (empty($schema)) {
6394ac44d1cSMichael Grosse                continue;
6404ac44d1cSMichael Grosse            }
64115929be2SAndreas Gohr            $col = $schema->findColumn($colname);
64215929be2SAndreas Gohr            if ($col) break;
64315929be2SAndreas Gohr        }
64415929be2SAndreas Gohr
64515929be2SAndreas Gohr        return $col;
64615929be2SAndreas Gohr    }
64715929be2SAndreas Gohr
6489dbc8ec0SMichael Grosse    /**
64999a70f28SAndreas Gohr     * Check if the given row is empty or references our own row
6509dbc8ec0SMichael Grosse     *
65199a70f28SAndreas Gohr     * @param Value $value
6529dbc8ec0SMichael Grosse     * @return bool
6539dbc8ec0SMichael Grosse     */
65461356325SAnna Dabrowska    protected function isEmptyValue(Value $value)
65561356325SAnna Dabrowska    {
65699a70f28SAndreas Gohr        if ($value->isEmpty()) return true;
6578cba7aa0SMichael Grosse        if ($value->getColumn()->getTid() == 0) return true;
6589dbc8ec0SMichael Grosse        return false;
6599dbc8ec0SMichael Grosse    }
66015929be2SAndreas Gohr}
661