xref: /dokuwiki/inc/Search/Indexer.php (revision 7d34963b3e75ea04c63ec066a6b7a692e123cb53)
16225b270SMichael Große<?php
26225b270SMichael Große
36225b270SMichael Großenamespace dokuwiki\Search;
46225b270SMichael Große
524870174SAndreas Gohruse dokuwiki\Utf8\Asian;
624870174SAndreas Gohruse dokuwiki\Utf8\Clean;
724870174SAndreas Gohruse dokuwiki\Utf8\PhpString;
86225b270SMichael Großeuse dokuwiki\Extension\Event;
96225b270SMichael Große
106225b270SMichael Große/**
116225b270SMichael Große * Class that encapsulates operations on the indexer database.
126225b270SMichael Große *
136225b270SMichael Große * @author Tom N Harris <tnharris@whoopdedo.org>
146225b270SMichael Große */
158c7c53b0SAndreas Gohrclass Indexer
168c7c53b0SAndreas Gohr{
176225b270SMichael Große    /**
186225b270SMichael Große     * @var array $pidCache Cache for getPID()
196225b270SMichael Große     */
2024870174SAndreas Gohr    protected $pidCache = [];
216225b270SMichael Große
226225b270SMichael Große    /**
236225b270SMichael Große     * Adds the contents of a page to the fulltext index
246225b270SMichael Große     *
256225b270SMichael Große     * The added text replaces previous words for the same page.
266225b270SMichael Große     * An empty value erases the page.
276225b270SMichael Große     *
286225b270SMichael Große     * @param string    $page   a page name
296225b270SMichael Große     * @param string    $text   the body of the page
306225b270SMichael Große     * @return string|boolean  the function completed successfully
316225b270SMichael Große     *
326225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
336225b270SMichael Große     * @author Andreas Gohr <andi@splitbrain.org>
346225b270SMichael Große     */
35d868eb89SAndreas Gohr    public function addPageWords($page, $text)
36d868eb89SAndreas Gohr    {
376225b270SMichael Große        if (!$this->lock())
386225b270SMichael Große            return "locked";
396225b270SMichael Große
406225b270SMichael Große        // load known documents
416225b270SMichael Große        $pid = $this->getPIDNoLock($page);
426225b270SMichael Große        if ($pid === false) {
436225b270SMichael Große            $this->unlock();
446225b270SMichael Große            return false;
456225b270SMichael Große        }
466225b270SMichael Große
4724870174SAndreas Gohr        $pagewords = [];
486225b270SMichael Große        // get word usage in page
496225b270SMichael Große        $words = $this->getPageWords($text);
506225b270SMichael Große        if ($words === false) {
516225b270SMichael Große            $this->unlock();
526225b270SMichael Große            return false;
536225b270SMichael Große        }
546225b270SMichael Große
556225b270SMichael Große        if (!empty($words)) {
566225b270SMichael Große            foreach (array_keys($words) as $wlen) {
576225b270SMichael Große                $index = $this->getIndex('i', $wlen);
586225b270SMichael Große                foreach ($words[$wlen] as $wid => $freq) {
596225b270SMichael Große                    $idx = ($wid<count($index)) ? $index[$wid] : '';
606225b270SMichael Große                    $index[$wid] = $this->updateTuple($idx, $pid, $freq);
616225b270SMichael Große                    $pagewords[] = "$wlen*$wid";
626225b270SMichael Große                }
636225b270SMichael Große                if (!$this->saveIndex('i', $wlen, $index)) {
646225b270SMichael Große                    $this->unlock();
656225b270SMichael Große                    return false;
666225b270SMichael Große                }
676225b270SMichael Große            }
686225b270SMichael Große        }
696225b270SMichael Große
706225b270SMichael Große        // Remove obsolete index entries
716225b270SMichael Große        $pageword_idx = $this->getIndexKey('pageword', '', $pid);
726225b270SMichael Große        if ($pageword_idx !== '') {
736225b270SMichael Große            $oldwords = explode(':', $pageword_idx);
746225b270SMichael Große            $delwords = array_diff($oldwords, $pagewords);
7524870174SAndreas Gohr            $upwords = [];
766225b270SMichael Große            foreach ($delwords as $word) {
776225b270SMichael Große                if ($word != '') {
7824870174SAndreas Gohr                    [$wlen, $wid] = explode('*', $word);
796225b270SMichael Große                    $wid = (int)$wid;
806225b270SMichael Große                    $upwords[$wlen][] = $wid;
816225b270SMichael Große                }
826225b270SMichael Große            }
836225b270SMichael Große            foreach ($upwords as $wlen => $widx) {
846225b270SMichael Große                $index = $this->getIndex('i', $wlen);
856225b270SMichael Große                foreach ($widx as $wid) {
866225b270SMichael Große                    $index[$wid] = $this->updateTuple($index[$wid], $pid, 0);
876225b270SMichael Große                }
886225b270SMichael Große                $this->saveIndex('i', $wlen, $index);
896225b270SMichael Große            }
906225b270SMichael Große        }
916225b270SMichael Große        // Save the reverse index
9224870174SAndreas Gohr        $pageword_idx = implode(':', $pagewords);
936225b270SMichael Große        if (!$this->saveIndexKey('pageword', '', $pid, $pageword_idx)) {
946225b270SMichael Große            $this->unlock();
956225b270SMichael Große            return false;
966225b270SMichael Große        }
976225b270SMichael Große
986225b270SMichael Große        $this->unlock();
996225b270SMichael Große        return true;
1006225b270SMichael Große    }
1016225b270SMichael Große
1026225b270SMichael Große    /**
1036225b270SMichael Große     * Split the words in a page and add them to the index.
1046225b270SMichael Große     *
1056225b270SMichael Große     * @param string    $text   content of the page
1066225b270SMichael Große     * @return array            list of word IDs and number of times used
1076225b270SMichael Große     *
1086225b270SMichael Große     * @author Andreas Gohr <andi@splitbrain.org>
1096225b270SMichael Große     * @author Christopher Smith <chris@jalakai.co.uk>
1106225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
1116225b270SMichael Große     */
112d868eb89SAndreas Gohr    protected function getPageWords($text)
113d868eb89SAndreas Gohr    {
1146225b270SMichael Große
1156225b270SMichael Große        $tokens = $this->tokenizer($text);
1166225b270SMichael Große        $tokens = array_count_values($tokens);  // count the frequency of each token
1176225b270SMichael Große
11824870174SAndreas Gohr        $words = [];
1196225b270SMichael Große        foreach ($tokens as $w => $c) {
1206225b270SMichael Große            $l = wordlen($w);
1216225b270SMichael Große            if (isset($words[$l])) {
12224870174SAndreas Gohr                $words[$l][$w] = $c + ($words[$l][$w] ?? 0);
1236225b270SMichael Große            } else {
12424870174SAndreas Gohr                $words[$l] = [$w => $c];
1256225b270SMichael Große            }
1266225b270SMichael Große        }
1276225b270SMichael Große
1286225b270SMichael Große        // arrive here with $words = array(wordlen => array(word => frequency))
12924870174SAndreas Gohr        $index = [];   //resulting index
1306225b270SMichael Große        foreach (array_keys($words) as $wlen) {
1316225b270SMichael Große            $word_idx = $this->getIndex('w', $wlen);
132173de31cSMoritz Raguschat            $word_idx_modified = false;
1336225b270SMichael Große            foreach ($words[$wlen] as $word => $freq) {
1346225b270SMichael Große                $word = (string)$word;
1356225b270SMichael Große                $wid = array_search($word, $word_idx, true);
1366225b270SMichael Große                if ($wid === false) {
1376225b270SMichael Große                    $wid = count($word_idx);
1386225b270SMichael Große                    $word_idx[] = $word;
1396225b270SMichael Große                    $word_idx_modified = true;
1406225b270SMichael Große                }
1416225b270SMichael Große                if (!isset($index[$wlen]))
14224870174SAndreas Gohr                    $index[$wlen] = [];
1436225b270SMichael Große                $index[$wlen][$wid] = $freq;
1446225b270SMichael Große            }
1456225b270SMichael Große            // save back the word index
1466225b270SMichael Große            if ($word_idx_modified && !$this->saveIndex('w', $wlen, $word_idx))
1476225b270SMichael Große                return false;
1486225b270SMichael Große        }
1496225b270SMichael Große
1506225b270SMichael Große        return $index;
1516225b270SMichael Große    }
1526225b270SMichael Große
1536225b270SMichael Große    /**
1546225b270SMichael Große     * Add/update keys to/of the metadata index.
1556225b270SMichael Große     *
1566225b270SMichael Große     * Adding new keys does not remove other keys for the page.
1576225b270SMichael Große     * An empty value will erase the key.
1586225b270SMichael Große     * The $key parameter can be an array to add multiple keys. $value will
1596225b270SMichael Große     * not be used if $key is an array.
1606225b270SMichael Große     *
1616225b270SMichael Große     * @param string    $page   a page name
1626225b270SMichael Große     * @param mixed     $key    a key string or array of key=>value pairs
1636225b270SMichael Große     * @param mixed     $value  the value or list of values
1646225b270SMichael Große     * @return boolean|string     the function completed successfully
1656225b270SMichael Große     *
1666225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
1676225b270SMichael Große     * @author Michael Hamann <michael@content-space.de>
1686225b270SMichael Große     */
169d868eb89SAndreas Gohr    public function addMetaKeys($page, $key, $value = null)
170d868eb89SAndreas Gohr    {
1716225b270SMichael Große        if (!is_array($key)) {
17224870174SAndreas Gohr            $key = [$key => $value];
1736225b270SMichael Große        } elseif (!is_null($value)) {
1746225b270SMichael Große            // $key is array, but $value is not null
1756225b270SMichael Große            trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING);
1766225b270SMichael Große        }
1776225b270SMichael Große
1786225b270SMichael Große        if (!$this->lock())
1796225b270SMichael Große            return "locked";
1806225b270SMichael Große
1816225b270SMichael Große        // load known documents
1826225b270SMichael Große        $pid = $this->getPIDNoLock($page);
1836225b270SMichael Große        if ($pid === false) {
1846225b270SMichael Große            $this->unlock();
1856225b270SMichael Große            return false;
1866225b270SMichael Große        }
1876225b270SMichael Große
1886225b270SMichael Große        // Special handling for titles so the index file is simpler
189ac1d8211SAndreas Gohr        if (isset($key['title'])) {
1906225b270SMichael Große            $value = $key['title'];
1916225b270SMichael Große            if (is_array($value)) {
1926225b270SMichael Große                $value = $value[0];
1936225b270SMichael Große            }
1946225b270SMichael Große            $this->saveIndexKey('title', '', $pid, $value);
1956225b270SMichael Große            unset($key['title']);
1966225b270SMichael Große        }
1976225b270SMichael Große
1986225b270SMichael Große        foreach ($key as $name => $values) {
1996225b270SMichael Große            $metaname = idx_cleanName($name);
2006225b270SMichael Große            $this->addIndexKey('metadata', '', $metaname);
2016225b270SMichael Große            $metaidx = $this->getIndex($metaname.'_i', '');
2026225b270SMichael Große            $metawords = $this->getIndex($metaname.'_w', '');
2036225b270SMichael Große            $addwords = false;
2046225b270SMichael Große
20524870174SAndreas Gohr            if (!is_array($values)) $values = [$values];
2066225b270SMichael Große
2076225b270SMichael Große            $val_idx = $this->getIndexKey($metaname.'_p', '', $pid);
2086225b270SMichael Große            if ($val_idx !== '') {
2096225b270SMichael Große                $val_idx = explode(':', $val_idx);
2106225b270SMichael Große                // -1 means remove, 0 keep, 1 add
2116225b270SMichael Große                $val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1));
2126225b270SMichael Große            } else {
21324870174SAndreas Gohr                $val_idx = [];
2146225b270SMichael Große            }
2156225b270SMichael Große
2166225b270SMichael Große            foreach ($values as $val) {
2176225b270SMichael Große                $val = (string)$val;
2186225b270SMichael Große                if ($val !== "") {
2196225b270SMichael Große                    $id = array_search($val, $metawords, true);
2206225b270SMichael Große                    if ($id === false) {
2216225b270SMichael Große                        // didn't find $val, so we'll add it to the end of metawords and create a placeholder in metaidx
2226225b270SMichael Große                        $id = count($metawords);
2236225b270SMichael Große                        $metawords[$id] = $val;
2246225b270SMichael Große                        $metaidx[$id] = '';
2256225b270SMichael Große                        $addwords = true;
2266225b270SMichael Große                    }
2276225b270SMichael Große                    // test if value is already in the index
2286225b270SMichael Große                    if (isset($val_idx[$id]) && $val_idx[$id] <= 0) {
2296225b270SMichael Große                        $val_idx[$id] = 0;
2306225b270SMichael Große                    } else { // else add it
2316225b270SMichael Große                        $val_idx[$id] = 1;
2326225b270SMichael Große                    }
2336225b270SMichael Große                }
2346225b270SMichael Große            }
2356225b270SMichael Große
2366225b270SMichael Große            if ($addwords) {
2376225b270SMichael Große                $this->saveIndex($metaname.'_w', '', $metawords);
2386225b270SMichael Große            }
2396225b270SMichael Große            $vals_changed = false;
2406225b270SMichael Große            foreach ($val_idx as $id => $action) {
2416225b270SMichael Große                if ($action == -1) {
2426225b270SMichael Große                    $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 0);
2436225b270SMichael Große                    $vals_changed = true;
2446225b270SMichael Große                    unset($val_idx[$id]);
2456225b270SMichael Große                } elseif ($action == 1) {
2466225b270SMichael Große                    $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 1);
2476225b270SMichael Große                    $vals_changed = true;
2486225b270SMichael Große                }
2496225b270SMichael Große            }
2506225b270SMichael Große
2516225b270SMichael Große            if ($vals_changed) {
2526225b270SMichael Große                $this->saveIndex($metaname.'_i', '', $metaidx);
2536225b270SMichael Große                $val_idx = implode(':', array_keys($val_idx));
2546225b270SMichael Große                $this->saveIndexKey($metaname.'_p', '', $pid, $val_idx);
2556225b270SMichael Große            }
2566225b270SMichael Große
2576225b270SMichael Große            unset($metaidx);
2586225b270SMichael Große            unset($metawords);
2596225b270SMichael Große        }
2606225b270SMichael Große
2616225b270SMichael Große        $this->unlock();
2626225b270SMichael Große        return true;
2636225b270SMichael Große    }
2646225b270SMichael Große
2656225b270SMichael Große    /**
2666225b270SMichael Große     * Rename a page in the search index without changing the indexed content. This function doesn't check if the
2676225b270SMichael Große     * old or new name exists in the filesystem. It returns an error if the old page isn't in the page list of the
2686225b270SMichael Große     * indexer and it deletes all previously indexed content of the new page.
2696225b270SMichael Große     *
2706225b270SMichael Große     * @param string $oldpage The old page name
2716225b270SMichael Große     * @param string $newpage The new page name
2726225b270SMichael Große     * @return string|bool If the page was successfully renamed, can be a message in the case of an error
2736225b270SMichael Große     */
274d868eb89SAndreas Gohr    public function renamePage($oldpage, $newpage)
275d868eb89SAndreas Gohr    {
2766225b270SMichael Große        if (!$this->lock()) return 'locked';
2776225b270SMichael Große
2786225b270SMichael Große        $pages = $this->getPages();
2796225b270SMichael Große
2806225b270SMichael Große        $id = array_search($oldpage, $pages, true);
2816225b270SMichael Große        if ($id === false) {
2826225b270SMichael Große            $this->unlock();
2836225b270SMichael Große            return 'page is not in index';
2846225b270SMichael Große        }
2856225b270SMichael Große
2866225b270SMichael Große        $new_id = array_search($newpage, $pages, true);
2876225b270SMichael Große        if ($new_id !== false) {
2886225b270SMichael Große            // make sure the page is not in the index anymore
28924870174SAndreas Gohr            if (!$this->deletePageNoLock($newpage)) {
2906225b270SMichael Große                return false;
2916225b270SMichael Große            }
2926225b270SMichael Große
29324870174SAndreas Gohr            $pages[$new_id] = 'deleted:'.time().random_int(0, 9999);
2946225b270SMichael Große        }
2956225b270SMichael Große
2966225b270SMichael Große        $pages[$id] = $newpage;
2976225b270SMichael Große
2986225b270SMichael Große        // update index
2996225b270SMichael Große        if (!$this->saveIndex('page', '', $pages)) {
3006225b270SMichael Große            $this->unlock();
3016225b270SMichael Große            return false;
3026225b270SMichael Große        }
3036225b270SMichael Große
3046225b270SMichael Große        // reset the pid cache
30524870174SAndreas Gohr        $this->pidCache = [];
3066225b270SMichael Große
3076225b270SMichael Große        $this->unlock();
3086225b270SMichael Große        return true;
3096225b270SMichael Große    }
3106225b270SMichael Große
3116225b270SMichael Große    /**
3126225b270SMichael Große     * Renames a meta value in the index. This doesn't change the meta value in the pages, it assumes that all pages
3136225b270SMichael Große     * will be updated.
3146225b270SMichael Große     *
3156225b270SMichael Große     * @param string $key       The metadata key of which a value shall be changed
3166225b270SMichael Große     * @param string $oldvalue  The old value that shall be renamed
3176225b270SMichael Große     * @param string $newvalue  The new value to which the old value shall be renamed, if exists values will be merged
3186225b270SMichael Große     * @return bool|string      If renaming the value has been successful, false or error message on error.
3196225b270SMichael Große     */
320d868eb89SAndreas Gohr    public function renameMetaValue($key, $oldvalue, $newvalue)
321d868eb89SAndreas Gohr    {
3226225b270SMichael Große        if (!$this->lock()) return 'locked';
3236225b270SMichael Große
3246225b270SMichael Große        // change the relation references index
3256225b270SMichael Große        $metavalues = $this->getIndex($key, '_w');
3266225b270SMichael Große        $oldid = array_search($oldvalue, $metavalues, true);
3276225b270SMichael Große        if ($oldid !== false) {
3286225b270SMichael Große            $newid = array_search($newvalue, $metavalues, true);
3296225b270SMichael Große            if ($newid !== false) {
3306225b270SMichael Große                // free memory
3316225b270SMichael Große                unset($metavalues);
3326225b270SMichael Große
3336225b270SMichael Große                // okay, now we have two entries for the same value. we need to merge them.
3346225b270SMichael Große                $indexline = $this->getIndexKey($key.'_i', '', $oldid);
3356225b270SMichael Große                if ($indexline != '') {
3366225b270SMichael Große                    $newindexline = $this->getIndexKey($key.'_i', '', $newid);
3376225b270SMichael Große                    $pagekeys     = $this->getIndex($key.'_p', '');
3386225b270SMichael Große                    $parts = explode(':', $indexline);
3396225b270SMichael Große                    foreach ($parts as $part) {
34024870174SAndreas Gohr                        [$id, $count] = explode('*', $part);
3416225b270SMichael Große                        $newindexline =  $this->updateTuple($newindexline, $id, $count);
3426225b270SMichael Große
3436225b270SMichael Große                        $keyline = explode(':', $pagekeys[$id]);
3446225b270SMichael Große                        // remove old meta value
34524870174SAndreas Gohr                        $keyline = array_diff($keyline, [$oldid]);
3466225b270SMichael Große                        // add new meta value when not already present
3476225b270SMichael Große                        if (!in_array($newid, $keyline)) {
34824870174SAndreas Gohr                            $keyline[] = $newid;
3496225b270SMichael Große                        }
3506225b270SMichael Große                        $pagekeys[$id] = implode(':', $keyline);
3516225b270SMichael Große                    }
3526225b270SMichael Große                    $this->saveIndex($key.'_p', '', $pagekeys);
3536225b270SMichael Große                    unset($pagekeys);
3546225b270SMichael Große                    $this->saveIndexKey($key.'_i', '', $oldid, '');
3556225b270SMichael Große                    $this->saveIndexKey($key.'_i', '', $newid, $newindexline);
3566225b270SMichael Große                }
3576225b270SMichael Große            } else {
3586225b270SMichael Große                $metavalues[$oldid] = $newvalue;
3596225b270SMichael Große                if (!$this->saveIndex($key.'_w', '', $metavalues)) {
3606225b270SMichael Große                    $this->unlock();
3616225b270SMichael Große                    return false;
3626225b270SMichael Große                }
3636225b270SMichael Große            }
3646225b270SMichael Große        }
3656225b270SMichael Große
3666225b270SMichael Große        $this->unlock();
3676225b270SMichael Große        return true;
3686225b270SMichael Große    }
3696225b270SMichael Große
3706225b270SMichael Große    /**
3716225b270SMichael Große     * Remove a page from the index
3726225b270SMichael Große     *
3736225b270SMichael Große     * Erases entries in all known indexes.
3746225b270SMichael Große     *
3756225b270SMichael Große     * @param string    $page   a page name
3766225b270SMichael Große     * @return string|boolean  the function completed successfully
3776225b270SMichael Große     *
3786225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
3796225b270SMichael Große     */
380d868eb89SAndreas Gohr    public function deletePage($page)
381d868eb89SAndreas Gohr    {
3826225b270SMichael Große        if (!$this->lock())
3836225b270SMichael Große            return "locked";
3846225b270SMichael Große
3856225b270SMichael Große        $result = $this->deletePageNoLock($page);
3866225b270SMichael Große
3876225b270SMichael Große        $this->unlock();
3886225b270SMichael Große
3896225b270SMichael Große        return $result;
3906225b270SMichael Große    }
3916225b270SMichael Große
3926225b270SMichael Große    /**
3936225b270SMichael Große     * Remove a page from the index without locking the index, only use this function if the index is already locked
3946225b270SMichael Große     *
3956225b270SMichael Große     * Erases entries in all known indexes.
3966225b270SMichael Große     *
3976225b270SMichael Große     * @param string    $page   a page name
3986225b270SMichael Große     * @return boolean          the function completed successfully
3996225b270SMichael Große     *
4006225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
4016225b270SMichael Große     */
402d868eb89SAndreas Gohr    protected function deletePageNoLock($page)
403d868eb89SAndreas Gohr    {
4046225b270SMichael Große        // load known documents
4056225b270SMichael Große        $pid = $this->getPIDNoLock($page);
4066225b270SMichael Große        if ($pid === false) {
4076225b270SMichael Große            return false;
4086225b270SMichael Große        }
4096225b270SMichael Große
4106225b270SMichael Große        // Remove obsolete index entries
4116225b270SMichael Große        $pageword_idx = $this->getIndexKey('pageword', '', $pid);
4126225b270SMichael Große        if ($pageword_idx !== '') {
4136225b270SMichael Große            $delwords = explode(':', $pageword_idx);
41424870174SAndreas Gohr            $upwords = [];
4156225b270SMichael Große            foreach ($delwords as $word) {
4166225b270SMichael Große                if ($word != '') {
41724870174SAndreas Gohr                    [$wlen, $wid] = explode('*', $word);
4186225b270SMichael Große                    $wid = (int)$wid;
4196225b270SMichael Große                    $upwords[$wlen][] = $wid;
4206225b270SMichael Große                }
4216225b270SMichael Große            }
4226225b270SMichael Große            foreach ($upwords as $wlen => $widx) {
4236225b270SMichael Große                $index = $this->getIndex('i', $wlen);
4246225b270SMichael Große                foreach ($widx as $wid) {
4256225b270SMichael Große                    $index[$wid] = $this->updateTuple($index[$wid], $pid, 0);
4266225b270SMichael Große                }
4276225b270SMichael Große                $this->saveIndex('i', $wlen, $index);
4286225b270SMichael Große            }
4296225b270SMichael Große        }
4306225b270SMichael Große        // Save the reverse index
4316225b270SMichael Große        if (!$this->saveIndexKey('pageword', '', $pid, "")) {
4326225b270SMichael Große            return false;
4336225b270SMichael Große        }
4346225b270SMichael Große
4356225b270SMichael Große        $this->saveIndexKey('title', '', $pid, "");
4366225b270SMichael Große        $keyidx = $this->getIndex('metadata', '');
4376225b270SMichael Große        foreach ($keyidx as $metaname) {
4386225b270SMichael Große            $val_idx = explode(':', $this->getIndexKey($metaname.'_p', '', $pid));
4396225b270SMichael Große            $meta_idx = $this->getIndex($metaname.'_i', '');
4406225b270SMichael Große            foreach ($val_idx as $id) {
4416225b270SMichael Große                if ($id === '') continue;
4426225b270SMichael Große                $meta_idx[$id] = $this->updateTuple($meta_idx[$id], $pid, 0);
4436225b270SMichael Große            }
4446225b270SMichael Große            $this->saveIndex($metaname.'_i', '', $meta_idx);
4456225b270SMichael Große            $this->saveIndexKey($metaname.'_p', '', $pid, '');
4466225b270SMichael Große        }
4476225b270SMichael Große
4486225b270SMichael Große        return true;
4496225b270SMichael Große    }
4506225b270SMichael Große
4516225b270SMichael Große    /**
4526225b270SMichael Große     * Clear the whole index
4536225b270SMichael Große     *
4546225b270SMichael Große     * @return bool If the index has been cleared successfully
4556225b270SMichael Große     */
456d868eb89SAndreas Gohr    public function clear()
457d868eb89SAndreas Gohr    {
4586225b270SMichael Große        global $conf;
4596225b270SMichael Große
4606225b270SMichael Große        if (!$this->lock()) return false;
4616225b270SMichael Große
4626225b270SMichael Große        @unlink($conf['indexdir'].'/page.idx');
4636225b270SMichael Große        @unlink($conf['indexdir'].'/title.idx');
4646225b270SMichael Große        @unlink($conf['indexdir'].'/pageword.idx');
4656225b270SMichael Große        @unlink($conf['indexdir'].'/metadata.idx');
4666225b270SMichael Große        $dir = @opendir($conf['indexdir']);
4676225b270SMichael Große        if ($dir!==false) {
4686225b270SMichael Große            while (($f = readdir($dir)) !== false) {
469*7d34963bSAndreas Gohr                if (
470*7d34963bSAndreas Gohr                    substr($f, -4)=='.idx' &&
471*7d34963bSAndreas Gohr                    (substr($f, 0, 1)=='i' ||
472*7d34963bSAndreas Gohr                    substr($f, 0, 1)=='w' ||
473*7d34963bSAndreas Gohr                        substr($f, -6)=='_w.idx' ||
474*7d34963bSAndreas Gohr                        substr($f, -6)=='_i.idx' ||
475*7d34963bSAndreas Gohr                        substr($f, -6)=='_p.idx')
476*7d34963bSAndreas Gohr                )
4776225b270SMichael Große                    @unlink($conf['indexdir']."/$f");
4786225b270SMichael Große            }
4796225b270SMichael Große        }
4806225b270SMichael Große        @unlink($conf['indexdir'].'/lengths.idx');
4816225b270SMichael Große
4826225b270SMichael Große        // clear the pid cache
48324870174SAndreas Gohr        $this->pidCache = [];
4846225b270SMichael Große
4856225b270SMichael Große        $this->unlock();
4866225b270SMichael Große        return true;
4876225b270SMichael Große    }
4886225b270SMichael Große
4896225b270SMichael Große    /**
4906225b270SMichael Große     * Split the text into words for fulltext search
4916225b270SMichael Große     *
4926225b270SMichael Große     * TODO: does this also need &$stopwords ?
4936225b270SMichael Große     *
4946225b270SMichael Große     * @triggers INDEXER_TEXT_PREPARE
4956225b270SMichael Große     * This event allows plugins to modify the text before it gets tokenized.
4966225b270SMichael Große     * Plugins intercepting this event should also intercept INDEX_VERSION_GET
4976225b270SMichael Große     *
4986225b270SMichael Große     * @param string    $text   plain text
4996225b270SMichael Große     * @param boolean   $wc     are wildcards allowed?
5006225b270SMichael Große     * @return array            list of words in the text
5016225b270SMichael Große     *
5026225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
5036225b270SMichael Große     * @author Andreas Gohr <andi@splitbrain.org>
5046225b270SMichael Große     */
505d868eb89SAndreas Gohr    public function tokenizer($text, $wc = false)
506d868eb89SAndreas Gohr    {
5076225b270SMichael Große        $wc = ($wc) ? '' : '\*';
5086225b270SMichael Große        $stopwords =& idx_get_stopwords();
5096225b270SMichael Große
5106225b270SMichael Große        // prepare the text to be tokenized
5116225b270SMichael Große        $evt = new Event('INDEXER_TEXT_PREPARE', $text);
5126225b270SMichael Große        if ($evt->advise_before(true)) {
5136225b270SMichael Große            if (preg_match('/[^0-9A-Za-z ]/u', $text)) {
51424870174SAndreas Gohr                $text = Asian::separateAsianWords($text);
5156225b270SMichael Große            }
5166225b270SMichael Große        }
5176225b270SMichael Große        $evt->advise_after();
5186225b270SMichael Große        unset($evt);
5196225b270SMichael Große
520dccd6b2bSAndreas Gohr        $text = strtr(
521dccd6b2bSAndreas Gohr            $text,
52224870174SAndreas Gohr            ["\r" => ' ', "\n" => ' ', "\t" => ' ', "\xC2\xAD" => '']
5236225b270SMichael Große        );
5246225b270SMichael Große        if (preg_match('/[^0-9A-Za-z ]/u', $text))
52524870174SAndreas Gohr            $text = Clean::stripspecials($text, ' ', '\._\-:'.$wc);
5266225b270SMichael Große
5276225b270SMichael Große        $wordlist = explode(' ', $text);
5286225b270SMichael Große        foreach ($wordlist as $i => $word) {
5296225b270SMichael Große            $wordlist[$i] = (preg_match('/[^0-9A-Za-z]/u', $word)) ?
53024870174SAndreas Gohr                PhpString::strtolower($word) : strtolower($word);
5316225b270SMichael Große        }
5326225b270SMichael Große
5336225b270SMichael Große        foreach ($wordlist as $i => $word) {
534*7d34963bSAndreas Gohr            if (
535*7d34963bSAndreas Gohr                (!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH)
536*7d34963bSAndreas Gohr                || in_array($word, $stopwords, true)
537*7d34963bSAndreas Gohr            )
5386225b270SMichael Große                unset($wordlist[$i]);
5396225b270SMichael Große        }
5406225b270SMichael Große        return array_values($wordlist);
5416225b270SMichael Große    }
5426225b270SMichael Große
5436225b270SMichael Große    /**
5446225b270SMichael Große     * Get the numeric PID of a page
5456225b270SMichael Große     *
5466225b270SMichael Große     * @param string $page The page to get the PID for
5476225b270SMichael Große     * @return bool|int The page id on success, false on error
5486225b270SMichael Große     */
549d868eb89SAndreas Gohr    public function getPID($page)
550d868eb89SAndreas Gohr    {
5516225b270SMichael Große        // return PID without locking when it is in the cache
5526225b270SMichael Große        if (isset($this->pidCache[$page])) return $this->pidCache[$page];
5536225b270SMichael Große
5546225b270SMichael Große        if (!$this->lock())
5556225b270SMichael Große            return false;
5566225b270SMichael Große
5576225b270SMichael Große        // load known documents
5586225b270SMichael Große        $pid = $this->getPIDNoLock($page);
5596225b270SMichael Große        if ($pid === false) {
5606225b270SMichael Große            $this->unlock();
5616225b270SMichael Große            return false;
5626225b270SMichael Große        }
5636225b270SMichael Große
5646225b270SMichael Große        $this->unlock();
5656225b270SMichael Große        return $pid;
5666225b270SMichael Große    }
5676225b270SMichael Große
5686225b270SMichael Große    /**
5696225b270SMichael Große     * Get the numeric PID of a page without locking the index.
5706225b270SMichael Große     * Only use this function when the index is already locked.
5716225b270SMichael Große     *
5726225b270SMichael Große     * @param string $page The page to get the PID for
5736225b270SMichael Große     * @return bool|int The page id on success, false on error
5746225b270SMichael Große     */
575d868eb89SAndreas Gohr    protected function getPIDNoLock($page)
576d868eb89SAndreas Gohr    {
5776225b270SMichael Große        // avoid expensive addIndexKey operation for the most recently requested pages by using a cache
5786225b270SMichael Große        if (isset($this->pidCache[$page])) return $this->pidCache[$page];
5796225b270SMichael Große        $pid = $this->addIndexKey('page', '', $page);
5806225b270SMichael Große        // limit cache to 10 entries by discarding the oldest element as in DokuWiki usually only the most recently
5816225b270SMichael Große        // added item will be requested again
5826225b270SMichael Große        if (count($this->pidCache) > 10) array_shift($this->pidCache);
5836225b270SMichael Große        $this->pidCache[$page] = $pid;
5846225b270SMichael Große        return $pid;
5856225b270SMichael Große    }
5866225b270SMichael Große
5876225b270SMichael Große    /**
5886225b270SMichael Große     * Get the page id of a numeric PID
5896225b270SMichael Große     *
5906225b270SMichael Große     * @param int $pid The PID to get the page id for
5916225b270SMichael Große     * @return string The page id
5926225b270SMichael Große     */
593d868eb89SAndreas Gohr    public function getPageFromPID($pid)
594d868eb89SAndreas Gohr    {
5956225b270SMichael Große        return $this->getIndexKey('page', '', $pid);
5966225b270SMichael Große    }
5976225b270SMichael Große
5986225b270SMichael Große    /**
5996225b270SMichael Große     * Find pages in the fulltext index containing the words,
6006225b270SMichael Große     *
6016225b270SMichael Große     * The search words must be pre-tokenized, meaning only letters and
6026225b270SMichael Große     * numbers with an optional wildcard
6036225b270SMichael Große     *
6046225b270SMichael Große     * The returned array will have the original tokens as key. The values
6056225b270SMichael Große     * in the returned list is an array with the page names as keys and the
6066225b270SMichael Große     * number of times that token appears on the page as value.
6076225b270SMichael Große     *
6086225b270SMichael Große     * @param array  $tokens list of words to search for
6096225b270SMichael Große     * @return array         list of page names with usage counts
6106225b270SMichael Große     *
6116225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
6126225b270SMichael Große     * @author Andreas Gohr <andi@splitbrain.org>
6136225b270SMichael Große     */
614d868eb89SAndreas Gohr    public function lookup(&$tokens)
615d868eb89SAndreas Gohr    {
61624870174SAndreas Gohr        $result = [];
6176225b270SMichael Große        $wids = $this->getIndexWords($tokens, $result);
61824870174SAndreas Gohr        if (empty($wids)) return [];
6196225b270SMichael Große        // load known words and documents
6206225b270SMichael Große        $page_idx = $this->getIndex('page', '');
62124870174SAndreas Gohr        $docs = [];
6226225b270SMichael Große        foreach (array_keys($wids) as $wlen) {
6236225b270SMichael Große            $wids[$wlen] = array_unique($wids[$wlen]);
6246225b270SMichael Große            $index = $this->getIndex('i', $wlen);
6256225b270SMichael Große            foreach ($wids[$wlen] as $ixid) {
6266225b270SMichael Große                if ($ixid < count($index))
6276225b270SMichael Große                    $docs["$wlen*$ixid"] = $this->parseTuples($page_idx, $index[$ixid]);
6286225b270SMichael Große            }
6296225b270SMichael Große        }
6306225b270SMichael Große        // merge found pages into final result array
63124870174SAndreas Gohr        $final = [];
6326225b270SMichael Große        foreach ($result as $word => $res) {
63324870174SAndreas Gohr            $final[$word] = [];
6346225b270SMichael Große            foreach ($res as $wid) {
6356225b270SMichael Große                // handle the case when ($ixid < count($index)) has been false
6366225b270SMichael Große                // and thus $docs[$wid] hasn't been set.
6376225b270SMichael Große                if (!isset($docs[$wid])) continue;
6386225b270SMichael Große                $hits = &$docs[$wid];
6396225b270SMichael Große                foreach ($hits as $hitkey => $hitcnt) {
6406225b270SMichael Große                    // make sure the document still exists
6416225b270SMichael Große                    if (!page_exists($hitkey, '', false)) continue;
6426225b270SMichael Große                    if (!isset($final[$word][$hitkey]))
6436225b270SMichael Große                        $final[$word][$hitkey] = $hitcnt;
644177d6836SAndreas Gohr                    else $final[$word][$hitkey] += $hitcnt;
6456225b270SMichael Große                }
6466225b270SMichael Große            }
6476225b270SMichael Große        }
6486225b270SMichael Große        return $final;
6496225b270SMichael Große    }
6506225b270SMichael Große
6516225b270SMichael Große    /**
6526225b270SMichael Große     * Find pages containing a metadata key.
6536225b270SMichael Große     *
6546225b270SMichael Große     * The metadata values are compared as case-sensitive strings. Pass a
6556225b270SMichael Große     * callback function that returns true or false to use a different
6566225b270SMichael Große     * comparison function. The function will be called with the $value being
6576225b270SMichael Große     * searched for as the first argument, and the word in the index as the
6586225b270SMichael Große     * second argument. The function preg_match can be used directly if the
6596225b270SMichael Große     * values are regexes.
6606225b270SMichael Große     *
6616225b270SMichael Große     * @param string    $key    name of the metadata key to look for
6626225b270SMichael Große     * @param string    $value  search term to look for, must be a string or array of strings
6636225b270SMichael Große     * @param callback  $func   comparison function
6646225b270SMichael Große     * @return array            lists with page names, keys are query values if $value is array
6656225b270SMichael Große     *
6666225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
6676225b270SMichael Große     * @author Michael Hamann <michael@content-space.de>
6686225b270SMichael Große     */
669d868eb89SAndreas Gohr    public function lookupKey($key, &$value, $func = null)
670d868eb89SAndreas Gohr    {
6716225b270SMichael Große        if (!is_array($value))
67224870174SAndreas Gohr            $value_array = [$value];
673177d6836SAndreas Gohr        else $value_array =& $value;
6746225b270SMichael Große
6756225b270SMichael Große        // the matching ids for the provided value(s)
67624870174SAndreas Gohr        $value_ids = [];
6776225b270SMichael Große
6786225b270SMichael Große        $metaname = idx_cleanName($key);
6796225b270SMichael Große
6806225b270SMichael Große        // get all words in order to search the matching ids
6816225b270SMichael Große        if ($key == 'title') {
6826225b270SMichael Große            $words = $this->getIndex('title', '');
6836225b270SMichael Große        } else {
6846225b270SMichael Große            $words = $this->getIndex($metaname.'_w', '');
6856225b270SMichael Große        }
6866225b270SMichael Große
6876225b270SMichael Große        if (!is_null($func)) {
6886225b270SMichael Große            foreach ($value_array as $val) {
6896225b270SMichael Große                foreach ($words as $i => $word) {
69024870174SAndreas Gohr                    if (call_user_func_array($func, [$val, $word]))
6916225b270SMichael Große                        $value_ids[$i][] = $val;
6926225b270SMichael Große                }
6936225b270SMichael Große            }
6946225b270SMichael Große        } else {
6956225b270SMichael Große            foreach ($value_array as $val) {
6966225b270SMichael Große                $xval = $val;
6976225b270SMichael Große                $caret = '^';
6986225b270SMichael Große                $dollar = '$';
6996225b270SMichael Große                // check for wildcards
7006225b270SMichael Große                if (substr($xval, 0, 1) == '*') {
7016225b270SMichael Große                    $xval = substr($xval, 1);
7026225b270SMichael Große                    $caret = '';
7036225b270SMichael Große                }
7046225b270SMichael Große                if (substr($xval, -1, 1) == '*') {
7056225b270SMichael Große                    $xval = substr($xval, 0, -1);
7066225b270SMichael Große                    $dollar = '';
7076225b270SMichael Große                }
7086225b270SMichael Große                if (!$caret || !$dollar) {
7096225b270SMichael Große                    $re = $caret.preg_quote($xval, '/').$dollar;
7106225b270SMichael Große                    foreach (array_keys(preg_grep('/'.$re.'/', $words)) as $i)
7116225b270SMichael Große                        $value_ids[$i][] = $val;
71224870174SAndreas Gohr                } elseif (($i = array_search($val, $words, true)) !== false) {
7136225b270SMichael Große                    $value_ids[$i][] = $val;
7146225b270SMichael Große                }
7156225b270SMichael Große            }
7166225b270SMichael Große        }
7176225b270SMichael Große
7186225b270SMichael Große        unset($words); // free the used memory
7196225b270SMichael Große
7206225b270SMichael Große        // initialize the result so it won't be null
72124870174SAndreas Gohr        $result = [];
7226225b270SMichael Große        foreach ($value_array as $val) {
72324870174SAndreas Gohr            $result[$val] = [];
7246225b270SMichael Große        }
7256225b270SMichael Große
7266225b270SMichael Große        $page_idx = $this->getIndex('page', '');
7276225b270SMichael Große
7286225b270SMichael Große        // Special handling for titles
7296225b270SMichael Große        if ($key == 'title') {
7306225b270SMichael Große            foreach ($value_ids as $pid => $val_list) {
7316225b270SMichael Große                $page = $page_idx[$pid];
7326225b270SMichael Große                foreach ($val_list as $val) {
7336225b270SMichael Große                    $result[$val][] = $page;
7346225b270SMichael Große                }
7356225b270SMichael Große            }
7366225b270SMichael Große        } else {
7376225b270SMichael Große            // load all lines and pages so the used lines can be taken and matched with the pages
7386225b270SMichael Große            $lines = $this->getIndex($metaname.'_i', '');
7396225b270SMichael Große
7406225b270SMichael Große            foreach ($value_ids as $value_id => $val_list) {
7416225b270SMichael Große                // parse the tuples of the form page_id*1:page2_id*1 and so on, return value
7426225b270SMichael Große                // is an array with page_id => 1, page2_id => 1 etc. so take the keys only
7436225b270SMichael Große                $pages = array_keys($this->parseTuples($page_idx, $lines[$value_id]));
7446225b270SMichael Große                foreach ($val_list as $val) {
74524870174SAndreas Gohr                    $result[$val] = [...$result[$val], ...$pages];
7466225b270SMichael Große                }
7476225b270SMichael Große            }
7486225b270SMichael Große        }
7496225b270SMichael Große        if (!is_array($value)) $result = $result[$value];
7506225b270SMichael Große        return $result;
7516225b270SMichael Große    }
7526225b270SMichael Große
7536225b270SMichael Große    /**
7546225b270SMichael Große     * Find the index ID of each search term.
7556225b270SMichael Große     *
7566225b270SMichael Große     * The query terms should only contain valid characters, with a '*' at
7576225b270SMichael Große     * either the beginning or end of the word (or both).
7586225b270SMichael Große     * The $result parameter can be used to merge the index locations with
7596225b270SMichael Große     * the appropriate query term.
7606225b270SMichael Große     *
7616225b270SMichael Große     * @param array  $words  The query terms.
7626225b270SMichael Große     * @param array  $result Set to word => array("length*id" ...)
7636225b270SMichael Große     * @return array         Set to length => array(id ...)
7646225b270SMichael Große     *
7656225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
7666225b270SMichael Große     */
767d868eb89SAndreas Gohr    protected function getIndexWords(&$words, &$result)
768d868eb89SAndreas Gohr    {
76924870174SAndreas Gohr        $tokens = [];
77024870174SAndreas Gohr        $tokenlength = [];
77124870174SAndreas Gohr        $tokenwild = [];
7726225b270SMichael Große        foreach ($words as $word) {
77324870174SAndreas Gohr            $result[$word] = [];
7746225b270SMichael Große            $caret = '^';
7756225b270SMichael Große            $dollar = '$';
7766225b270SMichael Große            $xword = $word;
7776225b270SMichael Große            $wlen = wordlen($word);
7786225b270SMichael Große
7796225b270SMichael Große            // check for wildcards
7806225b270SMichael Große            if (substr($xword, 0, 1) == '*') {
7816225b270SMichael Große                $xword = substr($xword, 1);
7826225b270SMichael Große                $caret = '';
78324870174SAndreas Gohr                --$wlen;
7846225b270SMichael Große            }
7856225b270SMichael Große            if (substr($xword, -1, 1) == '*') {
7866225b270SMichael Große                $xword = substr($xword, 0, -1);
7876225b270SMichael Große                $dollar = '';
78824870174SAndreas Gohr                --$wlen;
7896225b270SMichael Große            }
7906225b270SMichael Große            if ($wlen < IDX_MINWORDLENGTH && $caret && $dollar && !is_numeric($xword))
7916225b270SMichael Große                continue;
7926225b270SMichael Große            if (!isset($tokens[$xword]))
7936225b270SMichael Große                $tokenlength[$wlen][] = $xword;
7946225b270SMichael Große            if (!$caret || !$dollar) {
7956225b270SMichael Große                $re = $caret.preg_quote($xword, '/').$dollar;
79624870174SAndreas Gohr                $tokens[$xword][] = [$word, '/'.$re.'/'];
7976225b270SMichael Große                if (!isset($tokenwild[$xword]))
7986225b270SMichael Große                    $tokenwild[$xword] = $wlen;
7996225b270SMichael Große            } else {
80024870174SAndreas Gohr                $tokens[$xword][] = [$word, null];
8016225b270SMichael Große            }
8026225b270SMichael Große        }
8036225b270SMichael Große        asort($tokenwild);
8046225b270SMichael Große        // $tokens = array( base word => array( [ query term , regexp ] ... ) ... )
8056225b270SMichael Große        // $tokenlength = array( base word length => base word ... )
8066225b270SMichael Große        // $tokenwild = array( base word => base word length ... )
80724870174SAndreas Gohr        $length_filter = $tokenwild === [] ? $tokenlength : min(array_keys($tokenlength));
8086225b270SMichael Große        $indexes_known = $this->indexLengths($length_filter);
80924870174SAndreas Gohr        if ($tokenwild !== []) sort($indexes_known);
8106225b270SMichael Große        // get word IDs
81124870174SAndreas Gohr        $wids = [];
8126225b270SMichael Große        foreach ($indexes_known as $ixlen) {
8136225b270SMichael Große            $word_idx = $this->getIndex('w', $ixlen);
8146225b270SMichael Große            // handle exact search
8156225b270SMichael Große            if (isset($tokenlength[$ixlen])) {
8166225b270SMichael Große                foreach ($tokenlength[$ixlen] as $xword) {
8176225b270SMichael Große                    $wid = array_search($xword, $word_idx, true);
8186225b270SMichael Große                    if ($wid !== false) {
8196225b270SMichael Große                        $wids[$ixlen][] = $wid;
8206225b270SMichael Große                        foreach ($tokens[$xword] as $w)
8216225b270SMichael Große                            $result[$w[0]][] = "$ixlen*$wid";
8226225b270SMichael Große                    }
8236225b270SMichael Große                }
8246225b270SMichael Große            }
8256225b270SMichael Große            // handle wildcard search
8266225b270SMichael Große            foreach ($tokenwild as $xword => $wlen) {
8276225b270SMichael Große                if ($wlen >= $ixlen) break;
8286225b270SMichael Große                foreach ($tokens[$xword] as $w) {
8296225b270SMichael Große                    if (is_null($w[1])) continue;
8306225b270SMichael Große                    foreach (array_keys(preg_grep($w[1], $word_idx)) as $wid) {
8316225b270SMichael Große                        $wids[$ixlen][] = $wid;
8326225b270SMichael Große                        $result[$w[0]][] = "$ixlen*$wid";
8336225b270SMichael Große                    }
8346225b270SMichael Große                }
8356225b270SMichael Große            }
8366225b270SMichael Große        }
8376225b270SMichael Große        return $wids;
8386225b270SMichael Große    }
8396225b270SMichael Große
8406225b270SMichael Große    /**
8416225b270SMichael Große     * Return a list of all pages
8426225b270SMichael Große     * Warning: pages may not exist!
8436225b270SMichael Große     *
8446225b270SMichael Große     * @param string    $key    list only pages containing the metadata key (optional)
8456225b270SMichael Große     * @return array            list of page names
8466225b270SMichael Große     *
8476225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
8486225b270SMichael Große     */
849d868eb89SAndreas Gohr    public function getPages($key = null)
850d868eb89SAndreas Gohr    {
8516225b270SMichael Große        $page_idx = $this->getIndex('page', '');
8526225b270SMichael Große        if (is_null($key)) return $page_idx;
8536225b270SMichael Große
8546225b270SMichael Große        $metaname = idx_cleanName($key);
8556225b270SMichael Große
8566225b270SMichael Große        // Special handling for titles
8576225b270SMichael Große        if ($key == 'title') {
8586225b270SMichael Große            $title_idx = $this->getIndex('title', '');
8596225b270SMichael Große            array_splice($page_idx, count($title_idx));
8606225b270SMichael Große            foreach ($title_idx as $i => $title)
8616225b270SMichael Große                if ($title === "") unset($page_idx[$i]);
8626225b270SMichael Große            return array_values($page_idx);
8636225b270SMichael Große        }
8646225b270SMichael Große
86524870174SAndreas Gohr        $pages = [];
8666225b270SMichael Große        $lines = $this->getIndex($metaname.'_i', '');
8676225b270SMichael Große        foreach ($lines as $line) {
8686225b270SMichael Große            $pages = array_merge($pages, $this->parseTuples($page_idx, $line));
8696225b270SMichael Große        }
8706225b270SMichael Große        return array_keys($pages);
8716225b270SMichael Große    }
8726225b270SMichael Große
8736225b270SMichael Große    /**
8746225b270SMichael Große     * Return a list of words sorted by number of times used
8756225b270SMichael Große     *
8766225b270SMichael Große     * @param int       $min    bottom frequency threshold
8776225b270SMichael Große     * @param int       $max    upper frequency limit. No limit if $max<$min
8786225b270SMichael Große     * @param int       $minlen minimum length of words to count
8796225b270SMichael Große     * @param string    $key    metadata key to list. Uses the fulltext index if not given
8806225b270SMichael Große     * @return array            list of words as the keys and frequency as values
8816225b270SMichael Große     *
8826225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
8836225b270SMichael Große     */
884d868eb89SAndreas Gohr    public function histogram($min = 1, $max = 0, $minlen = 3, $key = null)
885d868eb89SAndreas Gohr    {
8866225b270SMichael Große        if ($min < 1)
8876225b270SMichael Große            $min = 1;
8886225b270SMichael Große        if ($max < $min)
8896225b270SMichael Große            $max = 0;
8906225b270SMichael Große
89124870174SAndreas Gohr        $result = [];
8926225b270SMichael Große
8936225b270SMichael Große        if ($key == 'title') {
8946225b270SMichael Große            $index = $this->getIndex('title', '');
8956225b270SMichael Große            $index = array_count_values($index);
8966225b270SMichael Große            foreach ($index as $val => $cnt) {
8976225b270SMichael Große                if ($cnt >= $min && (!$max || $cnt <= $max) && strlen($val) >= $minlen)
8986225b270SMichael Große                    $result[$val] = $cnt;
8996225b270SMichael Große            }
900177d6836SAndreas Gohr        } elseif (!is_null($key)) {
9016225b270SMichael Große            $metaname = idx_cleanName($key);
9026225b270SMichael Große            $index = $this->getIndex($metaname.'_i', '');
90324870174SAndreas Gohr            $val_idx = [];
9046225b270SMichael Große            foreach ($index as $wid => $line) {
9056225b270SMichael Große                $freq = $this->countTuples($line);
9066225b270SMichael Große                if ($freq >= $min && (!$max || $freq <= $max))
9076225b270SMichael Große                    $val_idx[$wid] = $freq;
9086225b270SMichael Große            }
9096225b270SMichael Große            if (!empty($val_idx)) {
9106225b270SMichael Große                $words = $this->getIndex($metaname.'_w', '');
9116225b270SMichael Große                foreach ($val_idx as $wid => $freq) {
9126225b270SMichael Große                    if (strlen($words[$wid]) >= $minlen)
9136225b270SMichael Große                        $result[$words[$wid]] = $freq;
9146225b270SMichael Große                }
9156225b270SMichael Große            }
916177d6836SAndreas Gohr        } else {
9176225b270SMichael Große            $lengths = idx_listIndexLengths();
9186225b270SMichael Große            foreach ($lengths as $length) {
9196225b270SMichael Große                if ($length < $minlen) continue;
9206225b270SMichael Große                $index = $this->getIndex('i', $length);
9216225b270SMichael Große                $words = null;
9226225b270SMichael Große                foreach ($index as $wid => $line) {
9236225b270SMichael Große                    $freq = $this->countTuples($line);
9246225b270SMichael Große                    if ($freq >= $min && (!$max || $freq <= $max)) {
9256225b270SMichael Große                        if ($words === null)
9266225b270SMichael Große                            $words = $this->getIndex('w', $length);
9276225b270SMichael Große                        $result[$words[$wid]] = $freq;
9286225b270SMichael Große                    }
9296225b270SMichael Große                }
9306225b270SMichael Große            }
9316225b270SMichael Große        }
9326225b270SMichael Große
9336225b270SMichael Große        arsort($result);
9346225b270SMichael Große        return $result;
9356225b270SMichael Große    }
9366225b270SMichael Große
9376225b270SMichael Große    /**
9386225b270SMichael Große     * Lock the indexer.
9396225b270SMichael Große     *
9406225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
9416225b270SMichael Große     *
9426225b270SMichael Große     * @return bool|string
9436225b270SMichael Große     */
944d868eb89SAndreas Gohr    protected function lock()
945d868eb89SAndreas Gohr    {
9466225b270SMichael Große        global $conf;
9476225b270SMichael Große        $status = true;
9486225b270SMichael Große        $run = 0;
9496225b270SMichael Große        $lock = $conf['lockdir'].'/_indexer.lock';
950bd539124SAndreas Gohr        while (!@mkdir($lock)) {
9516225b270SMichael Große            usleep(50);
9526225b270SMichael Große            if (is_dir($lock) && time()-@filemtime($lock) > 60*5) {
9536225b270SMichael Große                // looks like a stale lock - remove it
9546225b270SMichael Große                if (!@rmdir($lock)) {
9556225b270SMichael Große                    $status = "removing the stale lock failed";
9566225b270SMichael Große                    return false;
9576225b270SMichael Große                } else {
9586225b270SMichael Große                    $status = "stale lock removed";
9596225b270SMichael Große                }
9606225b270SMichael Große            } elseif ($run++ == 1000) {
9616225b270SMichael Große                // we waited 5 seconds for that lock
9626225b270SMichael Große                return false;
9636225b270SMichael Große            }
9646225b270SMichael Große        }
96523420346SDamien Regad        if ($conf['dperm']) {
9666225b270SMichael Große            chmod($lock, $conf['dperm']);
9676225b270SMichael Große        }
9686225b270SMichael Große        return $status;
9696225b270SMichael Große    }
9706225b270SMichael Große
9716225b270SMichael Große    /**
9726225b270SMichael Große     * Release the indexer lock.
9736225b270SMichael Große     *
9746225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
9756225b270SMichael Große     *
9766225b270SMichael Große     * @return bool
9776225b270SMichael Große     */
978d868eb89SAndreas Gohr    protected function unlock()
979d868eb89SAndreas Gohr    {
9806225b270SMichael Große        global $conf;
9816225b270SMichael Große        @rmdir($conf['lockdir'].'/_indexer.lock');
9826225b270SMichael Große        return true;
9836225b270SMichael Große    }
9846225b270SMichael Große
9856225b270SMichael Große    /**
9866225b270SMichael Große     * Retrieve the entire index.
9876225b270SMichael Große     *
9886225b270SMichael Große     * The $suffix argument is for an index that is split into
9896225b270SMichael Große     * multiple parts. Different index files should use different
9906225b270SMichael Große     * base names.
9916225b270SMichael Große     *
9926225b270SMichael Große     * @param string    $idx    name of the index
9936225b270SMichael Große     * @param string    $suffix subpart identifier
9946225b270SMichael Große     * @return array            list of lines without CR or LF
9956225b270SMichael Große     *
9966225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
9976225b270SMichael Große     */
998d868eb89SAndreas Gohr    protected function getIndex($idx, $suffix)
999d868eb89SAndreas Gohr    {
10006225b270SMichael Große        global $conf;
10016225b270SMichael Große        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
100224870174SAndreas Gohr        if (!file_exists($fn)) return [];
10036225b270SMichael Große        return file($fn, FILE_IGNORE_NEW_LINES);
10046225b270SMichael Große    }
10056225b270SMichael Große
10066225b270SMichael Große    /**
10076225b270SMichael Große     * Replace the contents of the index with an array.
10086225b270SMichael Große     *
10096225b270SMichael Große     * @param string    $idx    name of the index
10106225b270SMichael Große     * @param string    $suffix subpart identifier
10116225b270SMichael Große     * @param array     $lines  list of lines without LF
10126225b270SMichael Große     * @return bool             If saving succeeded
10136225b270SMichael Große     *
10146225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
10156225b270SMichael Große     */
1016d868eb89SAndreas Gohr    protected function saveIndex($idx, $suffix, &$lines)
1017d868eb89SAndreas Gohr    {
10186225b270SMichael Große        global $conf;
10196225b270SMichael Große        $fn = $conf['indexdir'].'/'.$idx.$suffix;
10206225b270SMichael Große        $fh = @fopen($fn.'.tmp', 'w');
10216225b270SMichael Große        if (!$fh) return false;
102224870174SAndreas Gohr        fwrite($fh, implode("\n", $lines));
10236225b270SMichael Große        if (!empty($lines))
10246225b270SMichael Große            fwrite($fh, "\n");
10256225b270SMichael Große        fclose($fh);
10263aa75874Smovatica        if ($conf['fperm'])
10276225b270SMichael Große            chmod($fn.'.tmp', $conf['fperm']);
10286225b270SMichael Große        io_rename($fn.'.tmp', $fn.'.idx');
10296225b270SMichael Große        return true;
10306225b270SMichael Große    }
10316225b270SMichael Große
10326225b270SMichael Große    /**
10336225b270SMichael Große     * Retrieve a line from the index.
10346225b270SMichael Große     *
10356225b270SMichael Große     * @param string    $idx    name of the index
10366225b270SMichael Große     * @param string    $suffix subpart identifier
10376225b270SMichael Große     * @param int       $id     the line number
10386225b270SMichael Große     * @return string           a line with trailing whitespace removed
10396225b270SMichael Große     *
10406225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
10416225b270SMichael Große     */
1042d868eb89SAndreas Gohr    protected function getIndexKey($idx, $suffix, $id)
1043d868eb89SAndreas Gohr    {
10446225b270SMichael Große        global $conf;
10456225b270SMichael Große        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
10466225b270SMichael Große        if (!file_exists($fn)) return '';
10476225b270SMichael Große        $fh = @fopen($fn, 'r');
10486225b270SMichael Große        if (!$fh) return '';
10496225b270SMichael Große        $ln = -1;
10506225b270SMichael Große        while (($line = fgets($fh)) !== false) {
10516225b270SMichael Große            if (++$ln == $id) break;
10526225b270SMichael Große        }
10536225b270SMichael Große        fclose($fh);
10546225b270SMichael Große        return rtrim((string)$line);
10556225b270SMichael Große    }
10566225b270SMichael Große
10576225b270SMichael Große    /**
10586225b270SMichael Große     * Write a line into the index.
10596225b270SMichael Große     *
10606225b270SMichael Große     * @param string    $idx    name of the index
10616225b270SMichael Große     * @param string    $suffix subpart identifier
10626225b270SMichael Große     * @param int       $id     the line number
10636225b270SMichael Große     * @param string    $line   line to write
10646225b270SMichael Große     * @return bool             If saving succeeded
10656225b270SMichael Große     *
10666225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
10676225b270SMichael Große     */
1068d868eb89SAndreas Gohr    protected function saveIndexKey($idx, $suffix, $id, $line)
1069d868eb89SAndreas Gohr    {
10706225b270SMichael Große        global $conf;
10716225b270SMichael Große        if (substr($line, -1) != "\n")
10726225b270SMichael Große            $line .= "\n";
10736225b270SMichael Große        $fn = $conf['indexdir'].'/'.$idx.$suffix;
10746225b270SMichael Große        $fh = @fopen($fn.'.tmp', 'w');
10756225b270SMichael Große        if (!$fh) return false;
10766225b270SMichael Große        $ih = @fopen($fn.'.idx', 'r');
10776225b270SMichael Große        if ($ih) {
10786225b270SMichael Große            $ln = -1;
10796225b270SMichael Große            while (($curline = fgets($ih)) !== false) {
10806225b270SMichael Große                fwrite($fh, (++$ln == $id) ? $line : $curline);
10816225b270SMichael Große            }
10826225b270SMichael Große            if ($id > $ln) {
10836225b270SMichael Große                while ($id > ++$ln)
10846225b270SMichael Große                    fwrite($fh, "\n");
10856225b270SMichael Große                fwrite($fh, $line);
10866225b270SMichael Große            }
10876225b270SMichael Große            fclose($ih);
10886225b270SMichael Große        } else {
10896225b270SMichael Große            $ln = -1;
10906225b270SMichael Große            while ($id > ++$ln)
10916225b270SMichael Große                fwrite($fh, "\n");
10926225b270SMichael Große            fwrite($fh, $line);
10936225b270SMichael Große        }
10946225b270SMichael Große        fclose($fh);
10953aa75874Smovatica        if ($conf['fperm'])
10966225b270SMichael Große            chmod($fn.'.tmp', $conf['fperm']);
10976225b270SMichael Große        io_rename($fn.'.tmp', $fn.'.idx');
10986225b270SMichael Große        return true;
10996225b270SMichael Große    }
11006225b270SMichael Große
11016225b270SMichael Große    /**
11026225b270SMichael Große     * Retrieve or insert a value in the index.
11036225b270SMichael Große     *
11046225b270SMichael Große     * @param string    $idx    name of the index
11056225b270SMichael Große     * @param string    $suffix subpart identifier
11066225b270SMichael Große     * @param string    $value  line to find in the index
11076225b270SMichael Große     * @return int|bool          line number of the value in the index or false if writing the index failed
11086225b270SMichael Große     *
11096225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
11106225b270SMichael Große     */
1111d868eb89SAndreas Gohr    protected function addIndexKey($idx, $suffix, $value)
1112d868eb89SAndreas Gohr    {
11136225b270SMichael Große        $index = $this->getIndex($idx, $suffix);
11146225b270SMichael Große        $id = array_search($value, $index, true);
11156225b270SMichael Große        if ($id === false) {
11166225b270SMichael Große            $id = count($index);
11176225b270SMichael Große            $index[$id] = $value;
11186225b270SMichael Große            if (!$this->saveIndex($idx, $suffix, $index)) {
11196225b270SMichael Große                trigger_error("Failed to write $idx index", E_USER_ERROR);
11206225b270SMichael Große                return false;
11216225b270SMichael Große            }
11226225b270SMichael Große        }
11236225b270SMichael Große        return $id;
11246225b270SMichael Große    }
11256225b270SMichael Große
11266225b270SMichael Große    /**
11276225b270SMichael Große     * Get the list of lengths indexed in the wiki.
11286225b270SMichael Große     *
11296225b270SMichael Große     * Read the index directory or a cache file and returns
11306225b270SMichael Große     * a sorted array of lengths of the words used in the wiki.
11316225b270SMichael Große     *
11326225b270SMichael Große     * @author YoBoY <yoboy.leguesh@gmail.com>
11336225b270SMichael Große     *
11346225b270SMichael Große     * @return array
11356225b270SMichael Große     */
1136d868eb89SAndreas Gohr    protected function listIndexLengths()
1137d868eb89SAndreas Gohr    {
11386225b270SMichael Große        return idx_listIndexLengths();
11396225b270SMichael Große    }
11406225b270SMichael Große
11416225b270SMichael Große    /**
11426225b270SMichael Große     * Get the word lengths that have been indexed.
11436225b270SMichael Große     *
11446225b270SMichael Große     * Reads the index directory and returns an array of lengths
11456225b270SMichael Große     * that there are indices for.
11466225b270SMichael Große     *
11476225b270SMichael Große     * @author YoBoY <yoboy.leguesh@gmail.com>
11486225b270SMichael Große     *
11496225b270SMichael Große     * @param array|int $filter
11506225b270SMichael Große     * @return array
11516225b270SMichael Große     */
1152d868eb89SAndreas Gohr    protected function indexLengths($filter)
1153d868eb89SAndreas Gohr    {
11546225b270SMichael Große        global $conf;
115524870174SAndreas Gohr        $idx = [];
11566225b270SMichael Große        if (is_array($filter)) {
11576225b270SMichael Große            // testing if index files exist only
11586225b270SMichael Große            $path = $conf['indexdir']."/i";
115924870174SAndreas Gohr            foreach (array_keys($filter) as $key) {
11606225b270SMichael Große                if (file_exists($path.$key.'.idx'))
11616225b270SMichael Große                    $idx[] = $key;
11626225b270SMichael Große            }
11636225b270SMichael Große        } else {
11646225b270SMichael Große            $lengths = idx_listIndexLengths();
116524870174SAndreas Gohr            foreach ($lengths as $length) {
11666225b270SMichael Große                // keep all the values equal or superior
11676225b270SMichael Große                if ((int)$length >= (int)$filter)
11686225b270SMichael Große                    $idx[] = $length;
11696225b270SMichael Große            }
11706225b270SMichael Große        }
11716225b270SMichael Große        return $idx;
11726225b270SMichael Große    }
11736225b270SMichael Große
11746225b270SMichael Große    /**
11756225b270SMichael Große     * Insert or replace a tuple in a line.
11766225b270SMichael Große     *
11776225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
11786225b270SMichael Große     *
11796225b270SMichael Große     * @param string $line
11806225b270SMichael Große     * @param string|int $id
11816225b270SMichael Große     * @param int    $count
11826225b270SMichael Große     * @return string
11836225b270SMichael Große     */
1184d868eb89SAndreas Gohr    protected function updateTuple($line, $id, $count)
1185d868eb89SAndreas Gohr    {
11866225b270SMichael Große        if ($line != '') {
11876225b270SMichael Große            $line = preg_replace('/(^|:)'.preg_quote($id, '/').'\*\d*/', '', $line);
11886225b270SMichael Große        }
11896225b270SMichael Große        $line = trim($line, ':');
11906225b270SMichael Große        if ($count) {
11916225b270SMichael Große            if ($line) {
11926225b270SMichael Große                return "$id*$count:".$line;
11936225b270SMichael Große            } else {
11946225b270SMichael Große                return "$id*$count";
11956225b270SMichael Große            }
11966225b270SMichael Große        }
11976225b270SMichael Große        return $line;
11986225b270SMichael Große    }
11996225b270SMichael Große
12006225b270SMichael Große    /**
12016225b270SMichael Große     * Split a line into an array of tuples.
12026225b270SMichael Große     *
12036225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
12046225b270SMichael Große     * @author Andreas Gohr <andi@splitbrain.org>
12056225b270SMichael Große     *
12066225b270SMichael Große     * @param array $keys
12076225b270SMichael Große     * @param string $line
12086225b270SMichael Große     * @return array
12096225b270SMichael Große     */
1210d868eb89SAndreas Gohr    protected function parseTuples(&$keys, $line)
1211d868eb89SAndreas Gohr    {
121224870174SAndreas Gohr        $result = [];
12136225b270SMichael Große        if ($line == '') return $result;
12146225b270SMichael Große        $parts = explode(':', $line);
12156225b270SMichael Große        foreach ($parts as $tuple) {
12166225b270SMichael Große            if ($tuple === '') continue;
121724870174SAndreas Gohr            [$key, $cnt] = explode('*', $tuple);
12186225b270SMichael Große            if (!$cnt) continue;
12197c392639SDamien Regad            if (isset($keys[$key])) {
12206225b270SMichael Große                $key = $keys[$key];
12216225b270SMichael Große                if ($key === false || is_null($key)) continue;
12227c392639SDamien Regad            }
12236225b270SMichael Große            $result[$key] = $cnt;
12246225b270SMichael Große        }
12256225b270SMichael Große        return $result;
12266225b270SMichael Große    }
12276225b270SMichael Große
12286225b270SMichael Große    /**
12296225b270SMichael Große     * Sum the counts in a list of tuples.
12306225b270SMichael Große     *
12316225b270SMichael Große     * @author Tom N Harris <tnharris@whoopdedo.org>
12326225b270SMichael Große     *
12336225b270SMichael Große     * @param string $line
12346225b270SMichael Große     * @return int
12356225b270SMichael Große     */
1236d868eb89SAndreas Gohr    protected function countTuples($line)
1237d868eb89SAndreas Gohr    {
12386225b270SMichael Große        $freq = 0;
12396225b270SMichael Große        $parts = explode(':', $line);
12406225b270SMichael Große        foreach ($parts as $tuple) {
12416225b270SMichael Große            if ($tuple === '') continue;
1242a19c9aa0SGerrit Uitslag            [/* pid */, $cnt] = explode('*', $tuple);
12436225b270SMichael Große            $freq += (int)$cnt;
12446225b270SMichael Große        }
12456225b270SMichael Große        return $freq;
12466225b270SMichael Große    }
12476225b270SMichael Große}
1248