xref: /dokuwiki/inc/Search/Indexer.php (revision 316e3ee67cce340deac79a8c6f89d881b178d094)
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($text,
516                      ["\r" => ' ', "\n" => ' ', "\t" => ' ', "\xC2\xAD" => '']
517        );
518        if (preg_match('/[^0-9A-Za-z ]/u', $text))
519            $text = Clean::stripspecials($text, ' ', '\._\-:'.$wc);
520
521        $wordlist = explode(' ', $text);
522        foreach ($wordlist as $i => $word) {
523            $wordlist[$i] = (preg_match('/[^0-9A-Za-z]/u', $word)) ?
524                PhpString::strtolower($word) : strtolower($word);
525        }
526
527        foreach ($wordlist as $i => $word) {
528            if ((!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH)
529                || in_array($word, $stopwords, true))
530                unset($wordlist[$i]);
531        }
532        return array_values($wordlist);
533    }
534
535    /**
536     * Get the numeric PID of a page
537     *
538     * @param string $page The page to get the PID for
539     * @return bool|int The page id on success, false on error
540     */
541    public function getPID($page)
542    {
543        // return PID without locking when it is in the cache
544        if (isset($this->pidCache[$page])) return $this->pidCache[$page];
545
546        if (!$this->lock())
547            return false;
548
549        // load known documents
550        $pid = $this->getPIDNoLock($page);
551        if ($pid === false) {
552            $this->unlock();
553            return false;
554        }
555
556        $this->unlock();
557        return $pid;
558    }
559
560    /**
561     * Get the numeric PID of a page without locking the index.
562     * Only use this function when the index is already locked.
563     *
564     * @param string $page The page to get the PID for
565     * @return bool|int The page id on success, false on error
566     */
567    protected function getPIDNoLock($page)
568    {
569        // avoid expensive addIndexKey operation for the most recently requested pages by using a cache
570        if (isset($this->pidCache[$page])) return $this->pidCache[$page];
571        $pid = $this->addIndexKey('page', '', $page);
572        // limit cache to 10 entries by discarding the oldest element as in DokuWiki usually only the most recently
573        // added item will be requested again
574        if (count($this->pidCache) > 10) array_shift($this->pidCache);
575        $this->pidCache[$page] = $pid;
576        return $pid;
577    }
578
579    /**
580     * Get the page id of a numeric PID
581     *
582     * @param int $pid The PID to get the page id for
583     * @return string The page id
584     */
585    public function getPageFromPID($pid)
586    {
587        return $this->getIndexKey('page', '', $pid);
588    }
589
590    /**
591     * Find pages in the fulltext index containing the words,
592     *
593     * The search words must be pre-tokenized, meaning only letters and
594     * numbers with an optional wildcard
595     *
596     * The returned array will have the original tokens as key. The values
597     * in the returned list is an array with the page names as keys and the
598     * number of times that token appears on the page as value.
599     *
600     * @param array  $tokens list of words to search for
601     * @return array         list of page names with usage counts
602     *
603     * @author Tom N Harris <tnharris@whoopdedo.org>
604     * @author Andreas Gohr <andi@splitbrain.org>
605     */
606    public function lookup(&$tokens)
607    {
608        $result = [];
609        $wids = $this->getIndexWords($tokens, $result);
610        if (empty($wids)) return [];
611        // load known words and documents
612        $page_idx = $this->getIndex('page', '');
613        $docs = [];
614        foreach (array_keys($wids) as $wlen) {
615            $wids[$wlen] = array_unique($wids[$wlen]);
616            $index = $this->getIndex('i', $wlen);
617            foreach($wids[$wlen] as $ixid) {
618                if ($ixid < count($index))
619                    $docs["$wlen*$ixid"] = $this->parseTuples($page_idx, $index[$ixid]);
620            }
621        }
622        // merge found pages into final result array
623        $final = [];
624        foreach ($result as $word => $res) {
625            $final[$word] = [];
626            foreach ($res as $wid) {
627                // handle the case when ($ixid < count($index)) has been false
628                // and thus $docs[$wid] hasn't been set.
629                if (!isset($docs[$wid])) continue;
630                $hits = &$docs[$wid];
631                foreach ($hits as $hitkey => $hitcnt) {
632                    // make sure the document still exists
633                    if (!page_exists($hitkey, '', false)) continue;
634                    if (!isset($final[$word][$hitkey]))
635                        $final[$word][$hitkey] = $hitcnt;
636                    else
637                        $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
667            $value_array =& $value;
668
669        // the matching ids for the provided value(s)
670        $value_ids = [];
671
672        $metaname = idx_cleanName($key);
673
674        // get all words in order to search the matching ids
675        if ($key == 'title') {
676            $words = $this->getIndex('title', '');
677        } else {
678            $words = $this->getIndex($metaname.'_w', '');
679        }
680
681        if (!is_null($func)) {
682            foreach ($value_array as $val) {
683                foreach ($words as $i => $word) {
684                    if (call_user_func_array($func, [$val, $word]))
685                        $value_ids[$i][] = $val;
686                }
687            }
688        } else {
689            foreach ($value_array as $val) {
690                $xval = $val;
691                $caret = '^';
692                $dollar = '$';
693                // check for wildcards
694                if (substr($xval, 0, 1) == '*') {
695                    $xval = substr($xval, 1);
696                    $caret = '';
697                }
698                if (substr($xval, -1, 1) == '*') {
699                    $xval = substr($xval, 0, -1);
700                    $dollar = '';
701                }
702                if (!$caret || !$dollar) {
703                    $re = $caret.preg_quote($xval, '/').$dollar;
704                    foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i)
705                        $value_ids[$i][] = $val;
706                } elseif (($i = array_search($val, $words, true)) !== false) {
707                    $value_ids[$i][] = $val;
708                }
709            }
710        }
711
712        unset($words); // free the used memory
713
714        // initialize the result so it won't be null
715        $result = [];
716        foreach ($value_array as $val) {
717            $result[$val] = [];
718        }
719
720        $page_idx = $this->getIndex('page', '');
721
722        // Special handling for titles
723        if ($key == 'title') {
724            foreach ($value_ids as $pid => $val_list) {
725                $page = $page_idx[$pid];
726                foreach ($val_list as $val) {
727                    $result[$val][] = $page;
728                }
729            }
730        } else {
731            // load all lines and pages so the used lines can be taken and matched with the pages
732            $lines = $this->getIndex($metaname.'_i', '');
733
734            foreach ($value_ids as $value_id => $val_list) {
735                // parse the tuples of the form page_id*1:page2_id*1 and so on, return value
736                // is an array with page_id => 1, page2_id => 1 etc. so take the keys only
737                $pages = array_keys($this->parseTuples($page_idx, $lines[$value_id]));
738                foreach ($val_list as $val) {
739                    $result[$val] = [...$result[$val], ...$pages];
740                }
741            }
742        }
743        if (!is_array($value)) $result = $result[$value];
744        return $result;
745    }
746
747    /**
748     * Find the index ID of each search term.
749     *
750     * The query terms should only contain valid characters, with a '*' at
751     * either the beginning or end of the word (or both).
752     * The $result parameter can be used to merge the index locations with
753     * the appropriate query term.
754     *
755     * @param array  $words  The query terms.
756     * @param array  $result Set to word => array("length*id" ...)
757     * @return array         Set to length => array(id ...)
758     *
759     * @author Tom N Harris <tnharris@whoopdedo.org>
760     */
761    protected function getIndexWords(&$words, &$result)
762    {
763        $tokens = [];
764        $tokenlength = [];
765        $tokenwild = [];
766        foreach ($words as $word) {
767            $result[$word] = [];
768            $caret = '^';
769            $dollar = '$';
770            $xword = $word;
771            $wlen = wordlen($word);
772
773            // check for wildcards
774            if (substr($xword, 0, 1) == '*') {
775                $xword = substr($xword, 1);
776                $caret = '';
777                --$wlen;
778            }
779            if (substr($xword, -1, 1) == '*') {
780                $xword = substr($xword, 0, -1);
781                $dollar = '';
782                --$wlen;
783            }
784            if ($wlen < IDX_MINWORDLENGTH && $caret && $dollar && !is_numeric($xword))
785                continue;
786            if (!isset($tokens[$xword]))
787                $tokenlength[$wlen][] = $xword;
788            if (!$caret || !$dollar) {
789                $re = $caret.preg_quote($xword, '/').$dollar;
790                $tokens[$xword][] = [$word, '/'.$re.'/'];
791                if (!isset($tokenwild[$xword]))
792                    $tokenwild[$xword] = $wlen;
793            } else {
794                $tokens[$xword][] = [$word, null];
795            }
796        }
797        asort($tokenwild);
798        // $tokens = array( base word => array( [ query term , regexp ] ... ) ... )
799        // $tokenlength = array( base word length => base word ... )
800        // $tokenwild = array( base word => base word length ... )
801        $length_filter = $tokenwild === [] ? $tokenlength : min(array_keys($tokenlength));
802        $indexes_known = $this->indexLengths($length_filter);
803        if ($tokenwild !== []) sort($indexes_known);
804        // get word IDs
805        $wids = [];
806        foreach ($indexes_known as $ixlen) {
807            $word_idx = $this->getIndex('w', $ixlen);
808            // handle exact search
809            if (isset($tokenlength[$ixlen])) {
810                foreach ($tokenlength[$ixlen] as $xword) {
811                    $wid = array_search($xword, $word_idx, true);
812                    if ($wid !== false) {
813                        $wids[$ixlen][] = $wid;
814                        foreach ($tokens[$xword] as $w)
815                            $result[$w[0]][] = "$ixlen*$wid";
816                    }
817                }
818            }
819            // handle wildcard search
820            foreach ($tokenwild as $xword => $wlen) {
821                if ($wlen >= $ixlen) break;
822                foreach ($tokens[$xword] as $w) {
823                    if (is_null($w[1])) continue;
824                    foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) {
825                        $wids[$ixlen][] = $wid;
826                        $result[$w[0]][] = "$ixlen*$wid";
827                    }
828                }
829            }
830        }
831        return $wids;
832    }
833
834    /**
835     * Return a list of all pages
836     * Warning: pages may not exist!
837     *
838     * @param string    $key    list only pages containing the metadata key (optional)
839     * @return array            list of page names
840     *
841     * @author Tom N Harris <tnharris@whoopdedo.org>
842     */
843    public function getPages($key = null)
844    {
845        $page_idx = $this->getIndex('page', '');
846        if (is_null($key)) return $page_idx;
847
848        $metaname = idx_cleanName($key);
849
850        // Special handling for titles
851        if ($key == 'title') {
852            $title_idx = $this->getIndex('title', '');
853            array_splice($page_idx, count($title_idx));
854            foreach ($title_idx as $i => $title)
855                if ($title === "") unset($page_idx[$i]);
856            return array_values($page_idx);
857        }
858
859        $pages = [];
860        $lines = $this->getIndex($metaname.'_i', '');
861        foreach ($lines as $line) {
862            $pages = array_merge($pages, $this->parseTuples($page_idx, $line));
863        }
864        return array_keys($pages);
865    }
866
867    /**
868     * Return a list of words sorted by number of times used
869     *
870     * @param int       $min    bottom frequency threshold
871     * @param int       $max    upper frequency limit. No limit if $max<$min
872     * @param int       $minlen minimum length of words to count
873     * @param string    $key    metadata key to list. Uses the fulltext index if not given
874     * @return array            list of words as the keys and frequency as values
875     *
876     * @author Tom N Harris <tnharris@whoopdedo.org>
877     */
878    public function histogram($min = 1, $max = 0, $minlen = 3, $key = null)
879    {
880        if ($min < 1)
881            $min = 1;
882        if ($max < $min)
883            $max = 0;
884
885        $result = [];
886
887        if ($key == 'title') {
888            $index = $this->getIndex('title', '');
889            $index = array_count_values($index);
890            foreach ($index as $val => $cnt) {
891                if ($cnt >= $min && (!$max || $cnt <= $max) && strlen($val) >= $minlen)
892                    $result[$val] = $cnt;
893            }
894        }
895        elseif (!is_null($key)) {
896            $metaname = idx_cleanName($key);
897            $index = $this->getIndex($metaname.'_i', '');
898            $val_idx = [];
899            foreach ($index as $wid => $line) {
900                $freq = $this->countTuples($line);
901                if ($freq >= $min && (!$max || $freq <= $max))
902                    $val_idx[$wid] = $freq;
903            }
904            if (!empty($val_idx)) {
905                $words = $this->getIndex($metaname.'_w', '');
906                foreach ($val_idx as $wid => $freq) {
907                    if (strlen($words[$wid]) >= $minlen)
908                        $result[$words[$wid]] = $freq;
909                }
910            }
911        }
912        else {
913            $lengths = idx_listIndexLengths();
914            foreach ($lengths as $length) {
915                if ($length < $minlen) continue;
916                $index = $this->getIndex('i', $length);
917                $words = null;
918                foreach ($index as $wid => $line) {
919                    $freq = $this->countTuples($line);
920                    if ($freq >= $min && (!$max || $freq <= $max)) {
921                        if ($words === null)
922                            $words = $this->getIndex('w', $length);
923                        $result[$words[$wid]] = $freq;
924                    }
925                }
926            }
927        }
928
929        arsort($result);
930        return $result;
931    }
932
933    /**
934     * Lock the indexer.
935     *
936     * @author Tom N Harris <tnharris@whoopdedo.org>
937     *
938     * @return bool|string
939     */
940    protected function lock()
941    {
942        global $conf;
943        $status = true;
944        $run = 0;
945        $lock = $conf['lockdir'].'/_indexer.lock';
946        while (!@mkdir($lock)) {
947            usleep(50);
948            if(is_dir($lock) && time()-@filemtime($lock) > 60*5){
949                // looks like a stale lock - remove it
950                if (!@rmdir($lock)) {
951                    $status = "removing the stale lock failed";
952                    return false;
953                } else {
954                    $status = "stale lock removed";
955                }
956            }elseif($run++ == 1000){
957                // we waited 5 seconds for that lock
958                return false;
959            }
960        }
961        if ($conf['dperm']) {
962            chmod($lock, $conf['dperm']);
963        }
964        return $status;
965    }
966
967    /**
968     * Release the indexer lock.
969     *
970     * @author Tom N Harris <tnharris@whoopdedo.org>
971     *
972     * @return bool
973     */
974    protected function unlock()
975    {
976        global $conf;
977        @rmdir($conf['lockdir'].'/_indexer.lock');
978        return true;
979    }
980
981    /**
982     * Retrieve the entire index.
983     *
984     * The $suffix argument is for an index that is split into
985     * multiple parts. Different index files should use different
986     * base names.
987     *
988     * @param string    $idx    name of the index
989     * @param string    $suffix subpart identifier
990     * @return array            list of lines without CR or LF
991     *
992     * @author Tom N Harris <tnharris@whoopdedo.org>
993     */
994    protected function getIndex($idx, $suffix)
995    {
996        global $conf;
997        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
998        if (!file_exists($fn)) return [];
999        return file($fn, FILE_IGNORE_NEW_LINES);
1000    }
1001
1002    /**
1003     * Replace the contents of the index with an array.
1004     *
1005     * @param string    $idx    name of the index
1006     * @param string    $suffix subpart identifier
1007     * @param array     $lines  list of lines without LF
1008     * @return bool             If saving succeeded
1009     *
1010     * @author Tom N Harris <tnharris@whoopdedo.org>
1011     */
1012    protected function saveIndex($idx, $suffix, &$lines)
1013    {
1014        global $conf;
1015        $fn = $conf['indexdir'].'/'.$idx.$suffix;
1016        $fh = @fopen($fn.'.tmp', 'w');
1017        if (!$fh) return false;
1018        fwrite($fh, implode("\n", $lines));
1019        if (!empty($lines))
1020            fwrite($fh, "\n");
1021        fclose($fh);
1022        if ($conf['fperm'])
1023            chmod($fn.'.tmp', $conf['fperm']);
1024        io_rename($fn.'.tmp', $fn.'.idx');
1025        return true;
1026    }
1027
1028    /**
1029     * Retrieve a line from the index.
1030     *
1031     * @param string    $idx    name of the index
1032     * @param string    $suffix subpart identifier
1033     * @param int       $id     the line number
1034     * @return string           a line with trailing whitespace removed
1035     *
1036     * @author Tom N Harris <tnharris@whoopdedo.org>
1037     */
1038    protected function getIndexKey($idx, $suffix, $id)
1039    {
1040        global $conf;
1041        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
1042        if (!file_exists($fn)) return '';
1043        $fh = @fopen($fn, 'r');
1044        if (!$fh) return '';
1045        $ln = -1;
1046        while (($line = fgets($fh)) !== false) {
1047            if (++$ln == $id) break;
1048        }
1049        fclose($fh);
1050        return rtrim((string)$line);
1051    }
1052
1053    /**
1054     * Write a line into the index.
1055     *
1056     * @param string    $idx    name of the index
1057     * @param string    $suffix subpart identifier
1058     * @param int       $id     the line number
1059     * @param string    $line   line to write
1060     * @return bool             If saving succeeded
1061     *
1062     * @author Tom N Harris <tnharris@whoopdedo.org>
1063     */
1064    protected function saveIndexKey($idx, $suffix, $id, $line)
1065    {
1066        global $conf;
1067        if (substr($line, -1) != "\n")
1068            $line .= "\n";
1069        $fn = $conf['indexdir'].'/'.$idx.$suffix;
1070        $fh = @fopen($fn.'.tmp', 'w');
1071        if (!$fh) return false;
1072        $ih = @fopen($fn.'.idx', 'r');
1073        if ($ih) {
1074            $ln = -1;
1075            while (($curline = fgets($ih)) !== false) {
1076                fwrite($fh, (++$ln == $id) ? $line : $curline);
1077            }
1078            if ($id > $ln) {
1079                while ($id > ++$ln)
1080                    fwrite($fh, "\n");
1081                fwrite($fh, $line);
1082            }
1083            fclose($ih);
1084        } else {
1085            $ln = -1;
1086            while ($id > ++$ln)
1087                fwrite($fh, "\n");
1088            fwrite($fh, $line);
1089        }
1090        fclose($fh);
1091        if ($conf['fperm'])
1092            chmod($fn.'.tmp', $conf['fperm']);
1093        io_rename($fn.'.tmp', $fn.'.idx');
1094        return true;
1095    }
1096
1097    /**
1098     * Retrieve or insert a value in the index.
1099     *
1100     * @param string    $idx    name of the index
1101     * @param string    $suffix subpart identifier
1102     * @param string    $value  line to find in the index
1103     * @return int|bool          line number of the value in the index or false if writing the index failed
1104     *
1105     * @author Tom N Harris <tnharris@whoopdedo.org>
1106     */
1107    protected function addIndexKey($idx, $suffix, $value)
1108    {
1109        $index = $this->getIndex($idx, $suffix);
1110        $id = array_search($value, $index, true);
1111        if ($id === false) {
1112            $id = count($index);
1113            $index[$id] = $value;
1114            if (!$this->saveIndex($idx, $suffix, $index)) {
1115                trigger_error("Failed to write $idx index", E_USER_ERROR);
1116                return false;
1117            }
1118        }
1119        return $id;
1120    }
1121
1122    /**
1123     * Get the list of lengths indexed in the wiki.
1124     *
1125     * Read the index directory or a cache file and returns
1126     * a sorted array of lengths of the words used in the wiki.
1127     *
1128     * @author YoBoY <yoboy.leguesh@gmail.com>
1129     *
1130     * @return array
1131     */
1132    protected function listIndexLengths()
1133    {
1134        return idx_listIndexLengths();
1135    }
1136
1137    /**
1138     * Get the word lengths that have been indexed.
1139     *
1140     * Reads the index directory and returns an array of lengths
1141     * that there are indices for.
1142     *
1143     * @author YoBoY <yoboy.leguesh@gmail.com>
1144     *
1145     * @param array|int $filter
1146     * @return array
1147     */
1148    protected function indexLengths($filter)
1149    {
1150        global $conf;
1151        $idx = [];
1152        if (is_array($filter)) {
1153            // testing if index files exist only
1154            $path = $conf['indexdir']."/i";
1155            foreach (array_keys($filter) as $key) {
1156                if (file_exists($path.$key.'.idx'))
1157                    $idx[] = $key;
1158            }
1159        } else {
1160            $lengths = idx_listIndexLengths();
1161            foreach ($lengths as $length) {
1162                // keep all the values equal or superior
1163                if ((int)$length >= (int)$filter)
1164                    $idx[] = $length;
1165            }
1166        }
1167        return $idx;
1168    }
1169
1170    /**
1171     * Insert or replace a tuple in a line.
1172     *
1173     * @author Tom N Harris <tnharris@whoopdedo.org>
1174     *
1175     * @param string $line
1176     * @param string|int $id
1177     * @param int    $count
1178     * @return string
1179     */
1180    protected function updateTuple($line, $id, $count)
1181    {
1182        if ($line != ''){
1183            $line = preg_replace('/(^|:)'.preg_quote($id, '/').'\*\d*/', '', $line);
1184        }
1185        $line = trim($line, ':');
1186        if ($count) {
1187            if ($line) {
1188                return "$id*$count:".$line;
1189            } else {
1190                return "$id*$count";
1191            }
1192        }
1193        return $line;
1194    }
1195
1196    /**
1197     * Split a line into an array of tuples.
1198     *
1199     * @author Tom N Harris <tnharris@whoopdedo.org>
1200     * @author Andreas Gohr <andi@splitbrain.org>
1201     *
1202     * @param array $keys
1203     * @param string $line
1204     * @return array
1205     */
1206    protected function parseTuples(&$keys, $line)
1207    {
1208        $result = [];
1209        if ($line == '') return $result;
1210        $parts = explode(':', $line);
1211        foreach ($parts as $tuple) {
1212            if ($tuple === '') continue;
1213            [$key, $cnt] = explode('*', $tuple);
1214            if (!$cnt) continue;
1215            if (isset($keys[$key])) {
1216                $key = $keys[$key];
1217                if ($key === false || is_null($key)) continue;
1218            }
1219            $result[$key] = $cnt;
1220        }
1221        return $result;
1222    }
1223
1224    /**
1225     * Sum the counts in a list of tuples.
1226     *
1227     * @author Tom N Harris <tnharris@whoopdedo.org>
1228     *
1229     * @param string $line
1230     * @return int
1231     */
1232    protected function countTuples($line)
1233    {
1234        $freq = 0;
1235        $parts = explode(':', $line);
1236        foreach ($parts as $tuple) {
1237            if ($tuple === '') continue;
1238            [, $cnt] = explode('*', $tuple);
1239            $freq += (int)$cnt;
1240        }
1241        return $freq;
1242    }
1243}
1244