xref: /dokuwiki/inc/indexer.php (revision adb16d4f36e6e2cfb75ce8c8d42724c7705dfe3c)
1b4ce25e9SAndreas Gohr<?php
2b4ce25e9SAndreas Gohr/**
3b4ce25e9SAndreas Gohr * Common DokuWiki functions
4b4ce25e9SAndreas Gohr *
5b4ce25e9SAndreas Gohr * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6b4ce25e9SAndreas Gohr * @author     Andreas Gohr <andi@splitbrain.org>
7b4ce25e9SAndreas Gohr */
8b4ce25e9SAndreas Gohr
9b4ce25e9SAndreas Gohr  if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../').'/');
10b4ce25e9SAndreas Gohr  require_once(DOKU_CONF.'dokuwiki.php');
11b4ce25e9SAndreas Gohr  require_once(DOKU_INC.'inc/io.php');
12b4ce25e9SAndreas Gohr  require_once(DOKU_INC.'inc/utf8.php');
13b4ce25e9SAndreas Gohr  require_once(DOKU_INC.'inc/parserutils.php');
14b4ce25e9SAndreas Gohr
1593a60ad2SAndreas Gohr// Asian characters are handled as words. The following regexp defines the
1693a60ad2SAndreas Gohr// Unicode-Ranges for Asian characters
1793a60ad2SAndreas Gohr// Ranges taken from http://en.wikipedia.org/wiki/Unicode_block
1893a60ad2SAndreas Gohr// I'm no language expert. If you think some ranges are wrongly chosen or
1993a60ad2SAndreas Gohr// a range is missing, please contact me
20d5b23302STom N Harrisdefine('IDX_ASIAN1','[\x{0E00}-\x{0E7F}]'); // Thai
21d5b23302STom N Harrisdefine('IDX_ASIAN2','['.
22d5b23302STom N Harris                   '\x{2E80}-\x{3040}'.  // CJK -> Hangul
23d5b23302STom N Harris                   '\x{309D}-\x{30A0}'.
24d5b23302STom N Harris                   '\x{30FB}-\x{31EF}\x{3200}-\x{D7AF}'.
2593a60ad2SAndreas Gohr                   '\x{F900}-\x{FAFF}'.  // CJK Compatibility Ideographs
2693a60ad2SAndreas Gohr                   '\x{FE30}-\x{FE4F}'.  // CJK Compatibility Forms
2793a60ad2SAndreas Gohr                   ']');
28d5b23302STom N Harrisdefine('IDX_ASIAN3','['.                // Hiragana/Katakana (can be two characters)
29d5b23302STom N Harris                   '\x{3042}\x{3044}\x{3046}\x{3048}'.
30d5b23302STom N Harris                   '\x{304A}-\x{3062}\x{3064}-\x{3082}'.
31d5b23302STom N Harris                   '\x{3084}\x{3086}\x{3088}-\x{308D}'.
32d5b23302STom N Harris                   '\x{308F}-\x{3094}'.
33d5b23302STom N Harris                   '\x{30A2}\x{30A4}\x{30A6}\x{30A8}'.
34d5b23302STom N Harris                   '\x{30AA}-\x{30C2}\x{30C4}-\x{30E2}'.
35d5b23302STom N Harris                   '\x{30E4}\x{30E6}\x{30E8}-\x{30ED}'.
36d5b23302STom N Harris                   '\x{30EF}-\x{30F4}\x{30F7}-\x{30FA}'.
37d5b23302STom N Harris                   ']['.
38d5b23302STom N Harris                   '\x{3041}\x{3043}\x{3045}\x{3047}\x{3049}'.
39d5b23302STom N Harris                   '\x{3063}\x{3083}\x{3085}\x{3087}\x{308E}\x{3095}-\x{309C}'.
40d5b23302STom N Harris                   '\x{30A1}\x{30A3}\x{30A5}\x{30A7}\x{30A9}'.
41d5b23302STom N Harris                   '\x{30C3}\x{30E3}\x{30E5}\x{30E7}\x{30EE}\x{30F5}\x{30F6}\x{30FB}\x{30FC}'.
42d5b23302STom N Harris                   '\x{31F0}-\x{31FF}'.
43d5b23302STom N Harris                   ']?');
4493a60ad2SAndreas Gohr
4593a60ad2SAndreas Gohr
46b4ce25e9SAndreas Gohr/**
47d5b23302STom N Harris * Measure the length of a string.
48d5b23302STom N Harris * Differs from strlen in handling of asian characters.
49d5b23302STom N Harris *
50d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
51d5b23302STom N Harris */
52d5b23302STom N Harrisfunction wordlen($w){
53d5b23302STom N Harris    $l = strlen($w);
54d5b23302STom N Harris    // If left alone, all chinese "words" will get put into w3.idx
55d5b23302STom N Harris    // So the "length" of a "word" is faked
56d5b23302STom N Harris    if(preg_match('/'.IDX_ASIAN2.'/u',$w))
57d5b23302STom N Harris        $l += ord($w) - 0xE1;  // Lead bytes from 0xE2-0xEF
58d5b23302STom N Harris    return $l;
59d5b23302STom N Harris}
60d5b23302STom N Harris
61d5b23302STom N Harris/**
62579b0f7eSTNHarris * Write a list of strings to an index file.
63579b0f7eSTNHarris *
64579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
65579b0f7eSTNHarris */
66579b0f7eSTNHarrisfunction idx_saveIndex($pre, $wlen, $idx){
67579b0f7eSTNHarris    global $conf;
68579b0f7eSTNHarris    $fn = $conf['indexdir'].'/'.$pre.$wlen;
69579b0f7eSTNHarris    $fh = @fopen($fn.'.tmp','w');
70579b0f7eSTNHarris    if(!$fh) return false;
71579b0f7eSTNHarris    fwrite($fh,join('',$idx));
72579b0f7eSTNHarris    fclose($fh);
73579b0f7eSTNHarris    if($conf['fperm']) chmod($fn.'.tmp', $conf['fperm']);
74579b0f7eSTNHarris    io_rename($fn.'.tmp', $fn.'.idx');
75579b0f7eSTNHarris    return true;
76579b0f7eSTNHarris}
77579b0f7eSTNHarris
78579b0f7eSTNHarris/**
79579b0f7eSTNHarris * Read the list of words in an index (if it exists).
80579b0f7eSTNHarris *
81579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
82579b0f7eSTNHarris */
83579b0f7eSTNHarrisfunction idx_getIndex($pre, $wlen){
84579b0f7eSTNHarris    global $conf;
85579b0f7eSTNHarris    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
86579b0f7eSTNHarris    if(!@file_exists($fn)) return array();
87579b0f7eSTNHarris    return file($fn);
88579b0f7eSTNHarris}
89579b0f7eSTNHarris
90579b0f7eSTNHarris/**
91579b0f7eSTNHarris * Create an empty index file if it doesn't exist yet.
92579b0f7eSTNHarris *
93579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
94579b0f7eSTNHarris */
95579b0f7eSTNHarrisfunction idx_touchIndex($pre, $wlen){
96579b0f7eSTNHarris    global $conf;
97579b0f7eSTNHarris    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
98579b0f7eSTNHarris    if(!@file_exists($fn)){
99579b0f7eSTNHarris        touch($fn);
100579b0f7eSTNHarris        if($conf['fperm']) chmod($fn, $conf['fperm']);
101579b0f7eSTNHarris    }
102579b0f7eSTNHarris}
103579b0f7eSTNHarris
104579b0f7eSTNHarris/**
10544ca0adfSAndreas Gohr * Split a page into words
10644ca0adfSAndreas Gohr *
107579b0f7eSTNHarris * Returns an array of word counts, false if an error occured.
108579b0f7eSTNHarris * Array is keyed on the word length, then the word index.
10944ca0adfSAndreas Gohr *
11044ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
11117f42b01SChris Smith * @author Christopher Smith <chris@jalakai.co.uk>
112b4ce25e9SAndreas Gohr */
11344ca0adfSAndreas Gohrfunction idx_getPageWords($page){
11444ca0adfSAndreas Gohr    global $conf;
1157367b368SAndreas Gohr    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
1167367b368SAndreas Gohr    if(@file_exists($swfile)){
1177367b368SAndreas Gohr        $stopwords = file($swfile);
1187367b368SAndreas Gohr    }else{
1197367b368SAndreas Gohr        $stopwords = array();
1207367b368SAndreas Gohr    }
12144ca0adfSAndreas Gohr
12244ca0adfSAndreas Gohr    $body   = rawWiki($page);
12317f42b01SChris Smith    $body   = strtr($body, "\r\n\t", '   ');
12417f42b01SChris Smith    $tokens = explode(' ', $body);
12517f42b01SChris Smith    $tokens = array_count_values($tokens);   // count the frequency of each token
12617f42b01SChris Smith
1276b06b652Schris// ensure the deaccented or romanised page names of internal links are added to the token array
1286b06b652Schris// (this is necessary for the backlink function -- there maybe a better way!)
1296b06b652Schris    if ($conf['deaccent']) {
1306b06b652Schris      $links = p_get_metadata($page,'relation references');
1316b06b652Schris
1323fc667cfSchris      if (!empty($links)) {
1336b06b652Schris        $tmp = join(' ',array_keys($links));                // make a single string
1346b06b652Schris        $tmp = strtr($tmp, ':', ' ');                       // replace namespace separator with a space
1356b06b652Schris        $link_tokens = array_unique(explode(' ', $tmp));    // break into tokens
1366b06b652Schris
1376b06b652Schris        foreach ($link_tokens as $link_token) {
1386b06b652Schris          if (isset($tokens[$link_token])) continue;
1396b06b652Schris          $tokens[$link_token] = 1;
1406b06b652Schris        }
1416b06b652Schris      }
1423fc667cfSchris    }
1436b06b652Schris
14417f42b01SChris Smith    $words = array();
14517f42b01SChris Smith    foreach ($tokens as $word => $count) {
146579b0f7eSTNHarris        $arr = idx_tokenizer($word,$stopwords);
14717f42b01SChris Smith        $arr = array_count_values($arr);
14817f42b01SChris Smith        foreach ($arr as $w => $c) {
149d5b23302STom N Harris            $l = wordlen($w);
150579b0f7eSTNHarris            if(isset($words[$l])){
151b2bc63f0SAndreas Gohr                $words[$l][$w] = $c * $count + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
15217f42b01SChris Smith            }else{
153579b0f7eSTNHarris                $words[$l] = array($w => $c * $count);
154579b0f7eSTNHarris            }
15517f42b01SChris Smith        }
15617f42b01SChris Smith    }
15717f42b01SChris Smith
158579b0f7eSTNHarris    // arrive here with $words = array(wordlen => array(word => frequency))
159b4ce25e9SAndreas Gohr
160b4ce25e9SAndreas Gohr    $index = array(); //resulting index
161579b0f7eSTNHarris    foreach (array_keys($words) as $wlen){
162579b0f7eSTNHarris        $word_idx = idx_getIndex('w',$wlen);
163579b0f7eSTNHarris        foreach ($words[$wlen] as $word => $freq) {
16444ca0adfSAndreas Gohr            $wid = array_search("$word\n",$word_idx);
16544ca0adfSAndreas Gohr            if(!is_int($wid)){
166d5b23302STom N Harris                $wid = count($word_idx);
16744ca0adfSAndreas Gohr                $word_idx[] = "$word\n";
168b4ce25e9SAndreas Gohr            }
169579b0f7eSTNHarris            if(!isset($index[$wlen]))
170579b0f7eSTNHarris                $index[$wlen] = array();
171579b0f7eSTNHarris            $index[$wlen][$wid] = $freq;
17244ca0adfSAndreas Gohr        }
17344ca0adfSAndreas Gohr
17444ca0adfSAndreas Gohr        // save back word index
175579b0f7eSTNHarris        if(!idx_saveIndex('w',$wlen,$word_idx)){
176579b0f7eSTNHarris            trigger_error("Failed to write word index", E_USER_ERROR);
17744ca0adfSAndreas Gohr            return false;
17844ca0adfSAndreas Gohr        }
179579b0f7eSTNHarris    }
180b4ce25e9SAndreas Gohr
181b4ce25e9SAndreas Gohr    return $index;
182b4ce25e9SAndreas Gohr}
183b4ce25e9SAndreas Gohr
18444ca0adfSAndreas Gohr/**
18544ca0adfSAndreas Gohr * Adds/updates the search for the given page
18644ca0adfSAndreas Gohr *
18744ca0adfSAndreas Gohr * This is the core function of the indexer which does most
18844ca0adfSAndreas Gohr * of the work. This function needs to be called with proper
18944ca0adfSAndreas Gohr * locking!
19044ca0adfSAndreas Gohr *
19144ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
19244ca0adfSAndreas Gohr */
19344ca0adfSAndreas Gohrfunction idx_addPage($page){
19444ca0adfSAndreas Gohr    global $conf;
195b4ce25e9SAndreas Gohr
196488dd6ceSAndreas Gohr    // load known documents
197579b0f7eSTNHarris    $page_idx = idx_getIndex('page','');
19844ca0adfSAndreas Gohr
19944ca0adfSAndreas Gohr    // get page id (this is the linenumber in page.idx)
20044ca0adfSAndreas Gohr    $pid = array_search("$page\n",$page_idx);
20144ca0adfSAndreas Gohr    if(!is_int($pid)){
20244ca0adfSAndreas Gohr        $page_idx[] = "$page\n";
20344ca0adfSAndreas Gohr        $pid = count($page_idx)-1;
20444ca0adfSAndreas Gohr        // page was new - write back
205d5b23302STom N Harris        if (!idx_saveIndex('page','',$page_idx)){
206d5b23302STom N Harris            trigger_error("Failed to write page index", E_USER_ERROR);
207579b0f7eSTNHarris            return false;
20844ca0adfSAndreas Gohr        }
209d5b23302STom N Harris    }
21044ca0adfSAndreas Gohr
21144ca0adfSAndreas Gohr    // get word usage in page
21244ca0adfSAndreas Gohr    $words = idx_getPageWords($page);
21344ca0adfSAndreas Gohr    if($words === false) return false;
21444ca0adfSAndreas Gohr    if(!count($words)) return true;
21544ca0adfSAndreas Gohr
216579b0f7eSTNHarris    foreach(array_keys($words) as $wlen){
217d5b23302STom N Harris        $index = idx_getIndex('i',$wlen);
218d5b23302STom N Harris        foreach($words[$wlen] as $wid => $freq){
219d5b23302STom N Harris            if($wid<count($index)){
220d5b23302STom N Harris                $index[$wid] = idx_updateIndexLine($index[$wid],$pid,$freq);
221d5b23302STom N Harris            }else{
222d5b23302STom N Harris                // New words **should** have been added in increasing order
223d5b23302STom N Harris                // starting with the first unassigned index.
224d5b23302STom N Harris                // If someone can show how this isn't true, then I'll need to sort
225d5b23302STom N Harris                // or do something special.
226d5b23302STom N Harris                $index[$wid] = idx_updateIndexLine('',$pid,$freq);
227d5b23302STom N Harris            }
228d5b23302STom N Harris        }
229d5b23302STom N Harris        // save back word index
230d5b23302STom N Harris        if(!idx_saveIndex('i',$wlen,$index)){
231d5b23302STom N Harris            trigger_error("Failed to write index", E_USER_ERROR);
23244ca0adfSAndreas Gohr            return false;
23344ca0adfSAndreas Gohr        }
234579b0f7eSTNHarris    }
235579b0f7eSTNHarris
236579b0f7eSTNHarris    return true;
23744ca0adfSAndreas Gohr}
23844ca0adfSAndreas Gohr
23944ca0adfSAndreas Gohr/**
24044ca0adfSAndreas Gohr * Write a new index line to the filehandle
24144ca0adfSAndreas Gohr *
24244ca0adfSAndreas Gohr * This function writes an line for the index file to the
24344ca0adfSAndreas Gohr * given filehandle. It removes the given document from
24444ca0adfSAndreas Gohr * the given line and readds it when $count is >0.
24544ca0adfSAndreas Gohr *
246d5b23302STom N Harris * @deprecated - see idx_updateIndexLine
24744ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
24844ca0adfSAndreas Gohr */
24944ca0adfSAndreas Gohrfunction idx_writeIndexLine($fh,$line,$pid,$count){
250d5b23302STom N Harris    fwrite($fh,idx_updateIndexLine($line,$pid,$count));
251d5b23302STom N Harris}
25244ca0adfSAndreas Gohr
253d5b23302STom N Harris/**
254d5b23302STom N Harris * Modify an index line with new information
255d5b23302STom N Harris *
256d5b23302STom N Harris * This returns a line of the index. It removes the
257d5b23302STom N Harris * given document from the line and readds it if
258d5b23302STom N Harris * $count is >0.
259d5b23302STom N Harris *
260d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
261d5b23302STom N Harris * @author Andreas Gohr <andi@splitbrain.org>
262d5b23302STom N Harris */
263d5b23302STom N Harrisfunction idx_updateIndexLine($line,$pid,$count){
264d5b23302STom N Harris    $line = trim($line);
265d5b23302STom N Harris    $updated = array();
26644ca0adfSAndreas Gohr    if($line != ''){
26744ca0adfSAndreas Gohr        $parts = explode(':',$line);
26844ca0adfSAndreas Gohr        // remove doc from given line
26944ca0adfSAndreas Gohr        foreach($parts as $part){
27044ca0adfSAndreas Gohr            if($part == '') continue;
27144ca0adfSAndreas Gohr            list($doc,$cnt) = explode('*',$part);
27244ca0adfSAndreas Gohr            if($doc != $pid){
273d5b23302STom N Harris                $updated[] = $part;
27444ca0adfSAndreas Gohr            }
27544ca0adfSAndreas Gohr        }
27644ca0adfSAndreas Gohr    }
27744ca0adfSAndreas Gohr
27844ca0adfSAndreas Gohr    // add doc
27944ca0adfSAndreas Gohr    if ($count){
280d5b23302STom N Harris        $updated[] = "$pid*$count";
28144ca0adfSAndreas Gohr    }
28244ca0adfSAndreas Gohr
283d5b23302STom N Harris    return join(':',$updated)."\n";
28444ca0adfSAndreas Gohr}
285b4ce25e9SAndreas Gohr
286488dd6ceSAndreas Gohr/**
287579b0f7eSTNHarris * Get the word lengths that have been indexed.
288579b0f7eSTNHarris *
289579b0f7eSTNHarris * Reads the index directory and returns an array of lengths
290579b0f7eSTNHarris * that there are indices for.
291579b0f7eSTNHarris *
292579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
293579b0f7eSTNHarris */
294d5b23302STom N Harrisfunction idx_indexLengths(&$filter){
295579b0f7eSTNHarris    global $conf;
296579b0f7eSTNHarris    $dir = @opendir($conf['indexdir']);
297579b0f7eSTNHarris    if($dir===false)
298579b0f7eSTNHarris        return array();
299579b0f7eSTNHarris    $idx = array();
300d5b23302STom N Harris    if(is_array($filter)){
301579b0f7eSTNHarris        while (($f = readdir($dir)) !== false) {
302579b0f7eSTNHarris            if (substr($f,0,1) == 'i' && substr($f,-4) == '.idx'){
303579b0f7eSTNHarris                $i = substr($f,1,-4);
304d5b23302STom N Harris                if (is_numeric($i) && isset($filter[(int)$i]))
305d5b23302STom N Harris                    $idx[] = (int)$i;
306d5b23302STom N Harris            }
307d5b23302STom N Harris        }
308d5b23302STom N Harris    }else{
309d5b23302STom N Harris        // Exact match first.
310d5b23302STom N Harris        if(@file_exists($conf['indexdir']."/i$filter.idx"))
311d5b23302STom N Harris            $idx[] = $filter;
312d5b23302STom N Harris        while (($f = readdir($dir)) !== false) {
313d5b23302STom N Harris            if (substr($f,0,1) == 'i' && substr($f,-4) == '.idx'){
314d5b23302STom N Harris                $i = substr($f,1,-4);
315d5b23302STom N Harris                if (is_numeric($i) && $i > $filter)
316d5b23302STom N Harris                    $idx[] = (int)$i;
317d5b23302STom N Harris            }
318579b0f7eSTNHarris        }
319579b0f7eSTNHarris    }
320579b0f7eSTNHarris    closedir($dir);
321579b0f7eSTNHarris    return $idx;
322579b0f7eSTNHarris}
323579b0f7eSTNHarris
324579b0f7eSTNHarris/**
325d5b23302STom N Harris * Find the the index number of each search term.
326d5b23302STom N Harris *
327*adb16d4fSAndreas Gohr * This will group together words that appear in the same index.
328d5b23302STom N Harris * So it should perform better, because it only opens each index once.
329d5b23302STom N Harris * Actually, it's not that great. (in my experience) Probably because of the disk cache.
330d5b23302STom N Harris * And the sorted function does more work, making it slightly slower in some cases.
331d5b23302STom N Harris *
332d5b23302STom N Harris * @param array    $words   The query terms. Words should only contain valid characters,
333d5b23302STom N Harris *                          with a '*' at either the beginning or end of the word (or both)
334d5b23302STom N Harris * @param arrayref $result  Set to word => array("length*id" ...), use this to merge the
335d5b23302STom N Harris *                          index locations with the appropriate query term.
336d5b23302STom N Harris * @return array            Set to length => array(id ...)
337d5b23302STom N Harris *
338d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
339d5b23302STom N Harris */
340d5b23302STom N Harrisfunction idx_getIndexWordsSorted($words,&$result){
341d5b23302STom N Harris    // parse and sort tokens
342d5b23302STom N Harris    $tokens = array();
343d5b23302STom N Harris    $tokenlength = array();
344d5b23302STom N Harris    $tokenwild = array();
345d5b23302STom N Harris    foreach($words as $word){
346d5b23302STom N Harris        $result[$word] = array();
347d5b23302STom N Harris        $wild = 0;
348d5b23302STom N Harris        $xword = $word;
349d5b23302STom N Harris        $wlen = wordlen($word);
350d5b23302STom N Harris
351d5b23302STom N Harris        // check for wildcards
352d5b23302STom N Harris        if(substr($xword,0,1) == '*'){
353d5b23302STom N Harris            $xword = substr($xword,1);
354d5b23302STom N Harris            $wild |= 1;
355d5b23302STom N Harris            $wlen -= 1;
356d5b23302STom N Harris        }
357d5b23302STom N Harris        if(substr($xword,-1,1) == '*'){
358d5b23302STom N Harris            $xword = substr($xword,0,-1);
359d5b23302STom N Harris            $wild |= 2;
360d5b23302STom N Harris            $wlen -= 1;
361d5b23302STom N Harris        }
362d5b23302STom N Harris        if ($wlen < 3 && $wild == 0 && !is_numeric($xword)) continue;
363d5b23302STom N Harris        if(!isset($tokens[$xword])){
364d5b23302STom N Harris            $tokenlength[$wlen][] = $xword;
365d5b23302STom N Harris        }
366d5b23302STom N Harris        if($wild){
367d5b23302STom N Harris            $ptn = preg_quote($xword,'/');
368d5b23302STom N Harris            if(($wild&1) == 0) $ptn = '^'.$ptn;
369d5b23302STom N Harris            if(($wild&2) == 0) $ptn = $ptn.'$';
370d5b23302STom N Harris            $tokens[$xword][] = array($word, '/'.$ptn.'/');
371d5b23302STom N Harris            if(!isset($tokenwild[$xword])) $tokenwild[$xword] = $wlen;
372d5b23302STom N Harris        }else
373d5b23302STom N Harris            $tokens[$xword][] = array($word, null);
374d5b23302STom N Harris    }
375d5b23302STom N Harris    asort($tokenwild);
376d5b23302STom N Harris    // $tokens = array( base word => array( [ query word , grep pattern ] ... ) ... )
377d5b23302STom N Harris    // $tokenlength = array( base word length => base word ... )
378d5b23302STom N Harris    // $tokenwild = array( base word => base word length ... )
379d5b23302STom N Harris
380d5b23302STom N Harris    $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
381d5b23302STom N Harris    $indexes_known = idx_indexLengths($length_filter);
382d5b23302STom N Harris    if(!empty($tokenwild)) sort($indexes_known);
383d5b23302STom N Harris    // get word IDs
384d5b23302STom N Harris    $wids = array();
385d5b23302STom N Harris    echo "\n";
386d5b23302STom N Harris    foreach($indexes_known as $ixlen){
387d5b23302STom N Harris        $word_idx = idx_getIndex('w',$ixlen);
388d5b23302STom N Harris        // handle exact search
389d5b23302STom N Harris        if(isset($tokenlength[$ixlen])){
390d5b23302STom N Harris            foreach($tokenlength[$ixlen] as $xword){
391d5b23302STom N Harris                $wid = array_search("$xword\n",$word_idx);
392d5b23302STom N Harris                if(is_int($wid)){
393d5b23302STom N Harris                    $wids[$ixlen][] = $wid;
394d5b23302STom N Harris                    foreach($tokens[$xword] as $w)
395d5b23302STom N Harris                        $result[$w[0]][] = "$ixlen*$wid";
396d5b23302STom N Harris                }
397d5b23302STom N Harris            }
398d5b23302STom N Harris        }
399d5b23302STom N Harris        // handle wildcard search
400d5b23302STom N Harris        foreach($tokenwild as $xword => $wlen){
401d5b23302STom N Harris            if($wlen >= $ixlen) break;
402d5b23302STom N Harris            foreach($tokens[$xword] as $w){
403d5b23302STom N Harris                if(is_null($w[1])) continue;
404d5b23302STom N Harris                foreach(array_keys(preg_grep($w[1],$word_idx)) as $wid){
405d5b23302STom N Harris                    $wids[$ixlen][] = $wid;
406d5b23302STom N Harris                    $result[$w[0]][] = "$ixlen*$wid";
407d5b23302STom N Harris                }
408d5b23302STom N Harris            }
409d5b23302STom N Harris        }
410d5b23302STom N Harris    }
411d5b23302STom N Harris  return $wids;
412d5b23302STom N Harris}
413d5b23302STom N Harris
414d5b23302STom N Harris/**
415488dd6ceSAndreas Gohr * Lookup words in index
416488dd6ceSAndreas Gohr *
417488dd6ceSAndreas Gohr * Takes an array of word and will return a list of matching
418488dd6ceSAndreas Gohr * documents for each one.
419488dd6ceSAndreas Gohr *
42063773904SAndreas Gohr * Important: No ACL checking is done here! All results are
42163773904SAndreas Gohr *            returned, regardless of permissions
42263773904SAndreas Gohr *
423488dd6ceSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
424488dd6ceSAndreas Gohr */
425488dd6ceSAndreas Gohrfunction idx_lookup($words){
426488dd6ceSAndreas Gohr    global $conf;
427488dd6ceSAndreas Gohr
428488dd6ceSAndreas Gohr    $result = array();
429488dd6ceSAndreas Gohr
430d5b23302STom N Harris    $wids = idx_getIndexWordsSorted($words, $result);
431d5b23302STom N Harris    if(empty($wids)) return array();
432d5b23302STom N Harris
433488dd6ceSAndreas Gohr    // load known words and documents
434579b0f7eSTNHarris    $page_idx = idx_getIndex('page','');
435488dd6ceSAndreas Gohr
436579b0f7eSTNHarris    $docs = array();                          // hold docs found
437579b0f7eSTNHarris    foreach(array_keys($wids) as $wlen){
438579b0f7eSTNHarris        $wids[$wlen] = array_unique($wids[$wlen]);
439d5b23302STom N Harris        $index = idx_getIndex('i',$wlen);
440d5b23302STom N Harris        foreach($wids[$wlen] as $ixid){
441d5b23302STom N Harris            if($ixid < count($index))
442d5b23302STom N Harris                $docs["$wlen*$ixid"] = idx_parseIndexLine($page_idx,$index[$ixid]);
443488dd6ceSAndreas Gohr        }
444488dd6ceSAndreas Gohr    }
445488dd6ceSAndreas Gohr
446ad81d431SAndreas Gohr    // merge found pages into final result array
447ad81d431SAndreas Gohr    $final = array();
448ad81d431SAndreas Gohr    foreach(array_keys($result) as $word){
449ad81d431SAndreas Gohr        $final[$word] = array();
450ad81d431SAndreas Gohr        foreach($result[$word] as $wid){
451ad81d431SAndreas Gohr            $hits = &$docs[$wid];
452ad81d431SAndreas Gohr            foreach ($hits as $hitkey => $hitcnt) {
453ad81d431SAndreas Gohr                $final[$word][$hitkey] = $hitcnt + $final[$word][$hitkey];
454ad81d431SAndreas Gohr            }
455ad81d431SAndreas Gohr        }
456ad81d431SAndreas Gohr    }
457ad81d431SAndreas Gohr    return $final;
458488dd6ceSAndreas Gohr}
459488dd6ceSAndreas Gohr
460488dd6ceSAndreas Gohr/**
461488dd6ceSAndreas Gohr * Returns a list of documents and counts from a index line
462488dd6ceSAndreas Gohr *
463488dd6ceSAndreas Gohr * It omits docs with a count of 0 and pages that no longer
464488dd6ceSAndreas Gohr * exist.
465488dd6ceSAndreas Gohr *
466488dd6ceSAndreas Gohr * @param  array  $page_idx The list of known pages
467488dd6ceSAndreas Gohr * @param  string $line     A line from the main index
468488dd6ceSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
469488dd6ceSAndreas Gohr */
470488dd6ceSAndreas Gohrfunction idx_parseIndexLine(&$page_idx,$line){
471488dd6ceSAndreas Gohr    $result = array();
472488dd6ceSAndreas Gohr
473488dd6ceSAndreas Gohr    $line = trim($line);
474f5eb7cf0SAndreas Gohr    if($line == '') return $result;
475488dd6ceSAndreas Gohr
476488dd6ceSAndreas Gohr    $parts = explode(':',$line);
477488dd6ceSAndreas Gohr    foreach($parts as $part){
478488dd6ceSAndreas Gohr        if($part == '') continue;
479488dd6ceSAndreas Gohr        list($doc,$cnt) = explode('*',$part);
480488dd6ceSAndreas Gohr        if(!$cnt) continue;
481488dd6ceSAndreas Gohr        $doc = trim($page_idx[$doc]);
482488dd6ceSAndreas Gohr        if(!$doc) continue;
483488dd6ceSAndreas Gohr        // make sure the document still exists
4840d8ea614Schris        if(!@file_exists(wikiFN($doc,'',false))) continue;
485488dd6ceSAndreas Gohr
486488dd6ceSAndreas Gohr        $result[$doc] = $cnt;
487488dd6ceSAndreas Gohr    }
488488dd6ceSAndreas Gohr    return $result;
489488dd6ceSAndreas Gohr}
490488dd6ceSAndreas Gohr
491f5eb7cf0SAndreas Gohr/**
492f5eb7cf0SAndreas Gohr * Tokenizes a string into an array of search words
493f5eb7cf0SAndreas Gohr *
494f5eb7cf0SAndreas Gohr * Uses the same algorithm as idx_getPageWords()
495f5eb7cf0SAndreas Gohr *
496ad81d431SAndreas Gohr * @param string   $string     the query as given by the user
497ad81d431SAndreas Gohr * @param arrayref $stopwords  array of stopwords
498ad81d431SAndreas Gohr * @param boolean  $wc         are wildcards allowed?
499f5eb7cf0SAndreas Gohr */
500ad81d431SAndreas Gohrfunction idx_tokenizer($string,&$stopwords,$wc=false){
501f5eb7cf0SAndreas Gohr    $words = array();
5024efb9a42SAndreas Gohr    $wc = ($wc) ? '' : $wc = '\*';
503f5eb7cf0SAndreas Gohr
504f5eb7cf0SAndreas Gohr    if(preg_match('/[^0-9A-Za-z]/u', $string)){
50591bb5faaSAndreas Gohr        // handle asian chars as single words (may fail on older PHP version)
506d5b23302STom N Harris        $asia = @preg_replace('/('.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')/u',' \1 ',$string);
50791bb5faaSAndreas Gohr        if(!is_null($asia)) $string = $asia; //recover from regexp failure
50893a60ad2SAndreas Gohr
5094efb9a42SAndreas Gohr        $arr = explode(' ', utf8_stripspecials($string,' ','\._\-:'.$wc));
510f5eb7cf0SAndreas Gohr        foreach ($arr as $w) {
511f5eb7cf0SAndreas Gohr            if (!is_numeric($w) && strlen($w) < 3) continue;
512f5eb7cf0SAndreas Gohr            $w = utf8_strtolower($w);
5133cbaa9a4SAndreas Gohr            if($stopwords && is_int(array_search("$w\n",$stopwords))) continue;
514f5eb7cf0SAndreas Gohr            $words[] = $w;
515f5eb7cf0SAndreas Gohr        }
516f5eb7cf0SAndreas Gohr    }else{
517f5eb7cf0SAndreas Gohr        $w = $string;
518f5eb7cf0SAndreas Gohr        if (!is_numeric($w) && strlen($w) < 3) return $words;
519f5eb7cf0SAndreas Gohr        $w = strtolower($w);
520f5eb7cf0SAndreas Gohr        if(is_int(array_search("$w\n",$stopwords))) return $words;
521f5eb7cf0SAndreas Gohr        $words[] = $w;
522f5eb7cf0SAndreas Gohr    }
523f5eb7cf0SAndreas Gohr
524f5eb7cf0SAndreas Gohr    return $words;
525f5eb7cf0SAndreas Gohr}
526f5eb7cf0SAndreas Gohr
527b4ce25e9SAndreas Gohr//Setup VIM: ex: et ts=4 enc=utf-8 :
528