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