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)
61
* Write a list of strings to an index file.
63
* @author Tom N Harris <tnharris@whoopdedo.org>
65
function idx_saveIndex($pre, $wlen, &$idx){
67
$fn = $conf['indexdir'].'/'.$pre.$wlen;
68
$fh = @fopen($fn.'.tmp','w');
69
if(!$fh) return false;
70
foreach ($idx as $line) {
74
if(isset($conf['fperm'])) chmod($fn.'.tmp', $conf['fperm']);
75
io_rename($fn.'.tmp', $fn.'.idx');
80
* Append a given line to an index file.
82
* @author Andreas Gohr <andi@splitbrain.org>
84
function idx_appendIndex($pre, $wlen, $line){
86
$fn = $conf['indexdir'].'/'.$pre.$wlen;
87
$fh = @fopen($fn.'.idx','a');
88
if(!$fh) return false;
95
* Read the list of words in an index (if it exists).
97
* @author Tom N Harris <tnharris@whoopdedo.org>
99
function idx_getIndex($pre, $wlen){
101
$fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
102
if(!@file_exists($fn)) return array();
107
* Create an empty index file if it doesn't exist yet.
109
* FIXME: This function isn't currently used. It will probably be removed soon.
111
* @author Tom N Harris <tnharris@whoopdedo.org>
113
function idx_touchIndex($pre, $wlen){
115
$fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
116
if(!@file_exists($fn)){
118
if($conf['fperm']) chmod($fn, $conf['fperm']);
123
* Read a line ending with \n.
124
* Returns false on EOF.
126
* @author Tom N Harris <tnharris@whoopdedo.org>
128
function _freadline($fh) {
129
if (feof($fh)) return false;
131
while (($buf = fgets($fh,4096)) !== false) {
133
if (substr($buf,-1) == "\n") break;
135
if ($ln === '') return false;
136
if (substr($ln,-1) != "\n") $ln .= "\n";
141
* Write a line to an index file.
143
* @author Tom N Harris <tnharris@whoopdedo.org>
145
function idx_saveIndexLine($pre, $wlen, $idx, $line){
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');
101
* Class that encapsulates operations on the indexer database.
103
* @author Tom N Harris <tnharris@whoopdedo.org>
108
* Adds the contents of a page to the fulltext index
110
* The added text replaces previous words for the same page.
111
* An empty value erases the page.
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>
119
public function addPageWords($page, $text) {
123
// load known documents
124
$pid = $this->addIndexKey('page', '', $page);
125
if ($pid === false) {
130
$pagewords = array();
131
// get word usage in page
132
$words = $this->getPageWords($text);
133
if ($words === false) {
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";
146
if (!$this->saveIndex('i', $wlen, $index)) {
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);
159
foreach ($delwords as $word) {
161
list($wlen,$wid) = explode('*', $word);
163
$upwords[$wlen][] = $wid;
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);
171
$this->saveIndex('i', $wlen, $index);
174
// Save the reverse index
175
$pageword_idx = join(':', $pagewords);
176
if (!$this->saveIndexKey('pageword', '', $pid, $pageword_idx)) {
186
* Split the words in a page and add them to the index.
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>
194
protected function getPageWords($text) {
197
$tokens = $this->tokenizer($text);
198
$tokens = array_count_values($tokens); // count the frequency of each token
201
foreach ($tokens as $w=>$c) {
203
if (isset($words[$l])){
204
$words[$l][$w] = $c + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
206
$words[$l] = array($w => $c);
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);
220
$word_idx_modified = true;
222
if (!isset($index[$wlen]))
223
$index[$wlen] = array();
224
$index[$wlen][$wid] = $freq;
226
// save back the word index
227
if ($word_idx_modified && !$this->saveIndex('w', $wlen, $word_idx))
235
* Add/update keys to/of the metadata index.
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.
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>
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);
260
// load known documents
261
$pid = $this->addIndexKey('page', '', $page);
262
if ($pid === false) {
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))
272
$this->saveIndexKey('title', '', $pid, $value);
273
unset($key['title']);
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', '');
283
if (!is_array($values)) $values = array($values);
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));
295
foreach ($values as $val) {
298
$id = array_search($val, $metawords);
300
$id = count($metawords);
301
$metawords[$id] = $val;
304
// test if value is already in the index
305
if (isset($val_idx[$id]) && $val_idx[$id] <= 0)
313
$this->saveIndex($metaname.'_w', '', $metawords);
314
$vals_changed = false;
315
foreach ($val_idx as $id => $action) {
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;
327
$this->saveIndex($metaname.'_i', '', $metaidx);
328
$val_idx = implode(':', array_keys($val_idx));
329
$this->saveIndexKey($metaname.'_p', '', $pid, $val_idx);
341
* Remove a page from the index
343
* Erases entries in all known indexes.
345
* @param string $page a page name
346
* @return boolean the function completed successfully
347
* @author Tom N Harris <tnharris@whoopdedo.org>
349
public function deletePage($page) {
353
// load known documents
354
$pid = $this->getIndexKey('page', '', $page);
355
if ($pid === false) {
360
// Remove obsolete index entries
361
$pageword_idx = $this->getIndexKey('pageword', '', $pid);
362
if ($pageword_idx !== '') {
363
$delwords = explode(':',$pageword_idx);
365
foreach ($delwords as $word) {
367
list($wlen,$wid) = explode('*', $word);
369
$upwords[$wlen][] = $wid;
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);
377
$this->saveIndex('i', $wlen, $index);
380
// Save the reverse index
381
if (!$this->saveIndexKey('pageword', '', $pid, "")) {
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);
394
$this->saveIndex($metaname.'_i', '', $meta_idx);
395
$this->saveIndexKey($metaname.'_p', '', $pid, '');
403
* Split the text into words for fulltext search
405
* TODO: does this also need &$stopwords ?
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
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>
417
public function tokenizer($text, $wc=false) {
420
$wc = ($wc) ? '' : '\*';
421
$stopwords =& idx_get_stopwords();
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
432
$evt->advise_after();
440
"\xC2\xAD" => '', //soft-hyphen
443
if (preg_match('/[^0-9A-Za-z ]/u', $text))
444
$text = utf8_stripspecials($text, ' ', '\._\-:'.$wc);
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]);
454
return array_values($wordlist);
458
* Find pages in the fulltext index containing the words,
460
* The search words must be pre-tokenized, meaning only letters and
461
* numbers with an optional wildcard
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.
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>
472
public function lookup(&$tokens) {
474
$wids = $this->getIndexWords($tokens, $result);
475
if (empty($wids)) return array();
476
// load known words and documents
477
$page_idx = $this->getIndex('page', '');
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]);
487
// merge found pages into final result 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;
502
$final[$word][$hitkey] += $hitcnt;
510
* Find pages containing a metadata key.
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.
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>
526
public function lookupKey($key, &$value, $func=null) {
527
if (!is_array($value))
528
$value_array = array($value);
530
$value_array =& $value;
532
// the matching ids for the provided value(s)
533
$value_ids = array();
535
$metaname = idx_cleanName($key);
537
// get all words in order to search the matching ids
538
if ($key == 'title') {
539
$words = $this->getIndex('title', '');
541
$words = $this->getIndex($metaname.'_w', '');
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;
552
foreach ($value_array as $val) {
556
// check for wildcards
557
if (substr($xval, 0, 1) == '*') {
558
$xval = substr($xval, 1);
561
if (substr($xval, -1, 1) == '*') {
562
$xval = substr($xval, 0, -1);
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;
570
if (($i = array_search($val, $words)) !== false)
571
$value_ids[$i][] = $val;
576
unset($words); // free the used memory
578
// initialize the result so it won't be null
580
foreach ($value_array as $val) {
581
$result[$val] = array();
584
$page_idx = $this->getIndex('page', '');
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;
595
// load all lines and pages so the used lines can be taken and matched with the pages
596
$lines = $this->getIndex($metaname.'_i', '');
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);
607
if (!is_array($value)) $result = $result[$value];
612
* Find the index ID of each search term.
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.
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>
624
protected function getIndexWords(&$words, &$result) {
626
$tokenlength = array();
627
$tokenwild = array();
628
foreach ($words as $word) {
629
$result[$word] = array();
633
$wlen = wordlen($word);
635
// check for wildcards
636
if (substr($xword, 0, 1) == '*') {
637
$xword = substr($xword, 1);
641
if (substr($xword, -1, 1) == '*') {
642
$xword = substr($xword, 0, -1);
646
if ($wlen < IDX_MINWORDLENGTH && $caret && $dollar && !is_numeric($xword))
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;
656
$tokens[$xword][] = array($word, null);
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);
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";
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";
697
* Return a list of all pages
698
* Warning: pages may not exist!
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>
704
public function getPages($key=null) {
705
$page_idx = $this->getIndex('page', '');
706
if (is_null($key)) return $page_idx;
708
$metaname = idx_cleanName($key);
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);
720
$lines = $this->getIndex($metaname.'_i', '');
721
foreach ($lines as $line) {
722
$pages = array_merge($pages, $this->parseTuples($page_idx, $line));
724
return array_keys($pages);
728
* Return a list of words sorted by number of times used
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>
737
public function histogram($min=1, $max=0, $minlen=3, $key=null) {
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;
753
elseif (!is_null($key)) {
754
$metaname = idx_cleanName($key);
755
$index = $this->getIndex($metaname.'_i', '');
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;
762
if (!empty($val_idx)) {
763
$words = $this->getIndex($metaname.'_w', '');
764
foreach ($val_idx as $wid => $freq)
765
$result[$words[$wid]] = $freq;
769
$lengths = idx_listIndexLengths();
770
foreach ($lengths as $length) {
771
if ($length < $minlen) continue;
772
$index = $this->getIndex('i', $length);
774
foreach ($index as $wid => $line) {
775
$freq = $this->countTuples($line);
776
if ($freq >= $min && (!$max || $freq <= $max)) {
778
$words = $this->getIndex('w', $length);
779
$result[$words[$wid]] = $freq;
792
* @author Tom N Harris <tnharris@whoopdedo.org>
794
protected function lock() {
798
$lock = $conf['lockdir'].'/_indexer.lock';
799
while (!@mkdir($lock, $conf['dmode'])) {
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";
807
$status = "stale lock removed";
809
}elseif($run++ == 1000){
810
// we waited 5 seconds for that lock
815
chmod($lock, $conf['dperm']);
820
* Release the indexer lock.
822
* @author Tom N Harris <tnharris@whoopdedo.org>
824
protected function unlock() {
826
@rmdir($conf['lockdir'].'/_indexer.lock');
831
* Retrieve the entire index.
833
* The $suffix argument is for an index that is split into
834
* multiple parts. Different index files should use different
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>
842
protected function getIndex($idx, $suffix) {
844
$fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
845
if (!@file_exists($fn)) return array();
846
return file($fn, FILE_IGNORE_NEW_LINES);
850
* Replace the contents of the index with an array.
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>
857
protected function saveIndex($idx, $suffix, &$lines) {
859
$fn = $conf['indexdir'].'/'.$idx.$suffix;
860
$fh = @fopen($fn.'.tmp', 'w');
861
if (!$fh) return false;
862
fwrite($fh, join("\n", $lines));
866
if (isset($conf['fperm']))
867
chmod($fn.'.tmp', $conf['fperm']);
868
io_rename($fn.'.tmp', $fn.'.idx');
870
$this->cacheIndexDir($idx, $suffix, empty($lines));
875
* Retrieve a line from the index.
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>
883
protected function getIndexKey($idx, $suffix, $id) {
885
$fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
886
if (!@file_exists($fn)) return '';
887
$fh = @fopen($fn, 'r');
154
while (($curline = _freadline($ih)) !== false) {
890
while (($line = fgets($fh)) !== false) {
891
if (++$ln == $id) break;
894
return rtrim((string)$line);
898
* Write a line into the index.
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>
906
protected function saveIndexKey($idx, $suffix, $id, $line) {
908
if (substr($line, -1) != "\n")
910
$fn = $conf['indexdir'].'/'.$idx.$suffix;
911
$fh = @fopen($fn.'.tmp', 'w');
912
if (!$fh) return false;
913
$ih = @fopen($fn.'.idx', 'r');
916
while (($curline = fgets($ih)) !== false) {
917
fwrite($fh, (++$ln == $id) ? $line : $curline);
156
922
fwrite($fh, $line);
158
fwrite($fh, $curline);
169
if($conf['fperm']) chmod($fn.'.tmp', $conf['fperm']);
170
io_rename($fn.'.tmp', $fn.'.idx');
175
* Read a single line from an index (if it exists).
177
* @author Tom N Harris <tnharris@whoopdedo.org>
179
function idx_getIndexLine($pre, $wlen, $idx){
181
$fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
182
if(!@file_exists($fn)) return '';
183
$fh = @fopen($fn,'r');
186
while (($line = _freadline($fh)) !== false) {
187
if (++$ln == $idx) break;
194
* Split a page into words
196
* Returns an array of word counts, false if an error occurred.
197
* Array is keyed on the word length, then the word index.
199
* @author Andreas Gohr <andi@splitbrain.org>
200
* @author Christopher Smith <chris@jalakai.co.uk>
202
function idx_getPageWords($page){
204
$swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
205
if(@file_exists($swfile)){
206
$stopwords = file($swfile);
208
$stopwords = array();
932
if (isset($conf['fperm']))
933
chmod($fn.'.tmp', $conf['fperm']);
934
io_rename($fn.'.tmp', $fn.'.idx');
936
$this->cacheIndexDir($idx, $suffix);
941
* Retrieve or insert a value in the index.
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>
949
protected function addIndexKey($idx, $suffix, $value) {
950
$index = $this->getIndex($idx, $suffix);
951
$id = array_search($value, $index);
954
$index[$id] = $value;
955
if (!$this->saveIndex($idx, $suffix, $index)) {
956
trigger_error("Failed to write $idx index", E_USER_ERROR);
963
protected function cacheIndexDir($idx, $suffix, $delete=false) {
966
$cachename = $conf['indexdir'].'/lengths';
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);
973
if ($old === false) return;
974
unset($lengths[$old]);
976
if ($old !== false) return;
977
$lengths[] = $suffix;
980
$fh = @fopen($cachename.'.tmp', 'w');
982
trigger_error("Failed to write index cache", E_USER_ERROR);
985
@fwrite($fh, implode("\n", $lengths));
987
if (isset($conf['fperm']))
988
chmod($cachename.'.tmp', $conf['fperm']);
989
io_rename($cachename.'.tmp', $cachename.'.idx');
993
* Get the list of lengths indexed in the wiki.
995
* Read the index directory or a cache file and returns
996
* a sorted array of lengths of the words used in the wiki.
998
* @author YoBoY <yoboy.leguesh@gmail.com>
1000
protected function listIndexLengths() {
1002
$cachename = $conf['indexdir'].'/lengths';
1004
if (@file_exists($cachename.'.idx')) {
1005
$lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
1006
if ($lengths !== false) {
1008
foreach ($lengths as $length)
1009
$idx[] = (int)$length;
1014
$dir = @opendir($conf['indexdir']);
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);
1022
$lengths[] = (int)$i;
1027
// save this in a file
1028
$fh = @fopen($cachename.'.tmp', 'w');
1030
trigger_error("Failed to write index cache", E_USER_ERROR);
1033
@fwrite($fh, implode("\n", $lengths));
1035
if (isset($conf['fperm']))
1036
chmod($cachename.'.tmp', $conf['fperm']);
1037
io_rename($cachename.'.tmp', $cachename.'.idx');
1043
* Get the word lengths that have been indexed.
1045
* Reads the index directory and returns an array of lengths
1046
* that there are indices for.
1048
* @author YoBoY <yoboy.leguesh@gmail.com>
1050
protected function indexLengths($filter) {
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'))
1061
$lengths = idx_listIndexLengths();
1062
foreach ($lengths as $key => $length) {
1063
// keep all the values equal or superior
1064
if ((int)$length >= (int)$filter)
1072
* Insert or replace a tuple in a line.
1074
* @author Tom N Harris <tnharris@whoopdedo.org>
1076
protected function updateTuple($line, $id, $count) {
1078
if ($newLine !== '')
1079
$newLine = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $newLine);
1080
$newLine = trim($newLine, ':');
1082
if (strlen($newLine) > 0)
1083
return "$id*$count:".$newLine;
1085
return "$id*$count".$newLine;
1091
* Split a line into an array of tuples.
1093
* @author Tom N Harris <tnharris@whoopdedo.org>
1094
* @author Andreas Gohr <andi@splitbrain.org>
1096
protected function parseTuples(&$keys, $line) {
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;
1105
if (!$key) continue;
1106
$result[$key] = $cnt;
1112
* Sum the counts in a list of tuples.
1114
* @author Tom N Harris <tnharris@whoopdedo.org>
1116
protected function countTuples($line) {
1118
$parts = explode(':', $line);
1119
foreach ($parts as $tuple) {
1120
if ($tuple === '') continue;
1121
list($pid, $cnt) = explode('*', $tuple);
1129
* Create an instance of the indexer.
1131
* @return object a Doku_Indexer
1132
* @author Tom N Harris <tnharris@whoopdedo.org>
1134
function idx_get_indexer() {
1135
static $Indexer = null;
1136
if (is_null($Indexer)) {
1137
$Indexer = new Doku_Indexer();
1143
* Returns words that will be ignored.
1145
* @return array list of stop words
1146
* @author Tom N Harris <tnharris@whoopdedo.org>
1148
function & idx_get_stopwords() {
1149
static $stopwords = null;
1150
if (is_null($stopwords)) {
1152
$swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
1153
if(@file_exists($swfile)){
1154
$stopwords = file($swfile, FILE_IGNORE_NEW_LINES);
1156
$stopwords = array();
1163
* Adds/updates the search index for the given page
1165
* Locking is handled internally.
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>
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);
1186
if (!page_exists($page)) {
1187
if (!@file_exists($idxtag)) {
1188
if ($verbose) print("Indexer: $page does not exist, ignoring".DOKU_LF);
1191
$Indexer = idx_get_indexer();
1192
$result = $Indexer->deletePage($page);
1193
if ($result === "locked") {
1194
if ($verbose) print("Indexer: locked".DOKU_LF);
1200
$indexenabled = p_get_metadata($page, 'internal index', METADATA_RENDER_UNLIMITED);
1201
if ($indexenabled === 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);
1212
if ($verbose) print("Indexer: index disabled for $page".DOKU_LF);
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);
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();
218
list($page,$body) = $data;
220
$body = strtr($body, "\r\n\t", ' ');
221
$tokens = explode(' ', $body);
222
$tokens = array_count_values($tokens); // count the frequency of each token
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');
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
234
foreach ($link_tokens as $link_token) {
235
if (isset($tokens[$link_token])) continue;
236
$tokens[$link_token] = 1;
242
foreach ($tokens as $word => $count) {
243
$arr = idx_tokenizer($word,$stopwords);
244
$arr = array_count_values($arr);
245
foreach ($arr as $w => $c) {
247
if(isset($words[$l])){
248
$words[$l][$w] = $c * $count + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
250
$words[$l] = array($w => $c * $count);
255
// arrive here with $words = array(wordlen => array(word => frequency))
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);
263
$wid = count($word_idx);
264
$word_idx[] = "$word\n";
266
if(!isset($index[$wlen]))
267
$index[$wlen] = array();
268
$index[$wlen][$wid] = $freq;
271
// save back word index
272
if(!idx_saveIndex('w',$wlen,$word_idx)){
273
trigger_error("Failed to write word index", E_USER_ERROR);
282
* Adds/updates the search for the given page
284
* This is the core function of the indexer which does most
285
* of the work. This function needs to be called with proper
288
* @author Andreas Gohr <andi@splitbrain.org>
290
function idx_addPage($page){
293
// load known documents
294
$page_idx = idx_getIndex('page','');
296
// get page id (this is the linenumber in page.idx)
297
$pid = array_search("$page\n",$page_idx);
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);
306
unset($page_idx); // free memory
308
idx_saveIndexLine('title', '', $pid, p_get_first_heading($page, false));
310
$pagewords = array();
311
// get word usage in page
312
$words = idx_getPageWords($page);
313
if($words === false) return false;
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);
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);
328
$pagewords[] = "$wlen*$wid";
330
// save back word index
331
if(!idx_saveIndex('i',$wlen,$index)){
332
trigger_error("Failed to write index", E_USER_ERROR);
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);
344
foreach ($delwords as $word) {
345
if($word=='') continue;
346
list($wlen,$wid) = explode('*',$word);
348
$upwords[$wlen][] = $wid;
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);
355
idx_saveIndex('i',$wlen,$index);
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);
1230
$Indexer = idx_get_indexer();
1231
$result = $Indexer->addPageWords($page, $body);
1232
if ($result === "locked") {
1233
if ($verbose) print("Indexer: locked".DOKU_LF);
369
* Write a new index line to the filehandle
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.
375
* @deprecated - see idx_updateIndexLine
376
* @author Andreas Gohr <andi@splitbrain.org>
378
function idx_writeIndexLine($fh,$line,$pid,$count){
379
fwrite($fh,idx_updateIndexLine($line,$pid,$count));
383
* Modify an index line with new information
385
* This returns a line of the index. It removes the
386
* given document from the line and readds it if
1238
$result = $Indexer->addMetaKeys($page, $metadata);
1239
if ($result === "locked") {
1240
if ($verbose) print("Indexer: locked".DOKU_LF);
1246
io_saveFile(metaFN($page,'.indexed'), idx_get_version());
1248
print("Indexer: finished".DOKU_LF);
1255
* Find tokens in the fulltext index
1257
* Takes an array of words and will return a list of matching
1258
* pages for each one.
1260
* Important: No ACL checking is done here! All results are
1261
* returned, regardless of permissions
1263
* @param arrayref $words list of words to search for
1264
* @return array list of pages found, associated with the search terms
1266
function idx_lookup(&$words) {
1267
$Indexer = idx_get_indexer();
1268
return $Indexer->lookup($words);
1272
* Split a string into tokens
1275
function idx_tokenizer($string, $wc=false) {
1276
$Indexer = idx_get_indexer();
1277
return $Indexer->tokenizer($string, $wc);
1280
/* For compatibility */
1283
* Read the list of words in an index (if it exists).
389
1285
* @author Tom N Harris <tnharris@whoopdedo.org>
390
* @author Andreas Gohr <andi@splitbrain.org>
392
function idx_updateIndexLine($line,$pid,$count){
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);
409
$updated[] = "$pid*$count";
412
return join(':',$updated)."\n";
1287
function idx_getIndex($idx, $suffix) {
1289
$fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
1290
if (!@file_exists($fn)) return array();
416
* Get the list of lenghts indexed in the wiki
1295
* Get the list of lengths indexed in the wiki.
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.