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