xref: /dokuwiki/inc/Search/Indexer.php (revision 177d6836e2f75d0e404be9c566e61725852a1e07)
1<?php
2
3namespace dokuwiki\Search;
4
5use dokuwiki\Utf8\Asian;
6use dokuwiki\Utf8\Clean;
7use dokuwiki\Utf8\PhpString;
8use dokuwiki\Extension\Event;
9
10/**
11 * Class that encapsulates operations on the indexer database.
12 *
13 * @author Tom N Harris <tnharris@whoopdedo.org>
14 */
15class Indexer
16{
17    /**
18     * @var array $pidCache Cache for getPID()
19     */
20    protected $pidCache = [];
21
22    /**
23     * Adds the contents of a page to the fulltext index
24     *
25     * The added text replaces previous words for the same page.
26     * An empty value erases the page.
27     *
28     * @param string    $page   a page name
29     * @param string    $text   the body of the page
30     * @return string|boolean  the function completed successfully
31     *
32     * @author Tom N Harris <tnharris@whoopdedo.org>
33     * @author Andreas Gohr <andi@splitbrain.org>
34     */
35    public function addPageWords($page, $text)
36    {
37        if (!$this->lock())
38            return "locked";
39
40        // load known documents
41        $pid = $this->getPIDNoLock($page);
42        if ($pid === false) {
43            $this->unlock();
44            return false;
45        }
46
47        $pagewords = [];
48        // get word usage in page
49        $words = $this->getPageWords($text);
50        if ($words === false) {
51            $this->unlock();
52            return false;
53        }
54
55        if (!empty($words)) {
56            foreach (array_keys($words) as $wlen) {
57                $index = $this->getIndex('i', $wlen);
58                foreach ($words[$wlen] as $wid => $freq) {
59                    $idx = ($wid<count($index)) ? $index[$wid] : '';
60                    $index[$wid] = $this->updateTuple($idx, $pid, $freq);
61                    $pagewords[] = "$wlen*$wid";
62                }
63                if (!$this->saveIndex('i', $wlen, $index)) {
64                    $this->unlock();
65                    return false;
66                }
67            }
68        }
69
70        // Remove obsolete index entries
71        $pageword_idx = $this->getIndexKey('pageword', '', $pid);
72        if ($pageword_idx !== '') {
73            $oldwords = explode(':', $pageword_idx);
74            $delwords = array_diff($oldwords, $pagewords);
75            $upwords = [];
76            foreach ($delwords as $word) {
77                if ($word != '') {
78                    [$wlen, $wid] = explode('*', $word);
79                    $wid = (int)$wid;
80                    $upwords[$wlen][] = $wid;
81                }
82            }
83            foreach ($upwords as $wlen => $widx) {
84                $index = $this->getIndex('i', $wlen);
85                foreach ($widx as $wid) {
86                    $index[$wid] = $this->updateTuple($index[$wid], $pid, 0);
87                }
88                $this->saveIndex('i', $wlen, $index);
89            }
90        }
91        // Save the reverse index
92        $pageword_idx = implode(':', $pagewords);
93        if (!$this->saveIndexKey('pageword', '', $pid, $pageword_idx)) {
94            $this->unlock();
95            return false;
96        }
97
98        $this->unlock();
99        return true;
100    }
101
102    /**
103     * Split the words in a page and add them to the index.
104     *
105     * @param string    $text   content of the page
106     * @return array            list of word IDs and number of times used
107     *
108     * @author Andreas Gohr <andi@splitbrain.org>
109     * @author Christopher Smith <chris@jalakai.co.uk>
110     * @author Tom N Harris <tnharris@whoopdedo.org>
111     */
112    protected function getPageWords($text)
113    {
114
115        $tokens = $this->tokenizer($text);
116        $tokens = array_count_values($tokens);  // count the frequency of each token
117
118        $words = [];
119        foreach ($tokens as $w => $c) {
120            $l = wordlen($w);
121            if (isset($words[$l])) {
122                $words[$l][$w] = $c + ($words[$l][$w] ?? 0);
123            } else {
124                $words[$l] = [$w => $c];
125            }
126        }
127
128        // arrive here with $words = array(wordlen => array(word => frequency))
129        $index = [];   //resulting index
130        foreach (array_keys($words) as $wlen) {
131            $word_idx = $this->getIndex('w', $wlen);
132            $word_idx_modified = false;
133            foreach ($words[$wlen] as $word => $freq) {
134                $word = (string)$word;
135                $wid = array_search($word, $word_idx, true);
136                if ($wid === false) {
137                    $wid = count($word_idx);
138                    $word_idx[] = $word;
139                    $word_idx_modified = true;
140                }
141                if (!isset($index[$wlen]))
142                    $index[$wlen] = [];
143                $index[$wlen][$wid] = $freq;
144            }
145            // save back the word index
146            if ($word_idx_modified && !$this->saveIndex('w', $wlen, $word_idx))
147                return false;
148        }
149
150        return $index;
151    }
152
153    /**
154     * Add/update keys to/of the metadata index.
155     *
156     * Adding new keys does not remove other keys for the page.
157     * An empty value will erase the key.
158     * The $key parameter can be an array to add multiple keys. $value will
159     * not be used if $key is an array.
160     *
161     * @param string    $page   a page name
162     * @param mixed     $key    a key string or array of key=>value pairs
163     * @param mixed     $value  the value or list of values
164     * @return boolean|string     the function completed successfully
165     *
166     * @author Tom N Harris <tnharris@whoopdedo.org>
167     * @author Michael Hamann <michael@content-space.de>
168     */
169    public function addMetaKeys($page, $key, $value = null)
170    {
171        if (!is_array($key)) {
172            $key = [$key => $value];
173        } elseif (!is_null($value)) {
174            // $key is array, but $value is not null
175            trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING);
176        }
177
178        if (!$this->lock())
179            return "locked";
180
181        // load known documents
182        $pid = $this->getPIDNoLock($page);
183        if ($pid === false) {
184            $this->unlock();
185            return false;
186        }
187
188        // Special handling for titles so the index file is simpler
189        if (isset($key['title'])) {
190            $value = $key['title'];
191            if (is_array($value)) {
192                $value = $value[0];
193            }
194            $this->saveIndexKey('title', '', $pid, $value);
195            unset($key['title']);
196        }
197
198        foreach ($key as $name => $values) {
199            $metaname = idx_cleanName($name);
200            $this->addIndexKey('metadata', '', $metaname);
201            $metaidx = $this->getIndex($metaname.'_i', '');
202            $metawords = $this->getIndex($metaname.'_w', '');
203            $addwords = false;
204
205            if (!is_array($values)) $values = [$values];
206
207            $val_idx = $this->getIndexKey($metaname.'_p', '', $pid);
208            if ($val_idx !== '') {
209                $val_idx = explode(':', $val_idx);
210                // -1 means remove, 0 keep, 1 add
211                $val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1));
212            } else {
213                $val_idx = [];
214            }
215
216            foreach ($values as $val) {
217                $val = (string)$val;
218                if ($val !== "") {
219                    $id = array_search($val, $metawords, true);
220                    if ($id === false) {
221                        // didn't find $val, so we'll add it to the end of metawords and create a placeholder in metaidx
222                        $id = count($metawords);
223                        $metawords[$id] = $val;
224                        $metaidx[$id] = '';
225                        $addwords = true;
226                    }
227                    // test if value is already in the index
228                    if (isset($val_idx[$id]) && $val_idx[$id] <= 0) {
229                        $val_idx[$id] = 0;
230                    } else { // else add it
231                        $val_idx[$id] = 1;
232                    }
233                }
234            }
235
236            if ($addwords) {
237                $this->saveIndex($metaname.'_w', '', $metawords);
238            }
239            $vals_changed = false;
240            foreach ($val_idx as $id => $action) {
241                if ($action == -1) {
242                    $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 0);
243                    $vals_changed = true;
244                    unset($val_idx[$id]);
245                } elseif ($action == 1) {
246                    $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 1);
247                    $vals_changed = true;
248                }
249            }
250
251            if ($vals_changed) {
252                $this->saveIndex($metaname.'_i', '', $metaidx);
253                $val_idx = implode(':', array_keys($val_idx));
254                $this->saveIndexKey($metaname.'_p', '', $pid, $val_idx);
255            }
256
257            unset($metaidx);
258            unset($metawords);
259        }
260
261        $this->unlock();
262        return true;
263    }
264
265    /**
266     * Rename a page in the search index without changing the indexed content. This function doesn't check if the
267     * old or new name exists in the filesystem. It returns an error if the old page isn't in the page list of the
268     * indexer and it deletes all previously indexed content of the new page.
269     *
270     * @param string $oldpage The old page name
271     * @param string $newpage The new page name
272     * @return string|bool If the page was successfully renamed, can be a message in the case of an error
273     */
274    public function renamePage($oldpage, $newpage)
275    {
276        if (!$this->lock()) return 'locked';
277
278        $pages = $this->getPages();
279
280        $id = array_search($oldpage, $pages, true);
281        if ($id === false) {
282            $this->unlock();
283            return 'page is not in index';
284        }
285
286        $new_id = array_search($newpage, $pages, true);
287        if ($new_id !== false) {
288            // make sure the page is not in the index anymore
289            if (!$this->deletePageNoLock($newpage)) {
290                return false;
291            }
292
293            $pages[$new_id] = 'deleted:'.time().random_int(0, 9999);
294        }
295
296        $pages[$id] = $newpage;
297
298        // update index
299        if (!$this->saveIndex('page', '', $pages)) {
300            $this->unlock();
301            return false;
302        }
303
304        // reset the pid cache
305        $this->pidCache = [];
306
307        $this->unlock();
308        return true;
309    }
310
311    /**
312     * Renames a meta value in the index. This doesn't change the meta value in the pages, it assumes that all pages
313     * will be updated.
314     *
315     * @param string $key       The metadata key of which a value shall be changed
316     * @param string $oldvalue  The old value that shall be renamed
317     * @param string $newvalue  The new value to which the old value shall be renamed, if exists values will be merged
318     * @return bool|string      If renaming the value has been successful, false or error message on error.
319     */
320    public function renameMetaValue($key, $oldvalue, $newvalue)
321    {
322        if (!$this->lock()) return 'locked';
323
324        // change the relation references index
325        $metavalues = $this->getIndex($key, '_w');
326        $oldid = array_search($oldvalue, $metavalues, true);
327        if ($oldid !== false) {
328            $newid = array_search($newvalue, $metavalues, true);
329            if ($newid !== false) {
330                // free memory
331                unset($metavalues);
332
333                // okay, now we have two entries for the same value. we need to merge them.
334                $indexline = $this->getIndexKey($key.'_i', '', $oldid);
335                if ($indexline != '') {
336                    $newindexline = $this->getIndexKey($key.'_i', '', $newid);
337                    $pagekeys     = $this->getIndex($key.'_p', '');
338                    $parts = explode(':', $indexline);
339                    foreach ($parts as $part) {
340                        [$id, $count] = explode('*', $part);
341                        $newindexline =  $this->updateTuple($newindexline, $id, $count);
342
343                        $keyline = explode(':', $pagekeys[$id]);
344                        // remove old meta value
345                        $keyline = array_diff($keyline, [$oldid]);
346                        // add new meta value when not already present
347                        if (!in_array($newid, $keyline)) {
348                            $keyline[] = $newid;
349                        }
350                        $pagekeys[$id] = implode(':', $keyline);
351                    }
352                    $this->saveIndex($key.'_p', '', $pagekeys);
353                    unset($pagekeys);
354                    $this->saveIndexKey($key.'_i', '', $oldid, '');
355                    $this->saveIndexKey($key.'_i', '', $newid, $newindexline);
356                }
357            } else {
358                $metavalues[$oldid] = $newvalue;
359                if (!$this->saveIndex($key.'_w', '', $metavalues)) {
360                    $this->unlock();
361                    return false;
362                }
363            }
364        }
365
366        $this->unlock();
367        return true;
368    }
369
370    /**
371     * Remove a page from the index
372     *
373     * Erases entries in all known indexes.
374     *
375     * @param string    $page   a page name
376     * @return string|boolean  the function completed successfully
377     *
378     * @author Tom N Harris <tnharris@whoopdedo.org>
379     */
380    public function deletePage($page)
381    {
382        if (!$this->lock())
383            return "locked";
384
385        $result = $this->deletePageNoLock($page);
386
387        $this->unlock();
388
389        return $result;
390    }
391
392    /**
393     * Remove a page from the index without locking the index, only use this function if the index is already locked
394     *
395     * Erases entries in all known indexes.
396     *
397     * @param string    $page   a page name
398     * @return boolean          the function completed successfully
399     *
400     * @author Tom N Harris <tnharris@whoopdedo.org>
401     */
402    protected function deletePageNoLock($page)
403    {
404        // load known documents
405        $pid = $this->getPIDNoLock($page);
406        if ($pid === false) {
407            return false;
408        }
409
410        // Remove obsolete index entries
411        $pageword_idx = $this->getIndexKey('pageword', '', $pid);
412        if ($pageword_idx !== '') {
413            $delwords = explode(':', $pageword_idx);
414            $upwords = [];
415            foreach ($delwords as $word) {
416                if ($word != '') {
417                    [$wlen, $wid] = explode('*', $word);
418                    $wid = (int)$wid;
419                    $upwords[$wlen][] = $wid;
420                }
421            }
422            foreach ($upwords as $wlen => $widx) {
423                $index = $this->getIndex('i', $wlen);
424                foreach ($widx as $wid) {
425                    $index[$wid] = $this->updateTuple($index[$wid], $pid, 0);
426                }
427                $this->saveIndex('i', $wlen, $index);
428            }
429        }
430        // Save the reverse index
431        if (!$this->saveIndexKey('pageword', '', $pid, "")) {
432            return false;
433        }
434
435        $this->saveIndexKey('title', '', $pid, "");
436        $keyidx = $this->getIndex('metadata', '');
437        foreach ($keyidx as $metaname) {
438            $val_idx = explode(':', $this->getIndexKey($metaname.'_p', '', $pid));
439            $meta_idx = $this->getIndex($metaname.'_i', '');
440            foreach ($val_idx as $id) {
441                if ($id === '') continue;
442                $meta_idx[$id] = $this->updateTuple($meta_idx[$id], $pid, 0);
443            }
444            $this->saveIndex($metaname.'_i', '', $meta_idx);
445            $this->saveIndexKey($metaname.'_p', '', $pid, '');
446        }
447
448        return true;
449    }
450
451    /**
452     * Clear the whole index
453     *
454     * @return bool If the index has been cleared successfully
455     */
456    public function clear()
457    {
458        global $conf;
459
460        if (!$this->lock()) return false;
461
462        @unlink($conf['indexdir'].'/page.idx');
463        @unlink($conf['indexdir'].'/title.idx');
464        @unlink($conf['indexdir'].'/pageword.idx');
465        @unlink($conf['indexdir'].'/metadata.idx');
466        $dir = @opendir($conf['indexdir']);
467        if ($dir!==false) {
468            while (($f = readdir($dir)) !== false) {
469                if (substr($f, -4)=='.idx' &&
470                    (substr($f, 0, 1)=='i' || substr($f, 0, 1)=='w'
471                        || substr($f, -6)=='_w.idx' || substr($f, -6)=='_i.idx' || substr($f, -6)=='_p.idx'))
472                    @unlink($conf['indexdir']."/$f");
473            }
474        }
475        @unlink($conf['indexdir'].'/lengths.idx');
476
477        // clear the pid cache
478        $this->pidCache = [];
479
480        $this->unlock();
481        return true;
482    }
483
484    /**
485     * Split the text into words for fulltext search
486     *
487     * TODO: does this also need &$stopwords ?
488     *
489     * @triggers INDEXER_TEXT_PREPARE
490     * This event allows plugins to modify the text before it gets tokenized.
491     * Plugins intercepting this event should also intercept INDEX_VERSION_GET
492     *
493     * @param string    $text   plain text
494     * @param boolean   $wc     are wildcards allowed?
495     * @return array            list of words in the text
496     *
497     * @author Tom N Harris <tnharris@whoopdedo.org>
498     * @author Andreas Gohr <andi@splitbrain.org>
499     */
500    public function tokenizer($text, $wc = false)
501    {
502        $wc = ($wc) ? '' : '\*';
503        $stopwords =& idx_get_stopwords();
504
505        // prepare the text to be tokenized
506        $evt = new Event('INDEXER_TEXT_PREPARE', $text);
507        if ($evt->advise_before(true)) {
508            if (preg_match('/[^0-9A-Za-z ]/u', $text)) {
509                $text = Asian::separateAsianWords($text);
510            }
511        }
512        $evt->advise_after();
513        unset($evt);
514
515        $text = strtr(
516            $text,
517            ["\r" => ' ', "\n" => ' ', "\t" => ' ', "\xC2\xAD" => '']
518        );
519        if (preg_match('/[^0-9A-Za-z ]/u', $text))
520            $text = Clean::stripspecials($text, ' ', '\._\-:'.$wc);
521
522        $wordlist = explode(' ', $text);
523        foreach ($wordlist as $i => $word) {
524            $wordlist[$i] = (preg_match('/[^0-9A-Za-z]/u', $word)) ?
525                PhpString::strtolower($word) : strtolower($word);
526        }
527
528        foreach ($wordlist as $i => $word) {
529            if ((!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH)
530                || in_array($word, $stopwords, true))
531                unset($wordlist[$i]);
532        }
533        return array_values($wordlist);
534    }
535
536    /**
537     * Get the numeric PID of a page
538     *
539     * @param string $page The page to get the PID for
540     * @return bool|int The page id on success, false on error
541     */
542    public function getPID($page)
543    {
544        // return PID without locking when it is in the cache
545        if (isset($this->pidCache[$page])) return $this->pidCache[$page];
546
547        if (!$this->lock())
548            return false;
549
550        // load known documents
551        $pid = $this->getPIDNoLock($page);
552        if ($pid === false) {
553            $this->unlock();
554            return false;
555        }
556
557        $this->unlock();
558        return $pid;
559    }
560
561    /**
562     * Get the numeric PID of a page without locking the index.
563     * Only use this function when the index is already locked.
564     *
565     * @param string $page The page to get the PID for
566     * @return bool|int The page id on success, false on error
567     */
568    protected function getPIDNoLock($page)
569    {
570        // avoid expensive addIndexKey operation for the most recently requested pages by using a cache
571        if (isset($this->pidCache[$page])) return $this->pidCache[$page];
572        $pid = $this->addIndexKey('page', '', $page);
573        // limit cache to 10 entries by discarding the oldest element as in DokuWiki usually only the most recently
574        // added item will be requested again
575        if (count($this->pidCache) > 10) array_shift($this->pidCache);
576        $this->pidCache[$page] = $pid;
577        return $pid;
578    }
579
580    /**
581     * Get the page id of a numeric PID
582     *
583     * @param int $pid The PID to get the page id for
584     * @return string The page id
585     */
586    public function getPageFromPID($pid)
587    {
588        return $this->getIndexKey('page', '', $pid);
589    }
590
591    /**
592     * Find pages in the fulltext index containing the words,
593     *
594     * The search words must be pre-tokenized, meaning only letters and
595     * numbers with an optional wildcard
596     *
597     * The returned array will have the original tokens as key. The values
598     * in the returned list is an array with the page names as keys and the
599     * number of times that token appears on the page as value.
600     *
601     * @param array  $tokens list of words to search for
602     * @return array         list of page names with usage counts
603     *
604     * @author Tom N Harris <tnharris@whoopdedo.org>
605     * @author Andreas Gohr <andi@splitbrain.org>
606     */
607    public function lookup(&$tokens)
608    {
609        $result = [];
610        $wids = $this->getIndexWords($tokens, $result);
611        if (empty($wids)) return [];
612        // load known words and documents
613        $page_idx = $this->getIndex('page', '');
614        $docs = [];
615        foreach (array_keys($wids) as $wlen) {
616            $wids[$wlen] = array_unique($wids[$wlen]);
617            $index = $this->getIndex('i', $wlen);
618            foreach ($wids[$wlen] as $ixid) {
619                if ($ixid < count($index))
620                    $docs["$wlen*$ixid"] = $this->parseTuples($page_idx, $index[$ixid]);
621            }
622        }
623        // merge found pages into final result array
624        $final = [];
625        foreach ($result as $word => $res) {
626            $final[$word] = [];
627            foreach ($res as $wid) {
628                // handle the case when ($ixid < count($index)) has been false
629                // and thus $docs[$wid] hasn't been set.
630                if (!isset($docs[$wid])) continue;
631                $hits = &$docs[$wid];
632                foreach ($hits as $hitkey => $hitcnt) {
633                    // make sure the document still exists
634                    if (!page_exists($hitkey, '', false)) continue;
635                    if (!isset($final[$word][$hitkey]))
636                        $final[$word][$hitkey] = $hitcnt;
637                    else $final[$word][$hitkey] += $hitcnt;
638                }
639            }
640        }
641        return $final;
642    }
643
644    /**
645     * Find pages containing a metadata key.
646     *
647     * The metadata values are compared as case-sensitive strings. Pass a
648     * callback function that returns true or false to use a different
649     * comparison function. The function will be called with the $value being
650     * searched for as the first argument, and the word in the index as the
651     * second argument. The function preg_match can be used directly if the
652     * values are regexes.
653     *
654     * @param string    $key    name of the metadata key to look for
655     * @param string    $value  search term to look for, must be a string or array of strings
656     * @param callback  $func   comparison function
657     * @return array            lists with page names, keys are query values if $value is array
658     *
659     * @author Tom N Harris <tnharris@whoopdedo.org>
660     * @author Michael Hamann <michael@content-space.de>
661     */
662    public function lookupKey($key, &$value, $func = null)
663    {
664        if (!is_array($value))
665            $value_array = [$value];
666        else $value_array =& $value;
667
668        // the matching ids for the provided value(s)
669        $value_ids = [];
670
671        $metaname = idx_cleanName($key);
672
673        // get all words in order to search the matching ids
674        if ($key == 'title') {
675            $words = $this->getIndex('title', '');
676        } else {
677            $words = $this->getIndex($metaname.'_w', '');
678        }
679
680        if (!is_null($func)) {
681            foreach ($value_array as $val) {
682                foreach ($words as $i => $word) {
683                    if (call_user_func_array($func, [$val, $word]))
684                        $value_ids[$i][] = $val;
685                }
686            }
687        } else {
688            foreach ($value_array as $val) {
689                $xval = $val;
690                $caret = '^';
691                $dollar = '$';
692                // check for wildcards
693                if (substr($xval, 0, 1) == '*') {
694                    $xval = substr($xval, 1);
695                    $caret = '';
696                }
697                if (substr($xval, -1, 1) == '*') {
698                    $xval = substr($xval, 0, -1);
699                    $dollar = '';
700                }
701                if (!$caret || !$dollar) {
702                    $re = $caret.preg_quote($xval, '/').$dollar;
703                    foreach (array_keys(preg_grep('/'.$re.'/', $words)) as $i)
704                        $value_ids[$i][] = $val;
705                } elseif (($i = array_search($val, $words, true)) !== false) {
706                    $value_ids[$i][] = $val;
707                }
708            }
709        }
710
711        unset($words); // free the used memory
712
713        // initialize the result so it won't be null
714        $result = [];
715        foreach ($value_array as $val) {
716            $result[$val] = [];
717        }
718
719        $page_idx = $this->getIndex('page', '');
720
721        // Special handling for titles
722        if ($key == 'title') {
723            foreach ($value_ids as $pid => $val_list) {
724                $page = $page_idx[$pid];
725                foreach ($val_list as $val) {
726                    $result[$val][] = $page;
727                }
728            }
729        } else {
730            // load all lines and pages so the used lines can be taken and matched with the pages
731            $lines = $this->getIndex($metaname.'_i', '');
732
733            foreach ($value_ids as $value_id => $val_list) {
734                // parse the tuples of the form page_id*1:page2_id*1 and so on, return value
735                // is an array with page_id => 1, page2_id => 1 etc. so take the keys only
736                $pages = array_keys($this->parseTuples($page_idx, $lines[$value_id]));
737                foreach ($val_list as $val) {
738                    $result[$val] = [...$result[$val], ...$pages];
739                }
740            }
741        }
742        if (!is_array($value)) $result = $result[$value];
743        return $result;
744    }
745
746    /**
747     * Find the index ID of each search term.
748     *
749     * The query terms should only contain valid characters, with a '*' at
750     * either the beginning or end of the word (or both).
751     * The $result parameter can be used to merge the index locations with
752     * the appropriate query term.
753     *
754     * @param array  $words  The query terms.
755     * @param array  $result Set to word => array("length*id" ...)
756     * @return array         Set to length => array(id ...)
757     *
758     * @author Tom N Harris <tnharris@whoopdedo.org>
759     */
760    protected function getIndexWords(&$words, &$result)
761    {
762        $tokens = [];
763        $tokenlength = [];
764        $tokenwild = [];
765        foreach ($words as $word) {
766            $result[$word] = [];
767            $caret = '^';
768            $dollar = '$';
769            $xword = $word;
770            $wlen = wordlen($word);
771
772            // check for wildcards
773            if (substr($xword, 0, 1) == '*') {
774                $xword = substr($xword, 1);
775                $caret = '';
776                --$wlen;
777            }
778            if (substr($xword, -1, 1) == '*') {
779                $xword = substr($xword, 0, -1);
780                $dollar = '';
781                --$wlen;
782            }
783            if ($wlen < IDX_MINWORDLENGTH && $caret && $dollar && !is_numeric($xword))
784                continue;
785            if (!isset($tokens[$xword]))
786                $tokenlength[$wlen][] = $xword;
787            if (!$caret || !$dollar) {
788                $re = $caret.preg_quote($xword, '/').$dollar;
789                $tokens[$xword][] = [$word, '/'.$re.'/'];
790                if (!isset($tokenwild[$xword]))
791                    $tokenwild[$xword] = $wlen;
792            } else {
793                $tokens[$xword][] = [$word, null];
794            }
795        }
796        asort($tokenwild);
797        // $tokens = array( base word => array( [ query term , regexp ] ... ) ... )
798        // $tokenlength = array( base word length => base word ... )
799        // $tokenwild = array( base word => base word length ... )
800        $length_filter = $tokenwild === [] ? $tokenlength : min(array_keys($tokenlength));
801        $indexes_known = $this->indexLengths($length_filter);
802        if ($tokenwild !== []) sort($indexes_known);
803        // get word IDs
804        $wids = [];
805        foreach ($indexes_known as $ixlen) {
806            $word_idx = $this->getIndex('w', $ixlen);
807            // handle exact search
808            if (isset($tokenlength[$ixlen])) {
809                foreach ($tokenlength[$ixlen] as $xword) {
810                    $wid = array_search($xword, $word_idx, true);
811                    if ($wid !== false) {
812                        $wids[$ixlen][] = $wid;
813                        foreach ($tokens[$xword] as $w)
814                            $result[$w[0]][] = "$ixlen*$wid";
815                    }
816                }
817            }
818            // handle wildcard search
819            foreach ($tokenwild as $xword => $wlen) {
820                if ($wlen >= $ixlen) break;
821                foreach ($tokens[$xword] as $w) {
822                    if (is_null($w[1])) continue;
823                    foreach (array_keys(preg_grep($w[1], $word_idx)) as $wid) {
824                        $wids[$ixlen][] = $wid;
825                        $result[$w[0]][] = "$ixlen*$wid";
826                    }
827                }
828            }
829        }
830        return $wids;
831    }
832
833    /**
834     * Return a list of all pages
835     * Warning: pages may not exist!
836     *
837     * @param string    $key    list only pages containing the metadata key (optional)
838     * @return array            list of page names
839     *
840     * @author Tom N Harris <tnharris@whoopdedo.org>
841     */
842    public function getPages($key = null)
843    {
844        $page_idx = $this->getIndex('page', '');
845        if (is_null($key)) return $page_idx;
846
847        $metaname = idx_cleanName($key);
848
849        // Special handling for titles
850        if ($key == 'title') {
851            $title_idx = $this->getIndex('title', '');
852            array_splice($page_idx, count($title_idx));
853            foreach ($title_idx as $i => $title)
854                if ($title === "") unset($page_idx[$i]);
855            return array_values($page_idx);
856        }
857
858        $pages = [];
859        $lines = $this->getIndex($metaname.'_i', '');
860        foreach ($lines as $line) {
861            $pages = array_merge($pages, $this->parseTuples($page_idx, $line));
862        }
863        return array_keys($pages);
864    }
865
866    /**
867     * Return a list of words sorted by number of times used
868     *
869     * @param int       $min    bottom frequency threshold
870     * @param int       $max    upper frequency limit. No limit if $max<$min
871     * @param int       $minlen minimum length of words to count
872     * @param string    $key    metadata key to list. Uses the fulltext index if not given
873     * @return array            list of words as the keys and frequency as values
874     *
875     * @author Tom N Harris <tnharris@whoopdedo.org>
876     */
877    public function histogram($min = 1, $max = 0, $minlen = 3, $key = null)
878    {
879        if ($min < 1)
880            $min = 1;
881        if ($max < $min)
882            $max = 0;
883
884        $result = [];
885
886        if ($key == 'title') {
887            $index = $this->getIndex('title', '');
888            $index = array_count_values($index);
889            foreach ($index as $val => $cnt) {
890                if ($cnt >= $min && (!$max || $cnt <= $max) && strlen($val) >= $minlen)
891                    $result[$val] = $cnt;
892            }
893        } elseif (!is_null($key)) {
894            $metaname = idx_cleanName($key);
895            $index = $this->getIndex($metaname.'_i', '');
896            $val_idx = [];
897            foreach ($index as $wid => $line) {
898                $freq = $this->countTuples($line);
899                if ($freq >= $min && (!$max || $freq <= $max))
900                    $val_idx[$wid] = $freq;
901            }
902            if (!empty($val_idx)) {
903                $words = $this->getIndex($metaname.'_w', '');
904                foreach ($val_idx as $wid => $freq) {
905                    if (strlen($words[$wid]) >= $minlen)
906                        $result[$words[$wid]] = $freq;
907                }
908            }
909        } else {
910            $lengths = idx_listIndexLengths();
911            foreach ($lengths as $length) {
912                if ($length < $minlen) continue;
913                $index = $this->getIndex('i', $length);
914                $words = null;
915                foreach ($index as $wid => $line) {
916                    $freq = $this->countTuples($line);
917                    if ($freq >= $min && (!$max || $freq <= $max)) {
918                        if ($words === null)
919                            $words = $this->getIndex('w', $length);
920                        $result[$words[$wid]] = $freq;
921                    }
922                }
923            }
924        }
925
926        arsort($result);
927        return $result;
928    }
929
930    /**
931     * Lock the indexer.
932     *
933     * @author Tom N Harris <tnharris@whoopdedo.org>
934     *
935     * @return bool|string
936     */
937    protected function lock()
938    {
939        global $conf;
940        $status = true;
941        $run = 0;
942        $lock = $conf['lockdir'].'/_indexer.lock';
943        while (!@mkdir($lock)) {
944            usleep(50);
945            if (is_dir($lock) && time()-@filemtime($lock) > 60*5) {
946                // looks like a stale lock - remove it
947                if (!@rmdir($lock)) {
948                    $status = "removing the stale lock failed";
949                    return false;
950                } else {
951                    $status = "stale lock removed";
952                }
953            } elseif ($run++ == 1000) {
954                // we waited 5 seconds for that lock
955                return false;
956            }
957        }
958        if ($conf['dperm']) {
959            chmod($lock, $conf['dperm']);
960        }
961        return $status;
962    }
963
964    /**
965     * Release the indexer lock.
966     *
967     * @author Tom N Harris <tnharris@whoopdedo.org>
968     *
969     * @return bool
970     */
971    protected function unlock()
972    {
973        global $conf;
974        @rmdir($conf['lockdir'].'/_indexer.lock');
975        return true;
976    }
977
978    /**
979     * Retrieve the entire index.
980     *
981     * The $suffix argument is for an index that is split into
982     * multiple parts. Different index files should use different
983     * base names.
984     *
985     * @param string    $idx    name of the index
986     * @param string    $suffix subpart identifier
987     * @return array            list of lines without CR or LF
988     *
989     * @author Tom N Harris <tnharris@whoopdedo.org>
990     */
991    protected function getIndex($idx, $suffix)
992    {
993        global $conf;
994        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
995        if (!file_exists($fn)) return [];
996        return file($fn, FILE_IGNORE_NEW_LINES);
997    }
998
999    /**
1000     * Replace the contents of the index with an array.
1001     *
1002     * @param string    $idx    name of the index
1003     * @param string    $suffix subpart identifier
1004     * @param array     $lines  list of lines without LF
1005     * @return bool             If saving succeeded
1006     *
1007     * @author Tom N Harris <tnharris@whoopdedo.org>
1008     */
1009    protected function saveIndex($idx, $suffix, &$lines)
1010    {
1011        global $conf;
1012        $fn = $conf['indexdir'].'/'.$idx.$suffix;
1013        $fh = @fopen($fn.'.tmp', 'w');
1014        if (!$fh) return false;
1015        fwrite($fh, implode("\n", $lines));
1016        if (!empty($lines))
1017            fwrite($fh, "\n");
1018        fclose($fh);
1019        if ($conf['fperm'])
1020            chmod($fn.'.tmp', $conf['fperm']);
1021        io_rename($fn.'.tmp', $fn.'.idx');
1022        return true;
1023    }
1024
1025    /**
1026     * Retrieve a line from the index.
1027     *
1028     * @param string    $idx    name of the index
1029     * @param string    $suffix subpart identifier
1030     * @param int       $id     the line number
1031     * @return string           a line with trailing whitespace removed
1032     *
1033     * @author Tom N Harris <tnharris@whoopdedo.org>
1034     */
1035    protected function getIndexKey($idx, $suffix, $id)
1036    {
1037        global $conf;
1038        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
1039        if (!file_exists($fn)) return '';
1040        $fh = @fopen($fn, 'r');
1041        if (!$fh) return '';
1042        $ln = -1;
1043        while (($line = fgets($fh)) !== false) {
1044            if (++$ln == $id) break;
1045        }
1046        fclose($fh);
1047        return rtrim((string)$line);
1048    }
1049
1050    /**
1051     * Write a line into the index.
1052     *
1053     * @param string    $idx    name of the index
1054     * @param string    $suffix subpart identifier
1055     * @param int       $id     the line number
1056     * @param string    $line   line to write
1057     * @return bool             If saving succeeded
1058     *
1059     * @author Tom N Harris <tnharris@whoopdedo.org>
1060     */
1061    protected function saveIndexKey($idx, $suffix, $id, $line)
1062    {
1063        global $conf;
1064        if (substr($line, -1) != "\n")
1065            $line .= "\n";
1066        $fn = $conf['indexdir'].'/'.$idx.$suffix;
1067        $fh = @fopen($fn.'.tmp', 'w');
1068        if (!$fh) return false;
1069        $ih = @fopen($fn.'.idx', 'r');
1070        if ($ih) {
1071            $ln = -1;
1072            while (($curline = fgets($ih)) !== false) {
1073                fwrite($fh, (++$ln == $id) ? $line : $curline);
1074            }
1075            if ($id > $ln) {
1076                while ($id > ++$ln)
1077                    fwrite($fh, "\n");
1078                fwrite($fh, $line);
1079            }
1080            fclose($ih);
1081        } else {
1082            $ln = -1;
1083            while ($id > ++$ln)
1084                fwrite($fh, "\n");
1085            fwrite($fh, $line);
1086        }
1087        fclose($fh);
1088        if ($conf['fperm'])
1089            chmod($fn.'.tmp', $conf['fperm']);
1090        io_rename($fn.'.tmp', $fn.'.idx');
1091        return true;
1092    }
1093
1094    /**
1095     * Retrieve or insert a value in the index.
1096     *
1097     * @param string    $idx    name of the index
1098     * @param string    $suffix subpart identifier
1099     * @param string    $value  line to find in the index
1100     * @return int|bool          line number of the value in the index or false if writing the index failed
1101     *
1102     * @author Tom N Harris <tnharris@whoopdedo.org>
1103     */
1104    protected function addIndexKey($idx, $suffix, $value)
1105    {
1106        $index = $this->getIndex($idx, $suffix);
1107        $id = array_search($value, $index, true);
1108        if ($id === false) {
1109            $id = count($index);
1110            $index[$id] = $value;
1111            if (!$this->saveIndex($idx, $suffix, $index)) {
1112                trigger_error("Failed to write $idx index", E_USER_ERROR);
1113                return false;
1114            }
1115        }
1116        return $id;
1117    }
1118
1119    /**
1120     * Get the list of lengths indexed in the wiki.
1121     *
1122     * Read the index directory or a cache file and returns
1123     * a sorted array of lengths of the words used in the wiki.
1124     *
1125     * @author YoBoY <yoboy.leguesh@gmail.com>
1126     *
1127     * @return array
1128     */
1129    protected function listIndexLengths()
1130    {
1131        return idx_listIndexLengths();
1132    }
1133
1134    /**
1135     * Get the word lengths that have been indexed.
1136     *
1137     * Reads the index directory and returns an array of lengths
1138     * that there are indices for.
1139     *
1140     * @author YoBoY <yoboy.leguesh@gmail.com>
1141     *
1142     * @param array|int $filter
1143     * @return array
1144     */
1145    protected function indexLengths($filter)
1146    {
1147        global $conf;
1148        $idx = [];
1149        if (is_array($filter)) {
1150            // testing if index files exist only
1151            $path = $conf['indexdir']."/i";
1152            foreach (array_keys($filter) as $key) {
1153                if (file_exists($path.$key.'.idx'))
1154                    $idx[] = $key;
1155            }
1156        } else {
1157            $lengths = idx_listIndexLengths();
1158            foreach ($lengths as $length) {
1159                // keep all the values equal or superior
1160                if ((int)$length >= (int)$filter)
1161                    $idx[] = $length;
1162            }
1163        }
1164        return $idx;
1165    }
1166
1167    /**
1168     * Insert or replace a tuple in a line.
1169     *
1170     * @author Tom N Harris <tnharris@whoopdedo.org>
1171     *
1172     * @param string $line
1173     * @param string|int $id
1174     * @param int    $count
1175     * @return string
1176     */
1177    protected function updateTuple($line, $id, $count)
1178    {
1179        if ($line != '') {
1180            $line = preg_replace('/(^|:)'.preg_quote($id, '/').'\*\d*/', '', $line);
1181        }
1182        $line = trim($line, ':');
1183        if ($count) {
1184            if ($line) {
1185                return "$id*$count:".$line;
1186            } else {
1187                return "$id*$count";
1188            }
1189        }
1190        return $line;
1191    }
1192
1193    /**
1194     * Split a line into an array of tuples.
1195     *
1196     * @author Tom N Harris <tnharris@whoopdedo.org>
1197     * @author Andreas Gohr <andi@splitbrain.org>
1198     *
1199     * @param array $keys
1200     * @param string $line
1201     * @return array
1202     */
1203    protected function parseTuples(&$keys, $line)
1204    {
1205        $result = [];
1206        if ($line == '') return $result;
1207        $parts = explode(':', $line);
1208        foreach ($parts as $tuple) {
1209            if ($tuple === '') continue;
1210            [$key, $cnt] = explode('*', $tuple);
1211            if (!$cnt) continue;
1212            if (isset($keys[$key])) {
1213                $key = $keys[$key];
1214                if ($key === false || is_null($key)) continue;
1215            }
1216            $result[$key] = $cnt;
1217        }
1218        return $result;
1219    }
1220
1221    /**
1222     * Sum the counts in a list of tuples.
1223     *
1224     * @author Tom N Harris <tnharris@whoopdedo.org>
1225     *
1226     * @param string $line
1227     * @return int
1228     */
1229    protected function countTuples($line)
1230    {
1231        $freq = 0;
1232        $parts = explode(':', $line);
1233        foreach ($parts as $tuple) {
1234            if ($tuple === '') continue;
1235            [/* pid */, $cnt] = explode('*', $tuple);
1236            $freq += (int)$cnt;
1237        }
1238        return $freq;
1239    }
1240}
1241