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