xref: /dokuwiki/inc/indexer.php (revision 4b9792c696658fe0cbedc187198fa463b6ff83fc)
1<?php
2/**
3 * Functions to create the fulltext search index
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 */
8
9if(!defined('DOKU_INC')) die('meh.');
10
11// set the minimum token length to use in the index (note, this doesn't apply to numeric tokens)
12if (!defined('IDX_MINWORDLENGTH')) define('IDX_MINWORDLENGTH',2);
13
14// Asian characters are handled as words. The following regexp defines the
15// Unicode-Ranges for Asian characters
16// Ranges taken from http://en.wikipedia.org/wiki/Unicode_block
17// I'm no language expert. If you think some ranges are wrongly chosen or
18// a range is missing, please contact me
19define('IDX_ASIAN1','[\x{0E00}-\x{0E7F}]'); // Thai
20define('IDX_ASIAN2','['.
21                   '\x{2E80}-\x{3040}'.  // CJK -> Hangul
22                   '\x{309D}-\x{30A0}'.
23                   '\x{30FD}-\x{31EF}\x{3200}-\x{D7AF}'.
24                   '\x{F900}-\x{FAFF}'.  // CJK Compatibility Ideographs
25                   '\x{FE30}-\x{FE4F}'.  // CJK Compatibility Forms
26                   ']');
27define('IDX_ASIAN3','['.                // Hiragana/Katakana (can be two characters)
28                   '\x{3042}\x{3044}\x{3046}\x{3048}'.
29                   '\x{304A}-\x{3062}\x{3064}-\x{3082}'.
30                   '\x{3084}\x{3086}\x{3088}-\x{308D}'.
31                   '\x{308F}-\x{3094}'.
32                   '\x{30A2}\x{30A4}\x{30A6}\x{30A8}'.
33                   '\x{30AA}-\x{30C2}\x{30C4}-\x{30E2}'.
34                   '\x{30E4}\x{30E6}\x{30E8}-\x{30ED}'.
35                   '\x{30EF}-\x{30F4}\x{30F7}-\x{30FA}'.
36                   ']['.
37                   '\x{3041}\x{3043}\x{3045}\x{3047}\x{3049}'.
38                   '\x{3063}\x{3083}\x{3085}\x{3087}\x{308E}\x{3095}-\x{309C}'.
39                   '\x{30A1}\x{30A3}\x{30A5}\x{30A7}\x{30A9}'.
40                   '\x{30C3}\x{30E3}\x{30E5}\x{30E7}\x{30EE}\x{30F5}\x{30F6}\x{30FB}\x{30FC}'.
41                   '\x{31F0}-\x{31FF}'.
42                   ']?');
43define('IDX_ASIAN', '(?:'.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')');
44
45/**
46 * Measure the length of a string.
47 * Differs from strlen in handling of asian characters.
48 *
49 * @author Tom N Harris <tnharris@whoopdedo.org>
50 */
51function wordlen($w){
52    $l = strlen($w);
53    // If left alone, all chinese "words" will get put into w3.idx
54    // So the "length" of a "word" is faked
55    if(preg_match_all('/[\xE2-\xEF]/',$w,$leadbytes)) {
56        foreach($leadbytes[0] as $b)
57            $l += ord($b) - 0xE1;
58    }
59    return $l;
60}
61
62/**
63 * Write a list of strings to an index file.
64 *
65 * @author Tom N Harris <tnharris@whoopdedo.org>
66 */
67function idx_saveIndex($pre, $wlen, &$idx){
68    global $conf;
69    $fn = $conf['indexdir'].'/'.$pre.$wlen;
70    $fh = @fopen($fn.'.tmp','w');
71    if(!$fh) return false;
72    foreach ($idx as $line) {
73        fwrite($fh,$line);
74    }
75    fclose($fh);
76    if(isset($conf['fperm'])) chmod($fn.'.tmp', $conf['fperm']);
77    io_rename($fn.'.tmp', $fn.'.idx');
78    return true;
79}
80
81/**
82 * Append a given line to an index file.
83 *
84 * @author Andreas Gohr <andi@splitbrain.org>
85 */
86function idx_appendIndex($pre, $wlen, $line){
87    global $conf;
88    $fn = $conf['indexdir'].'/'.$pre.$wlen;
89    $fh = @fopen($fn.'.idx','a');
90    if(!$fh) return false;
91    fwrite($fh,$line);
92    fclose($fh);
93    return true;
94}
95
96/**
97 * Read the list of words in an index (if it exists).
98 *
99 * @author Tom N Harris <tnharris@whoopdedo.org>
100 */
101function idx_getIndex($pre, $wlen){
102    global $conf;
103    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
104    if(!@file_exists($fn)) return array();
105    return file($fn);
106}
107
108/**
109 * Read a line ending with \n.
110 * Returns false on EOF.
111 *
112 * @author Tom N Harris <tnharris@whoopdedo.org>
113 */
114function _freadline($fh) {
115    if (feof($fh)) return false;
116    $ln = '';
117    while (($buf = fgets($fh,4096)) !== false) {
118        $ln .= $buf;
119        if (substr($buf,-1) == "\n") break;
120    }
121    if ($ln === '') return false;
122    if (substr($ln,-1) != "\n") $ln .= "\n";
123    return $ln;
124}
125
126/**
127 * Write a line to an index file.
128 *
129 * @author Tom N Harris <tnharris@whoopdedo.org>
130 */
131function idx_saveIndexLine($pre, $wlen, $idx, $line){
132    global $conf;
133    if(substr($line,-1) != "\n") $line .= "\n";
134    $fn = $conf['indexdir'].'/'.$pre.$wlen;
135    $fh = @fopen($fn.'.tmp','w');
136    if(!$fh) return false;
137    $ih = @fopen($fn.'.idx','r');
138    if ($ih) {
139        $ln = -1;
140        while (($curline = _freadline($ih)) !== false) {
141            if (++$ln == $idx) {
142                fwrite($fh, $line);
143            } else {
144                fwrite($fh, $curline);
145            }
146        }
147        if ($idx > $ln) {
148            fwrite($fh,$line);
149        }
150        fclose($ih);
151    } else {
152        fwrite($fh,$line);
153    }
154    fclose($fh);
155    if($conf['fperm']) chmod($fn.'.tmp', $conf['fperm']);
156    io_rename($fn.'.tmp', $fn.'.idx');
157    return true;
158}
159
160/**
161 * Read a single line from an index (if it exists).
162 *
163 * @author Tom N Harris <tnharris@whoopdedo.org>
164 */
165function idx_getIndexLine($pre, $wlen, $idx){
166    global $conf;
167    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
168    if(!@file_exists($fn)) return '';
169    $fh = @fopen($fn,'r');
170    if(!$fh) return '';
171    $ln = -1;
172    while (($line = _freadline($fh)) !== false) {
173        if (++$ln == $idx) break;
174    }
175    fclose($fh);
176    return "$line";
177}
178
179/**
180 * Split a page into words
181 *
182 * Returns an array of word counts, false if an error occurred.
183 * Array is keyed on the word length, then the word index.
184 *
185 * @author Andreas Gohr <andi@splitbrain.org>
186 * @author Christopher Smith <chris@jalakai.co.uk>
187 */
188function idx_getPageWords($page){
189    global $conf;
190    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
191    if(@file_exists($swfile)){
192        $stopwords = file($swfile);
193    }else{
194        $stopwords = array();
195    }
196
197    $body = '';
198    $data = array($page, $body);
199    $evt = new Doku_Event('INDEXER_PAGE_ADD', $data);
200    if ($evt->advise_before()) $data[1] .= rawWiki($page);
201    $evt->advise_after();
202    unset($evt);
203
204    list($page,$body) = $data;
205
206    $body   = strtr($body, "\r\n\t", '   ');
207    $tokens = explode(' ', $body);
208    $tokens = array_count_values($tokens);   // count the frequency of each token
209
210    // ensure the deaccented or romanised page names of internal links are added to the token array
211    // (this is necessary for the backlink function -- there maybe a better way!)
212    if ($conf['deaccent']) {
213        $links = p_get_metadata($page,'relation references');
214
215        if (!empty($links)) {
216            $tmp = join(' ',array_keys($links));                // make a single string
217            $tmp = strtr($tmp, ':', ' ');                       // replace namespace separator with a space
218            $link_tokens = array_unique(explode(' ', $tmp));    // break into tokens
219
220            foreach ($link_tokens as $link_token) {
221                if (isset($tokens[$link_token])) continue;
222                $tokens[$link_token] = 1;
223            }
224        }
225    }
226
227    $words = array();
228    foreach ($tokens as $word => $count) {
229        $arr = idx_tokenizer($word,$stopwords);
230        $arr = array_count_values($arr);
231        foreach ($arr as $w => $c) {
232            $l = wordlen($w);
233            if(isset($words[$l])){
234                $words[$l][$w] = $c * $count + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
235            }else{
236                $words[$l] = array($w => $c * $count);
237            }
238        }
239    }
240
241    // arrive here with $words = array(wordlen => array(word => frequency))
242
243    $index = array(); //resulting index
244    foreach (array_keys($words) as $wlen){
245        $word_idx = idx_getIndex('w',$wlen);
246        foreach ($words[$wlen] as $word => $freq) {
247            $wid = array_search("$word\n",$word_idx);
248            if(!is_int($wid)){
249                $wid = count($word_idx);
250                $word_idx[] = "$word\n";
251            }
252            if(!isset($index[$wlen]))
253                $index[$wlen] = array();
254            $index[$wlen][$wid] = $freq;
255        }
256
257        // save back word index
258        if(!idx_saveIndex('w',$wlen,$word_idx)){
259            trigger_error("Failed to write word index", E_USER_ERROR);
260            return false;
261        }
262    }
263
264    return $index;
265}
266
267/**
268 * Adds/updates the search for the given page
269 *
270 * This is the core function of the indexer which does most
271 * of the work. This function needs to be called with proper
272 * locking!
273 *
274 * @author Andreas Gohr <andi@splitbrain.org>
275 */
276function idx_addPage($page){
277    global $conf;
278
279    // load known documents
280    $page_idx = idx_getIndex('page','');
281
282    // get page id (this is the linenumber in page.idx)
283    $pid = array_search("$page\n",$page_idx);
284    if(!is_int($pid)){
285        $pid = count($page_idx);
286        // page was new - write back
287        if (!idx_appendIndex('page','',"$page\n")){
288            trigger_error("Failed to write page index", E_USER_ERROR);
289            return false;
290        }
291    }
292    unset($page_idx); // free memory
293
294    idx_saveIndexLine('title', '', $pid, p_get_first_heading($page, false));
295
296    $pagewords = array();
297    // get word usage in page
298    $words = idx_getPageWords($page);
299    if($words === false) return false;
300
301    if(!empty($words)) {
302        foreach(array_keys($words) as $wlen){
303            $index = idx_getIndex('i',$wlen);
304            foreach($words[$wlen] as $wid => $freq){
305                if($wid<count($index)){
306                    $index[$wid] = idx_updateIndexLine($index[$wid],$pid,$freq);
307                }else{
308                    // New words **should** have been added in increasing order
309                    // starting with the first unassigned index.
310                    // If someone can show how this isn't true, then I'll need to sort
311                    // or do something special.
312                    $index[$wid] = idx_updateIndexLine('',$pid,$freq);
313                }
314                $pagewords[] = "$wlen*$wid";
315            }
316            // save back word index
317            if(!idx_saveIndex('i',$wlen,$index)){
318                trigger_error("Failed to write index", E_USER_ERROR);
319                return false;
320            }
321        }
322    }
323
324    // Remove obsolete index entries
325    $pageword_idx = trim(idx_getIndexLine('pageword','',$pid));
326    if ($pageword_idx !== '') {
327        $oldwords = explode(':',$pageword_idx);
328        $delwords = array_diff($oldwords, $pagewords);
329        $upwords = array();
330        foreach ($delwords as $word) {
331            if($word=='') continue;
332            list($wlen,$wid) = explode('*',$word);
333            $wid = (int)$wid;
334            $upwords[$wlen][] = $wid;
335        }
336        foreach ($upwords as $wlen => $widx) {
337            $index = idx_getIndex('i',$wlen);
338            foreach ($widx as $wid) {
339                $index[$wid] = idx_updateIndexLine($index[$wid],$pid,0);
340            }
341            idx_saveIndex('i',$wlen,$index);
342        }
343    }
344    // Save the reverse index
345    $pageword_idx = join(':',$pagewords)."\n";
346    if(!idx_saveIndexLine('pageword','',$pid,$pageword_idx)){
347        trigger_error("Failed to write word index", E_USER_ERROR);
348        return false;
349    }
350
351    return true;
352}
353
354/**
355 * Write a new index line to the filehandle
356 *
357 * This function writes an line for the index file to the
358 * given filehandle. It removes the given document from
359 * the given line and readds it when $count is >0.
360 *
361 * @deprecated - see idx_updateIndexLine
362 * @author Andreas Gohr <andi@splitbrain.org>
363 */
364function idx_writeIndexLine($fh,$line,$pid,$count){
365    fwrite($fh,idx_updateIndexLine($line,$pid,$count));
366}
367
368/**
369 * Modify an index line with new information
370 *
371 * This returns a line of the index. It removes the
372 * given document from the line and readds it if
373 * $count is >0.
374 *
375 * @author Tom N Harris <tnharris@whoopdedo.org>
376 * @author Andreas Gohr <andi@splitbrain.org>
377 */
378function idx_updateIndexLine($line,$pid,$count){
379    $line = trim($line);
380    $updated = array();
381    if($line != ''){
382        $parts = explode(':',$line);
383        // remove doc from given line
384        foreach($parts as $part){
385            if($part == '') continue;
386            list($doc,$cnt) = explode('*',$part);
387            if($doc != $pid){
388                $updated[] = $part;
389            }
390        }
391    }
392
393    // add doc
394    if ($count){
395        $updated[] = "$pid*$count";
396    }
397
398    return join(':',$updated)."\n";
399}
400
401/**
402 * Get the list of lenghts indexed in the wiki
403 *
404 * Read the index directory or a cache file and returns
405 * a sorted array of lengths of the words used in the wiki.
406 *
407 * @author YoBoY <yoboy.leguesh@gmail.com>
408 */
409function idx_listIndexLengths() {
410    global $conf;
411    // testing what we have to do, create a cache file or not.
412    if ($conf['readdircache'] == 0) {
413        $docache = false;
414    } else {
415        clearstatcache();
416        if (@file_exists($conf['indexdir'].'/lengths.idx') and (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) {
417            if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ) !== false) {
418                $idx = array();
419                foreach ( $lengths as $length) {
420                    $idx[] = (int)$length;
421                }
422                return $idx;
423            }
424        }
425        $docache = true;
426    }
427
428    if ($conf['readdircache'] == 0 or $docache ) {
429        $dir = @opendir($conf['indexdir']);
430        if($dir===false)
431            return array();
432        $idx[] = array();
433        while (($f = readdir($dir)) !== false) {
434            if (substr($f,0,1) == 'i' && substr($f,-4) == '.idx'){
435                $i = substr($f,1,-4);
436                if (is_numeric($i))
437                    $idx[] = (int)$i;
438            }
439        }
440        closedir($dir);
441        sort($idx);
442        // we save this in a file.
443        if ($docache === true) {
444            $handle = @fopen($conf['indexdir'].'/lengths.idx','w');
445            @fwrite($handle, implode("\n",$idx));
446            @fclose($handle);
447        }
448        return $idx;
449    }
450
451    return array();
452}
453
454/**
455 * Get the word lengths that have been indexed.
456 *
457 * Reads the index directory and returns an array of lengths
458 * that there are indices for.
459 *
460 * @author YoBoY <yoboy.leguesh@gmail.com>
461 */
462function idx_indexLengths(&$filter){
463    global $conf;
464    $idx = array();
465    if (is_array($filter)){
466        // testing if index files exists only
467        foreach ($filter as $key => $value) {
468            if (@file_exists($conf['indexdir']."/i$key.idx")) {
469                $idx[] = $key;
470            }
471        }
472    } else {
473        $lengths = idx_listIndexLengths();
474        foreach ( $lengths as $key => $length) {
475            // we keep all the values equal or superior
476            if ((int)$length >= (int)$filter) {
477                $idx[] = $length;
478            }
479        }
480    }
481    return $idx;
482}
483
484/**
485 * Find the the index number of each search term.
486 *
487 * This will group together words that appear in the same index.
488 * So it should perform better, because it only opens each index once.
489 * Actually, it's not that great. (in my experience) Probably because of the disk cache.
490 * And the sorted function does more work, making it slightly slower in some cases.
491 *
492 * @param array    $words   The query terms. Words should only contain valid characters,
493 *                          with a '*' at either the beginning or end of the word (or both)
494 * @param arrayref $result  Set to word => array("length*id" ...), use this to merge the
495 *                          index locations with the appropriate query term.
496 * @return array            Set to length => array(id ...)
497 *
498 * @author Tom N Harris <tnharris@whoopdedo.org>
499 */
500function idx_getIndexWordsSorted($words,&$result){
501    // parse and sort tokens
502    $tokens = array();
503    $tokenlength = array();
504    $tokenwild = array();
505    foreach($words as $word){
506        $result[$word] = array();
507        $wild = 0;
508        $xword = $word;
509        $wlen = wordlen($word);
510
511        // check for wildcards
512        if(substr($xword,0,1) == '*'){
513            $xword = substr($xword,1);
514            $wild |= 1;
515            $wlen -= 1;
516        }
517        if(substr($xword,-1,1) == '*'){
518            $xword = substr($xword,0,-1);
519            $wild |= 2;
520            $wlen -= 1;
521        }
522        if ($wlen < IDX_MINWORDLENGTH && $wild == 0 && !is_numeric($xword)) continue;
523        if(!isset($tokens[$xword])){
524            $tokenlength[$wlen][] = $xword;
525        }
526        if($wild){
527            $ptn = preg_quote($xword,'/');
528            if(($wild&1) == 0) $ptn = '^'.$ptn;
529            if(($wild&2) == 0) $ptn = $ptn.'$';
530            $tokens[$xword][] = array($word, '/'.$ptn.'/');
531            if(!isset($tokenwild[$xword])) $tokenwild[$xword] = $wlen;
532        }else
533            $tokens[$xword][] = array($word, null);
534    }
535    asort($tokenwild);
536    // $tokens = array( base word => array( [ query word , grep pattern ] ... ) ... )
537    // $tokenlength = array( base word length => base word ... )
538    // $tokenwild = array( base word => base word length ... )
539
540    $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
541    $indexes_known = idx_indexLengths($length_filter);
542    if(!empty($tokenwild)) sort($indexes_known);
543    // get word IDs
544    $wids = array();
545    foreach($indexes_known as $ixlen){
546        $word_idx = idx_getIndex('w',$ixlen);
547        // handle exact search
548        if(isset($tokenlength[$ixlen])){
549            foreach($tokenlength[$ixlen] as $xword){
550                $wid = array_search("$xword\n",$word_idx);
551                if(is_int($wid)){
552                    $wids[$ixlen][] = $wid;
553                    foreach($tokens[$xword] as $w)
554                        $result[$w[0]][] = "$ixlen*$wid";
555                }
556            }
557        }
558        // handle wildcard search
559        foreach($tokenwild as $xword => $wlen){
560            if($wlen >= $ixlen) break;
561            foreach($tokens[$xword] as $w){
562                if(is_null($w[1])) continue;
563                foreach(array_keys(preg_grep($w[1],$word_idx)) as $wid){
564                    $wids[$ixlen][] = $wid;
565                    $result[$w[0]][] = "$ixlen*$wid";
566                }
567            }
568        }
569    }
570    return $wids;
571}
572
573/**
574 * Lookup words in index
575 *
576 * Takes an array of word and will return a list of matching
577 * documents for each one.
578 *
579 * Important: No ACL checking is done here! All results are
580 *            returned, regardless of permissions
581 *
582 * @author Andreas Gohr <andi@splitbrain.org>
583 */
584function idx_lookup($words){
585    global $conf;
586
587    $result = array();
588
589    $wids = idx_getIndexWordsSorted($words, $result);
590    if(empty($wids)) return array();
591
592    // load known words and documents
593    $page_idx = idx_getIndex('page','');
594
595    $docs = array();                          // hold docs found
596    foreach(array_keys($wids) as $wlen){
597        $wids[$wlen] = array_unique($wids[$wlen]);
598        $index = idx_getIndex('i',$wlen);
599        foreach($wids[$wlen] as $ixid){
600            if($ixid < count($index))
601                $docs["$wlen*$ixid"] = idx_parseIndexLine($page_idx,$index[$ixid]);
602        }
603    }
604
605    // merge found pages into final result array
606    $final = array();
607    foreach($result as $word => $res){
608        $final[$word] = array();
609        foreach($res as $wid){
610            $hits = &$docs[$wid];
611            foreach ($hits as $hitkey => $hitcnt) {
612                if (!isset($final[$word][$hitkey])) {
613                    $final[$word][$hitkey] = $hitcnt;
614                } else {
615                    $final[$word][$hitkey] += $hitcnt;
616                }
617            }
618        }
619    }
620    return $final;
621}
622
623/**
624 * Returns a list of documents and counts from a index line
625 *
626 * It omits docs with a count of 0 and pages that no longer
627 * exist.
628 *
629 * @param  array  $page_idx The list of known pages
630 * @param  string $line     A line from the main index
631 * @author Andreas Gohr <andi@splitbrain.org>
632 */
633function idx_parseIndexLine(&$page_idx,$line){
634    $result = array();
635
636    $line = trim($line);
637    if($line == '') return $result;
638
639    $parts = explode(':',$line);
640    foreach($parts as $part){
641        if($part == '') continue;
642        list($doc,$cnt) = explode('*',$part);
643        if(!$cnt) continue;
644        $doc = trim($page_idx[$doc]);
645        if(!$doc) continue;
646        // make sure the document still exists
647        if(!page_exists($doc,'',false)) continue;
648
649        $result[$doc] = $cnt;
650    }
651    return $result;
652}
653
654/**
655 * Tokenizes a string into an array of search words
656 *
657 * Uses the same algorithm as idx_getPageWords()
658 *
659 * @param string   $string     the query as given by the user
660 * @param arrayref $stopwords  array of stopwords
661 * @param boolean  $wc         are wildcards allowed?
662 */
663function idx_tokenizer($string,&$stopwords,$wc=false){
664    $words = array();
665    $wc = ($wc) ? '' : $wc = '\*';
666
667    if(preg_match('/[^0-9A-Za-z]/u', $string)){
668        // handle asian chars as single words (may fail on older PHP version)
669        $asia = @preg_replace('/('.IDX_ASIAN.')/u',' \1 ',$string);
670        if(!is_null($asia)) $string = $asia; //recover from regexp failure
671
672        $arr = explode(' ', utf8_stripspecials($string,' ','\._\-:'.$wc));
673        foreach ($arr as $w) {
674            if (!is_numeric($w) && strlen($w) < IDX_MINWORDLENGTH) continue;
675            $w = utf8_strtolower($w);
676            if($stopwords && is_int(array_search("$w\n",$stopwords))) continue;
677            $words[] = $w;
678        }
679    }else{
680        $w = $string;
681        if (!is_numeric($w) && strlen($w) < IDX_MINWORDLENGTH) return $words;
682        $w = strtolower($w);
683        if(is_int(array_search("$w\n",$stopwords))) return $words;
684        $words[] = $w;
685    }
686
687    return $words;
688}
689
690//Setup VIM: ex: et ts=4 enc=utf-8 :
691