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