~fabiocbalbuquerque/sahana-agasti/web-services

« back to all changes in this revision

Viewing changes to web/wiki/inc/indexer.php

  • Committer: Chad Heuschober
  • Date: 2011-06-06 13:37:45 UTC
  • mfrom: (1.1.1244 trunk)
  • mto: This revision was merged to the branch mainline in revision 17.
  • Revision ID: chad.heuschober@mail.cuny.edu-20110606133745-850mdvnjtv392zta
Pulled in most recent batch of changes from the cuny sps trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
4
4
 *
5
5
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6
6
 * @author     Andreas Gohr <andi@splitbrain.org>
 
7
 * @author     Tom N Harris <tnharris@whoopdedo.org>
7
8
 */
8
9
 
9
10
if(!defined('DOKU_INC')) die('meh.');
10
11
 
 
12
// Version tag used to force rebuild on upgrade
 
13
define('INDEXER_VERSION', 4);
 
14
 
11
15
// set the minimum token length to use in the index (note, this doesn't apply to numeric tokens)
12
16
if (!defined('IDX_MINWORDLENGTH')) define('IDX_MINWORDLENGTH',2);
13
17
 
23
27
                   '\x{30FD}-\x{31EF}\x{3200}-\x{D7AF}'.
24
28
                   '\x{F900}-\x{FAFF}'.  // CJK Compatibility Ideographs
25
29
                   '\x{FE30}-\x{FE4F}'.  // CJK Compatibility Forms
 
30
                   "\xF0\xA0\x80\x80-\xF0\xAA\x9B\x9F". // CJK Extension B
 
31
                   "\xF0\xAA\x9C\x80-\xF0\xAB\x9C\xBF". // CJK Extension C
 
32
                   "\xF0\xAB\x9D\x80-\xF0\xAB\xA0\x9F". // CJK Extension D
 
33
                   "\xF0\xAF\xA0\x80-\xF0\xAF\xAB\xBF". // CJK Compatibility Supplement
26
34
                   ']');
27
35
define('IDX_ASIAN3','['.                // Hiragana/Katakana (can be two characters)
28
36
                   '\x{3042}\x{3044}\x{3046}\x{3048}'.
43
51
define('IDX_ASIAN', '(?:'.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')');
44
52
 
45
53
/**
 
54
 * Version of the indexer taking into consideration the external tokenizer.
 
55
 * The indexer is only compatible with data written by the same version.
 
56
 *
 
57
 * @triggers INDEXER_VERSION_GET
 
58
 * Plugins that modify what gets indexed should hook this event and
 
59
 * add their version info to the event data like so:
 
60
 *     $data[$plugin_name] = $plugin_version;
 
61
 *
 
62
 * @author Tom N Harris <tnharris@whoopdedo.org>
 
63
 * @author Michael Hamann <michael@content-space.de>
 
64
 */
 
65
function idx_get_version(){
 
66
    static $indexer_version = null;
 
67
    if ($indexer_version == null) {
 
68
        global $conf;
 
69
        $version = INDEXER_VERSION;
 
70
 
 
71
        // DokuWiki version is included for the convenience of plugins
 
72
        $data = array('dokuwiki'=>$version);
 
73
        trigger_event('INDEXER_VERSION_GET', $data, null, false);
 
74
        unset($data['dokuwiki']); // this needs to be first
 
75
        ksort($data);
 
76
        foreach ($data as $plugin=>$vers)
 
77
            $version .= '+'.$plugin.'='.$vers;
 
78
        $indexer_version = $version;
 
79
    }
 
80
    return $indexer_version;
 
81
}
 
82
 
 
83
/**
46
84
 * Measure the length of a string.
47
85
 * Differs from strlen in handling of asian characters.
48
86
 *
52
90
    $l = strlen($w);
53
91
    // If left alone, all chinese "words" will get put into w3.idx
54
92
    // So the "length" of a "word" is faked
55
 
    if(preg_match('/'.IDX_ASIAN2.'/u',$w))
56
 
        $l += ord($w) - 0xE1;  // Lead bytes from 0xE2-0xEF
 
93
    if(preg_match_all('/[\xE2-\xEF]/',$w,$leadbytes)) {
 
94
        foreach($leadbytes[0] as $b)
 
95
            $l += ord($b) - 0xE1;
 
96
    }
57
97
    return $l;
58
98
}
59
99
 
60
100
/**
61
 
 * Write a list of strings to an index file.
62
 
 *
63
 
 * @author Tom N Harris <tnharris@whoopdedo.org>
64
 
 */
65
 
function idx_saveIndex($pre, $wlen, &$idx){
66
 
    global $conf;
67
 
    $fn = $conf['indexdir'].'/'.$pre.$wlen;
68
 
    $fh = @fopen($fn.'.tmp','w');
69
 
    if(!$fh) return false;
70
 
    foreach ($idx as $line) {
71
 
        fwrite($fh,$line);
72
 
    }
73
 
    fclose($fh);
74
 
    if(isset($conf['fperm'])) chmod($fn.'.tmp', $conf['fperm']);
75
 
    io_rename($fn.'.tmp', $fn.'.idx');
76
 
    return true;
77
 
}
78
 
 
79
 
/**
80
 
 * Append a given line to an index file.
81
 
 *
82
 
 * @author Andreas Gohr <andi@splitbrain.org>
83
 
 */
84
 
function idx_appendIndex($pre, $wlen, $line){
85
 
    global $conf;
86
 
    $fn = $conf['indexdir'].'/'.$pre.$wlen;
87
 
    $fh = @fopen($fn.'.idx','a');
88
 
    if(!$fh) return false;
89
 
    fwrite($fh,$line);
90
 
    fclose($fh);
91
 
    return true;
92
 
}
93
 
 
94
 
/**
95
 
 * Read the list of words in an index (if it exists).
96
 
 *
97
 
 * @author Tom N Harris <tnharris@whoopdedo.org>
98
 
 */
99
 
function idx_getIndex($pre, $wlen){
100
 
    global $conf;
101
 
    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
102
 
    if(!@file_exists($fn)) return array();
103
 
    return file($fn);
104
 
}
105
 
 
106
 
/**
107
 
 * Create an empty index file if it doesn't exist yet.
108
 
 *
109
 
 * FIXME: This function isn't currently used. It will probably be removed soon.
110
 
 *
111
 
 * @author Tom N Harris <tnharris@whoopdedo.org>
112
 
 */
113
 
function idx_touchIndex($pre, $wlen){
114
 
    global $conf;
115
 
    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
116
 
    if(!@file_exists($fn)){
117
 
        touch($fn);
118
 
        if($conf['fperm']) chmod($fn, $conf['fperm']);
119
 
    }
120
 
}
121
 
 
122
 
/**
123
 
 * Read a line ending with \n.
124
 
 * Returns false on EOF.
125
 
 *
126
 
 * @author Tom N Harris <tnharris@whoopdedo.org>
127
 
 */
128
 
function _freadline($fh) {
129
 
    if (feof($fh)) return false;
130
 
    $ln = '';
131
 
    while (($buf = fgets($fh,4096)) !== false) {
132
 
        $ln .= $buf;
133
 
        if (substr($buf,-1) == "\n") break;
134
 
    }
135
 
    if ($ln === '') return false;
136
 
    if (substr($ln,-1) != "\n") $ln .= "\n";
137
 
    return $ln;
138
 
}
139
 
 
140
 
/**
141
 
 * Write a line to an index file.
142
 
 *
143
 
 * @author Tom N Harris <tnharris@whoopdedo.org>
144
 
 */
145
 
function idx_saveIndexLine($pre, $wlen, $idx, $line){
146
 
    global $conf;
147
 
    if(substr($line,-1) != "\n") $line .= "\n";
148
 
    $fn = $conf['indexdir'].'/'.$pre.$wlen;
149
 
    $fh = @fopen($fn.'.tmp','w');
150
 
    if(!$fh) return false;
151
 
    $ih = @fopen($fn.'.idx','r');
152
 
    if ($ih) {
 
101
 * Class that encapsulates operations on the indexer database.
 
102
 *
 
103
 * @author Tom N Harris <tnharris@whoopdedo.org>
 
104
 */
 
105
class Doku_Indexer {
 
106
 
 
107
    /**
 
108
     * Adds the contents of a page to the fulltext index
 
109
     *
 
110
     * The added text replaces previous words for the same page.
 
111
     * An empty value erases the page.
 
112
     *
 
113
     * @param string    $page   a page name
 
114
     * @param string    $text   the body of the page
 
115
     * @return boolean          the function completed successfully
 
116
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
117
     * @author Andreas Gohr <andi@splitbrain.org>
 
118
     */
 
119
    public function addPageWords($page, $text) {
 
120
        if (!$this->lock())
 
121
            return "locked";
 
122
 
 
123
        // load known documents
 
124
        $pid = $this->addIndexKey('page', '', $page);
 
125
        if ($pid === false) {
 
126
            $this->unlock();
 
127
            return false;
 
128
        }
 
129
 
 
130
        $pagewords = array();
 
131
        // get word usage in page
 
132
        $words = $this->getPageWords($text);
 
133
        if ($words === false) {
 
134
            $this->unlock();
 
135
            return false;
 
136
        }
 
137
 
 
138
        if (!empty($words)) {
 
139
            foreach (array_keys($words) as $wlen) {
 
140
                $index = $this->getIndex('i', $wlen);
 
141
                foreach ($words[$wlen] as $wid => $freq) {
 
142
                    $idx = ($wid<count($index)) ? $index[$wid] : '';
 
143
                    $index[$wid] = $this->updateTuple($idx, $pid, $freq);
 
144
                    $pagewords[] = "$wlen*$wid";
 
145
                }
 
146
                if (!$this->saveIndex('i', $wlen, $index)) {
 
147
                    $this->unlock();
 
148
                    return false;
 
149
                }
 
150
            }
 
151
        }
 
152
 
 
153
        // Remove obsolete index entries
 
154
        $pageword_idx = $this->getIndexKey('pageword', '', $pid);
 
155
        if ($pageword_idx !== '') {
 
156
            $oldwords = explode(':',$pageword_idx);
 
157
            $delwords = array_diff($oldwords, $pagewords);
 
158
            $upwords = array();
 
159
            foreach ($delwords as $word) {
 
160
                if ($word != '') {
 
161
                    list($wlen,$wid) = explode('*', $word);
 
162
                    $wid = (int)$wid;
 
163
                    $upwords[$wlen][] = $wid;
 
164
                }
 
165
            }
 
166
            foreach ($upwords as $wlen => $widx) {
 
167
                $index = $this->getIndex('i', $wlen);
 
168
                foreach ($widx as $wid) {
 
169
                    $index[$wid] = $this->updateTuple($index[$wid], $pid, 0);
 
170
                }
 
171
                $this->saveIndex('i', $wlen, $index);
 
172
            }
 
173
        }
 
174
        // Save the reverse index
 
175
        $pageword_idx = join(':', $pagewords);
 
176
        if (!$this->saveIndexKey('pageword', '', $pid, $pageword_idx)) {
 
177
            $this->unlock();
 
178
            return false;
 
179
        }
 
180
 
 
181
        $this->unlock();
 
182
        return true;
 
183
    }
 
184
 
 
185
    /**
 
186
     * Split the words in a page and add them to the index.
 
187
     *
 
188
     * @param string    $text   content of the page
 
189
     * @return array            list of word IDs and number of times used
 
190
     * @author Andreas Gohr <andi@splitbrain.org>
 
191
     * @author Christopher Smith <chris@jalakai.co.uk>
 
192
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
193
     */
 
194
    protected function getPageWords($text) {
 
195
        global $conf;
 
196
 
 
197
        $tokens = $this->tokenizer($text);
 
198
        $tokens = array_count_values($tokens);  // count the frequency of each token
 
199
 
 
200
        $words = array();
 
201
        foreach ($tokens as $w=>$c) {
 
202
            $l = wordlen($w);
 
203
            if (isset($words[$l])){
 
204
                $words[$l][$w] = $c + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
 
205
            }else{
 
206
                $words[$l] = array($w => $c);
 
207
            }
 
208
        }
 
209
 
 
210
        // arrive here with $words = array(wordlen => array(word => frequency))
 
211
        $word_idx_modified = false;
 
212
        $index = array();   //resulting index
 
213
        foreach (array_keys($words) as $wlen) {
 
214
            $word_idx = $this->getIndex('w', $wlen);
 
215
            foreach ($words[$wlen] as $word => $freq) {
 
216
                $wid = array_search($word, $word_idx);
 
217
                if ($wid === false) {
 
218
                    $wid = count($word_idx);
 
219
                    $word_idx[] = $word;
 
220
                    $word_idx_modified = true;
 
221
                }
 
222
                if (!isset($index[$wlen]))
 
223
                    $index[$wlen] = array();
 
224
                $index[$wlen][$wid] = $freq;
 
225
            }
 
226
            // save back the word index
 
227
            if ($word_idx_modified && !$this->saveIndex('w', $wlen, $word_idx))
 
228
                return false;
 
229
        }
 
230
 
 
231
        return $index;
 
232
    }
 
233
 
 
234
    /**
 
235
     * Add/update keys to/of the metadata index.
 
236
     *
 
237
     * Adding new keys does not remove other keys for the page.
 
238
     * An empty value will erase the key.
 
239
     * The $key parameter can be an array to add multiple keys. $value will
 
240
     * not be used if $key is an array.
 
241
     *
 
242
     * @param string    $page   a page name
 
243
     * @param mixed     $key    a key string or array of key=>value pairs
 
244
     * @param mixed     $value  the value or list of values
 
245
     * @return boolean          the function completed successfully
 
246
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
247
     * @author Michael Hamann <michael@content-space.de>
 
248
     */
 
249
    public function addMetaKeys($page, $key, $value=null) {
 
250
        if (!is_array($key)) {
 
251
            $key = array($key => $value);
 
252
        } elseif (!is_null($value)) {
 
253
            // $key is array, but $value is not null
 
254
            trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING);
 
255
        }
 
256
 
 
257
        if (!$this->lock())
 
258
            return "locked";
 
259
 
 
260
        // load known documents
 
261
        $pid = $this->addIndexKey('page', '', $page);
 
262
        if ($pid === false) {
 
263
            $this->unlock();
 
264
            return false;
 
265
        }
 
266
 
 
267
        // Special handling for titles so the index file is simpler
 
268
        if (array_key_exists('title', $key)) {
 
269
            $value = $key['title'];
 
270
            if (is_array($value))
 
271
                $value = $value[0];
 
272
            $this->saveIndexKey('title', '', $pid, $value);
 
273
            unset($key['title']);
 
274
        }
 
275
 
 
276
        foreach ($key as $name => $values) {
 
277
            $metaname = idx_cleanName($name);
 
278
            $this->addIndexKey('metadata', '', $metaname);
 
279
            $metaidx = $this->getIndex($metaname.'_i', '');
 
280
            $metawords = $this->getIndex($metaname.'_w', '');
 
281
            $addwords = false;
 
282
 
 
283
            if (!is_array($values)) $values = array($values);
 
284
 
 
285
            $val_idx = $this->getIndexKey($metaname.'_p', '', $pid);
 
286
            if ($val_idx != '') {
 
287
                $val_idx = explode(':', $val_idx);
 
288
                // -1 means remove, 0 keep, 1 add
 
289
                $val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1));
 
290
            } else {
 
291
                $val_idx = array();
 
292
            }
 
293
 
 
294
 
 
295
            foreach ($values as $val) {
 
296
                $val = (string)$val;
 
297
                if ($val !== "") {
 
298
                    $id = array_search($val, $metawords);
 
299
                    if ($id === false) {
 
300
                        $id = count($metawords);
 
301
                        $metawords[$id] = $val;
 
302
                        $addwords = true;
 
303
                    }
 
304
                    // test if value is already in the index
 
305
                    if (isset($val_idx[$id]) && $val_idx[$id] <= 0)
 
306
                        $val_idx[$id] = 0;
 
307
                    else // else add it
 
308
                        $val_idx[$id] = 1;
 
309
                }
 
310
            }
 
311
 
 
312
            if ($addwords)
 
313
                $this->saveIndex($metaname.'_w', '', $metawords);
 
314
            $vals_changed = false;
 
315
            foreach ($val_idx as $id => $action) {
 
316
                if ($action == -1) {
 
317
                    $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 0);
 
318
                    $vals_changed = true;
 
319
                    unset($val_idx[$id]);
 
320
                } elseif ($action == 1) {
 
321
                    $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 1);
 
322
                    $vals_changed = true;
 
323
                }
 
324
            }
 
325
 
 
326
            if ($vals_changed) {
 
327
                $this->saveIndex($metaname.'_i', '', $metaidx);
 
328
                $val_idx = implode(':', array_keys($val_idx));
 
329
                $this->saveIndexKey($metaname.'_p', '', $pid, $val_idx);
 
330
            }
 
331
 
 
332
            unset($metaidx);
 
333
            unset($metawords);
 
334
        }
 
335
 
 
336
        $this->unlock();
 
337
        return true;
 
338
    }
 
339
 
 
340
    /**
 
341
     * Remove a page from the index
 
342
     *
 
343
     * Erases entries in all known indexes.
 
344
     *
 
345
     * @param string    $page   a page name
 
346
     * @return boolean          the function completed successfully
 
347
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
348
     */
 
349
    public function deletePage($page) {
 
350
        if (!$this->lock())
 
351
            return "locked";
 
352
 
 
353
        // load known documents
 
354
        $pid = $this->getIndexKey('page', '', $page);
 
355
        if ($pid === false) {
 
356
            $this->unlock();
 
357
            return false;
 
358
        }
 
359
 
 
360
        // Remove obsolete index entries
 
361
        $pageword_idx = $this->getIndexKey('pageword', '', $pid);
 
362
        if ($pageword_idx !== '') {
 
363
            $delwords = explode(':',$pageword_idx);
 
364
            $upwords = array();
 
365
            foreach ($delwords as $word) {
 
366
                if ($word != '') {
 
367
                    list($wlen,$wid) = explode('*', $word);
 
368
                    $wid = (int)$wid;
 
369
                    $upwords[$wlen][] = $wid;
 
370
                }
 
371
            }
 
372
            foreach ($upwords as $wlen => $widx) {
 
373
                $index = $this->getIndex('i', $wlen);
 
374
                foreach ($widx as $wid) {
 
375
                    $index[$wid] = $this->updateTuple($index[$wid], $pid, 0);
 
376
                }
 
377
                $this->saveIndex('i', $wlen, $index);
 
378
            }
 
379
        }
 
380
        // Save the reverse index
 
381
        if (!$this->saveIndexKey('pageword', '', $pid, "")) {
 
382
            $this->unlock();
 
383
            return false;
 
384
        }
 
385
 
 
386
        $this->saveIndexKey('title', '', $pid, "");
 
387
        $keyidx = $this->getIndex('metadata', '');
 
388
        foreach ($keyidx as $metaname) {
 
389
            $val_idx = explode(':', $this->getIndexKey($metaname.'_p', '', $pid));
 
390
            $meta_idx = $this->getIndex($metaname.'_i', '');
 
391
            foreach ($val_idx as $id) {
 
392
                $meta_idx[$id] = $this->updateTuple($meta_idx[$id], $pid, 0);
 
393
            }
 
394
            $this->saveIndex($metaname.'_i', '', $meta_idx);
 
395
            $this->saveIndexKey($metaname.'_p', '', $pid, '');
 
396
        }
 
397
 
 
398
        $this->unlock();
 
399
        return true;
 
400
    }
 
401
 
 
402
    /**
 
403
     * Split the text into words for fulltext search
 
404
     *
 
405
     * TODO: does this also need &$stopwords ?
 
406
     *
 
407
     * @triggers INDEXER_TEXT_PREPARE
 
408
     * This event allows plugins to modify the text before it gets tokenized.
 
409
     * Plugins intercepting this event should also intercept INDEX_VERSION_GET
 
410
     *
 
411
     * @param string    $text   plain text
 
412
     * @param boolean   $wc     are wildcards allowed?
 
413
     * @return array            list of words in the text
 
414
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
415
     * @author Andreas Gohr <andi@splitbrain.org>
 
416
     */
 
417
    public function tokenizer($text, $wc=false) {
 
418
        global $conf;
 
419
        $words = array();
 
420
        $wc = ($wc) ? '' : '\*';
 
421
        $stopwords =& idx_get_stopwords();
 
422
 
 
423
        // prepare the text to be tokenized
 
424
        $evt = new Doku_Event('INDEXER_TEXT_PREPARE', $text);
 
425
        if ($evt->advise_before(true)) {
 
426
            if (preg_match('/[^0-9A-Za-z ]/u', $text)) {
 
427
                // handle asian chars as single words (may fail on older PHP version)
 
428
                $asia = @preg_replace('/('.IDX_ASIAN.')/u', ' \1 ', $text);
 
429
                if (!is_null($asia)) $text = $asia; // recover from regexp falure
 
430
            }
 
431
        }
 
432
        $evt->advise_after();
 
433
        unset($evt);
 
434
 
 
435
        $text = strtr($text,
 
436
                       array(
 
437
                           "\r" => ' ',
 
438
                           "\n" => ' ',
 
439
                           "\t" => ' ',
 
440
                           "\xC2\xAD" => '', //soft-hyphen
 
441
                       )
 
442
                     );
 
443
        if (preg_match('/[^0-9A-Za-z ]/u', $text))
 
444
            $text = utf8_stripspecials($text, ' ', '\._\-:'.$wc);
 
445
 
 
446
        $wordlist = explode(' ', $text);
 
447
        foreach ($wordlist as $i => &$word) {
 
448
            $word = (preg_match('/[^0-9A-Za-z]/u', $word)) ?
 
449
                utf8_strtolower($word) : strtolower($word);
 
450
            if ((!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH)
 
451
              || array_search($word, $stopwords) !== false)
 
452
                unset($wordlist[$i]);
 
453
        }
 
454
        return array_values($wordlist);
 
455
    }
 
456
 
 
457
    /**
 
458
     * Find pages in the fulltext index containing the words,
 
459
     *
 
460
     * The search words must be pre-tokenized, meaning only letters and
 
461
     * numbers with an optional wildcard
 
462
     *
 
463
     * The returned array will have the original tokens as key. The values
 
464
     * in the returned list is an array with the page names as keys and the
 
465
     * number of times that token appears on the page as value.
 
466
     *
 
467
     * @param arrayref  $tokens list of words to search for
 
468
     * @return array            list of page names with usage counts
 
469
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
470
     * @author Andreas Gohr <andi@splitbrain.org>
 
471
     */
 
472
    public function lookup(&$tokens) {
 
473
        $result = array();
 
474
        $wids = $this->getIndexWords($tokens, $result);
 
475
        if (empty($wids)) return array();
 
476
        // load known words and documents
 
477
        $page_idx = $this->getIndex('page', '');
 
478
        $docs = array();
 
479
        foreach (array_keys($wids) as $wlen) {
 
480
            $wids[$wlen] = array_unique($wids[$wlen]);
 
481
            $index = $this->getIndex('i', $wlen);
 
482
            foreach($wids[$wlen] as $ixid) {
 
483
                if ($ixid < count($index))
 
484
                    $docs["$wlen*$ixid"] = $this->parseTuples($page_idx, $index[$ixid]);
 
485
            }
 
486
        }
 
487
        // merge found pages into final result array
 
488
        $final = array();
 
489
        foreach ($result as $word => $res) {
 
490
            $final[$word] = array();
 
491
            foreach ($res as $wid) {
 
492
                // handle the case when ($ixid < count($index)) has been false
 
493
                // and thus $docs[$wid] hasn't been set.
 
494
                if (!isset($docs[$wid])) continue;
 
495
                $hits = &$docs[$wid];
 
496
                foreach ($hits as $hitkey => $hitcnt) {
 
497
                    // make sure the document still exists
 
498
                    if (!page_exists($hitkey, '', false)) continue;
 
499
                    if (!isset($final[$word][$hitkey]))
 
500
                        $final[$word][$hitkey] = $hitcnt;
 
501
                    else
 
502
                        $final[$word][$hitkey] += $hitcnt;
 
503
                }
 
504
            }
 
505
        }
 
506
        return $final;
 
507
    }
 
508
 
 
509
    /**
 
510
     * Find pages containing a metadata key.
 
511
     *
 
512
     * The metadata values are compared as case-sensitive strings. Pass a
 
513
     * callback function that returns true or false to use a different
 
514
     * comparison function. The function will be called with the $value being
 
515
     * searched for as the first argument, and the word in the index as the
 
516
     * second argument. The function preg_match can be used directly if the
 
517
     * values are regexes.
 
518
     *
 
519
     * @param string    $key    name of the metadata key to look for
 
520
     * @param string    $value  search term to look for, must be a string or array of strings
 
521
     * @param callback  $func   comparison function
 
522
     * @return array            lists with page names, keys are query values if $value is array
 
523
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
524
     * @author Michael Hamann <michael@content-space.de>
 
525
     */
 
526
    public function lookupKey($key, &$value, $func=null) {
 
527
        if (!is_array($value))
 
528
            $value_array = array($value);
 
529
        else
 
530
            $value_array =& $value;
 
531
 
 
532
        // the matching ids for the provided value(s)
 
533
        $value_ids = array();
 
534
 
 
535
        $metaname = idx_cleanName($key);
 
536
 
 
537
        // get all words in order to search the matching ids
 
538
        if ($key == 'title') {
 
539
            $words = $this->getIndex('title', '');
 
540
        } else {
 
541
            $words = $this->getIndex($metaname.'_w', '');
 
542
        }
 
543
 
 
544
        if (!is_null($func)) {
 
545
            foreach ($value_array as $val) {
 
546
                foreach ($words as $i => $word) {
 
547
                    if (call_user_func_array($func, array($val, $word)))
 
548
                        $value_ids[$i][] = $val;
 
549
                }
 
550
            }
 
551
        } else {
 
552
            foreach ($value_array as $val) {
 
553
                $xval = $val;
 
554
                $caret = '^';
 
555
                $dollar = '$';
 
556
                // check for wildcards
 
557
                if (substr($xval, 0, 1) == '*') {
 
558
                    $xval = substr($xval, 1);
 
559
                    $caret = '';
 
560
                }
 
561
                if (substr($xval, -1, 1) == '*') {
 
562
                    $xval = substr($xval, 0, -1);
 
563
                    $dollar = '';
 
564
                }
 
565
                if (!$caret || !$dollar) {
 
566
                    $re = $caret.preg_quote($xval, '/').$dollar;
 
567
                    foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i)
 
568
                        $value_ids[$i][] = $val;
 
569
                } else {
 
570
                    if (($i = array_search($val, $words)) !== false)
 
571
                        $value_ids[$i][] = $val;
 
572
                }
 
573
            }
 
574
        }
 
575
 
 
576
        unset($words); // free the used memory
 
577
 
 
578
        // initialize the result so it won't be null
 
579
        $result = array();
 
580
        foreach ($value_array as $val) {
 
581
            $result[$val] = array();
 
582
        }
 
583
 
 
584
        $page_idx = $this->getIndex('page', '');
 
585
 
 
586
        // Special handling for titles
 
587
        if ($key == 'title') {
 
588
            foreach ($value_ids as $pid => $val_list) {
 
589
                $page = $page_idx[$pid];
 
590
                foreach ($val_list as $val) {
 
591
                    $result[$val][] = $page;
 
592
                }
 
593
            }
 
594
        } else {
 
595
            // load all lines and pages so the used lines can be taken and matched with the pages
 
596
            $lines = $this->getIndex($metaname.'_i', '');
 
597
 
 
598
            foreach ($value_ids as $value_id => $val_list) {
 
599
                // parse the tuples of the form page_id*1:page2_id*1 and so on, return value
 
600
                // is an array with page_id => 1, page2_id => 1 etc. so take the keys only
 
601
                $pages = array_keys($this->parseTuples($page_idx, $lines[$value_id]));
 
602
                foreach ($val_list as $val) {
 
603
                    $result[$val] = array_merge($result[$val], $pages);
 
604
                }
 
605
            }
 
606
        }
 
607
        if (!is_array($value)) $result = $result[$value];
 
608
        return $result;
 
609
    }
 
610
 
 
611
    /**
 
612
     * Find the index ID of each search term.
 
613
     *
 
614
     * The query terms should only contain valid characters, with a '*' at
 
615
     * either the beginning or end of the word (or both).
 
616
     * The $result parameter can be used to merge the index locations with
 
617
     * the appropriate query term.
 
618
     *
 
619
     * @param arrayref  $words  The query terms.
 
620
     * @param arrayref  $result Set to word => array("length*id" ...)
 
621
     * @return array            Set to length => array(id ...)
 
622
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
623
     */
 
624
    protected function getIndexWords(&$words, &$result) {
 
625
        $tokens = array();
 
626
        $tokenlength = array();
 
627
        $tokenwild = array();
 
628
        foreach ($words as $word) {
 
629
            $result[$word] = array();
 
630
            $caret = '^';
 
631
            $dollar = '$';
 
632
            $xword = $word;
 
633
            $wlen = wordlen($word);
 
634
 
 
635
            // check for wildcards
 
636
            if (substr($xword, 0, 1) == '*') {
 
637
                $xword = substr($xword, 1);
 
638
                $caret = '';
 
639
                $wlen -= 1;
 
640
            }
 
641
            if (substr($xword, -1, 1) == '*') {
 
642
                $xword = substr($xword, 0, -1);
 
643
                $dollar = '';
 
644
                $wlen -= 1;
 
645
            }
 
646
            if ($wlen < IDX_MINWORDLENGTH && $caret && $dollar && !is_numeric($xword))
 
647
                continue;
 
648
            if (!isset($tokens[$xword]))
 
649
                $tokenlength[$wlen][] = $xword;
 
650
            if (!$caret || !$dollar) {
 
651
                $re = $caret.preg_quote($xword, '/').$dollar;
 
652
                $tokens[$xword][] = array($word, '/'.$re.'/');
 
653
                if (!isset($tokenwild[$xword]))
 
654
                    $tokenwild[$xword] = $wlen;
 
655
            } else {
 
656
                $tokens[$xword][] = array($word, null);
 
657
            }
 
658
        }
 
659
        asort($tokenwild);
 
660
        // $tokens = array( base word => array( [ query term , regexp ] ... ) ... )
 
661
        // $tokenlength = array( base word length => base word ... )
 
662
        // $tokenwild = array( base word => base word length ... )
 
663
        $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
 
664
        $indexes_known = $this->indexLengths($length_filter);
 
665
        if (!empty($tokenwild)) sort($indexes_known);
 
666
        // get word IDs
 
667
        $wids = array();
 
668
        foreach ($indexes_known as $ixlen) {
 
669
            $word_idx = $this->getIndex('w', $ixlen);
 
670
            // handle exact search
 
671
            if (isset($tokenlength[$ixlen])) {
 
672
                foreach ($tokenlength[$ixlen] as $xword) {
 
673
                    $wid = array_search($xword, $word_idx);
 
674
                    if ($wid !== false) {
 
675
                        $wids[$ixlen][] = $wid;
 
676
                        foreach ($tokens[$xword] as $w)
 
677
                            $result[$w[0]][] = "$ixlen*$wid";
 
678
                    }
 
679
                }
 
680
            }
 
681
            // handle wildcard search
 
682
            foreach ($tokenwild as $xword => $wlen) {
 
683
                if ($wlen >= $ixlen) break;
 
684
                foreach ($tokens[$xword] as $w) {
 
685
                    if (is_null($w[1])) continue;
 
686
                    foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) {
 
687
                        $wids[$ixlen][] = $wid;
 
688
                        $result[$w[0]][] = "$ixlen*$wid";
 
689
                    }
 
690
                }
 
691
            }
 
692
        }
 
693
        return $wids;
 
694
    }
 
695
 
 
696
    /**
 
697
     * Return a list of all pages
 
698
     * Warning: pages may not exist!
 
699
     *
 
700
     * @param string    $key    list only pages containing the metadata key (optional)
 
701
     * @return array            list of page names
 
702
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
703
     */
 
704
    public function getPages($key=null) {
 
705
        $page_idx = $this->getIndex('page', '');
 
706
        if (is_null($key)) return $page_idx;
 
707
 
 
708
        $metaname = idx_cleanName($key);
 
709
 
 
710
        // Special handling for titles
 
711
        if ($key == 'title') {
 
712
            $title_idx = $this->getIndex('title', '');
 
713
            array_splice($page_idx, count($title_idx));
 
714
            foreach ($title_idx as $i => $title)
 
715
                if ($title === "") unset($page_idx[$i]);
 
716
            return array_values($page_idx);
 
717
        }
 
718
 
 
719
        $pages = array();
 
720
        $lines = $this->getIndex($metaname.'_i', '');
 
721
        foreach ($lines as $line) {
 
722
            $pages = array_merge($pages, $this->parseTuples($page_idx, $line));
 
723
        }
 
724
        return array_keys($pages);
 
725
    }
 
726
 
 
727
    /**
 
728
     * Return a list of words sorted by number of times used
 
729
     *
 
730
     * @param int       $min    bottom frequency threshold
 
731
     * @param int       $max    upper frequency limit. No limit if $max<$min
 
732
     * @param int       $length minimum length of words to count
 
733
     * @param string    $key    metadata key to list. Uses the fulltext index if not given
 
734
     * @return array            list of words as the keys and frequency as values
 
735
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
736
     */
 
737
    public function histogram($min=1, $max=0, $minlen=3, $key=null) {
 
738
        if ($min < 1)
 
739
            $min = 1;
 
740
        if ($max < $min)
 
741
            $max = 0;
 
742
 
 
743
        $result = array();
 
744
 
 
745
        if ($key == 'title') {
 
746
            $index = $this->getIndex('title', '');
 
747
            $index = array_count_values($index);
 
748
            foreach ($index as $val => $cnt) {
 
749
                if ($cnt >= $min && (!$max || $cnt <= $max) && strlen($val) >= $minlen)
 
750
                    $result[$val] = $cnt;
 
751
            }
 
752
        }
 
753
        elseif (!is_null($key)) {
 
754
            $metaname = idx_cleanName($key);
 
755
            $index = $this->getIndex($metaname.'_i', '');
 
756
            $val_idx = array();
 
757
            foreach ($index as $wid => $line) {
 
758
                $freq = $this->countTuples($line);
 
759
                if ($freq >= $min && (!$max || $freq <= $max) && strlen($val) >= $minlen)
 
760
                    $val_idx[$wid] = $freq;
 
761
            }
 
762
            if (!empty($val_idx)) {
 
763
                $words = $this->getIndex($metaname.'_w', '');
 
764
                foreach ($val_idx as $wid => $freq)
 
765
                    $result[$words[$wid]] = $freq;
 
766
            }
 
767
        }
 
768
        else {
 
769
            $lengths = idx_listIndexLengths();
 
770
            foreach ($lengths as $length) {
 
771
                if ($length < $minlen) continue;
 
772
                $index = $this->getIndex('i', $length);
 
773
                $words = null;
 
774
                foreach ($index as $wid => $line) {
 
775
                    $freq = $this->countTuples($line);
 
776
                    if ($freq >= $min && (!$max || $freq <= $max)) {
 
777
                        if ($words === null)
 
778
                            $words = $this->getIndex('w', $length);
 
779
                        $result[$words[$wid]] = $freq;
 
780
                    }
 
781
                }
 
782
            }
 
783
        }
 
784
 
 
785
        arsort($result);
 
786
        return $result;
 
787
    }
 
788
 
 
789
    /**
 
790
     * Lock the indexer.
 
791
     *
 
792
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
793
     */
 
794
    protected function lock() {
 
795
        global $conf;
 
796
        $status = true;
 
797
        $run = 0;
 
798
        $lock = $conf['lockdir'].'/_indexer.lock';
 
799
        while (!@mkdir($lock, $conf['dmode'])) {
 
800
            usleep(50);
 
801
            if(is_dir($lock) && time()-@filemtime($lock) > 60*5){
 
802
                // looks like a stale lock - remove it
 
803
                if (!@rmdir($lock)) {
 
804
                    $status = "removing the stale lock failed";
 
805
                    return false;
 
806
                } else {
 
807
                    $status = "stale lock removed";
 
808
                }
 
809
            }elseif($run++ == 1000){
 
810
                // we waited 5 seconds for that lock
 
811
                return false;
 
812
            }
 
813
        }
 
814
        if ($conf['dperm'])
 
815
            chmod($lock, $conf['dperm']);
 
816
        return $status;
 
817
    }
 
818
 
 
819
    /**
 
820
     * Release the indexer lock.
 
821
     *
 
822
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
823
     */
 
824
    protected function unlock() {
 
825
        global $conf;
 
826
        @rmdir($conf['lockdir'].'/_indexer.lock');
 
827
        return true;
 
828
    }
 
829
 
 
830
    /**
 
831
     * Retrieve the entire index.
 
832
     *
 
833
     * The $suffix argument is for an index that is split into
 
834
     * multiple parts. Different index files should use different
 
835
     * base names.
 
836
     *
 
837
     * @param string    $idx    name of the index
 
838
     * @param string    $suffix subpart identifier
 
839
     * @return array            list of lines without CR or LF
 
840
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
841
     */
 
842
    protected function getIndex($idx, $suffix) {
 
843
        global $conf;
 
844
        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
 
845
        if (!@file_exists($fn)) return array();
 
846
        return file($fn, FILE_IGNORE_NEW_LINES);
 
847
    }
 
848
 
 
849
    /**
 
850
     * Replace the contents of the index with an array.
 
851
     *
 
852
     * @param string    $idx    name of the index
 
853
     * @param string    $suffix subpart identifier
 
854
     * @param arrayref  $linex  list of lines without LF
 
855
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
856
     */
 
857
    protected function saveIndex($idx, $suffix, &$lines) {
 
858
        global $conf;
 
859
        $fn = $conf['indexdir'].'/'.$idx.$suffix;
 
860
        $fh = @fopen($fn.'.tmp', 'w');
 
861
        if (!$fh) return false;
 
862
        fwrite($fh, join("\n", $lines));
 
863
        if (!empty($lines))
 
864
            fwrite($fh, "\n");
 
865
        fclose($fh);
 
866
        if (isset($conf['fperm']))
 
867
            chmod($fn.'.tmp', $conf['fperm']);
 
868
        io_rename($fn.'.tmp', $fn.'.idx');
 
869
        if ($suffix !== '')
 
870
            $this->cacheIndexDir($idx, $suffix, empty($lines));
 
871
        return true;
 
872
    }
 
873
 
 
874
    /**
 
875
     * Retrieve a line from the index.
 
876
     *
 
877
     * @param string    $idx    name of the index
 
878
     * @param string    $suffix subpart identifier
 
879
     * @param int       $id     the line number
 
880
     * @return string           a line with trailing whitespace removed
 
881
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
882
     */
 
883
    protected function getIndexKey($idx, $suffix, $id) {
 
884
        global $conf;
 
885
        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
 
886
        if (!@file_exists($fn)) return '';
 
887
        $fh = @fopen($fn, 'r');
 
888
        if (!$fh) return '';
153
889
        $ln = -1;
154
 
        while (($curline = _freadline($ih)) !== false) {
155
 
            if (++$ln == $idx) {
 
890
        while (($line = fgets($fh)) !== false) {
 
891
            if (++$ln == $id) break;
 
892
        }
 
893
        fclose($fh);
 
894
        return rtrim((string)$line);
 
895
    }
 
896
 
 
897
    /**
 
898
     * Write a line into the index.
 
899
     *
 
900
     * @param string    $idx    name of the index
 
901
     * @param string    $suffix subpart identifier
 
902
     * @param int       $id     the line number
 
903
     * @param string    $line   line to write
 
904
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
905
     */
 
906
    protected function saveIndexKey($idx, $suffix, $id, $line) {
 
907
        global $conf;
 
908
        if (substr($line, -1) != "\n")
 
909
            $line .= "\n";
 
910
        $fn = $conf['indexdir'].'/'.$idx.$suffix;
 
911
        $fh = @fopen($fn.'.tmp', 'w');
 
912
        if (!$fh) return false;
 
913
        $ih = @fopen($fn.'.idx', 'r');
 
914
        if ($ih) {
 
915
            $ln = -1;
 
916
            while (($curline = fgets($ih)) !== false) {
 
917
                fwrite($fh, (++$ln == $id) ? $line : $curline);
 
918
            }
 
919
            if ($id > $ln) {
 
920
                while ($id > ++$ln)
 
921
                    fwrite($fh, "\n");
156
922
                fwrite($fh, $line);
157
 
            } else {
158
 
                fwrite($fh, $curline);
159
 
            }
160
 
        }
161
 
        if ($idx > $ln) {
162
 
            fwrite($fh,$line);
163
 
        }
164
 
        fclose($ih);
165
 
    } else {
166
 
        fwrite($fh,$line);
167
 
    }
168
 
    fclose($fh);
169
 
    if($conf['fperm']) chmod($fn.'.tmp', $conf['fperm']);
170
 
    io_rename($fn.'.tmp', $fn.'.idx');
171
 
    return true;
172
 
}
173
 
 
174
 
/**
175
 
 * Read a single line from an index (if it exists).
176
 
 *
177
 
 * @author Tom N Harris <tnharris@whoopdedo.org>
178
 
 */
179
 
function idx_getIndexLine($pre, $wlen, $idx){
180
 
    global $conf;
181
 
    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
182
 
    if(!@file_exists($fn)) return '';
183
 
    $fh = @fopen($fn,'r');
184
 
    if(!$fh) return '';
185
 
    $ln = -1;
186
 
    while (($line = _freadline($fh)) !== false) {
187
 
        if (++$ln == $idx) break;
188
 
    }
189
 
    fclose($fh);
190
 
    return "$line";
191
 
}
192
 
 
193
 
/**
194
 
 * Split a page into words
195
 
 *
196
 
 * Returns an array of word counts, false if an error occurred.
197
 
 * Array is keyed on the word length, then the word index.
198
 
 *
199
 
 * @author Andreas Gohr <andi@splitbrain.org>
200
 
 * @author Christopher Smith <chris@jalakai.co.uk>
201
 
 */
202
 
function idx_getPageWords($page){
203
 
    global $conf;
204
 
    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
205
 
    if(@file_exists($swfile)){
206
 
        $stopwords = file($swfile);
207
 
    }else{
208
 
        $stopwords = array();
 
923
            }
 
924
            fclose($ih);
 
925
        } else {
 
926
            $ln = -1;
 
927
            while ($id > ++$ln)
 
928
                fwrite($fh, "\n");
 
929
            fwrite($fh, $line);
 
930
        }
 
931
        fclose($fh);
 
932
        if (isset($conf['fperm']))
 
933
            chmod($fn.'.tmp', $conf['fperm']);
 
934
        io_rename($fn.'.tmp', $fn.'.idx');
 
935
        if ($suffix !== '')
 
936
            $this->cacheIndexDir($idx, $suffix);
 
937
        return true;
 
938
    }
 
939
 
 
940
    /**
 
941
     * Retrieve or insert a value in the index.
 
942
     *
 
943
     * @param string    $idx    name of the index
 
944
     * @param string    $suffix subpart identifier
 
945
     * @param string    $value  line to find in the index
 
946
     * @return int              line number of the value in the index
 
947
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
948
     */
 
949
    protected function addIndexKey($idx, $suffix, $value) {
 
950
        $index = $this->getIndex($idx, $suffix);
 
951
        $id = array_search($value, $index);
 
952
        if ($id === false) {
 
953
            $id = count($index);
 
954
            $index[$id] = $value;
 
955
            if (!$this->saveIndex($idx, $suffix, $index)) {
 
956
                trigger_error("Failed to write $idx index", E_USER_ERROR);
 
957
                return false;
 
958
            }
 
959
        }
 
960
        return $id;
 
961
    }
 
962
 
 
963
    protected function cacheIndexDir($idx, $suffix, $delete=false) {
 
964
        global $conf;
 
965
        if ($idx == 'i')
 
966
            $cachename = $conf['indexdir'].'/lengths';
 
967
        else
 
968
            $cachename = $conf['indexdir'].'/'.$idx.'lengths';
 
969
        $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
 
970
        if ($lengths === false) $lengths = array();
 
971
        $old = array_search((string)$suffix, $lengths);
 
972
        if (empty($lines)) {
 
973
            if ($old === false) return;
 
974
            unset($lengths[$old]);
 
975
        } else {
 
976
            if ($old !== false) return;
 
977
            $lengths[] = $suffix;
 
978
            sort($lengths);
 
979
        }
 
980
        $fh = @fopen($cachename.'.tmp', 'w');
 
981
        if (!$fh) {
 
982
            trigger_error("Failed to write index cache", E_USER_ERROR);
 
983
            return;
 
984
        }
 
985
        @fwrite($fh, implode("\n", $lengths));
 
986
        @fclose($fh);
 
987
        if (isset($conf['fperm']))
 
988
            chmod($cachename.'.tmp', $conf['fperm']);
 
989
        io_rename($cachename.'.tmp', $cachename.'.idx');
 
990
    }
 
991
 
 
992
    /**
 
993
     * Get the list of lengths indexed in the wiki.
 
994
     *
 
995
     * Read the index directory or a cache file and returns
 
996
     * a sorted array of lengths of the words used in the wiki.
 
997
     *
 
998
     * @author YoBoY <yoboy.leguesh@gmail.com>
 
999
     */
 
1000
    protected function listIndexLengths() {
 
1001
        global $conf;
 
1002
        $cachename = $conf['indexdir'].'/lengths';
 
1003
        clearstatcache();
 
1004
        if (@file_exists($cachename.'.idx')) {
 
1005
            $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
 
1006
            if ($lengths !== false) {
 
1007
                $idx = array();
 
1008
                foreach ($lengths as $length)
 
1009
                    $idx[] = (int)$length;
 
1010
                return $idx;
 
1011
            }
 
1012
        }
 
1013
 
 
1014
        $dir = @opendir($conf['indexdir']);
 
1015
        if ($dir === false)
 
1016
            return array();
 
1017
        $lengths[] = array();
 
1018
        while (($f = readdir($dir)) !== false) {
 
1019
            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
 
1020
                $i = substr($f, 1, -4);
 
1021
                if (is_numeric($i))
 
1022
                    $lengths[] = (int)$i;
 
1023
            }
 
1024
        }
 
1025
        closedir($dir);
 
1026
        sort($lengths);
 
1027
        // save this in a file
 
1028
        $fh = @fopen($cachename.'.tmp', 'w');
 
1029
        if (!$fh) {
 
1030
            trigger_error("Failed to write index cache", E_USER_ERROR);
 
1031
            return;
 
1032
        }
 
1033
        @fwrite($fh, implode("\n", $lengths));
 
1034
        @fclose($fh);
 
1035
        if (isset($conf['fperm']))
 
1036
            chmod($cachename.'.tmp', $conf['fperm']);
 
1037
        io_rename($cachename.'.tmp', $cachename.'.idx');
 
1038
 
 
1039
        return $lengths;
 
1040
    }
 
1041
 
 
1042
    /**
 
1043
     * Get the word lengths that have been indexed.
 
1044
     *
 
1045
     * Reads the index directory and returns an array of lengths
 
1046
     * that there are indices for.
 
1047
     *
 
1048
     * @author YoBoY <yoboy.leguesh@gmail.com>
 
1049
     */
 
1050
    protected function indexLengths($filter) {
 
1051
        global $conf;
 
1052
        $idx = array();
 
1053
        if (is_array($filter)) {
 
1054
            // testing if index files exist only
 
1055
            $path = $conf['indexdir']."/i";
 
1056
            foreach ($filter as $key => $value) {
 
1057
                if (@file_exists($path.$key.'.idx'))
 
1058
                    $idx[] = $key;
 
1059
            }
 
1060
        } else {
 
1061
            $lengths = idx_listIndexLengths();
 
1062
            foreach ($lengths as $key => $length) {
 
1063
                // keep all the values equal or superior
 
1064
                if ((int)$length >= (int)$filter)
 
1065
                    $idx[] = $length;
 
1066
            }
 
1067
        }
 
1068
        return $idx;
 
1069
    }
 
1070
 
 
1071
    /**
 
1072
     * Insert or replace a tuple in a line.
 
1073
     *
 
1074
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
1075
     */
 
1076
    protected function updateTuple($line, $id, $count) {
 
1077
        $newLine = $line;
 
1078
        if ($newLine !== '')
 
1079
            $newLine = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $newLine);
 
1080
        $newLine = trim($newLine, ':');
 
1081
        if ($count) {
 
1082
            if (strlen($newLine) > 0)
 
1083
                return "$id*$count:".$newLine;
 
1084
            else
 
1085
                return "$id*$count".$newLine;
 
1086
        }
 
1087
        return $newLine;
 
1088
    }
 
1089
 
 
1090
    /**
 
1091
     * Split a line into an array of tuples.
 
1092
     *
 
1093
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
1094
     * @author Andreas Gohr <andi@splitbrain.org>
 
1095
     */
 
1096
    protected function parseTuples(&$keys, $line) {
 
1097
        $result = array();
 
1098
        if ($line == '') return $result;
 
1099
        $parts = explode(':', $line);
 
1100
        foreach ($parts as $tuple) {
 
1101
            if ($tuple === '') continue;
 
1102
            list($key, $cnt) = explode('*', $tuple);
 
1103
            if (!$cnt) continue;
 
1104
            $key = $keys[$key];
 
1105
            if (!$key) continue;
 
1106
            $result[$key] = $cnt;
 
1107
        }
 
1108
        return $result;
 
1109
    }
 
1110
 
 
1111
    /**
 
1112
     * Sum the counts in a list of tuples.
 
1113
     *
 
1114
     * @author Tom N Harris <tnharris@whoopdedo.org>
 
1115
     */
 
1116
    protected function countTuples($line) {
 
1117
        $freq = 0;
 
1118
        $parts = explode(':', $line);
 
1119
        foreach ($parts as $tuple) {
 
1120
            if ($tuple === '') continue;
 
1121
            list($pid, $cnt) = explode('*', $tuple);
 
1122
            $freq += (int)$cnt;
 
1123
        }
 
1124
        return $freq;
 
1125
    }
 
1126
}
 
1127
 
 
1128
/**
 
1129
 * Create an instance of the indexer.
 
1130
 *
 
1131
 * @return object               a Doku_Indexer
 
1132
 * @author Tom N Harris <tnharris@whoopdedo.org>
 
1133
 */
 
1134
function idx_get_indexer() {
 
1135
    static $Indexer = null;
 
1136
    if (is_null($Indexer)) {
 
1137
        $Indexer = new Doku_Indexer();
 
1138
    }
 
1139
    return $Indexer;
 
1140
}
 
1141
 
 
1142
/**
 
1143
 * Returns words that will be ignored.
 
1144
 *
 
1145
 * @return array                list of stop words
 
1146
 * @author Tom N Harris <tnharris@whoopdedo.org>
 
1147
 */
 
1148
function & idx_get_stopwords() {
 
1149
    static $stopwords = null;
 
1150
    if (is_null($stopwords)) {
 
1151
        global $conf;
 
1152
        $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
 
1153
        if(@file_exists($swfile)){
 
1154
            $stopwords = file($swfile, FILE_IGNORE_NEW_LINES);
 
1155
        }else{
 
1156
            $stopwords = array();
 
1157
        }
 
1158
    }
 
1159
    return $stopwords;
 
1160
}
 
1161
 
 
1162
/**
 
1163
 * Adds/updates the search index for the given page
 
1164
 *
 
1165
 * Locking is handled internally.
 
1166
 *
 
1167
 * @param string        $page   name of the page to index
 
1168
 * @param boolean       $verbose    print status messages
 
1169
 * @param boolean       $force  force reindexing even when the index is up to date
 
1170
 * @return boolean              the function completed successfully
 
1171
 * @author Tom N Harris <tnharris@whoopdedo.org>
 
1172
 */
 
1173
function idx_addPage($page, $verbose=false, $force=false) {
 
1174
    // check if indexing needed
 
1175
    $idxtag = metaFN($page,'.indexed');
 
1176
    if(!$force && @file_exists($idxtag)){
 
1177
        if(trim(io_readFile($idxtag)) == idx_get_version()){
 
1178
            $last = @filemtime($idxtag);
 
1179
            if($last > @filemtime(wikiFN($page))){
 
1180
                if ($verbose) print("Indexer: index for $page up to date".DOKU_LF);
 
1181
                return false;
 
1182
            }
 
1183
        }
 
1184
    }
 
1185
 
 
1186
    if (!page_exists($page)) {
 
1187
        if (!@file_exists($idxtag)) {
 
1188
            if ($verbose) print("Indexer: $page does not exist, ignoring".DOKU_LF);
 
1189
            return false;
 
1190
        }
 
1191
        $Indexer = idx_get_indexer();
 
1192
        $result = $Indexer->deletePage($page);
 
1193
        if ($result === "locked") {
 
1194
            if ($verbose) print("Indexer: locked".DOKU_LF);
 
1195
            return false;
 
1196
        }
 
1197
        @unlink($idxtag);
 
1198
        return $result;
 
1199
    }
 
1200
    $indexenabled = p_get_metadata($page, 'internal index', METADATA_RENDER_UNLIMITED);
 
1201
    if ($indexenabled === false) {
 
1202
        $result = false;
 
1203
        if (@file_exists($idxtag)) {
 
1204
            $Indexer = idx_get_indexer();
 
1205
            $result = $Indexer->deletePage($page);
 
1206
            if ($result === "locked") {
 
1207
                if ($verbose) print("Indexer: locked".DOKU_LF);
 
1208
                return false;
 
1209
            }
 
1210
            @unlink($idxtag);
 
1211
        }
 
1212
        if ($verbose) print("Indexer: index disabled for $page".DOKU_LF);
 
1213
        return $result;
209
1214
    }
210
1215
 
211
1216
    $body = '';
212
 
    $data = array($page, $body);
 
1217
    $metadata = array();
 
1218
    $metadata['title'] = p_get_metadata($page, 'title', METADATA_RENDER_UNLIMITED);
 
1219
    if (($references = p_get_metadata($page, 'relation references', METADATA_RENDER_UNLIMITED)) !== null)
 
1220
        $metadata['relation_references'] = array_keys($references);
 
1221
    else
 
1222
        $metadata['relation_references'] = array();
 
1223
    $data = compact('page', 'body', 'metadata');
213
1224
    $evt = new Doku_Event('INDEXER_PAGE_ADD', $data);
214
 
    if ($evt->advise_before()) $data[1] .= rawWiki($page);
 
1225
    if ($evt->advise_before()) $data['body'] = $data['body'] . " " . rawWiki($page);
215
1226
    $evt->advise_after();
216
1227
    unset($evt);
217
 
 
218
 
    list($page,$body) = $data;
219
 
 
220
 
    $body   = strtr($body, "\r\n\t", '   ');
221
 
    $tokens = explode(' ', $body);
222
 
    $tokens = array_count_values($tokens);   // count the frequency of each token
223
 
 
224
 
    // ensure the deaccented or romanised page names of internal links are added to the token array
225
 
    // (this is necessary for the backlink function -- there maybe a better way!)
226
 
    if ($conf['deaccent']) {
227
 
        $links = p_get_metadata($page,'relation references');
228
 
 
229
 
        if (!empty($links)) {
230
 
            $tmp = join(' ',array_keys($links));                // make a single string
231
 
            $tmp = strtr($tmp, ':', ' ');                       // replace namespace separator with a space
232
 
            $link_tokens = array_unique(explode(' ', $tmp));    // break into tokens
233
 
 
234
 
            foreach ($link_tokens as $link_token) {
235
 
                if (isset($tokens[$link_token])) continue;
236
 
                $tokens[$link_token] = 1;
237
 
            }
238
 
        }
239
 
    }
240
 
 
241
 
    $words = array();
242
 
    foreach ($tokens as $word => $count) {
243
 
        $arr = idx_tokenizer($word,$stopwords);
244
 
        $arr = array_count_values($arr);
245
 
        foreach ($arr as $w => $c) {
246
 
            $l = wordlen($w);
247
 
            if(isset($words[$l])){
248
 
                $words[$l][$w] = $c * $count + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
249
 
            }else{
250
 
                $words[$l] = array($w => $c * $count);
251
 
            }
252
 
        }
253
 
    }
254
 
 
255
 
    // arrive here with $words = array(wordlen => array(word => frequency))
256
 
 
257
 
    $index = array(); //resulting index
258
 
    foreach (array_keys($words) as $wlen){
259
 
        $word_idx = idx_getIndex('w',$wlen);
260
 
        foreach ($words[$wlen] as $word => $freq) {
261
 
            $wid = array_search("$word\n",$word_idx);
262
 
            if(!is_int($wid)){
263
 
                $wid = count($word_idx);
264
 
                $word_idx[] = "$word\n";
265
 
            }
266
 
            if(!isset($index[$wlen]))
267
 
                $index[$wlen] = array();
268
 
            $index[$wlen][$wid] = $freq;
269
 
        }
270
 
 
271
 
        // save back word index
272
 
        if(!idx_saveIndex('w',$wlen,$word_idx)){
273
 
            trigger_error("Failed to write word index", E_USER_ERROR);
274
 
            return false;
275
 
        }
276
 
    }
277
 
 
278
 
    return $index;
279
 
}
280
 
 
281
 
/**
282
 
 * Adds/updates the search for the given page
283
 
 *
284
 
 * This is the core function of the indexer which does most
285
 
 * of the work. This function needs to be called with proper
286
 
 * locking!
287
 
 *
288
 
 * @author Andreas Gohr <andi@splitbrain.org>
289
 
 */
290
 
function idx_addPage($page){
291
 
    global $conf;
292
 
 
293
 
    // load known documents
294
 
    $page_idx = idx_getIndex('page','');
295
 
 
296
 
    // get page id (this is the linenumber in page.idx)
297
 
    $pid = array_search("$page\n",$page_idx);
298
 
    if(!is_int($pid)){
299
 
        $pid = count($page_idx);
300
 
        // page was new - write back
301
 
        if (!idx_appendIndex('page','',"$page\n")){
302
 
            trigger_error("Failed to write page index", E_USER_ERROR);
303
 
            return false;
304
 
        }
305
 
    }
306
 
    unset($page_idx); // free memory
307
 
 
308
 
    idx_saveIndexLine('title', '', $pid, p_get_first_heading($page, false));
309
 
 
310
 
    $pagewords = array();
311
 
    // get word usage in page
312
 
    $words = idx_getPageWords($page);
313
 
    if($words === false) return false;
314
 
 
315
 
    if(!empty($words)) {
316
 
        foreach(array_keys($words) as $wlen){
317
 
            $index = idx_getIndex('i',$wlen);
318
 
            foreach($words[$wlen] as $wid => $freq){
319
 
                if($wid<count($index)){
320
 
                    $index[$wid] = idx_updateIndexLine($index[$wid],$pid,$freq);
321
 
                }else{
322
 
                    // New words **should** have been added in increasing order
323
 
                    // starting with the first unassigned index.
324
 
                    // If someone can show how this isn't true, then I'll need to sort
325
 
                    // or do something special.
326
 
                    $index[$wid] = idx_updateIndexLine('',$pid,$freq);
327
 
                }
328
 
                $pagewords[] = "$wlen*$wid";
329
 
            }
330
 
            // save back word index
331
 
            if(!idx_saveIndex('i',$wlen,$index)){
332
 
                trigger_error("Failed to write index", E_USER_ERROR);
333
 
                return false;
334
 
            }
335
 
        }
336
 
    }
337
 
 
338
 
    // Remove obsolete index entries
339
 
    $pageword_idx = trim(idx_getIndexLine('pageword','',$pid));
340
 
    if ($pageword_idx !== '') {
341
 
        $oldwords = explode(':',$pageword_idx);
342
 
        $delwords = array_diff($oldwords, $pagewords);
343
 
        $upwords = array();
344
 
        foreach ($delwords as $word) {
345
 
            if($word=='') continue;
346
 
            list($wlen,$wid) = explode('*',$word);
347
 
            $wid = (int)$wid;
348
 
            $upwords[$wlen][] = $wid;
349
 
        }
350
 
        foreach ($upwords as $wlen => $widx) {
351
 
            $index = idx_getIndex('i',$wlen);
352
 
            foreach ($widx as $wid) {
353
 
                $index[$wid] = idx_updateIndexLine($index[$wid],$pid,0);
354
 
            }
355
 
            idx_saveIndex('i',$wlen,$index);
356
 
        }
357
 
    }
358
 
    // Save the reverse index
359
 
    $pageword_idx = join(':',$pagewords)."\n";
360
 
    if(!idx_saveIndexLine('pageword','',$pid,$pageword_idx)){
361
 
        trigger_error("Failed to write word index", E_USER_ERROR);
 
1228
    extract($data);
 
1229
 
 
1230
    $Indexer = idx_get_indexer();
 
1231
    $result = $Indexer->addPageWords($page, $body);
 
1232
    if ($result === "locked") {
 
1233
        if ($verbose) print("Indexer: locked".DOKU_LF);
362
1234
        return false;
363
1235
    }
364
1236
 
365
 
    return true;
366
 
}
367
 
 
368
 
/**
369
 
 * Write a new index line to the filehandle
370
 
 *
371
 
 * This function writes an line for the index file to the
372
 
 * given filehandle. It removes the given document from
373
 
 * the given line and readds it when $count is >0.
374
 
 *
375
 
 * @deprecated - see idx_updateIndexLine
376
 
 * @author Andreas Gohr <andi@splitbrain.org>
377
 
 */
378
 
function idx_writeIndexLine($fh,$line,$pid,$count){
379
 
    fwrite($fh,idx_updateIndexLine($line,$pid,$count));
380
 
}
381
 
 
382
 
/**
383
 
 * Modify an index line with new information
384
 
 *
385
 
 * This returns a line of the index. It removes the
386
 
 * given document from the line and readds it if
387
 
 * $count is >0.
 
1237
    if ($result) {
 
1238
        $result = $Indexer->addMetaKeys($page, $metadata);
 
1239
        if ($result === "locked") {
 
1240
            if ($verbose) print("Indexer: locked".DOKU_LF);
 
1241
            return false;
 
1242
        }
 
1243
    }
 
1244
 
 
1245
    if ($result)
 
1246
        io_saveFile(metaFN($page,'.indexed'), idx_get_version());
 
1247
    if ($verbose) {
 
1248
        print("Indexer: finished".DOKU_LF);
 
1249
        return true;
 
1250
    }
 
1251
    return $result;
 
1252
}
 
1253
 
 
1254
/**
 
1255
 * Find tokens in the fulltext index
 
1256
 *
 
1257
 * Takes an array of words and will return a list of matching
 
1258
 * pages for each one.
 
1259
 *
 
1260
 * Important: No ACL checking is done here! All results are
 
1261
 *            returned, regardless of permissions
 
1262
 *
 
1263
 * @param arrayref      $words  list of words to search for
 
1264
 * @return array                list of pages found, associated with the search terms
 
1265
 */
 
1266
function idx_lookup(&$words) {
 
1267
    $Indexer = idx_get_indexer();
 
1268
    return $Indexer->lookup($words);
 
1269
}
 
1270
 
 
1271
/**
 
1272
 * Split a string into tokens
 
1273
 *
 
1274
 */
 
1275
function idx_tokenizer($string, $wc=false) {
 
1276
    $Indexer = idx_get_indexer();
 
1277
    return $Indexer->tokenizer($string, $wc);
 
1278
}
 
1279
 
 
1280
/* For compatibility */
 
1281
 
 
1282
/**
 
1283
 * Read the list of words in an index (if it exists).
388
1284
 *
389
1285
 * @author Tom N Harris <tnharris@whoopdedo.org>
390
 
 * @author Andreas Gohr <andi@splitbrain.org>
391
1286
 */
392
 
function idx_updateIndexLine($line,$pid,$count){
393
 
    $line = trim($line);
394
 
    $updated = array();
395
 
    if($line != ''){
396
 
        $parts = explode(':',$line);
397
 
        // remove doc from given line
398
 
        foreach($parts as $part){
399
 
            if($part == '') continue;
400
 
            list($doc,$cnt) = explode('*',$part);
401
 
            if($doc != $pid){
402
 
                $updated[] = $part;
403
 
            }
404
 
        }
405
 
    }
406
 
 
407
 
    // add doc
408
 
    if ($count){
409
 
        $updated[] = "$pid*$count";
410
 
    }
411
 
 
412
 
    return join(':',$updated)."\n";
 
1287
function idx_getIndex($idx, $suffix) {
 
1288
    global $conf;
 
1289
    $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
 
1290
    if (!@file_exists($fn)) return array();
 
1291
    return file($fn);
413
1292
}
414
1293
 
415
1294
/**
416
 
 * Get the list of lenghts indexed in the wiki
 
1295
 * Get the list of lengths indexed in the wiki.
417
1296
 *
418
1297
 * Read the index directory or a cache file and returns
419
1298
 * a sorted array of lengths of the words used in the wiki.
427
1306
        $docache = false;
428
1307
    } else {
429
1308
        clearstatcache();
430
 
        if (@file_exists($conf['indexdir'].'/lengths.idx') and (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) {
431
 
            if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ) !== false) {
 
1309
        if (@file_exists($conf['indexdir'].'/lengths.idx')
 
1310
        && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) {
 
1311
            if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) !== false) {
432
1312
                $idx = array();
433
 
                foreach ( $lengths as $length) {
 
1313
                foreach ($lengths as $length) {
434
1314
                    $idx[] = (int)$length;
435
1315
                }
436
1316
                return $idx;
439
1319
        $docache = true;
440
1320
    }
441
1321
 
442
 
    if ($conf['readdircache'] == 0 or $docache ) {
 
1322
    if ($conf['readdircache'] == 0 || $docache) {
443
1323
        $dir = @opendir($conf['indexdir']);
444
 
        if($dir===false)
 
1324
        if ($dir === false)
445
1325
            return array();
446
 
        $idx[] = array();
 
1326
        $idx = array();
447
1327
        while (($f = readdir($dir)) !== false) {
448
 
            if (substr($f,0,1) == 'i' && substr($f,-4) == '.idx'){
449
 
                $i = substr($f,1,-4);
 
1328
            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
 
1329
                $i = substr($f, 1, -4);
450
1330
                if (is_numeric($i))
451
1331
                    $idx[] = (int)$i;
452
1332
            }
453
1333
        }
454
1334
        closedir($dir);
455
1335
        sort($idx);
456
 
        // we save this in a file.
457
 
        if ($docache === true) {
458
 
            $handle = @fopen($conf['indexdir'].'/lengths.idx','w');
459
 
            @fwrite($handle, implode("\n",$idx));
 
1336
        // save this in a file
 
1337
        if ($docache) {
 
1338
            $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w');
 
1339
            @fwrite($handle, implode("\n", $idx));
460
1340
            @fclose($handle);
461
1341
        }
462
1342
        return $idx;
473
1353
 *
474
1354
 * @author YoBoY <yoboy.leguesh@gmail.com>
475
1355
 */
476
 
function idx_indexLengths(&$filter){
 
1356
function idx_indexLengths($filter) {
477
1357
    global $conf;
478
1358
    $idx = array();
479
 
    if (is_array($filter)){
480
 
        // testing if index files exists only
 
1359
    if (is_array($filter)) {
 
1360
        // testing if index files exist only
 
1361
        $path = $conf['indexdir']."/i";
481
1362
        foreach ($filter as $key => $value) {
482
 
            if (@file_exists($conf['indexdir']."/i$key.idx")) {
 
1363
            if (@file_exists($path.$key.'.idx'))
483
1364
                $idx[] = $key;
484
 
            }
485
1365
        }
486
1366
    } else {
487
1367
        $lengths = idx_listIndexLengths();
488
 
        foreach ( $lengths as $key => $length) {
489
 
            // we keep all the values equal or superior 
490
 
            if ((int)$length >= (int)$filter) {
 
1368
        foreach ($lengths as $key => $length) {
 
1369
            // keep all the values equal or superior
 
1370
            if ((int)$length >= (int)$filter)
491
1371
                $idx[] = $length;
492
 
            }
493
1372
        }
494
1373
    }
495
1374
    return $idx;
496
1375
}
497
1376
 
498
1377
/**
499
 
 * Find the the index number of each search term.
500
 
 *
501
 
 * This will group together words that appear in the same index.
502
 
 * So it should perform better, because it only opens each index once.
503
 
 * Actually, it's not that great. (in my experience) Probably because of the disk cache.
504
 
 * And the sorted function does more work, making it slightly slower in some cases.
505
 
 *
506
 
 * @param array    $words   The query terms. Words should only contain valid characters,
507
 
 *                          with a '*' at either the beginning or end of the word (or both)
508
 
 * @param arrayref $result  Set to word => array("length*id" ...), use this to merge the
509
 
 *                          index locations with the appropriate query term.
510
 
 * @return array            Set to length => array(id ...)
 
1378
 * Clean a name of a key for use as a file name.
 
1379
 *
 
1380
 * Romanizes non-latin characters, then strips away anything that's
 
1381
 * not a letter, number, or underscore.
511
1382
 *
512
1383
 * @author Tom N Harris <tnharris@whoopdedo.org>
513
1384
 */
514
 
function idx_getIndexWordsSorted($words,&$result){
515
 
    // parse and sort tokens
516
 
    $tokens = array();
517
 
    $tokenlength = array();
518
 
    $tokenwild = array();
519
 
    foreach($words as $word){
520
 
        $result[$word] = array();
521
 
        $wild = 0;
522
 
        $xword = $word;
523
 
        $wlen = wordlen($word);
524
 
 
525
 
        // check for wildcards
526
 
        if(substr($xword,0,1) == '*'){
527
 
            $xword = substr($xword,1);
528
 
            $wild |= 1;
529
 
            $wlen -= 1;
530
 
        }
531
 
        if(substr($xword,-1,1) == '*'){
532
 
            $xword = substr($xword,0,-1);
533
 
            $wild |= 2;
534
 
            $wlen -= 1;
535
 
        }
536
 
        if ($wlen < IDX_MINWORDLENGTH && $wild == 0 && !is_numeric($xword)) continue;
537
 
        if(!isset($tokens[$xword])){
538
 
            $tokenlength[$wlen][] = $xword;
539
 
        }
540
 
        if($wild){
541
 
            $ptn = preg_quote($xword,'/');
542
 
            if(($wild&1) == 0) $ptn = '^'.$ptn;
543
 
            if(($wild&2) == 0) $ptn = $ptn.'$';
544
 
            $tokens[$xword][] = array($word, '/'.$ptn.'/');
545
 
            if(!isset($tokenwild[$xword])) $tokenwild[$xword] = $wlen;
546
 
        }else
547
 
            $tokens[$xword][] = array($word, null);
548
 
    }
549
 
    asort($tokenwild);
550
 
    // $tokens = array( base word => array( [ query word , grep pattern ] ... ) ... )
551
 
    // $tokenlength = array( base word length => base word ... )
552
 
    // $tokenwild = array( base word => base word length ... )
553
 
 
554
 
    $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
555
 
    $indexes_known = idx_indexLengths($length_filter);
556
 
    if(!empty($tokenwild)) sort($indexes_known);
557
 
    // get word IDs
558
 
    $wids = array();
559
 
    foreach($indexes_known as $ixlen){
560
 
        $word_idx = idx_getIndex('w',$ixlen);
561
 
        // handle exact search
562
 
        if(isset($tokenlength[$ixlen])){
563
 
            foreach($tokenlength[$ixlen] as $xword){
564
 
                $wid = array_search("$xword\n",$word_idx);
565
 
                if(is_int($wid)){
566
 
                    $wids[$ixlen][] = $wid;
567
 
                    foreach($tokens[$xword] as $w)
568
 
                        $result[$w[0]][] = "$ixlen*$wid";
569
 
                }
570
 
            }
571
 
        }
572
 
        // handle wildcard search
573
 
        foreach($tokenwild as $xword => $wlen){
574
 
            if($wlen >= $ixlen) break;
575
 
            foreach($tokens[$xword] as $w){
576
 
                if(is_null($w[1])) continue;
577
 
                foreach(array_keys(preg_grep($w[1],$word_idx)) as $wid){
578
 
                    $wids[$ixlen][] = $wid;
579
 
                    $result[$w[0]][] = "$ixlen*$wid";
580
 
                }
581
 
            }
582
 
        }
583
 
    }
584
 
    return $wids;
585
 
}
586
 
 
587
 
/**
588
 
 * Lookup words in index
589
 
 *
590
 
 * Takes an array of word and will return a list of matching
591
 
 * documents for each one.
592
 
 *
593
 
 * Important: No ACL checking is done here! All results are
594
 
 *            returned, regardless of permissions
595
 
 *
596
 
 * @author Andreas Gohr <andi@splitbrain.org>
597
 
 */
598
 
function idx_lookup($words){
599
 
    global $conf;
600
 
 
601
 
    $result = array();
602
 
 
603
 
    $wids = idx_getIndexWordsSorted($words, $result);
604
 
    if(empty($wids)) return array();
605
 
 
606
 
    // load known words and documents
607
 
    $page_idx = idx_getIndex('page','');
608
 
 
609
 
    $docs = array();                          // hold docs found
610
 
    foreach(array_keys($wids) as $wlen){
611
 
        $wids[$wlen] = array_unique($wids[$wlen]);
612
 
        $index = idx_getIndex('i',$wlen);
613
 
        foreach($wids[$wlen] as $ixid){
614
 
            if($ixid < count($index))
615
 
                $docs["$wlen*$ixid"] = idx_parseIndexLine($page_idx,$index[$ixid]);
616
 
        }
617
 
    }
618
 
 
619
 
    // merge found pages into final result array
620
 
    $final = array();
621
 
    foreach($result as $word => $res){
622
 
        $final[$word] = array();
623
 
        foreach($res as $wid){
624
 
            $hits = &$docs[$wid];
625
 
            foreach ($hits as $hitkey => $hitcnt) {
626
 
                if (!isset($final[$word][$hitkey])) {
627
 
                    $final[$word][$hitkey] = $hitcnt;
628
 
                } else {
629
 
                    $final[$word][$hitkey] += $hitcnt;
630
 
                }
631
 
            }
632
 
        }
633
 
    }
634
 
    return $final;
635
 
}
636
 
 
637
 
/**
638
 
 * Returns a list of documents and counts from a index line
639
 
 *
640
 
 * It omits docs with a count of 0 and pages that no longer
641
 
 * exist.
642
 
 *
643
 
 * @param  array  $page_idx The list of known pages
644
 
 * @param  string $line     A line from the main index
645
 
 * @author Andreas Gohr <andi@splitbrain.org>
646
 
 */
647
 
function idx_parseIndexLine(&$page_idx,$line){
648
 
    $result = array();
649
 
 
650
 
    $line = trim($line);
651
 
    if($line == '') return $result;
652
 
 
653
 
    $parts = explode(':',$line);
654
 
    foreach($parts as $part){
655
 
        if($part == '') continue;
656
 
        list($doc,$cnt) = explode('*',$part);
657
 
        if(!$cnt) continue;
658
 
        $doc = trim($page_idx[$doc]);
659
 
        if(!$doc) continue;
660
 
        // make sure the document still exists
661
 
        if(!page_exists($doc,'',false)) continue;
662
 
 
663
 
        $result[$doc] = $cnt;
664
 
    }
665
 
    return $result;
666
 
}
667
 
 
668
 
/**
669
 
 * Tokenizes a string into an array of search words
670
 
 *
671
 
 * Uses the same algorithm as idx_getPageWords()
672
 
 *
673
 
 * @param string   $string     the query as given by the user
674
 
 * @param arrayref $stopwords  array of stopwords
675
 
 * @param boolean  $wc         are wildcards allowed?
676
 
 */
677
 
function idx_tokenizer($string,&$stopwords,$wc=false){
678
 
    $words = array();
679
 
    $wc = ($wc) ? '' : $wc = '\*';
680
 
 
681
 
    if(preg_match('/[^0-9A-Za-z]/u', $string)){
682
 
        // handle asian chars as single words (may fail on older PHP version)
683
 
        $asia = @preg_replace('/('.IDX_ASIAN.')/u',' \1 ',$string);
684
 
        if(!is_null($asia)) $string = $asia; //recover from regexp failure
685
 
 
686
 
        $arr = explode(' ', utf8_stripspecials($string,' ','\._\-:'.$wc));
687
 
        foreach ($arr as $w) {
688
 
            if (!is_numeric($w) && strlen($w) < IDX_MINWORDLENGTH) continue;
689
 
            $w = utf8_strtolower($w);
690
 
            if($stopwords && is_int(array_search("$w\n",$stopwords))) continue;
691
 
            $words[] = $w;
692
 
        }
693
 
    }else{
694
 
        $w = $string;
695
 
        if (!is_numeric($w) && strlen($w) < IDX_MINWORDLENGTH) return $words;
696
 
        $w = strtolower($w);
697
 
        if(is_int(array_search("$w\n",$stopwords))) return $words;
698
 
        $words[] = $w;
699
 
    }
700
 
 
701
 
    return $words;
702
 
}
703
 
 
704
 
//Setup VIM: ex: et ts=4 enc=utf-8 :
 
1385
function idx_cleanName($name) {
 
1386
    $name = utf8_romanize(trim((string)$name));
 
1387
    $name = preg_replace('#[ \./\\:-]+#', '_', $name);
 
1388
    $name = preg_replace('/[^A-Za-z0-9_]/', '', $name);
 
1389
    return strtolower($name);
 
1390
}
 
1391
 
 
1392
//Setup VIM: ex: et ts=4 :