xref: /plugin/struct/meta/Search.php (revision 8ce43f5ab42efe8fe5ce7e11f2f27a0f680c32dd)
115929be2SAndreas Gohr<?php
215929be2SAndreas Gohr
3ba766201SAndreas Gohrnamespace dokuwiki\plugin\struct\meta;
415929be2SAndreas Gohr
5cadfc3ccSAndreas Gohruse dokuwiki\plugin\struct\types\DateTime;
6f107f479SAndreas Gohruse dokuwiki\plugin\struct\types\Decimal;
7ba766201SAndreas Gohruse dokuwiki\plugin\struct\types\Page;
86781c68dSSzymon Olewniczakuse dokuwiki\plugin\struct\types\AutoSummary;
988b58a21SSzymon Olewniczakuse dokuwiki\plugin\struct\types\Text;
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     */
179d7a36f9SAndreas Gohr    const CONCAT_SEPARATOR = "\n!_-_-_-_-_!\n";
189d7a36f9SAndreas Gohr
195511bd5bSAndreas Gohr    /**
205511bd5bSAndreas Gohr     * The list of known and allowed comparators
212e7595e7SAndreas Gohr     * (order matters)
225511bd5bSAndreas Gohr     */
2361356325SAnna Dabrowska    public static $COMPARATORS = array(
24aaa187abSSzymon Olewniczak        '<=', '>=', '=*', '=', '<', '>', '!=', '!~', '~', 'IN'
255511bd5bSAndreas Gohr    );
265511bd5bSAndreas Gohr
279d7a36f9SAndreas Gohr    /** @var  \helper_plugin_sqlite */
289d7a36f9SAndreas Gohr    protected $sqlite;
2915929be2SAndreas Gohr
3015929be2SAndreas Gohr    /** @var Schema[] list of schemas to query */
3115929be2SAndreas Gohr    protected $schemas = array();
3215929be2SAndreas Gohr
3315929be2SAndreas Gohr    /** @var Column[] list of columns to select */
3415929be2SAndreas Gohr    protected $columns = array();
3515929be2SAndreas Gohr
3615929be2SAndreas Gohr    /** @var array the sorting of the result */
3715929be2SAndreas Gohr    protected $sortby = array();
3815929be2SAndreas Gohr
399d7a36f9SAndreas Gohr    /** @var array the filters */
409d7a36f9SAndreas Gohr    protected $filter = array();
4115929be2SAndreas Gohr
4215929be2SAndreas Gohr    /** @var array list of aliases tables can be referenced by */
4315929be2SAndreas Gohr    protected $aliases = array();
4415929be2SAndreas Gohr
457f9cb794SAndreas Gohr    /** @var  int begin results from here */
467f9cb794SAndreas Gohr    protected $range_begin = 0;
477f9cb794SAndreas Gohr
487f9cb794SAndreas Gohr    /** @var  int end results here */
497f9cb794SAndreas Gohr    protected $range_end = 0;
507f9cb794SAndreas Gohr
517f9cb794SAndreas Gohr    /** @var int the number of results */
527f9cb794SAndreas Gohr    protected $count = -1;
53d4b5a17cSAndreas Gohr    /** @var  string[] the PIDs of the result rows */
54d4b5a17cSAndreas Gohr    protected $result_pids = null;
550ceefd5cSAnna Dabrowska    /** @var  array the row ids of the result rows */
560ceefd5cSAnna Dabrowska    protected $result_rids = [];
576fd73b4bSAnna Dabrowska    /** @var  array the revisions of the result rows */
586fd73b4bSAnna Dabrowska    protected $result_revs = [];
597f9cb794SAndreas Gohr
6015929be2SAndreas Gohr    /**
619d7a36f9SAndreas Gohr     * Search constructor.
629d7a36f9SAndreas Gohr     */
6361356325SAnna Dabrowska    public function __construct()
6461356325SAnna Dabrowska    {
659d7a36f9SAndreas Gohr        /** @var \helper_plugin_struct_db $plugin */
669d7a36f9SAndreas Gohr        $plugin = plugin_load('helper', 'struct_db');
679d7a36f9SAndreas Gohr        $this->sqlite = $plugin->getDB();
689d7a36f9SAndreas Gohr    }
699d7a36f9SAndreas Gohr
709d7a36f9SAndreas Gohr    /**
7115929be2SAndreas Gohr     * Add a schema to be searched
7215929be2SAndreas Gohr     *
7315929be2SAndreas Gohr     * Call multiple times for multiple schemas.
7415929be2SAndreas Gohr     *
7515929be2SAndreas Gohr     * @param string $table
7615929be2SAndreas Gohr     * @param string $alias
7715929be2SAndreas Gohr     */
7861356325SAnna Dabrowska    public function addSchema($table, $alias = '')
7961356325SAnna Dabrowska    {
802be187cdSAndreas Gohr        $schema = new Schema($table);
812be187cdSAndreas Gohr        if (!$schema->getId()) {
822be187cdSAndreas Gohr            throw new StructException('schema missing', $table);
832be187cdSAndreas Gohr        }
842be187cdSAndreas Gohr
850ceefd5cSAnna Dabrowska        // FIXME is the mixing still relevant?
860ceefd5cSAnna Dabrowska//        if($this->schemas &&
870ceefd5cSAnna Dabrowska//            (
880ceefd5cSAnna Dabrowska//                $schema->isLookup() ||
890ceefd5cSAnna Dabrowska//                reset($this->schemas)->isLookup()
900ceefd5cSAnna Dabrowska//            )
910ceefd5cSAnna Dabrowska//        ) {
920ceefd5cSAnna Dabrowska//            throw new StructException('nolookupmix');
930ceefd5cSAnna Dabrowska//        }
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?
11015929be2SAndreas Gohr        $col = $this->findColumn($colname);
11115929be2SAndreas Gohr        if (!$col) return; //FIXME do we really want to ignore missing columns?
11215929be2SAndreas Gohr        $this->columns[] = $col;
11315929be2SAndreas Gohr    }
11415929be2SAndreas Gohr
11515929be2SAndreas Gohr    /**
11615929be2SAndreas Gohr     * Add sorting options
11715929be2SAndreas Gohr     *
11815929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
11915929be2SAndreas Gohr     * added before
12015929be2SAndreas Gohr     *
12115929be2SAndreas Gohr     * @param string $colname may contain an alias
12215929be2SAndreas Gohr     * @param bool $asc sort direction (ASC = true, DESC = false)
123eb55dc17SAndreas Gohr     * @param bool $nc set true for caseinsensitivity
12415929be2SAndreas Gohr     */
12561356325SAnna Dabrowska    public function addSort($colname, $asc = true, $nc = true)
12661356325SAnna Dabrowska    {
12715929be2SAndreas Gohr        $col = $this->findColumn($colname);
12815929be2SAndreas Gohr        if (!$col) return; //FIXME do we really want to ignore missing columns?
12915929be2SAndreas Gohr
130eb55dc17SAndreas Gohr        $this->sortby[$col->getFullQualifiedLabel()] = array($col, $asc, $nc);
13107993756SAndreas Gohr    }
13207993756SAndreas Gohr
13307993756SAndreas Gohr    /**
13407993756SAndreas Gohr     * Returns all set sort columns
13507993756SAndreas Gohr     *
13607993756SAndreas Gohr     * @return array
13707993756SAndreas Gohr     */
13861356325SAnna Dabrowska    public function getSorts()
13961356325SAnna Dabrowska    {
14007993756SAndreas Gohr        return $this->sortby;
14115929be2SAndreas Gohr    }
14215929be2SAndreas Gohr
14315929be2SAndreas Gohr    /**
1449d7a36f9SAndreas Gohr     * Adds a filter
14515929be2SAndreas Gohr     *
14615929be2SAndreas Gohr     * @param string $colname may contain an alias
14753528ecfSAndreas Gohr     * @param string|string[] $value
1485511bd5bSAndreas Gohr     * @param string $comp @see self::COMPARATORS
1494c13ff97SAndreas Gohr     * @param string $op either 'OR' or 'AND'
15015929be2SAndreas Gohr     */
15161356325SAnna Dabrowska    public function addFilter($colname, $value, $comp, $op = 'OR')
15261356325SAnna Dabrowska    {
1539dbc32aeSAndreas Gohr        /* Convert certain filters into others
1549dbc32aeSAndreas Gohr         * this reduces the number of supported filters to implement in types */
1559dbc32aeSAndreas Gohr        if ($comp == '*~') {
15653528ecfSAndreas Gohr            $value = $this->filterWrapAsterisks($value);
1579dbc32aeSAndreas Gohr            $comp = '~';
1589dbc32aeSAndreas Gohr        } elseif ($comp == '<>') {
1599dbc32aeSAndreas Gohr            $comp = '!=';
1609dbc32aeSAndreas Gohr        }
1619dbc32aeSAndreas Gohr
16274461852SAndreas Gohr        if (!in_array($comp, self::$COMPARATORS)) throw new StructException("Bad comperator. Use " . join(',', self::$COMPARATORS));
1634c13ff97SAndreas Gohr        if ($op != 'OR' && $op != 'AND') throw new StructException('Bad filter type . Only AND or OR allowed');
1649d7a36f9SAndreas Gohr
16515929be2SAndreas Gohr        $col = $this->findColumn($colname);
1667da1a0fdSAndreas Gohr        if (!$col) return; // ignore missing columns, filter might have been for different schema
1677da1a0fdSAndreas Gohr
1687da1a0fdSAndreas Gohr        // map filter operators to SQL syntax
1697da1a0fdSAndreas Gohr        switch ($comp) {
1707da1a0fdSAndreas Gohr            case '~':
1717da1a0fdSAndreas Gohr                $comp = 'LIKE';
1727da1a0fdSAndreas Gohr                break;
1737da1a0fdSAndreas Gohr            case '!~':
1747da1a0fdSAndreas Gohr                $comp = 'NOT LIKE';
1757da1a0fdSAndreas Gohr                break;
1767da1a0fdSAndreas Gohr            case '=*':
1777da1a0fdSAndreas Gohr                $comp = 'REGEXP';
1787da1a0fdSAndreas Gohr                break;
1797da1a0fdSAndreas Gohr        }
1807da1a0fdSAndreas Gohr
1817da1a0fdSAndreas Gohr        // we use asterisks, but SQL wants percents
1827da1a0fdSAndreas Gohr        if ($comp == 'LIKE' || $comp == 'NOT LIKE') {
18353528ecfSAndreas Gohr            $value = $this->filterChangeToLike($value);
1847da1a0fdSAndreas Gohr        }
1857da1a0fdSAndreas Gohr
186aaa187abSSzymon Olewniczak        if ($comp == 'IN' && !is_array($value)) {
187efff5841SSzymon Olewniczak            $value = $this->parseFilterValueList($value);
188aaa187abSSzymon Olewniczak            //col IN ('a', 'b', 'c') is equal to col = 'a' OR 'col = 'b' OR col = 'c'
189aaa187abSSzymon Olewniczak            $comp = '=';
190aaa187abSSzymon Olewniczak        }
191aaa187abSSzymon Olewniczak
1927da1a0fdSAndreas Gohr        // add the filter
1934c13ff97SAndreas Gohr        $this->filter[] = array($col, $value, $comp, $op);
19415929be2SAndreas Gohr    }
19515929be2SAndreas Gohr
19615929be2SAndreas Gohr    /**
197aaa187abSSzymon Olewniczak     * Parse SQLite row value into array
198aaa187abSSzymon Olewniczak     *
199aaa187abSSzymon Olewniczak     * @param string $value
200aaa187abSSzymon Olewniczak     * @return string[]
201aaa187abSSzymon Olewniczak     */
20261356325SAnna Dabrowska    protected function parseFilterValueList($value)
20361356325SAnna Dabrowska    {
204efff5841SSzymon Olewniczak        $Handler = new FilterValueListHandler();
205670a6894SAnna Dabrowska        $LexerClass = class_exists('\Doku_Lexer') ? '\Doku_Lexer' : '\dokuwiki\Parsing\Lexer\Lexer';
206670a6894SAnna Dabrowska        $isLegacy = $LexerClass === '\Doku_Lexer';
207670a6894SAnna Dabrowska        /** @var \Doku_Lexer|\dokuwiki\Parsing\Lexer\Lexer $Lexer */
208670a6894SAnna Dabrowska        $Lexer = new $LexerClass($Handler, 'base', true);
209670a6894SAnna Dabrowska
210aaa187abSSzymon Olewniczak
211aaa187abSSzymon Olewniczak        $Lexer->addEntryPattern('\(', 'base', 'row');
212aaa187abSSzymon Olewniczak        $Lexer->addPattern('\s*,\s*', 'row');
213aaa187abSSzymon Olewniczak        $Lexer->addExitPattern('\)', 'row');
214aaa187abSSzymon Olewniczak
215aaa187abSSzymon Olewniczak        $Lexer->addEntryPattern('"', 'row', 'double_quote_string');
216dfe3ae67SAnna Dabrowska        $Lexer->addSpecialPattern('\\\\"', 'double_quote_string', 'escapeSequence');
217aaa187abSSzymon Olewniczak        $Lexer->addExitPattern('"', 'double_quote_string');
218aaa187abSSzymon Olewniczak
219dfe3ae67SAnna Dabrowska        $Lexer->addEntryPattern("'", 'row', 'singleQuoteString');
220dfe3ae67SAnna Dabrowska        $Lexer->addSpecialPattern("\\\\'", 'singleQuoteString', 'escapeSequence');
221dfe3ae67SAnna Dabrowska        $Lexer->addExitPattern("'", 'singleQuoteString');
222aaa187abSSzymon Olewniczak
223dfe3ae67SAnna Dabrowska        $Lexer->mapHandler('double_quote_string', 'singleQuoteString');
224aaa187abSSzymon Olewniczak
225aaa187abSSzymon Olewniczak        $Lexer->addSpecialPattern('[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?', 'row', 'number');
226aaa187abSSzymon Olewniczak
227aaa187abSSzymon Olewniczak        $res = $Lexer->parse($value);
228aaa187abSSzymon Olewniczak
229670a6894SAnna Dabrowska        $currentMode = $isLegacy ? $Lexer->_mode->getCurrent() : $Lexer->getModeStack()->getCurrent();
230670a6894SAnna Dabrowska        if (!$res || $currentMode != 'base') {
231aaa187abSSzymon Olewniczak            throw new StructException('invalid row value syntax');
232aaa187abSSzymon Olewniczak        }
233aaa187abSSzymon Olewniczak
234dfe3ae67SAnna Dabrowska        return $Handler->getRow();
235aaa187abSSzymon Olewniczak    }
236aaa187abSSzymon Olewniczak
237aaa187abSSzymon Olewniczak    /**
23853528ecfSAndreas Gohr     * Wrap given value in asterisks
23953528ecfSAndreas Gohr     *
24053528ecfSAndreas Gohr     * @param string|string[] $value
24153528ecfSAndreas Gohr     * @return string|string[]
24253528ecfSAndreas Gohr     */
24361356325SAnna Dabrowska    protected function filterWrapAsterisks($value)
24461356325SAnna Dabrowska    {
24553528ecfSAndreas Gohr        $map = function ($input) {
24653528ecfSAndreas Gohr            return "*$input*";
24753528ecfSAndreas Gohr        };
24853528ecfSAndreas Gohr
24953528ecfSAndreas Gohr        if (is_array($value)) {
25053528ecfSAndreas Gohr            $value = array_map($map, $value);
25153528ecfSAndreas Gohr        } else {
25253528ecfSAndreas Gohr            $value = $map($value);
25353528ecfSAndreas Gohr        }
25453528ecfSAndreas Gohr        return $value;
25553528ecfSAndreas Gohr    }
25653528ecfSAndreas Gohr
25753528ecfSAndreas Gohr    /**
25853528ecfSAndreas Gohr     * Change given string to use % instead of *
25953528ecfSAndreas Gohr     *
26053528ecfSAndreas Gohr     * @param string|string[] $value
26153528ecfSAndreas Gohr     * @return string|string[]
26253528ecfSAndreas Gohr     */
26361356325SAnna Dabrowska    protected function filterChangeToLike($value)
26461356325SAnna Dabrowska    {
26553528ecfSAndreas Gohr        $map = function ($input) {
26653528ecfSAndreas Gohr            return str_replace('*', '%', $input);
26753528ecfSAndreas Gohr        };
26853528ecfSAndreas Gohr
26953528ecfSAndreas Gohr        if (is_array($value)) {
27053528ecfSAndreas Gohr            $value = array_map($map, $value);
27153528ecfSAndreas Gohr        } else {
27253528ecfSAndreas Gohr            $value = $map($value);
27353528ecfSAndreas Gohr        }
27453528ecfSAndreas Gohr        return $value;
27553528ecfSAndreas Gohr    }
27653528ecfSAndreas Gohr
27753528ecfSAndreas Gohr    /**
2787f9cb794SAndreas Gohr     * Set offset for the results
2797f9cb794SAndreas Gohr     *
2807f9cb794SAndreas Gohr     * @param int $offset
2817f9cb794SAndreas Gohr     */
28261356325SAnna Dabrowska    public function setOffset($offset)
28361356325SAnna Dabrowska    {
2847f9cb794SAndreas Gohr        $limit = 0;
2857f9cb794SAndreas Gohr        if ($this->range_end) {
2867f9cb794SAndreas Gohr            // if there was a limit set previously, the range_end needs to be recalculated
2877f9cb794SAndreas Gohr            $limit = $this->range_end - $this->range_begin;
2887f9cb794SAndreas Gohr        }
2897f9cb794SAndreas Gohr        $this->range_begin = $offset;
2907f9cb794SAndreas Gohr        if ($limit) $this->setLimit($limit);
2917f9cb794SAndreas Gohr    }
2927f9cb794SAndreas Gohr
2937f9cb794SAndreas Gohr    /**
2947f9cb794SAndreas Gohr     * Limit results to this number
2957f9cb794SAndreas Gohr     *
2967f9cb794SAndreas Gohr     * @param int $limit Set to 0 to disable limit again
2977f9cb794SAndreas Gohr     */
29861356325SAnna Dabrowska    public function setLimit($limit)
29961356325SAnna Dabrowska    {
3007f9cb794SAndreas Gohr        if ($limit) {
3017f9cb794SAndreas Gohr            $this->range_end = $this->range_begin + $limit;
3027f9cb794SAndreas Gohr        } else {
3037f9cb794SAndreas Gohr            $this->range_end = 0;
3047f9cb794SAndreas Gohr        }
3057f9cb794SAndreas Gohr    }
3067f9cb794SAndreas Gohr
3077f9cb794SAndreas Gohr    /**
3087f9cb794SAndreas Gohr     * Return the number of results (regardless of limit and offset settings)
3097f9cb794SAndreas Gohr     *
3107f9cb794SAndreas Gohr     * Use this to implement paging. Important: this may only be called after running @see execute()
3117f9cb794SAndreas Gohr     *
3127f9cb794SAndreas Gohr     * @return int
3137f9cb794SAndreas Gohr     */
31461356325SAnna Dabrowska    public function getCount()
31561356325SAnna Dabrowska    {
3167f9cb794SAndreas Gohr        if ($this->count < 0) throw new StructException('Count is only accessible after executing the search');
3177f9cb794SAndreas Gohr        return $this->count;
3187f9cb794SAndreas Gohr    }
3197f9cb794SAndreas Gohr
320c46f5fb1SAndreas Gohr    /**
321c46f5fb1SAndreas Gohr     * Returns the PID associated with each result row
322c46f5fb1SAndreas Gohr     *
323c46f5fb1SAndreas Gohr     * Important: this may only be called after running @see execute()
324c46f5fb1SAndreas Gohr     *
325c46f5fb1SAndreas Gohr     * @return \string[]
326c46f5fb1SAndreas Gohr     */
32761356325SAnna Dabrowska    public function getPids()
32861356325SAnna Dabrowska    {
329d4b5a17cSAndreas Gohr        if ($this->result_pids === null) throw new StructException('PIDs are only accessible after executing the search');
330d4b5a17cSAndreas Gohr        return $this->result_pids;
331d4b5a17cSAndreas Gohr    }
332d4b5a17cSAndreas Gohr
3337f9cb794SAndreas Gohr    /**
3340ceefd5cSAnna Dabrowska     * Returns the rid associated with each result row
3350ceefd5cSAnna Dabrowska     *
3360ceefd5cSAnna Dabrowska     * Important: this may only be called after running @see execute()
3370ceefd5cSAnna Dabrowska     *
3380ceefd5cSAnna Dabrowska     * @return array
3390ceefd5cSAnna Dabrowska     */
34061356325SAnna Dabrowska    public function getRids()
34161356325SAnna Dabrowska    {
3420ceefd5cSAnna Dabrowska        if ($this->result_rids === null) throw new StructException('rids are only accessible after executing the search');
3430ceefd5cSAnna Dabrowska        return $this->result_rids;
3440ceefd5cSAnna Dabrowska    }
3450ceefd5cSAnna Dabrowska
3460ceefd5cSAnna Dabrowska    /**
3476fd73b4bSAnna Dabrowska     * Returns the rid associated with each result row
3486fd73b4bSAnna Dabrowska     *
3496fd73b4bSAnna Dabrowska     * Important: this may only be called after running @see execute()
3506fd73b4bSAnna Dabrowska     *
3516fd73b4bSAnna Dabrowska     * @return array
3526fd73b4bSAnna Dabrowska     */
35361356325SAnna Dabrowska    public function getRevs()
35461356325SAnna Dabrowska    {
3556fd73b4bSAnna Dabrowska        if ($this->result_revs === null) throw new StructException('revs are only accessible after executing the search');
3566fd73b4bSAnna Dabrowska        return $this->result_revs;
3576fd73b4bSAnna Dabrowska    }
3586fd73b4bSAnna Dabrowska
3596fd73b4bSAnna Dabrowska    /**
360b2ed727aSAndreas Gohr     * Execute this search and return the result
361b2ed727aSAndreas Gohr     *
36238fa36fbSAndreas Gohr     * The result is a two dimensional array of Value()s.
3637f9cb794SAndreas Gohr     *
3647f9cb794SAndreas Gohr     * This will always query for the full result (not using offset and limit) and then
3657f9cb794SAndreas Gohr     * return the wanted range, setting the count (@see getCount) to the whole result number
36638fa36fbSAndreas Gohr     *
36738fa36fbSAndreas Gohr     * @return Value[][]
368b2ed727aSAndreas Gohr     */
369*8ce43f5aSAnna Dabrowska    public function execute()
37061356325SAnna Dabrowska    {
371*8ce43f5aSAnna Dabrowska        list($sql, $opts) = $this->getSQL();
372b2ed727aSAndreas Gohr
3737f9cb794SAndreas Gohr        /** @var \PDOStatement $res */
374b2ed727aSAndreas Gohr        $res = $this->sqlite->query($sql, $opts);
37559b668aaSAndreas Gohr        if ($res === false) throw new StructException("SQL execution failed for\n\n$sql");
376b2ed727aSAndreas Gohr
377d4b5a17cSAndreas Gohr        $this->result_pids = array();
378b2ed727aSAndreas Gohr        $result = array();
3797f9cb794SAndreas Gohr        $cursor = -1;
3805e4bfdb0SMichael Grosse        $pageidAndRevOnly = array_reduce($this->columns, function ($pageidAndRevOnly, Column $col) {
3815e4bfdb0SMichael Grosse            return $pageidAndRevOnly && ($col->getTid() == 0);
3825e4bfdb0SMichael Grosse        }, true);
3837f9cb794SAndreas Gohr        while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
3847f9cb794SAndreas Gohr            $cursor++;
3857f9cb794SAndreas Gohr            if ($cursor < $this->range_begin) continue;
3867f9cb794SAndreas Gohr            if ($this->range_end && $cursor >= $this->range_end) continue;
3877f9cb794SAndreas Gohr
388b2ed727aSAndreas Gohr            $C = 0;
389b2ed727aSAndreas Gohr            $resrow = array();
39099a70f28SAndreas Gohr            $isempty = true;
391b2ed727aSAndreas Gohr            foreach ($this->columns as $col) {
39238fa36fbSAndreas Gohr                $val = $row["C$C"];
393b2ed727aSAndreas Gohr                if ($col->isMulti()) {
39438fa36fbSAndreas Gohr                    $val = explode(self::CONCAT_SEPARATOR, $val);
395b2ed727aSAndreas Gohr                }
39699a70f28SAndreas Gohr                $value = new Value($col, $val);
3978cba7aa0SMichael Grosse                $isempty &= $this->isEmptyValue($value);
39899a70f28SAndreas Gohr                $resrow[] = $value;
399b2ed727aSAndreas Gohr                $C++;
400b2ed727aSAndreas Gohr            }
40199a70f28SAndreas Gohr
40299a70f28SAndreas Gohr            // skip empty rows
4038cba7aa0SMichael Grosse            if ($isempty && !$pageidAndRevOnly) {
40499a70f28SAndreas Gohr                $cursor--;
40599a70f28SAndreas Gohr                continue;
40699a70f28SAndreas Gohr            }
40799a70f28SAndreas Gohr
40899a70f28SAndreas Gohr            $this->result_pids[] = $row['PID'];
4090ceefd5cSAnna Dabrowska            $this->result_rids[] = $row['rid'];
4106fd73b4bSAnna Dabrowska            $this->result_revs[] = $row['rev'];
411b2ed727aSAndreas Gohr            $result[] = $resrow;
412b2ed727aSAndreas Gohr        }
4137f9cb794SAndreas Gohr
4147f9cb794SAndreas Gohr        $this->sqlite->res_close($res);
4157f9cb794SAndreas Gohr        $this->count = $cursor + 1;
416b2ed727aSAndreas Gohr        return $result;
417b2ed727aSAndreas Gohr    }
418b2ed727aSAndreas Gohr
419b2ed727aSAndreas Gohr    /**
42015929be2SAndreas Gohr     * Transform the set search parameters into a statement
42115929be2SAndreas Gohr     *
422b2ed727aSAndreas Gohr     * @return array ($sql, $opts) The SQL and parameters to execute
42315929be2SAndreas Gohr     */
424*8ce43f5aSAnna Dabrowska    public function getSQL()
42561356325SAnna Dabrowska    {
4265511bd5bSAndreas Gohr        if (!$this->columns) throw new StructException('nocolname');
42715929be2SAndreas Gohr
4282f68434dSAndreas Gohr        $QB = new QueryBuilder();
42915929be2SAndreas Gohr
4309d7a36f9SAndreas Gohr        // basic tables
431b2d67e7dSAndreas Gohr        $first_table = '';
4329d7a36f9SAndreas Gohr        foreach ($this->schemas as $schema) {
4332f68434dSAndreas Gohr            $datatable = 'data_' . $schema->getTable();
434b2d67e7dSAndreas Gohr            if ($first_table) {
4359d7a36f9SAndreas Gohr                // follow up tables
436*8ce43f5aSAnna Dabrowska                $QB->addLeftJoin($first_table, $datatable, $datatable, "$first_table.pid = $datatable.pid");
4379d7a36f9SAndreas Gohr            } else {
4389d7a36f9SAndreas Gohr                // first table
43913c321dbSAndreas Gohr                $QB->addTable($datatable);
440*8ce43f5aSAnna Dabrowska
441*8ce43f5aSAnna Dabrowska                // add conditional page clauses if pid has a value
442*8ce43f5aSAnna Dabrowska                $subAnd = $QB->filters()->whereSubAnd();
443*8ce43f5aSAnna Dabrowska                $subAnd->whereAnd("$datatable.pid = ''");
444*8ce43f5aSAnna Dabrowska                $subOr = $subAnd->whereSubOr();
445*8ce43f5aSAnna Dabrowska                $subOr->whereAnd("GETACCESSLEVEL($datatable.pid) > 0");
446*8ce43f5aSAnna Dabrowska                $subOr->whereAnd("PAGEEXISTS($datatable.pid) = 1");
447*8ce43f5aSAnna Dabrowska
448*8ce43f5aSAnna Dabrowska                // add conditional schema assignment check
449*8ce43f5aSAnna Dabrowska                $QB->addLeftJoin($datatable,'schema_assignments','',
450*8ce43f5aSAnna Dabrowska                    "$datatable.pid != ''
451*8ce43f5aSAnna Dabrowska                    AND $datatable.pid = schema_assignments.pid
452*8ce43f5aSAnna Dabrowska                    AND schema_assignments.tbl = '{$schema->getTable()}'
453*8ce43f5aSAnna Dabrowska                    AND schema_assignments.assigned = 1"
454*8ce43f5aSAnna Dabrowska                );
455*8ce43f5aSAnna Dabrowska
4560ceefd5cSAnna Dabrowska                $QB->addSelectColumn($datatable, 'rid');
45713c321dbSAndreas Gohr                $QB->addSelectColumn($datatable, 'pid', 'PID');
4586fd73b4bSAnna Dabrowska                $QB->addSelectColumn($datatable, 'rev');
45913c321dbSAndreas Gohr                $QB->addGroupByColumn($datatable, 'pid');
460b2d67e7dSAndreas Gohr
4612f68434dSAndreas Gohr                $first_table = $datatable;
46215929be2SAndreas Gohr            }
4632f68434dSAndreas Gohr            $QB->filters()->whereAnd("$datatable.latest = 1");
4649d7a36f9SAndreas Gohr        }
46515929be2SAndreas Gohr
46615929be2SAndreas Gohr        // columns to select, handling multis
4679d7a36f9SAndreas Gohr        $sep = self::CONCAT_SEPARATOR;
46815929be2SAndreas Gohr        $n = 0;
46915929be2SAndreas Gohr        foreach ($this->columns as $col) {
47015929be2SAndreas Gohr            $CN = 'C' . $n++;
47115929be2SAndreas Gohr
472d1b04e89SAndreas Gohr            if ($col->isMulti()) {
4732f68434dSAndreas Gohr                $datatable = "data_{$col->getTable()}";
4742f68434dSAndreas Gohr                $multitable = "multi_{$col->getTable()}";
475db7970caSAndreas Gohr                $MN = $QB->generateTableAlias('M');
4762f68434dSAndreas Gohr
4772f68434dSAndreas Gohr                $QB->addLeftJoin(
4782f68434dSAndreas Gohr                    $datatable,
4792f68434dSAndreas Gohr                    $multitable,
4802f68434dSAndreas Gohr                    $MN,
481*8ce43f5aSAnna Dabrowska                    "$datatable.pid = $MN.pid AND $datatable.rid = $MN.rid AND
4822f68434dSAndreas Gohr                     $datatable.rev = $MN.rev AND
4832f68434dSAndreas Gohr                     $MN.colref = {$col->getColref()}"
4842f68434dSAndreas Gohr                );
485578407b2SAndreas Gohr
486578407b2SAndreas Gohr                $col->getType()->select($QB, $MN, 'value', $CN);
487578407b2SAndreas Gohr                $sel = $QB->getSelectStatement($CN);
488578407b2SAndreas Gohr                $QB->addSelectStatement("GROUP_CONCAT($sel, '$sep')", $CN);
48915929be2SAndreas Gohr            } else {
490578407b2SAndreas Gohr                $col->getType()->select($QB, 'data_' . $col->getTable(), $col->getColName(), $CN);
4910dbe7bf6SAndreas Gohr                $QB->addGroupByStatement($CN);
49215929be2SAndreas Gohr            }
49315929be2SAndreas Gohr        }
49415929be2SAndreas Gohr
4959d7a36f9SAndreas Gohr        // where clauses
496af993d55SMichael Grosse        if (!empty($this->filter)) {
497af993d55SMichael Grosse            $userWHERE = $QB->filters()->where('AND');
498af993d55SMichael Grosse        }
499b8fe6730SAndreas Gohr        foreach ($this->filter as $filter) {
5009ebd2ed6SAndreas Gohr            /** @var Column $col */
5014c13ff97SAndreas Gohr            list($col, $value, $comp, $op) = $filter;
502b8fe6730SAndreas Gohr
5032f68434dSAndreas Gohr            $datatable = "data_{$col->getTable()}";
5042f68434dSAndreas Gohr            $multitable = "multi_{$col->getTable()}";
5059d7a36f9SAndreas Gohr
5069d7a36f9SAndreas Gohr            /** @var $col Column */
5079d7a36f9SAndreas Gohr            if ($col->isMulti()) {
508db7970caSAndreas Gohr                $MN = $QB->generateTableAlias('MN');
50915929be2SAndreas Gohr
5102f68434dSAndreas Gohr                $QB->addLeftJoin(
5112f68434dSAndreas Gohr                    $datatable,
5122f68434dSAndreas Gohr                    $multitable,
5132f68434dSAndreas Gohr                    $MN,
514*8ce43f5aSAnna Dabrowska                    "$datatable.pid = $MN.pid AND $datatable.rid = $MN.rid AND
5152f68434dSAndreas Gohr                     $datatable.rev = $MN.rev AND
5162f68434dSAndreas Gohr                     $MN.colref = {$col->getColref()}"
5172f68434dSAndreas Gohr                );
518690e4ebaSAndreas Gohr                $coltbl = $MN;
519690e4ebaSAndreas Gohr                $colnam = 'value';
5209d7a36f9SAndreas Gohr            } else {
521690e4ebaSAndreas Gohr                $coltbl = $datatable;
522690e4ebaSAndreas Gohr                $colnam = $col->getColName();
5239d7a36f9SAndreas Gohr            }
52453528ecfSAndreas Gohr
525af993d55SMichael Grosse            $col->getType()->filter($userWHERE, $coltbl, $colnam, $comp, $value, $op); // type based filter
5269d7a36f9SAndreas Gohr        }
5279d7a36f9SAndreas Gohr
52829394e6cSAndreas Gohr        // sorting - we always sort by the single val column
529b8fe6730SAndreas Gohr        foreach ($this->sortby as $sort) {
530eb55dc17SAndreas Gohr            list($col, $asc, $nc) = $sort;
5319d7a36f9SAndreas Gohr            /** @var $col Column */
532eb55dc17SAndreas Gohr            $colname = $col->getColName(false);
533eb55dc17SAndreas Gohr            if ($nc) $colname .= ' COLLATE NOCASE';
534eb55dc17SAndreas Gohr            $col->getType()->sort($QB, 'data_' . $col->getTable(), $colname, $asc ? 'ASC' : 'DESC');
5359e07bdbfSAndreas Gohr        }
5369e07bdbfSAndreas Gohr
5372f68434dSAndreas Gohr        return $QB->getSQL();
53815929be2SAndreas Gohr    }
53915929be2SAndreas Gohr
54015929be2SAndreas Gohr    /**
54101dd90deSAndreas Gohr     * Returns all the columns that where added to the search
54201dd90deSAndreas Gohr     *
54301dd90deSAndreas Gohr     * @return Column[]
54401dd90deSAndreas Gohr     */
54561356325SAnna Dabrowska    public function getColumns()
54661356325SAnna Dabrowska    {
54701dd90deSAndreas Gohr        return $this->columns;
54801dd90deSAndreas Gohr    }
54901dd90deSAndreas Gohr
550577b462bSAndreas Gohr    /**
5515a4df70dSAndreas Gohr     * All the schemas currently added
5525a4df70dSAndreas Gohr     *
5535a4df70dSAndreas Gohr     * @return Schema[]
5545a4df70dSAndreas Gohr     */
55561356325SAnna Dabrowska    public function getSchemas()
55661356325SAnna Dabrowska    {
5575a4df70dSAndreas Gohr        return array_values($this->schemas);
5585a4df70dSAndreas Gohr    }
5595a4df70dSAndreas Gohr
5605a4df70dSAndreas Gohr    /**
561577b462bSAndreas Gohr     * Checks if the given column is a * wildcard
562577b462bSAndreas Gohr     *
563577b462bSAndreas Gohr     * If it's a wildcard all matching columns are added to the column list, otherwise
564577b462bSAndreas Gohr     * nothing happens
565577b462bSAndreas Gohr     *
566577b462bSAndreas Gohr     * @param string $colname
567577b462bSAndreas Gohr     * @return bool was wildcard?
568577b462bSAndreas Gohr     */
56961356325SAnna Dabrowska    protected function processWildcard($colname)
57061356325SAnna Dabrowska    {
571636a5173SAndreas Gohr        list($colname, $table) = $this->resolveColumn($colname);
572577b462bSAndreas Gohr        if ($colname !== '*') return false;
573577b462bSAndreas Gohr
574577b462bSAndreas Gohr        // no table given? assume the first is meant
575577b462bSAndreas Gohr        if ($table === null) {
576577b462bSAndreas Gohr            $schema_list = array_keys($this->schemas);
577577b462bSAndreas Gohr            $table = $schema_list[0];
578577b462bSAndreas Gohr        }
579577b462bSAndreas Gohr
580577b462bSAndreas Gohr        $schema = $this->schemas[$table];
581577b462bSAndreas Gohr        if (!$schema) return false;
582577b462bSAndreas Gohr        $this->columns = array_merge($this->columns, $schema->getColumns(false));
583577b462bSAndreas Gohr        return true;
584577b462bSAndreas Gohr    }
585577b462bSAndreas Gohr
586577b462bSAndreas Gohr    /**
587577b462bSAndreas Gohr     * Split a given column name into table and column
588577b462bSAndreas Gohr     *
589577b462bSAndreas Gohr     * Handles Aliases. Table might be null if none given.
590577b462bSAndreas Gohr     *
591577b462bSAndreas Gohr     * @param $colname
592636a5173SAndreas Gohr     * @return array (colname, table)
593577b462bSAndreas Gohr     */
59461356325SAnna Dabrowska    protected function resolveColumn($colname)
59561356325SAnna Dabrowska    {
596577b462bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
597577b462bSAndreas Gohr
598577b462bSAndreas Gohr        // resolve the alias or table name
5999007da58SMichael Große        @list($table, $colname) = explode('.', $colname, 2);
600577b462bSAndreas Gohr        if (!$colname) {
601577b462bSAndreas Gohr            $colname = $table;
602577b462bSAndreas Gohr            $table = null;
603577b462bSAndreas Gohr        }
604577b462bSAndreas Gohr        if ($table && isset($this->aliases[$table])) {
605577b462bSAndreas Gohr            $table = $this->aliases[$table];
606577b462bSAndreas Gohr        }
607577b462bSAndreas Gohr
608577b462bSAndreas Gohr        if (!$colname) throw new StructException('nocolname');
609577b462bSAndreas Gohr
610577b462bSAndreas Gohr        return array($colname, $table);
611577b462bSAndreas Gohr    }
61201dd90deSAndreas Gohr
61301dd90deSAndreas Gohr    /**
61415929be2SAndreas Gohr     * Find a column to be used in the search
61515929be2SAndreas Gohr     *
61615929be2SAndreas Gohr     * @param string $colname may contain an alias
61715929be2SAndreas Gohr     * @return bool|Column
61815929be2SAndreas Gohr     */
61961356325SAnna Dabrowska    public function findColumn($colname)
62061356325SAnna Dabrowska    {
6215511bd5bSAndreas Gohr        if (!$this->schemas) throw new StructException('noschemas');
622df02ffe6SMichael Große        $schema_list = array_keys($this->schemas);
623f107f479SAndreas Gohr
624f107f479SAndreas Gohr        // add "fake" column for special col
625128d4e83SAndreas Gohr        if ($colname == '%pageid%') {
626128d4e83SAndreas Gohr            return new PageColumn(0, new Page(), $schema_list[0]);
627d1b04e89SAndreas Gohr        }
628128d4e83SAndreas Gohr        if ($colname == '%title%') {
629128d4e83SAndreas Gohr            return new PageColumn(0, new Page(array('usetitles' => true)), $schema_list[0]);
630128d4e83SAndreas Gohr        }
631cadfc3ccSAndreas Gohr        if ($colname == '%lastupdate%') {
632cadfc3ccSAndreas Gohr            return new RevisionColumn(0, new DateTime(), $schema_list[0]);
633cadfc3ccSAndreas Gohr        }
6342e12ac22SMichael Grosse        if ($colname == '%lasteditor%') {
6352e12ac22SMichael Grosse            return new UserColumn(0, new User(), $schema_list[0]);
6362e12ac22SMichael Grosse        }
63788b58a21SSzymon Olewniczak        if ($colname == '%lastsummary%') {
6386781c68dSSzymon Olewniczak            return new SummaryColumn(0, new AutoSummary(), $schema_list[0]);
63988b58a21SSzymon Olewniczak        }
640f107f479SAndreas Gohr        if ($colname == '%rowid%') {
641f107f479SAndreas Gohr            return new RowColumn(0, new Decimal(), $schema_list[0]);
642f107f479SAndreas Gohr        }
643d1b04e89SAndreas Gohr
644636a5173SAndreas Gohr        list($colname, $table) = $this->resolveColumn($colname);
64515929be2SAndreas Gohr
646bd363da9SAndreas Gohr        // if table name given search only that, otherwise try all for matching column name
647577b462bSAndreas Gohr        if ($table !== null) {
64815929be2SAndreas Gohr            $schemas = array($table => $this->schemas[$table]);
64915929be2SAndreas Gohr        } else {
65015929be2SAndreas Gohr            $schemas = $this->schemas;
65115929be2SAndreas Gohr        }
65215929be2SAndreas Gohr
65315929be2SAndreas Gohr        // find it
65415929be2SAndreas Gohr        $col = false;
65515929be2SAndreas Gohr        foreach ($schemas as $schema) {
6564ac44d1cSMichael Grosse            if (empty($schema)) {
6574ac44d1cSMichael Grosse                continue;
6584ac44d1cSMichael Grosse            }
65915929be2SAndreas Gohr            $col = $schema->findColumn($colname);
66015929be2SAndreas Gohr            if ($col) break;
66115929be2SAndreas Gohr        }
66215929be2SAndreas Gohr
66315929be2SAndreas Gohr        return $col;
66415929be2SAndreas Gohr    }
66515929be2SAndreas Gohr
6669dbc8ec0SMichael Grosse    /**
66799a70f28SAndreas Gohr     * Check if the given row is empty or references our own row
6689dbc8ec0SMichael Grosse     *
66999a70f28SAndreas Gohr     * @param Value $value
6709dbc8ec0SMichael Grosse     * @return bool
6719dbc8ec0SMichael Grosse     */
67261356325SAnna Dabrowska    protected function isEmptyValue(Value $value)
67361356325SAnna Dabrowska    {
67499a70f28SAndreas Gohr        if ($value->isEmpty()) return true;
6758cba7aa0SMichael Grosse        if ($value->getColumn()->getTid() == 0) return true;
6769dbc8ec0SMichael Grosse        return false;
6779dbc8ec0SMichael Grosse    }
67815929be2SAndreas Gohr}
679