xref: /dokuwiki/inc/indexer.php (revision 4cab3ca7bcb592c65b93e21e7528f0c2a02deaf3)
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 = '';
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    // get word usage in page
220    $words = idx_getPageWords($page);
221    if($words === false) return false;
222    if(!count($words)) return true;
223
224    foreach(array_keys($words) as $wlen){
225        $index = idx_getIndex('i',$wlen);
226        foreach($words[$wlen] as $wid => $freq){
227            if($wid<count($index)){
228                $index[$wid] = idx_updateIndexLine($index[$wid],$pid,$freq);
229            }else{
230                // New words **should** have been added in increasing order
231                // starting with the first unassigned index.
232                // If someone can show how this isn't true, then I'll need to sort
233                // or do something special.
234                $index[$wid] = idx_updateIndexLine('',$pid,$freq);
235            }
236        }
237        // save back word index
238        if(!idx_saveIndex('i',$wlen,$index)){
239            trigger_error("Failed to write index", E_USER_ERROR);
240            return false;
241        }
242    }
243
244    return true;
245}
246
247/**
248 * Write a new index line to the filehandle
249 *
250 * This function writes an line for the index file to the
251 * given filehandle. It removes the given document from
252 * the given line and readds it when $count is >0.
253 *
254 * @deprecated - see idx_updateIndexLine
255 * @author Andreas Gohr <andi@splitbrain.org>
256 */
257function idx_writeIndexLine($fh,$line,$pid,$count){
258    fwrite($fh,idx_updateIndexLine($line,$pid,$count));
259}
260
261/**
262 * Modify an index line with new information
263 *
264 * This returns a line of the index. It removes the
265 * given document from the line and readds it if
266 * $count is >0.
267 *
268 * @author Tom N Harris <tnharris@whoopdedo.org>
269 * @author Andreas Gohr <andi@splitbrain.org>
270 */
271function idx_updateIndexLine($line,$pid,$count){
272    $line = trim($line);
273    $updated = array();
274    if($line != ''){
275        $parts = explode(':',$line);
276        // remove doc from given line
277        foreach($parts as $part){
278            if($part == '') continue;
279            list($doc,$cnt) = explode('*',$part);
280            if($doc != $pid){
281                $updated[] = $part;
282            }
283        }
284    }
285
286    // add doc
287    if ($count){
288        $updated[] = "$pid*$count";
289    }
290
291    return join(':',$updated)."\n";
292}
293
294/**
295 * Get the word lengths that have been indexed.
296 *
297 * Reads the index directory and returns an array of lengths
298 * that there are indices for.
299 *
300 * @author Tom N Harris <tnharris@whoopdedo.org>
301 */
302function idx_indexLengths(&$filter){
303    global $conf;
304    $dir = @opendir($conf['indexdir']);
305    if($dir===false)
306        return array();
307    $idx = array();
308    if(is_array($filter)){
309        while (($f = readdir($dir)) !== false) {
310            if (substr($f,0,1) == 'i' && substr($f,-4) == '.idx'){
311                $i = substr($f,1,-4);
312                if (is_numeric($i) && isset($filter[(int)$i]))
313                    $idx[] = (int)$i;
314            }
315        }
316    }else{
317        // Exact match first.
318        if(@file_exists($conf['indexdir']."/i$filter.idx"))
319            $idx[] = $filter;
320        while (($f = readdir($dir)) !== false) {
321            if (substr($f,0,1) == 'i' && substr($f,-4) == '.idx'){
322                $i = substr($f,1,-4);
323                if (is_numeric($i) && $i > $filter)
324                    $idx[] = (int)$i;
325            }
326        }
327    }
328    closedir($dir);
329    return $idx;
330}
331
332/**
333 * Find the the index number of each search term.
334 *
335 * This will group together words that appear in the same index.
336 * So it should perform better, because it only opens each index once.
337 * Actually, it's not that great. (in my experience) Probably because of the disk cache.
338 * And the sorted function does more work, making it slightly slower in some cases.
339 *
340 * @param array    $words   The query terms. Words should only contain valid characters,
341 *                          with a '*' at either the beginning or end of the word (or both)
342 * @param arrayref $result  Set to word => array("length*id" ...), use this to merge the
343 *                          index locations with the appropriate query term.
344 * @return array            Set to length => array(id ...)
345 *
346 * @author Tom N Harris <tnharris@whoopdedo.org>
347 */
348function idx_getIndexWordsSorted($words,&$result){
349    // parse and sort tokens
350    $tokens = array();
351    $tokenlength = array();
352    $tokenwild = array();
353    foreach($words as $word){
354        $result[$word] = array();
355        $wild = 0;
356        $xword = $word;
357        $wlen = wordlen($word);
358
359        // check for wildcards
360        if(substr($xword,0,1) == '*'){
361            $xword = substr($xword,1);
362            $wild |= 1;
363            $wlen -= 1;
364        }
365        if(substr($xword,-1,1) == '*'){
366            $xword = substr($xword,0,-1);
367            $wild |= 2;
368            $wlen -= 1;
369        }
370        if ($wlen < 3 && $wild == 0 && !is_numeric($xword)) continue;
371        if(!isset($tokens[$xword])){
372            $tokenlength[$wlen][] = $xword;
373        }
374        if($wild){
375            $ptn = preg_quote($xword,'/');
376            if(($wild&1) == 0) $ptn = '^'.$ptn;
377            if(($wild&2) == 0) $ptn = $ptn.'$';
378            $tokens[$xword][] = array($word, '/'.$ptn.'/');
379            if(!isset($tokenwild[$xword])) $tokenwild[$xword] = $wlen;
380        }else
381            $tokens[$xword][] = array($word, null);
382    }
383    asort($tokenwild);
384    // $tokens = array( base word => array( [ query word , grep pattern ] ... ) ... )
385    // $tokenlength = array( base word length => base word ... )
386    // $tokenwild = array( base word => base word length ... )
387
388    $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
389    $indexes_known = idx_indexLengths($length_filter);
390    if(!empty($tokenwild)) sort($indexes_known);
391    // get word IDs
392    $wids = array();
393    echo "\n";
394    foreach($indexes_known as $ixlen){
395        $word_idx = idx_getIndex('w',$ixlen);
396        // handle exact search
397        if(isset($tokenlength[$ixlen])){
398            foreach($tokenlength[$ixlen] as $xword){
399                $wid = array_search("$xword\n",$word_idx);
400                if(is_int($wid)){
401                    $wids[$ixlen][] = $wid;
402                    foreach($tokens[$xword] as $w)
403                        $result[$w[0]][] = "$ixlen*$wid";
404                }
405            }
406        }
407        // handle wildcard search
408        foreach($tokenwild as $xword => $wlen){
409            if($wlen >= $ixlen) break;
410            foreach($tokens[$xword] as $w){
411                if(is_null($w[1])) continue;
412                foreach(array_keys(preg_grep($w[1],$word_idx)) as $wid){
413                    $wids[$ixlen][] = $wid;
414                    $result[$w[0]][] = "$ixlen*$wid";
415                }
416            }
417        }
418    }
419  return $wids;
420}
421
422/**
423 * Lookup words in index
424 *
425 * Takes an array of word and will return a list of matching
426 * documents for each one.
427 *
428 * Important: No ACL checking is done here! All results are
429 *            returned, regardless of permissions
430 *
431 * @author Andreas Gohr <andi@splitbrain.org>
432 */
433function idx_lookup($words){
434    global $conf;
435
436    $result = array();
437
438    $wids = idx_getIndexWordsSorted($words, $result);
439    if(empty($wids)) return array();
440
441    // load known words and documents
442    $page_idx = idx_getIndex('page','');
443
444    $docs = array();                          // hold docs found
445    foreach(array_keys($wids) as $wlen){
446        $wids[$wlen] = array_unique($wids[$wlen]);
447        $index = idx_getIndex('i',$wlen);
448        foreach($wids[$wlen] as $ixid){
449            if($ixid < count($index))
450                $docs["$wlen*$ixid"] = idx_parseIndexLine($page_idx,$index[$ixid]);
451        }
452    }
453
454    // merge found pages into final result array
455    $final = array();
456    foreach(array_keys($result) as $word){
457        $final[$word] = array();
458        foreach($result[$word] as $wid){
459            $hits = &$docs[$wid];
460            foreach ($hits as $hitkey => $hitcnt) {
461                $final[$word][$hitkey] = $hitcnt + $final[$word][$hitkey];
462            }
463        }
464    }
465    return $final;
466}
467
468/**
469 * Returns a list of documents and counts from a index line
470 *
471 * It omits docs with a count of 0 and pages that no longer
472 * exist.
473 *
474 * @param  array  $page_idx The list of known pages
475 * @param  string $line     A line from the main index
476 * @author Andreas Gohr <andi@splitbrain.org>
477 */
478function idx_parseIndexLine(&$page_idx,$line){
479    $result = array();
480
481    $line = trim($line);
482    if($line == '') return $result;
483
484    $parts = explode(':',$line);
485    foreach($parts as $part){
486        if($part == '') continue;
487        list($doc,$cnt) = explode('*',$part);
488        if(!$cnt) continue;
489        $doc = trim($page_idx[$doc]);
490        if(!$doc) continue;
491        // make sure the document still exists
492        if(!@file_exists(wikiFN($doc,'',false))) continue;
493
494        $result[$doc] = $cnt;
495    }
496    return $result;
497}
498
499/**
500 * Tokenizes a string into an array of search words
501 *
502 * Uses the same algorithm as idx_getPageWords()
503 *
504 * @param string   $string     the query as given by the user
505 * @param arrayref $stopwords  array of stopwords
506 * @param boolean  $wc         are wildcards allowed?
507 */
508function idx_tokenizer($string,&$stopwords,$wc=false){
509    $words = array();
510    $wc = ($wc) ? '' : $wc = '\*';
511
512    if(preg_match('/[^0-9A-Za-z]/u', $string)){
513        // handle asian chars as single words (may fail on older PHP version)
514        $asia = @preg_replace('/('.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')/u',' \1 ',$string);
515        if(!is_null($asia)) $string = $asia; //recover from regexp failure
516
517        $arr = explode(' ', utf8_stripspecials($string,' ','\._\-:'.$wc));
518        foreach ($arr as $w) {
519            if (!is_numeric($w) && strlen($w) < 3) continue;
520            $w = utf8_strtolower($w);
521            if($stopwords && is_int(array_search("$w\n",$stopwords))) continue;
522            $words[] = $w;
523        }
524    }else{
525        $w = $string;
526        if (!is_numeric($w) && strlen($w) < 3) return $words;
527        $w = strtolower($w);
528        if(is_int(array_search("$w\n",$stopwords))) return $words;
529        $words[] = $w;
530    }
531
532    return $words;
533}
534
535//Setup VIM: ex: et ts=4 enc=utf-8 :
536