xref: /dokuwiki/inc/indexer.php (revision bc6ecc12f39db1fe4b3e22e2a939f70691d6d1fc)
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',realpath(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{30FB}-\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                   ']?');
44
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 occured.
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   = rawWiki($page);
123    $body   = strtr($body, "\r\n\t", '   ');
124    $tokens = explode(' ', $body);
125    $tokens = array_count_values($tokens);   // count the frequency of each token
126
127// ensure the deaccented or romanised page names of internal links are added to the token array
128// (this is necessary for the backlink function -- there maybe a better way!)
129    if ($conf['deaccent']) {
130      $links = p_get_metadata($page,'relation references');
131
132      if (!empty($links)) {
133        $tmp = join(' ',array_keys($links));                // make a single string
134        $tmp = strtr($tmp, ':', ' ');                       // replace namespace separator with a space
135        $link_tokens = array_unique(explode(' ', $tmp));    // break into tokens
136
137        foreach ($link_tokens as $link_token) {
138          if (isset($tokens[$link_token])) continue;
139          $tokens[$link_token] = 1;
140        }
141      }
142    }
143
144    $words = array();
145    foreach ($tokens as $word => $count) {
146        $arr = idx_tokenizer($word,$stopwords);
147        $arr = array_count_values($arr);
148        foreach ($arr as $w => $c) {
149            $l = wordlen($w);
150            if(isset($words[$l])){
151                $words[$l][$w] = $c * $count + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
152            }else{
153                $words[$l] = array($w => $c * $count);
154            }
155        }
156    }
157
158    // arrive here with $words = array(wordlen => array(word => frequency))
159
160    $index = array(); //resulting index
161    foreach (array_keys($words) as $wlen){
162        $word_idx = idx_getIndex('w',$wlen);
163        foreach ($words[$wlen] as $word => $freq) {
164            $wid = array_search("$word\n",$word_idx);
165            if(!is_int($wid)){
166                $wid = count($word_idx);
167                $word_idx[] = "$word\n";
168            }
169            if(!isset($index[$wlen]))
170                $index[$wlen] = array();
171            $index[$wlen][$wid] = $freq;
172        }
173
174        // save back word index
175        if(!idx_saveIndex('w',$wlen,$word_idx)){
176            trigger_error("Failed to write word index", E_USER_ERROR);
177            return false;
178        }
179    }
180
181    return $index;
182}
183
184/**
185 * Adds/updates the search for the given page
186 *
187 * This is the core function of the indexer which does most
188 * of the work. This function needs to be called with proper
189 * locking!
190 *
191 * @author Andreas Gohr <andi@splitbrain.org>
192 */
193function idx_addPage($page){
194    global $conf;
195
196    // load known documents
197    $page_idx = idx_getIndex('page','');
198
199    // get page id (this is the linenumber in page.idx)
200    $pid = array_search("$page\n",$page_idx);
201    if(!is_int($pid)){
202        $page_idx[] = "$page\n";
203        $pid = count($page_idx)-1;
204        // page was new - write back
205        if (!idx_saveIndex('page','',$page_idx)){
206            trigger_error("Failed to write page index", E_USER_ERROR);
207            return false;
208        }
209    }
210
211    // get word usage in page
212    $words = idx_getPageWords($page);
213    if($words === false) return false;
214    if(!count($words)) return true;
215
216    foreach(array_keys($words) as $wlen){
217        $index = idx_getIndex('i',$wlen);
218        foreach($words[$wlen] as $wid => $freq){
219            if($wid<count($index)){
220                $index[$wid] = idx_updateIndexLine($index[$wid],$pid,$freq);
221            }else{
222                // New words **should** have been added in increasing order
223                // starting with the first unassigned index.
224                // If someone can show how this isn't true, then I'll need to sort
225                // or do something special.
226                $index[$wid] = idx_updateIndexLine('',$pid,$freq);
227            }
228        }
229        // save back word index
230        if(!idx_saveIndex('i',$wlen,$index)){
231            trigger_error("Failed to write index", E_USER_ERROR);
232            return false;
233        }
234    }
235
236    return true;
237}
238
239/**
240 * Write a new index line to the filehandle
241 *
242 * This function writes an line for the index file to the
243 * given filehandle. It removes the given document from
244 * the given line and readds it when $count is >0.
245 *
246 * @deprecated - see idx_updateIndexLine
247 * @author Andreas Gohr <andi@splitbrain.org>
248 */
249function idx_writeIndexLine($fh,$line,$pid,$count){
250    fwrite($fh,idx_updateIndexLine($line,$pid,$count));
251}
252
253/**
254 * Modify an index line with new information
255 *
256 * This returns a line of the index. It removes the
257 * given document from the line and readds it if
258 * $count is >0.
259 *
260 * @author Tom N Harris <tnharris@whoopdedo.org>
261 * @author Andreas Gohr <andi@splitbrain.org>
262 */
263function idx_updateIndexLine($line,$pid,$count){
264    $line = trim($line);
265    $updated = array();
266    if($line != ''){
267        $parts = explode(':',$line);
268        // remove doc from given line
269        foreach($parts as $part){
270            if($part == '') continue;
271            list($doc,$cnt) = explode('*',$part);
272            if($doc != $pid){
273                $updated[] = $part;
274            }
275        }
276    }
277
278    // add doc
279    if ($count){
280        $updated[] = "$pid*$count";
281    }
282
283    return join(':',$updated)."\n";
284}
285
286/**
287 * Get the word lengths that have been indexed.
288 *
289 * Reads the index directory and returns an array of lengths
290 * that there are indices for.
291 *
292 * @author Tom N Harris <tnharris@whoopdedo.org>
293 */
294function idx_indexLengths(&$filter){
295    global $conf;
296    $dir = @opendir($conf['indexdir']);
297    if($dir===false)
298        return array();
299    $idx = array();
300    if(is_array($filter)){
301        while (($f = readdir($dir)) !== false) {
302            if (substr($f,0,1) == 'i' && substr($f,-4) == '.idx'){
303                $i = substr($f,1,-4);
304                if (is_numeric($i) && isset($filter[(int)$i]))
305                    $idx[] = (int)$i;
306            }
307        }
308    }else{
309        // Exact match first.
310        if(@file_exists($conf['indexdir']."/i$filter.idx"))
311            $idx[] = $filter;
312        while (($f = readdir($dir)) !== false) {
313            if (substr($f,0,1) == 'i' && substr($f,-4) == '.idx'){
314                $i = substr($f,1,-4);
315                if (is_numeric($i) && $i > $filter)
316                    $idx[] = (int)$i;
317            }
318        }
319    }
320    closedir($dir);
321    return $idx;
322}
323
324/**
325 * Find the the index number of each search term.
326 *
327 * There are two variation: Simple and Sorted.
328 * The simple version just takes the words one at a time.
329 * The sorted version will group together words that appear in the same index.
330 * So it should perform better, because it only opens each index once.
331 * Actually, it's not that great. (in my experience) Probably because of the disk cache.
332 * And the sorted function does more work, making it slightly slower in some cases.
333 *
334 * For now, you can choose to use the sorted version by setting $conf['test_indexer'] = 1
335 * Eventually, the more worthy will be chosen and the loser cast into the deepest depths.
336 *
337 * @param array    $words   The query terms. Words should only contain valid characters,
338 *                          with a '*' at either the beginning or end of the word (or both)
339 * @param arrayref $result  Set to word => array("length*id" ...), use this to merge the
340 *                          index locations with the appropriate query term.
341 * @return array            Set to length => array(id ...)
342 *
343 * @author Tom N Harris <tnharris@whoopdedo.org>
344 */
345function idx_getIndexWordsSimple($words, &$result){
346    // get word IDs
347    $wids = array();
348    foreach($words as $word){
349        $result[$word] = array();
350        $wild = 0;
351        $xword = $word;
352        $wlen = wordlen($word);
353
354        // check for wildcards
355        if(substr($xword,0,1) == '*'){
356            $xword = substr($xword,1);
357            $wild |= 1;
358            $wlen -= 1;
359        }
360        if(substr($xword,-1,1) == '*'){
361            $xword = substr($xword,0,-1);
362            $wild |= 2;
363            $wlen -= 1;
364        }
365        if ($wlen < 3 && $wild == 0 && !is_numeric($xword)) continue;
366
367        // look for the ID(s) for the given word
368        if($wild){  // handle wildcard search
369            $ptn = preg_quote($xword,'/');
370            if(($wild&1) == 0) $ptn = '^'.$ptn;
371            if(($wild&2) == 0) $ptn = $ptn.'$';
372            $ptn = '/'.$ptn.'/';
373            foreach (idx_indexLengths($wlen) as $ixlen){
374                $word_idx = idx_getIndex('w',$ixlen);
375                foreach(array_keys(preg_grep($ptn,$word_idx)) as $wid){
376                    $wids[$ixlen][] = $wid;
377                    $result[$word][] = "$ixlen*$wid";
378                }
379            }
380        }else{     // handle exact search
381            $word_idx = idx_getIndex('w',$wlen);
382            $wid = array_search("$word\n",$word_idx);
383            if(is_int($wid)){
384                $wids[$wlen][] = $wid;
385                $result[$word][] = "$wlen*$wid";
386            }else{
387                $result[$word] = array();
388            }
389        }
390    }
391    return $wids;
392}
393function idx_getIndexWordsSorted($words,&$result){
394    // parse and sort tokens
395    $tokens = array();
396    $tokenlength = array();
397    $tokenwild = array();
398    foreach($words as $word){
399        $result[$word] = array();
400        $wild = 0;
401        $xword = $word;
402        $wlen = wordlen($word);
403
404        // check for wildcards
405        if(substr($xword,0,1) == '*'){
406            $xword = substr($xword,1);
407            $wild |= 1;
408            $wlen -= 1;
409        }
410        if(substr($xword,-1,1) == '*'){
411            $xword = substr($xword,0,-1);
412            $wild |= 2;
413            $wlen -= 1;
414        }
415        if ($wlen < 3 && $wild == 0 && !is_numeric($xword)) continue;
416        if(!isset($tokens[$xword])){
417            $tokenlength[$wlen][] = $xword;
418        }
419        if($wild){
420            $ptn = preg_quote($xword,'/');
421            if(($wild&1) == 0) $ptn = '^'.$ptn;
422            if(($wild&2) == 0) $ptn = $ptn.'$';
423            $tokens[$xword][] = array($word, '/'.$ptn.'/');
424            if(!isset($tokenwild[$xword])) $tokenwild[$xword] = $wlen;
425        }else
426            $tokens[$xword][] = array($word, null);
427    }
428    asort($tokenwild);
429    // $tokens = array( base word => array( [ query word , grep pattern ] ... ) ... )
430    // $tokenlength = array( base word length => base word ... )
431    // $tokenwild = array( base word => base word length ... )
432
433    $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
434    $indexes_known = idx_indexLengths($length_filter);
435    if(!empty($tokenwild)) sort($indexes_known);
436    // get word IDs
437    $wids = array();
438    echo "\n";
439    foreach($indexes_known as $ixlen){
440        $word_idx = idx_getIndex('w',$ixlen);
441        // handle exact search
442        if(isset($tokenlength[$ixlen])){
443            foreach($tokenlength[$ixlen] as $xword){
444                $wid = array_search("$xword\n",$word_idx);
445                if(is_int($wid)){
446                    $wids[$ixlen][] = $wid;
447                    foreach($tokens[$xword] as $w)
448                        $result[$w[0]][] = "$ixlen*$wid";
449                }
450            }
451        }
452        // handle wildcard search
453        foreach($tokenwild as $xword => $wlen){
454            if($wlen >= $ixlen) break;
455            foreach($tokens[$xword] as $w){
456                if(is_null($w[1])) continue;
457                foreach(array_keys(preg_grep($w[1],$word_idx)) as $wid){
458                    $wids[$ixlen][] = $wid;
459                    $result[$w[0]][] = "$ixlen*$wid";
460                }
461            }
462        }
463    }
464  return $wids;
465}
466
467/**
468 * Lookup words in index
469 *
470 * Takes an array of word and will return a list of matching
471 * documents for each one.
472 *
473 * Important: No ACL checking is done here! All results are
474 *            returned, regardless of permissions
475 *
476 * @author Andreas Gohr <andi@splitbrain.org>
477 */
478function idx_lookup($words){
479    global $conf;
480
481    $result = array();
482
483    if(isset($conf['test_indexer']) && ($conf['test_indexer']&1))
484        $wids = idx_getIndexWordsSorted($words, $result);
485    else
486        $wids = idx_getIndexWordsSimple($words, $result);
487    if(empty($wids)) return array();
488
489    // load known words and documents
490    $page_idx = idx_getIndex('page','');
491
492    $docs = array();                          // hold docs found
493    foreach(array_keys($wids) as $wlen){
494        $wids[$wlen] = array_unique($wids[$wlen]);
495        $index = idx_getIndex('i',$wlen);
496        foreach($wids[$wlen] as $ixid){
497            if($ixid < count($index))
498                $docs["$wlen*$ixid"] = idx_parseIndexLine($page_idx,$index[$ixid]);
499        }
500    }
501
502    // merge found pages into final result array
503    $final = array();
504    foreach(array_keys($result) as $word){
505        $final[$word] = array();
506        foreach($result[$word] as $wid){
507            $hits = &$docs[$wid];
508            foreach ($hits as $hitkey => $hitcnt) {
509                $final[$word][$hitkey] = $hitcnt + $final[$word][$hitkey];
510            }
511        }
512    }
513    return $final;
514}
515
516/**
517 * Returns a list of documents and counts from a index line
518 *
519 * It omits docs with a count of 0 and pages that no longer
520 * exist.
521 *
522 * @param  array  $page_idx The list of known pages
523 * @param  string $line     A line from the main index
524 * @author Andreas Gohr <andi@splitbrain.org>
525 */
526function idx_parseIndexLine(&$page_idx,$line){
527    $result = array();
528
529    $line = trim($line);
530    if($line == '') return $result;
531
532    $parts = explode(':',$line);
533    foreach($parts as $part){
534        if($part == '') continue;
535        list($doc,$cnt) = explode('*',$part);
536        if(!$cnt) continue;
537        $doc = trim($page_idx[$doc]);
538        if(!$doc) continue;
539        // make sure the document still exists
540        if(!@file_exists(wikiFN($doc,'',false))) continue;
541
542        $result[$doc] = $cnt;
543    }
544    return $result;
545}
546
547/**
548 * Tokenizes a string into an array of search words
549 *
550 * Uses the same algorithm as idx_getPageWords()
551 *
552 * @param string   $string     the query as given by the user
553 * @param arrayref $stopwords  array of stopwords
554 * @param boolean  $wc         are wildcards allowed?
555 */
556function idx_tokenizer($string,&$stopwords,$wc=false){
557    $words = array();
558    $wc = ($wc) ? '' : $wc = '\*';
559
560    if(preg_match('/[^0-9A-Za-z]/u', $string)){
561        // handle asian chars as single words (may fail on older PHP version)
562        $asia = @preg_replace('/('.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')/u',' \1 ',$string);
563        if(!is_null($asia)) $string = $asia; //recover from regexp failure
564
565        $arr = explode(' ', utf8_stripspecials($string,' ','\._\-:'.$wc));
566        foreach ($arr as $w) {
567            if (!is_numeric($w) && strlen($w) < 3) continue;
568            $w = utf8_strtolower($w);
569            if($stopwords && is_int(array_search("$w\n",$stopwords))) continue;
570            $words[] = $w;
571        }
572    }else{
573        $w = $string;
574        if (!is_numeric($w) && strlen($w) < 3) return $words;
575        $w = strtolower($w);
576        if(is_int(array_search("$w\n",$stopwords))) return $words;
577        $words[] = $w;
578    }
579
580    return $words;
581}
582
583//Setup VIM: ex: et ts=4 enc=utf-8 :
584