Indexer.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. <?php
  2. namespace dokuwiki\Search;
  3. use dokuwiki\Extension\Event;
  4. /**
  5. * Class that encapsulates operations on the indexer database.
  6. *
  7. * @author Tom N Harris <tnharris@whoopdedo.org>
  8. */
  9. class Indexer {
  10. /**
  11. * @var array $pidCache Cache for getPID()
  12. */
  13. protected $pidCache = array();
  14. /**
  15. * Adds the contents of a page to the fulltext index
  16. *
  17. * The added text replaces previous words for the same page.
  18. * An empty value erases the page.
  19. *
  20. * @param string $page a page name
  21. * @param string $text the body of the page
  22. * @return string|boolean the function completed successfully
  23. *
  24. * @author Tom N Harris <tnharris@whoopdedo.org>
  25. * @author Andreas Gohr <andi@splitbrain.org>
  26. */
  27. public function addPageWords($page, $text) {
  28. if (!$this->lock())
  29. return "locked";
  30. // load known documents
  31. $pid = $this->getPIDNoLock($page);
  32. if ($pid === false) {
  33. $this->unlock();
  34. return false;
  35. }
  36. $pagewords = array();
  37. // get word usage in page
  38. $words = $this->getPageWords($text);
  39. if ($words === false) {
  40. $this->unlock();
  41. return false;
  42. }
  43. if (!empty($words)) {
  44. foreach (array_keys($words) as $wlen) {
  45. $index = $this->getIndex('i', $wlen);
  46. foreach ($words[$wlen] as $wid => $freq) {
  47. $idx = ($wid<count($index)) ? $index[$wid] : '';
  48. $index[$wid] = $this->updateTuple($idx, $pid, $freq);
  49. $pagewords[] = "$wlen*$wid";
  50. }
  51. if (!$this->saveIndex('i', $wlen, $index)) {
  52. $this->unlock();
  53. return false;
  54. }
  55. }
  56. }
  57. // Remove obsolete index entries
  58. $pageword_idx = $this->getIndexKey('pageword', '', $pid);
  59. if ($pageword_idx !== '') {
  60. $oldwords = explode(':',$pageword_idx);
  61. $delwords = array_diff($oldwords, $pagewords);
  62. $upwords = array();
  63. foreach ($delwords as $word) {
  64. if ($word != '') {
  65. list($wlen, $wid) = explode('*', $word);
  66. $wid = (int)$wid;
  67. $upwords[$wlen][] = $wid;
  68. }
  69. }
  70. foreach ($upwords as $wlen => $widx) {
  71. $index = $this->getIndex('i', $wlen);
  72. foreach ($widx as $wid) {
  73. $index[$wid] = $this->updateTuple($index[$wid], $pid, 0);
  74. }
  75. $this->saveIndex('i', $wlen, $index);
  76. }
  77. }
  78. // Save the reverse index
  79. $pageword_idx = join(':', $pagewords);
  80. if (!$this->saveIndexKey('pageword', '', $pid, $pageword_idx)) {
  81. $this->unlock();
  82. return false;
  83. }
  84. $this->unlock();
  85. return true;
  86. }
  87. /**
  88. * Split the words in a page and add them to the index.
  89. *
  90. * @param string $text content of the page
  91. * @return array list of word IDs and number of times used
  92. *
  93. * @author Andreas Gohr <andi@splitbrain.org>
  94. * @author Christopher Smith <chris@jalakai.co.uk>
  95. * @author Tom N Harris <tnharris@whoopdedo.org>
  96. */
  97. protected function getPageWords($text) {
  98. $tokens = $this->tokenizer($text);
  99. $tokens = array_count_values($tokens); // count the frequency of each token
  100. $words = array();
  101. foreach ($tokens as $w=>$c) {
  102. $l = wordlen($w);
  103. if (isset($words[$l])){
  104. $words[$l][$w] = $c + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
  105. }else{
  106. $words[$l] = array($w => $c);
  107. }
  108. }
  109. // arrive here with $words = array(wordlen => array(word => frequency))
  110. $index = array(); //resulting index
  111. foreach (array_keys($words) as $wlen) {
  112. $word_idx = $this->getIndex('w', $wlen);
  113. $word_idx_modified = false;
  114. foreach ($words[$wlen] as $word => $freq) {
  115. $word = (string)$word;
  116. $wid = array_search($word, $word_idx, true);
  117. if ($wid === false) {
  118. $wid = count($word_idx);
  119. $word_idx[] = $word;
  120. $word_idx_modified = true;
  121. }
  122. if (!isset($index[$wlen]))
  123. $index[$wlen] = array();
  124. $index[$wlen][$wid] = $freq;
  125. }
  126. // save back the word index
  127. if ($word_idx_modified && !$this->saveIndex('w', $wlen, $word_idx))
  128. return false;
  129. }
  130. return $index;
  131. }
  132. /**
  133. * Add/update keys to/of the metadata index.
  134. *
  135. * Adding new keys does not remove other keys for the page.
  136. * An empty value will erase the key.
  137. * The $key parameter can be an array to add multiple keys. $value will
  138. * not be used if $key is an array.
  139. *
  140. * @param string $page a page name
  141. * @param mixed $key a key string or array of key=>value pairs
  142. * @param mixed $value the value or list of values
  143. * @return boolean|string the function completed successfully
  144. *
  145. * @author Tom N Harris <tnharris@whoopdedo.org>
  146. * @author Michael Hamann <michael@content-space.de>
  147. */
  148. public function addMetaKeys($page, $key, $value=null) {
  149. if (!is_array($key)) {
  150. $key = array($key => $value);
  151. } elseif (!is_null($value)) {
  152. // $key is array, but $value is not null
  153. trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING);
  154. }
  155. if (!$this->lock())
  156. return "locked";
  157. // load known documents
  158. $pid = $this->getPIDNoLock($page);
  159. if ($pid === false) {
  160. $this->unlock();
  161. return false;
  162. }
  163. // Special handling for titles so the index file is simpler
  164. if (isset($key['title'])) {
  165. $value = $key['title'];
  166. if (is_array($value)) {
  167. $value = $value[0];
  168. }
  169. $this->saveIndexKey('title', '', $pid, $value);
  170. unset($key['title']);
  171. }
  172. foreach ($key as $name => $values) {
  173. $metaname = idx_cleanName($name);
  174. $this->addIndexKey('metadata', '', $metaname);
  175. $metaidx = $this->getIndex($metaname.'_i', '');
  176. $metawords = $this->getIndex($metaname.'_w', '');
  177. $addwords = false;
  178. if (!is_array($values)) $values = array($values);
  179. $val_idx = $this->getIndexKey($metaname.'_p', '', $pid);
  180. if ($val_idx !== '') {
  181. $val_idx = explode(':', $val_idx);
  182. // -1 means remove, 0 keep, 1 add
  183. $val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1));
  184. } else {
  185. $val_idx = array();
  186. }
  187. foreach ($values as $val) {
  188. $val = (string)$val;
  189. if ($val !== "") {
  190. $id = array_search($val, $metawords, true);
  191. if ($id === false) {
  192. // didn't find $val, so we'll add it to the end of metawords and create a placeholder in metaidx
  193. $id = count($metawords);
  194. $metawords[$id] = $val;
  195. $metaidx[$id] = '';
  196. $addwords = true;
  197. }
  198. // test if value is already in the index
  199. if (isset($val_idx[$id]) && $val_idx[$id] <= 0){
  200. $val_idx[$id] = 0;
  201. } else { // else add it
  202. $val_idx[$id] = 1;
  203. }
  204. }
  205. }
  206. if ($addwords) {
  207. $this->saveIndex($metaname.'_w', '', $metawords);
  208. }
  209. $vals_changed = false;
  210. foreach ($val_idx as $id => $action) {
  211. if ($action == -1) {
  212. $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 0);
  213. $vals_changed = true;
  214. unset($val_idx[$id]);
  215. } elseif ($action == 1) {
  216. $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 1);
  217. $vals_changed = true;
  218. }
  219. }
  220. if ($vals_changed) {
  221. $this->saveIndex($metaname.'_i', '', $metaidx);
  222. $val_idx = implode(':', array_keys($val_idx));
  223. $this->saveIndexKey($metaname.'_p', '', $pid, $val_idx);
  224. }
  225. unset($metaidx);
  226. unset($metawords);
  227. }
  228. $this->unlock();
  229. return true;
  230. }
  231. /**
  232. * Rename a page in the search index without changing the indexed content. This function doesn't check if the
  233. * old or new name exists in the filesystem. It returns an error if the old page isn't in the page list of the
  234. * indexer and it deletes all previously indexed content of the new page.
  235. *
  236. * @param string $oldpage The old page name
  237. * @param string $newpage The new page name
  238. * @return string|bool If the page was successfully renamed, can be a message in the case of an error
  239. */
  240. public function renamePage($oldpage, $newpage) {
  241. if (!$this->lock()) return 'locked';
  242. $pages = $this->getPages();
  243. $id = array_search($oldpage, $pages, true);
  244. if ($id === false) {
  245. $this->unlock();
  246. return 'page is not in index';
  247. }
  248. $new_id = array_search($newpage, $pages, true);
  249. if ($new_id !== false) {
  250. // make sure the page is not in the index anymore
  251. if ($this->deletePageNoLock($newpage) !== true) {
  252. return false;
  253. }
  254. $pages[$new_id] = 'deleted:'.time().rand(0, 9999);
  255. }
  256. $pages[$id] = $newpage;
  257. // update index
  258. if (!$this->saveIndex('page', '', $pages)) {
  259. $this->unlock();
  260. return false;
  261. }
  262. // reset the pid cache
  263. $this->pidCache = array();
  264. $this->unlock();
  265. return true;
  266. }
  267. /**
  268. * Renames a meta value in the index. This doesn't change the meta value in the pages, it assumes that all pages
  269. * will be updated.
  270. *
  271. * @param string $key The metadata key of which a value shall be changed
  272. * @param string $oldvalue The old value that shall be renamed
  273. * @param string $newvalue The new value to which the old value shall be renamed, if exists values will be merged
  274. * @return bool|string If renaming the value has been successful, false or error message on error.
  275. */
  276. public function renameMetaValue($key, $oldvalue, $newvalue) {
  277. if (!$this->lock()) return 'locked';
  278. // change the relation references index
  279. $metavalues = $this->getIndex($key, '_w');
  280. $oldid = array_search($oldvalue, $metavalues, true);
  281. if ($oldid !== false) {
  282. $newid = array_search($newvalue, $metavalues, true);
  283. if ($newid !== false) {
  284. // free memory
  285. unset ($metavalues);
  286. // okay, now we have two entries for the same value. we need to merge them.
  287. $indexline = $this->getIndexKey($key.'_i', '', $oldid);
  288. if ($indexline != '') {
  289. $newindexline = $this->getIndexKey($key.'_i', '', $newid);
  290. $pagekeys = $this->getIndex($key.'_p', '');
  291. $parts = explode(':', $indexline);
  292. foreach ($parts as $part) {
  293. list($id, $count) = explode('*', $part);
  294. $newindexline = $this->updateTuple($newindexline, $id, $count);
  295. $keyline = explode(':', $pagekeys[$id]);
  296. // remove old meta value
  297. $keyline = array_diff($keyline, array($oldid));
  298. // add new meta value when not already present
  299. if (!in_array($newid, $keyline)) {
  300. array_push($keyline, $newid);
  301. }
  302. $pagekeys[$id] = implode(':', $keyline);
  303. }
  304. $this->saveIndex($key.'_p', '', $pagekeys);
  305. unset($pagekeys);
  306. $this->saveIndexKey($key.'_i', '', $oldid, '');
  307. $this->saveIndexKey($key.'_i', '', $newid, $newindexline);
  308. }
  309. } else {
  310. $metavalues[$oldid] = $newvalue;
  311. if (!$this->saveIndex($key.'_w', '', $metavalues)) {
  312. $this->unlock();
  313. return false;
  314. }
  315. }
  316. }
  317. $this->unlock();
  318. return true;
  319. }
  320. /**
  321. * Remove a page from the index
  322. *
  323. * Erases entries in all known indexes.
  324. *
  325. * @param string $page a page name
  326. * @return string|boolean the function completed successfully
  327. *
  328. * @author Tom N Harris <tnharris@whoopdedo.org>
  329. */
  330. public function deletePage($page) {
  331. if (!$this->lock())
  332. return "locked";
  333. $result = $this->deletePageNoLock($page);
  334. $this->unlock();
  335. return $result;
  336. }
  337. /**
  338. * Remove a page from the index without locking the index, only use this function if the index is already locked
  339. *
  340. * Erases entries in all known indexes.
  341. *
  342. * @param string $page a page name
  343. * @return boolean the function completed successfully
  344. *
  345. * @author Tom N Harris <tnharris@whoopdedo.org>
  346. */
  347. protected function deletePageNoLock($page) {
  348. // load known documents
  349. $pid = $this->getPIDNoLock($page);
  350. if ($pid === false) {
  351. return false;
  352. }
  353. // Remove obsolete index entries
  354. $pageword_idx = $this->getIndexKey('pageword', '', $pid);
  355. if ($pageword_idx !== '') {
  356. $delwords = explode(':',$pageword_idx);
  357. $upwords = array();
  358. foreach ($delwords as $word) {
  359. if ($word != '') {
  360. list($wlen,$wid) = explode('*', $word);
  361. $wid = (int)$wid;
  362. $upwords[$wlen][] = $wid;
  363. }
  364. }
  365. foreach ($upwords as $wlen => $widx) {
  366. $index = $this->getIndex('i', $wlen);
  367. foreach ($widx as $wid) {
  368. $index[$wid] = $this->updateTuple($index[$wid], $pid, 0);
  369. }
  370. $this->saveIndex('i', $wlen, $index);
  371. }
  372. }
  373. // Save the reverse index
  374. if (!$this->saveIndexKey('pageword', '', $pid, "")) {
  375. return false;
  376. }
  377. $this->saveIndexKey('title', '', $pid, "");
  378. $keyidx = $this->getIndex('metadata', '');
  379. foreach ($keyidx as $metaname) {
  380. $val_idx = explode(':', $this->getIndexKey($metaname.'_p', '', $pid));
  381. $meta_idx = $this->getIndex($metaname.'_i', '');
  382. foreach ($val_idx as $id) {
  383. if ($id === '') continue;
  384. $meta_idx[$id] = $this->updateTuple($meta_idx[$id], $pid, 0);
  385. }
  386. $this->saveIndex($metaname.'_i', '', $meta_idx);
  387. $this->saveIndexKey($metaname.'_p', '', $pid, '');
  388. }
  389. return true;
  390. }
  391. /**
  392. * Clear the whole index
  393. *
  394. * @return bool If the index has been cleared successfully
  395. */
  396. public function clear() {
  397. global $conf;
  398. if (!$this->lock()) return false;
  399. @unlink($conf['indexdir'].'/page.idx');
  400. @unlink($conf['indexdir'].'/title.idx');
  401. @unlink($conf['indexdir'].'/pageword.idx');
  402. @unlink($conf['indexdir'].'/metadata.idx');
  403. $dir = @opendir($conf['indexdir']);
  404. if($dir!==false){
  405. while(($f = readdir($dir)) !== false){
  406. if(substr($f,-4)=='.idx' &&
  407. (substr($f,0,1)=='i' || substr($f,0,1)=='w'
  408. || substr($f,-6)=='_w.idx' || substr($f,-6)=='_i.idx' || substr($f,-6)=='_p.idx'))
  409. @unlink($conf['indexdir']."/$f");
  410. }
  411. }
  412. @unlink($conf['indexdir'].'/lengths.idx');
  413. // clear the pid cache
  414. $this->pidCache = array();
  415. $this->unlock();
  416. return true;
  417. }
  418. /**
  419. * Split the text into words for fulltext search
  420. *
  421. * TODO: does this also need &$stopwords ?
  422. *
  423. * @triggers INDEXER_TEXT_PREPARE
  424. * This event allows plugins to modify the text before it gets tokenized.
  425. * Plugins intercepting this event should also intercept INDEX_VERSION_GET
  426. *
  427. * @param string $text plain text
  428. * @param boolean $wc are wildcards allowed?
  429. * @return array list of words in the text
  430. *
  431. * @author Tom N Harris <tnharris@whoopdedo.org>
  432. * @author Andreas Gohr <andi@splitbrain.org>
  433. */
  434. public function tokenizer($text, $wc=false) {
  435. $wc = ($wc) ? '' : '\*';
  436. $stopwords =& idx_get_stopwords();
  437. // prepare the text to be tokenized
  438. $evt = new Event('INDEXER_TEXT_PREPARE', $text);
  439. if ($evt->advise_before(true)) {
  440. if (preg_match('/[^0-9A-Za-z ]/u', $text)) {
  441. $text = \dokuwiki\Utf8\Asian::separateAsianWords($text);
  442. }
  443. }
  444. $evt->advise_after();
  445. unset($evt);
  446. $text = strtr($text,
  447. array(
  448. "\r" => ' ',
  449. "\n" => ' ',
  450. "\t" => ' ',
  451. "\xC2\xAD" => '', //soft-hyphen
  452. )
  453. );
  454. if (preg_match('/[^0-9A-Za-z ]/u', $text))
  455. $text = \dokuwiki\Utf8\Clean::stripspecials($text, ' ', '\._\-:'.$wc);
  456. $wordlist = explode(' ', $text);
  457. foreach ($wordlist as $i => $word) {
  458. $wordlist[$i] = (preg_match('/[^0-9A-Za-z]/u', $word)) ?
  459. \dokuwiki\Utf8\PhpString::strtolower($word) : strtolower($word);
  460. }
  461. foreach ($wordlist as $i => $word) {
  462. if ((!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH)
  463. || array_search($word, $stopwords, true) !== false)
  464. unset($wordlist[$i]);
  465. }
  466. return array_values($wordlist);
  467. }
  468. /**
  469. * Get the numeric PID of a page
  470. *
  471. * @param string $page The page to get the PID for
  472. * @return bool|int The page id on success, false on error
  473. */
  474. public function getPID($page) {
  475. // return PID without locking when it is in the cache
  476. if (isset($this->pidCache[$page])) return $this->pidCache[$page];
  477. if (!$this->lock())
  478. return false;
  479. // load known documents
  480. $pid = $this->getPIDNoLock($page);
  481. if ($pid === false) {
  482. $this->unlock();
  483. return false;
  484. }
  485. $this->unlock();
  486. return $pid;
  487. }
  488. /**
  489. * Get the numeric PID of a page without locking the index.
  490. * Only use this function when the index is already locked.
  491. *
  492. * @param string $page The page to get the PID for
  493. * @return bool|int The page id on success, false on error
  494. */
  495. protected function getPIDNoLock($page) {
  496. // avoid expensive addIndexKey operation for the most recently requested pages by using a cache
  497. if (isset($this->pidCache[$page])) return $this->pidCache[$page];
  498. $pid = $this->addIndexKey('page', '', $page);
  499. // limit cache to 10 entries by discarding the oldest element as in DokuWiki usually only the most recently
  500. // added item will be requested again
  501. if (count($this->pidCache) > 10) array_shift($this->pidCache);
  502. $this->pidCache[$page] = $pid;
  503. return $pid;
  504. }
  505. /**
  506. * Get the page id of a numeric PID
  507. *
  508. * @param int $pid The PID to get the page id for
  509. * @return string The page id
  510. */
  511. public function getPageFromPID($pid) {
  512. return $this->getIndexKey('page', '', $pid);
  513. }
  514. /**
  515. * Find pages in the fulltext index containing the words,
  516. *
  517. * The search words must be pre-tokenized, meaning only letters and
  518. * numbers with an optional wildcard
  519. *
  520. * The returned array will have the original tokens as key. The values
  521. * in the returned list is an array with the page names as keys and the
  522. * number of times that token appears on the page as value.
  523. *
  524. * @param array $tokens list of words to search for
  525. * @return array list of page names with usage counts
  526. *
  527. * @author Tom N Harris <tnharris@whoopdedo.org>
  528. * @author Andreas Gohr <andi@splitbrain.org>
  529. */
  530. public function lookup(&$tokens) {
  531. $result = array();
  532. $wids = $this->getIndexWords($tokens, $result);
  533. if (empty($wids)) return array();
  534. // load known words and documents
  535. $page_idx = $this->getIndex('page', '');
  536. $docs = array();
  537. foreach (array_keys($wids) as $wlen) {
  538. $wids[$wlen] = array_unique($wids[$wlen]);
  539. $index = $this->getIndex('i', $wlen);
  540. foreach($wids[$wlen] as $ixid) {
  541. if ($ixid < count($index))
  542. $docs["$wlen*$ixid"] = $this->parseTuples($page_idx, $index[$ixid]);
  543. }
  544. }
  545. // merge found pages into final result array
  546. $final = array();
  547. foreach ($result as $word => $res) {
  548. $final[$word] = array();
  549. foreach ($res as $wid) {
  550. // handle the case when ($ixid < count($index)) has been false
  551. // and thus $docs[$wid] hasn't been set.
  552. if (!isset($docs[$wid])) continue;
  553. $hits = &$docs[$wid];
  554. foreach ($hits as $hitkey => $hitcnt) {
  555. // make sure the document still exists
  556. if (!page_exists($hitkey, '', false)) continue;
  557. if (!isset($final[$word][$hitkey]))
  558. $final[$word][$hitkey] = $hitcnt;
  559. else
  560. $final[$word][$hitkey] += $hitcnt;
  561. }
  562. }
  563. }
  564. return $final;
  565. }
  566. /**
  567. * Find pages containing a metadata key.
  568. *
  569. * The metadata values are compared as case-sensitive strings. Pass a
  570. * callback function that returns true or false to use a different
  571. * comparison function. The function will be called with the $value being
  572. * searched for as the first argument, and the word in the index as the
  573. * second argument. The function preg_match can be used directly if the
  574. * values are regexes.
  575. *
  576. * @param string $key name of the metadata key to look for
  577. * @param string $value search term to look for, must be a string or array of strings
  578. * @param callback $func comparison function
  579. * @return array lists with page names, keys are query values if $value is array
  580. *
  581. * @author Tom N Harris <tnharris@whoopdedo.org>
  582. * @author Michael Hamann <michael@content-space.de>
  583. */
  584. public function lookupKey($key, &$value, $func=null) {
  585. if (!is_array($value))
  586. $value_array = array($value);
  587. else
  588. $value_array =& $value;
  589. // the matching ids for the provided value(s)
  590. $value_ids = array();
  591. $metaname = idx_cleanName($key);
  592. // get all words in order to search the matching ids
  593. if ($key == 'title') {
  594. $words = $this->getIndex('title', '');
  595. } else {
  596. $words = $this->getIndex($metaname.'_w', '');
  597. }
  598. if (!is_null($func)) {
  599. foreach ($value_array as $val) {
  600. foreach ($words as $i => $word) {
  601. if (call_user_func_array($func, array($val, $word)))
  602. $value_ids[$i][] = $val;
  603. }
  604. }
  605. } else {
  606. foreach ($value_array as $val) {
  607. $xval = $val;
  608. $caret = '^';
  609. $dollar = '$';
  610. // check for wildcards
  611. if (substr($xval, 0, 1) == '*') {
  612. $xval = substr($xval, 1);
  613. $caret = '';
  614. }
  615. if (substr($xval, -1, 1) == '*') {
  616. $xval = substr($xval, 0, -1);
  617. $dollar = '';
  618. }
  619. if (!$caret || !$dollar) {
  620. $re = $caret.preg_quote($xval, '/').$dollar;
  621. foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i)
  622. $value_ids[$i][] = $val;
  623. } else {
  624. if (($i = array_search($val, $words, true)) !== false)
  625. $value_ids[$i][] = $val;
  626. }
  627. }
  628. }
  629. unset($words); // free the used memory
  630. // initialize the result so it won't be null
  631. $result = array();
  632. foreach ($value_array as $val) {
  633. $result[$val] = array();
  634. }
  635. $page_idx = $this->getIndex('page', '');
  636. // Special handling for titles
  637. if ($key == 'title') {
  638. foreach ($value_ids as $pid => $val_list) {
  639. $page = $page_idx[$pid];
  640. foreach ($val_list as $val) {
  641. $result[$val][] = $page;
  642. }
  643. }
  644. } else {
  645. // load all lines and pages so the used lines can be taken and matched with the pages
  646. $lines = $this->getIndex($metaname.'_i', '');
  647. foreach ($value_ids as $value_id => $val_list) {
  648. // parse the tuples of the form page_id*1:page2_id*1 and so on, return value
  649. // is an array with page_id => 1, page2_id => 1 etc. so take the keys only
  650. $pages = array_keys($this->parseTuples($page_idx, $lines[$value_id]));
  651. foreach ($val_list as $val) {
  652. $result[$val] = array_merge($result[$val], $pages);
  653. }
  654. }
  655. }
  656. if (!is_array($value)) $result = $result[$value];
  657. return $result;
  658. }
  659. /**
  660. * Find the index ID of each search term.
  661. *
  662. * The query terms should only contain valid characters, with a '*' at
  663. * either the beginning or end of the word (or both).
  664. * The $result parameter can be used to merge the index locations with
  665. * the appropriate query term.
  666. *
  667. * @param array $words The query terms.
  668. * @param array $result Set to word => array("length*id" ...)
  669. * @return array Set to length => array(id ...)
  670. *
  671. * @author Tom N Harris <tnharris@whoopdedo.org>
  672. */
  673. protected function getIndexWords(&$words, &$result) {
  674. $tokens = array();
  675. $tokenlength = array();
  676. $tokenwild = array();
  677. foreach ($words as $word) {
  678. $result[$word] = array();
  679. $caret = '^';
  680. $dollar = '$';
  681. $xword = $word;
  682. $wlen = wordlen($word);
  683. // check for wildcards
  684. if (substr($xword, 0, 1) == '*') {
  685. $xword = substr($xword, 1);
  686. $caret = '';
  687. $wlen -= 1;
  688. }
  689. if (substr($xword, -1, 1) == '*') {
  690. $xword = substr($xword, 0, -1);
  691. $dollar = '';
  692. $wlen -= 1;
  693. }
  694. if ($wlen < IDX_MINWORDLENGTH && $caret && $dollar && !is_numeric($xword))
  695. continue;
  696. if (!isset($tokens[$xword]))
  697. $tokenlength[$wlen][] = $xword;
  698. if (!$caret || !$dollar) {
  699. $re = $caret.preg_quote($xword, '/').$dollar;
  700. $tokens[$xword][] = array($word, '/'.$re.'/');
  701. if (!isset($tokenwild[$xword]))
  702. $tokenwild[$xword] = $wlen;
  703. } else {
  704. $tokens[$xword][] = array($word, null);
  705. }
  706. }
  707. asort($tokenwild);
  708. // $tokens = array( base word => array( [ query term , regexp ] ... ) ... )
  709. // $tokenlength = array( base word length => base word ... )
  710. // $tokenwild = array( base word => base word length ... )
  711. $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
  712. $indexes_known = $this->indexLengths($length_filter);
  713. if (!empty($tokenwild)) sort($indexes_known);
  714. // get word IDs
  715. $wids = array();
  716. foreach ($indexes_known as $ixlen) {
  717. $word_idx = $this->getIndex('w', $ixlen);
  718. // handle exact search
  719. if (isset($tokenlength[$ixlen])) {
  720. foreach ($tokenlength[$ixlen] as $xword) {
  721. $wid = array_search($xword, $word_idx, true);
  722. if ($wid !== false) {
  723. $wids[$ixlen][] = $wid;
  724. foreach ($tokens[$xword] as $w)
  725. $result[$w[0]][] = "$ixlen*$wid";
  726. }
  727. }
  728. }
  729. // handle wildcard search
  730. foreach ($tokenwild as $xword => $wlen) {
  731. if ($wlen >= $ixlen) break;
  732. foreach ($tokens[$xword] as $w) {
  733. if (is_null($w[1])) continue;
  734. foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) {
  735. $wids[$ixlen][] = $wid;
  736. $result[$w[0]][] = "$ixlen*$wid";
  737. }
  738. }
  739. }
  740. }
  741. return $wids;
  742. }
  743. /**
  744. * Return a list of all pages
  745. * Warning: pages may not exist!
  746. *
  747. * @param string $key list only pages containing the metadata key (optional)
  748. * @return array list of page names
  749. *
  750. * @author Tom N Harris <tnharris@whoopdedo.org>
  751. */
  752. public function getPages($key=null) {
  753. $page_idx = $this->getIndex('page', '');
  754. if (is_null($key)) return $page_idx;
  755. $metaname = idx_cleanName($key);
  756. // Special handling for titles
  757. if ($key == 'title') {
  758. $title_idx = $this->getIndex('title', '');
  759. array_splice($page_idx, count($title_idx));
  760. foreach ($title_idx as $i => $title)
  761. if ($title === "") unset($page_idx[$i]);
  762. return array_values($page_idx);
  763. }
  764. $pages = array();
  765. $lines = $this->getIndex($metaname.'_i', '');
  766. foreach ($lines as $line) {
  767. $pages = array_merge($pages, $this->parseTuples($page_idx, $line));
  768. }
  769. return array_keys($pages);
  770. }
  771. /**
  772. * Return a list of words sorted by number of times used
  773. *
  774. * @param int $min bottom frequency threshold
  775. * @param int $max upper frequency limit. No limit if $max<$min
  776. * @param int $minlen minimum length of words to count
  777. * @param string $key metadata key to list. Uses the fulltext index if not given
  778. * @return array list of words as the keys and frequency as values
  779. *
  780. * @author Tom N Harris <tnharris@whoopdedo.org>
  781. */
  782. public function histogram($min=1, $max=0, $minlen=3, $key=null) {
  783. if ($min < 1)
  784. $min = 1;
  785. if ($max < $min)
  786. $max = 0;
  787. $result = array();
  788. if ($key == 'title') {
  789. $index = $this->getIndex('title', '');
  790. $index = array_count_values($index);
  791. foreach ($index as $val => $cnt) {
  792. if ($cnt >= $min && (!$max || $cnt <= $max) && strlen($val) >= $minlen)
  793. $result[$val] = $cnt;
  794. }
  795. }
  796. elseif (!is_null($key)) {
  797. $metaname = idx_cleanName($key);
  798. $index = $this->getIndex($metaname.'_i', '');
  799. $val_idx = array();
  800. foreach ($index as $wid => $line) {
  801. $freq = $this->countTuples($line);
  802. if ($freq >= $min && (!$max || $freq <= $max))
  803. $val_idx[$wid] = $freq;
  804. }
  805. if (!empty($val_idx)) {
  806. $words = $this->getIndex($metaname.'_w', '');
  807. foreach ($val_idx as $wid => $freq) {
  808. if (strlen($words[$wid]) >= $minlen)
  809. $result[$words[$wid]] = $freq;
  810. }
  811. }
  812. }
  813. else {
  814. $lengths = idx_listIndexLengths();
  815. foreach ($lengths as $length) {
  816. if ($length < $minlen) continue;
  817. $index = $this->getIndex('i', $length);
  818. $words = null;
  819. foreach ($index as $wid => $line) {
  820. $freq = $this->countTuples($line);
  821. if ($freq >= $min && (!$max || $freq <= $max)) {
  822. if ($words === null)
  823. $words = $this->getIndex('w', $length);
  824. $result[$words[$wid]] = $freq;
  825. }
  826. }
  827. }
  828. }
  829. arsort($result);
  830. return $result;
  831. }
  832. /**
  833. * Lock the indexer.
  834. *
  835. * @author Tom N Harris <tnharris@whoopdedo.org>
  836. *
  837. * @return bool|string
  838. */
  839. protected function lock() {
  840. global $conf;
  841. $status = true;
  842. $run = 0;
  843. $lock = $conf['lockdir'].'/_indexer.lock';
  844. while (!@mkdir($lock)) {
  845. usleep(50);
  846. if(is_dir($lock) && time()-@filemtime($lock) > 60*5){
  847. // looks like a stale lock - remove it
  848. if (!@rmdir($lock)) {
  849. $status = "removing the stale lock failed";
  850. return false;
  851. } else {
  852. $status = "stale lock removed";
  853. }
  854. }elseif($run++ == 1000){
  855. // we waited 5 seconds for that lock
  856. return false;
  857. }
  858. }
  859. if ($conf['dperm']) {
  860. chmod($lock, $conf['dperm']);
  861. }
  862. return $status;
  863. }
  864. /**
  865. * Release the indexer lock.
  866. *
  867. * @author Tom N Harris <tnharris@whoopdedo.org>
  868. *
  869. * @return bool
  870. */
  871. protected function unlock() {
  872. global $conf;
  873. @rmdir($conf['lockdir'].'/_indexer.lock');
  874. return true;
  875. }
  876. /**
  877. * Retrieve the entire index.
  878. *
  879. * The $suffix argument is for an index that is split into
  880. * multiple parts. Different index files should use different
  881. * base names.
  882. *
  883. * @param string $idx name of the index
  884. * @param string $suffix subpart identifier
  885. * @return array list of lines without CR or LF
  886. *
  887. * @author Tom N Harris <tnharris@whoopdedo.org>
  888. */
  889. protected function getIndex($idx, $suffix) {
  890. global $conf;
  891. $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
  892. if (!file_exists($fn)) return array();
  893. return file($fn, FILE_IGNORE_NEW_LINES);
  894. }
  895. /**
  896. * Replace the contents of the index with an array.
  897. *
  898. * @param string $idx name of the index
  899. * @param string $suffix subpart identifier
  900. * @param array $lines list of lines without LF
  901. * @return bool If saving succeeded
  902. *
  903. * @author Tom N Harris <tnharris@whoopdedo.org>
  904. */
  905. protected function saveIndex($idx, $suffix, &$lines) {
  906. global $conf;
  907. $fn = $conf['indexdir'].'/'.$idx.$suffix;
  908. $fh = @fopen($fn.'.tmp', 'w');
  909. if (!$fh) return false;
  910. fwrite($fh, join("\n", $lines));
  911. if (!empty($lines))
  912. fwrite($fh, "\n");
  913. fclose($fh);
  914. if ($conf['fperm'])
  915. chmod($fn.'.tmp', $conf['fperm']);
  916. io_rename($fn.'.tmp', $fn.'.idx');
  917. return true;
  918. }
  919. /**
  920. * Retrieve a line from the index.
  921. *
  922. * @param string $idx name of the index
  923. * @param string $suffix subpart identifier
  924. * @param int $id the line number
  925. * @return string a line with trailing whitespace removed
  926. *
  927. * @author Tom N Harris <tnharris@whoopdedo.org>
  928. */
  929. protected function getIndexKey($idx, $suffix, $id) {
  930. global $conf;
  931. $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
  932. if (!file_exists($fn)) return '';
  933. $fh = @fopen($fn, 'r');
  934. if (!$fh) return '';
  935. $ln = -1;
  936. while (($line = fgets($fh)) !== false) {
  937. if (++$ln == $id) break;
  938. }
  939. fclose($fh);
  940. return rtrim((string)$line);
  941. }
  942. /**
  943. * Write a line into the index.
  944. *
  945. * @param string $idx name of the index
  946. * @param string $suffix subpart identifier
  947. * @param int $id the line number
  948. * @param string $line line to write
  949. * @return bool If saving succeeded
  950. *
  951. * @author Tom N Harris <tnharris@whoopdedo.org>
  952. */
  953. protected function saveIndexKey($idx, $suffix, $id, $line) {
  954. global $conf;
  955. if (substr($line, -1) != "\n")
  956. $line .= "\n";
  957. $fn = $conf['indexdir'].'/'.$idx.$suffix;
  958. $fh = @fopen($fn.'.tmp', 'w');
  959. if (!$fh) return false;
  960. $ih = @fopen($fn.'.idx', 'r');
  961. if ($ih) {
  962. $ln = -1;
  963. while (($curline = fgets($ih)) !== false) {
  964. fwrite($fh, (++$ln == $id) ? $line : $curline);
  965. }
  966. if ($id > $ln) {
  967. while ($id > ++$ln)
  968. fwrite($fh, "\n");
  969. fwrite($fh, $line);
  970. }
  971. fclose($ih);
  972. } else {
  973. $ln = -1;
  974. while ($id > ++$ln)
  975. fwrite($fh, "\n");
  976. fwrite($fh, $line);
  977. }
  978. fclose($fh);
  979. if ($conf['fperm'])
  980. chmod($fn.'.tmp', $conf['fperm']);
  981. io_rename($fn.'.tmp', $fn.'.idx');
  982. return true;
  983. }
  984. /**
  985. * Retrieve or insert a value in the index.
  986. *
  987. * @param string $idx name of the index
  988. * @param string $suffix subpart identifier
  989. * @param string $value line to find in the index
  990. * @return int|bool line number of the value in the index or false if writing the index failed
  991. *
  992. * @author Tom N Harris <tnharris@whoopdedo.org>
  993. */
  994. protected function addIndexKey($idx, $suffix, $value) {
  995. $index = $this->getIndex($idx, $suffix);
  996. $id = array_search($value, $index, true);
  997. if ($id === false) {
  998. $id = count($index);
  999. $index[$id] = $value;
  1000. if (!$this->saveIndex($idx, $suffix, $index)) {
  1001. trigger_error("Failed to write $idx index", E_USER_ERROR);
  1002. return false;
  1003. }
  1004. }
  1005. return $id;
  1006. }
  1007. /**
  1008. * Get the list of lengths indexed in the wiki.
  1009. *
  1010. * Read the index directory or a cache file and returns
  1011. * a sorted array of lengths of the words used in the wiki.
  1012. *
  1013. * @author YoBoY <yoboy.leguesh@gmail.com>
  1014. *
  1015. * @return array
  1016. */
  1017. protected function listIndexLengths() {
  1018. return idx_listIndexLengths();
  1019. }
  1020. /**
  1021. * Get the word lengths that have been indexed.
  1022. *
  1023. * Reads the index directory and returns an array of lengths
  1024. * that there are indices for.
  1025. *
  1026. * @author YoBoY <yoboy.leguesh@gmail.com>
  1027. *
  1028. * @param array|int $filter
  1029. * @return array
  1030. */
  1031. protected function indexLengths($filter) {
  1032. global $conf;
  1033. $idx = array();
  1034. if (is_array($filter)) {
  1035. // testing if index files exist only
  1036. $path = $conf['indexdir']."/i";
  1037. foreach ($filter as $key => $value) {
  1038. if (file_exists($path.$key.'.idx'))
  1039. $idx[] = $key;
  1040. }
  1041. } else {
  1042. $lengths = idx_listIndexLengths();
  1043. foreach ($lengths as $key => $length) {
  1044. // keep all the values equal or superior
  1045. if ((int)$length >= (int)$filter)
  1046. $idx[] = $length;
  1047. }
  1048. }
  1049. return $idx;
  1050. }
  1051. /**
  1052. * Insert or replace a tuple in a line.
  1053. *
  1054. * @author Tom N Harris <tnharris@whoopdedo.org>
  1055. *
  1056. * @param string $line
  1057. * @param string|int $id
  1058. * @param int $count
  1059. * @return string
  1060. */
  1061. protected function updateTuple($line, $id, $count) {
  1062. if ($line != ''){
  1063. $line = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $line);
  1064. }
  1065. $line = trim($line, ':');
  1066. if ($count) {
  1067. if ($line) {
  1068. return "$id*$count:".$line;
  1069. } else {
  1070. return "$id*$count";
  1071. }
  1072. }
  1073. return $line;
  1074. }
  1075. /**
  1076. * Split a line into an array of tuples.
  1077. *
  1078. * @author Tom N Harris <tnharris@whoopdedo.org>
  1079. * @author Andreas Gohr <andi@splitbrain.org>
  1080. *
  1081. * @param array $keys
  1082. * @param string $line
  1083. * @return array
  1084. */
  1085. protected function parseTuples(&$keys, $line) {
  1086. $result = array();
  1087. if ($line == '') return $result;
  1088. $parts = explode(':', $line);
  1089. foreach ($parts as $tuple) {
  1090. if ($tuple === '') continue;
  1091. list($key, $cnt) = explode('*', $tuple);
  1092. if (!$cnt) continue;
  1093. if (isset($keys[$key])) {
  1094. $key = $keys[$key];
  1095. if ($key === false || is_null($key)) continue;
  1096. }
  1097. $result[$key] = $cnt;
  1098. }
  1099. return $result;
  1100. }
  1101. /**
  1102. * Sum the counts in a list of tuples.
  1103. *
  1104. * @author Tom N Harris <tnharris@whoopdedo.org>
  1105. *
  1106. * @param string $line
  1107. * @return int
  1108. */
  1109. protected function countTuples($line) {
  1110. $freq = 0;
  1111. $parts = explode(':', $line);
  1112. foreach ($parts as $tuple) {
  1113. if ($tuple === '') continue;
  1114. list(/* $pid */, $cnt) = explode('*', $tuple);
  1115. $freq += (int)$cnt;
  1116. }
  1117. return $freq;
  1118. }
  1119. }