xref: /dokuwiki/inc/indexer.php (revision 63fe0db9b39037ea1ffe8b6cfa4f760a08ebe27a)
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 * This will group together words that appear in the same index.
328 * So it should perform better, because it only opens each index once.
329 * Actually, it's not that great. (in my experience) Probably because of the disk cache.
330 * And the sorted function does more work, making it slightly slower in some cases.
331 *
332 * @param array    $words   The query terms. Words should only contain valid characters,
333 *                          with a '*' at either the beginning or end of the word (or both)
334 * @param arrayref $result  Set to word => array("length*id" ...), use this to merge the
335 *                          index locations with the appropriate query term.
336 * @return array            Set to length => array(id ...)
337 *
338 * @author Tom N Harris <tnharris@whoopdedo.org>
339 */
340function idx_getIndexWordsSorted($words,&$result){
341    // parse and sort tokens
342    $tokens = array();
343    $tokenlength = array();
344    $tokenwild = array();
345    foreach($words as $word){
346        $result[$word] = array();
347        $wild = 0;
348        $xword = $word;
349        $wlen = wordlen($word);
350
351        // check for wildcards
352        if(substr($xword,0,1) == '*'){
353            $xword = substr($xword,1);
354            $wild |= 1;
355            $wlen -= 1;
356        }
357        if(substr($xword,-1,1) == '*'){
358            $xword = substr($xword,0,-1);
359            $wild |= 2;
360            $wlen -= 1;
361        }
362        if ($wlen < 3 && $wild == 0 && !is_numeric($xword)) continue;
363        if(!isset($tokens[$xword])){
364            $tokenlength[$wlen][] = $xword;
365        }
366        if($wild){
367            $ptn = preg_quote($xword,'/');
368            if(($wild&1) == 0) $ptn = '^'.$ptn;
369            if(($wild&2) == 0) $ptn = $ptn.'$';
370            $tokens[$xword][] = array($word, '/'.$ptn.'/');
371            if(!isset($tokenwild[$xword])) $tokenwild[$xword] = $wlen;
372        }else
373            $tokens[$xword][] = array($word, null);
374    }
375    asort($tokenwild);
376    // $tokens = array( base word => array( [ query word , grep pattern ] ... ) ... )
377    // $tokenlength = array( base word length => base word ... )
378    // $tokenwild = array( base word => base word length ... )
379
380    $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
381    $indexes_known = idx_indexLengths($length_filter);
382    if(!empty($tokenwild)) sort($indexes_known);
383    // get word IDs
384    $wids = array();
385    echo "\n";
386    foreach($indexes_known as $ixlen){
387        $word_idx = idx_getIndex('w',$ixlen);
388        // handle exact search
389        if(isset($tokenlength[$ixlen])){
390            foreach($tokenlength[$ixlen] as $xword){
391                $wid = array_search("$xword\n",$word_idx);
392                if(is_int($wid)){
393                    $wids[$ixlen][] = $wid;
394                    foreach($tokens[$xword] as $w)
395                        $result[$w[0]][] = "$ixlen*$wid";
396                }
397            }
398        }
399        // handle wildcard search
400        foreach($tokenwild as $xword => $wlen){
401            if($wlen >= $ixlen) break;
402            foreach($tokens[$xword] as $w){
403                if(is_null($w[1])) continue;
404                foreach(array_keys(preg_grep($w[1],$word_idx)) as $wid){
405                    $wids[$ixlen][] = $wid;
406                    $result[$w[0]][] = "$ixlen*$wid";
407                }
408            }
409        }
410    }
411  return $wids;
412}
413
414/**
415 * Lookup words in index
416 *
417 * Takes an array of word and will return a list of matching
418 * documents for each one.
419 *
420 * Important: No ACL checking is done here! All results are
421 *            returned, regardless of permissions
422 *
423 * @author Andreas Gohr <andi@splitbrain.org>
424 */
425function idx_lookup($words){
426    global $conf;
427
428    $result = array();
429
430    $wids = idx_getIndexWordsSorted($words, $result);
431    if(empty($wids)) return array();
432
433    // load known words and documents
434    $page_idx = idx_getIndex('page','');
435
436    $docs = array();                          // hold docs found
437    foreach(array_keys($wids) as $wlen){
438        $wids[$wlen] = array_unique($wids[$wlen]);
439        $index = idx_getIndex('i',$wlen);
440        foreach($wids[$wlen] as $ixid){
441            if($ixid < count($index))
442                $docs["$wlen*$ixid"] = idx_parseIndexLine($page_idx,$index[$ixid]);
443        }
444    }
445
446    // merge found pages into final result array
447    $final = array();
448    foreach(array_keys($result) as $word){
449        $final[$word] = array();
450        foreach($result[$word] as $wid){
451            $hits = &$docs[$wid];
452            foreach ($hits as $hitkey => $hitcnt) {
453                $final[$word][$hitkey] = $hitcnt + $final[$word][$hitkey];
454            }
455        }
456    }
457    return $final;
458}
459
460/**
461 * Returns a list of documents and counts from a index line
462 *
463 * It omits docs with a count of 0 and pages that no longer
464 * exist.
465 *
466 * @param  array  $page_idx The list of known pages
467 * @param  string $line     A line from the main index
468 * @author Andreas Gohr <andi@splitbrain.org>
469 */
470function idx_parseIndexLine(&$page_idx,$line){
471    $result = array();
472
473    $line = trim($line);
474    if($line == '') return $result;
475
476    $parts = explode(':',$line);
477    foreach($parts as $part){
478        if($part == '') continue;
479        list($doc,$cnt) = explode('*',$part);
480        if(!$cnt) continue;
481        $doc = trim($page_idx[$doc]);
482        if(!$doc) continue;
483        // make sure the document still exists
484        if(!@file_exists(wikiFN($doc,'',false))) continue;
485
486        $result[$doc] = $cnt;
487    }
488    return $result;
489}
490
491/**
492 * Tokenizes a string into an array of search words
493 *
494 * Uses the same algorithm as idx_getPageWords()
495 *
496 * @param string   $string     the query as given by the user
497 * @param arrayref $stopwords  array of stopwords
498 * @param boolean  $wc         are wildcards allowed?
499 */
500function idx_tokenizer($string,&$stopwords,$wc=false){
501    $words = array();
502    $wc = ($wc) ? '' : $wc = '\*';
503
504    if(preg_match('/[^0-9A-Za-z]/u', $string)){
505        // handle asian chars as single words (may fail on older PHP version)
506        $asia = @preg_replace('/('.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')/u',' \1 ',$string);
507        if(!is_null($asia)) $string = $asia; //recover from regexp failure
508
509        $arr = explode(' ', utf8_stripspecials($string,' ','\._\-:'.$wc));
510        foreach ($arr as $w) {
511            if (!is_numeric($w) && strlen($w) < 3) continue;
512            $w = utf8_strtolower($w);
513            if($stopwords && is_int(array_search("$w\n",$stopwords))) continue;
514            $words[] = $w;
515        }
516    }else{
517        $w = $string;
518        if (!is_numeric($w) && strlen($w) < 3) return $words;
519        $w = strtolower($w);
520        if(is_int(array_search("$w\n",$stopwords))) return $words;
521        $words[] = $w;
522    }
523
524    return $words;
525}
526
527//Setup VIM: ex: et ts=4 enc=utf-8 :
528