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