1<?php 2 3namespace dokuwiki\Search; 4 5use dokuwiki\Debug\DebugHelper; 6use dokuwiki\Extension\Event; 7use dokuwiki\Search\Collection\PageFulltextCollection; 8use dokuwiki\Search\Collection\PageMetaCollection; 9use dokuwiki\Search\Collection\PageTitleCollection; 10use dokuwiki\Search\Exception\IndexAccessException; 11use dokuwiki\Search\Exception\IndexIntegrityException; 12use dokuwiki\Search\Exception\IndexLockException; 13use dokuwiki\Search\Exception\IndexWriteException; 14use dokuwiki\Search\Index\FileIndex; 15use dokuwiki\Search\Index\Lock; 16use dokuwiki\Search\Index\MemoryIndex; 17 18// Version tag used to force rebuild on upgrade 19const INDEXER_VERSION = 9; 20 21/** 22 * Class DokuWiki Indexer 23 * 24 * Manages the page search index by delegating to Collection classes. 25 * 26 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) 27 * @author Andreas Gohr <andi@splitbrain.org> 28 * @author Tom N Harris <tnharris@whoopdedo.org> 29 */ 30class Indexer 31{ 32 /** @var callable|null Logging callback, receives a string message */ 33 protected $logger; 34 35 /** 36 * Set a logging callback 37 * 38 * The callback receives a single string message. Use this to integrate 39 * with different output mechanisms (TaskRunner echo, CLI output, Logger, etc.) 40 * 41 * @param callable $logger 42 * @return static 43 */ 44 public function setLogger(callable $logger): static 45 { 46 $this->logger = $logger; 47 return $this; 48 } 49 50 /** 51 * Send a message to the registered logger 52 * 53 * @param string $message 54 */ 55 protected function log(string $message): void 56 { 57 if ($this->logger)($this->logger)($message); 58 } 59 60 /** 61 * Version of the indexer taking into consideration the external tokenizer. 62 * The indexer is only compatible with data written by the same version. 63 * 64 * @triggers INDEXER_VERSION_GET 65 * Plugins that modify what gets indexed should hook this event and 66 * add their version info to the event data like so: 67 * $data[$plugin_name] = $plugin_version; 68 * 69 * @return int|string 70 */ 71 public function getVersion(): int|string 72 { 73 static $indexer_version = null; 74 if ($indexer_version == null) { 75 $version = INDEXER_VERSION; 76 77 $data = ['dokuwiki' => $version]; 78 Event::createAndTrigger('INDEXER_VERSION_GET', $data, null, false); 79 unset($data['dokuwiki']); // this needs to be first 80 ksort($data); 81 foreach ($data as $plugin => $vers) { 82 $version .= '+' . $plugin . '=' . $vers; 83 } 84 $indexer_version = $version; 85 } 86 return $indexer_version; 87 } 88 89 /** 90 * Return a list of all indexed pages 91 * 92 * @param bool $existsFilter only return pages that exist on disk 93 * @return string[] list of page names (keys are the RIDs in the page index) 94 */ 95 public function getAllPages(bool $existsFilter = false): array 96 { 97 $pageIndex = new MemoryIndex('page'); 98 return array_filter( 99 iterator_to_array($pageIndex), 100 static fn($v) => $v !== '' && (!$existsFilter || page_exists($v, '', false)) 101 ); 102 } 103 104 /** 105 * Check if a page needs (re-)indexing 106 * 107 * @param string $page 108 * @param bool $force 109 * @return bool true if indexing is needed 110 */ 111 public function needsIndexing(string $page, bool $force = false): bool 112 { 113 $idxtag = metaFN($page, '.indexed'); 114 if ($force || !file_exists($idxtag)) return true; 115 116 if (trim(io_readFile($idxtag)) != $this->getVersion()) return true; 117 118 $last = @filemtime($idxtag); 119 return $last <= @filemtime(wikiFN($page)); 120 } 121 122 /** 123 * Add/update the search index for a page 124 * 125 * Locking is handled internally. 126 * 127 * @param string $page The page to index 128 * @param bool $force force reindexing even when the index is up to date 129 * 130 * @throws IndexAccessException 131 * @throws IndexLockException 132 * @throws IndexWriteException 133 */ 134 public function addPage(string $page, bool $force = false): void 135 { 136 if (!$this->needsIndexing($page, $force)) { 137 $this->log("Indexer: index for $page up to date"); 138 return; 139 } 140 141 // create shared writable page index early so we can resolve the PID for plugins 142 $pageIndex = new FileIndex('page', '', true); 143 144 // prepare event data 145 $data = [ 146 'page' => $page, 147 'body' => '', 148 'metadata' => [ 149 'title' => p_get_metadata($page, 'title', METADATA_RENDER_UNLIMITED), 150 'relation_references' => array_keys( 151 p_get_metadata($page, 'relation references', METADATA_RENDER_UNLIMITED) ?? [] 152 ), 153 'relation_media' => array_keys( 154 p_get_metadata($page, 'relation media', METADATA_RENDER_UNLIMITED) ?? [] 155 ), 156 'internal_index' => p_get_metadata($page, 'internal index', METADATA_RENDER_UNLIMITED) !== false, 157 ], 158 'pid' => $pageIndex->accessCachedValue($page), 159 ]; 160 161 // let plugins modify the data 162 $event = new Event('INDEXER_PAGE_ADD', $data); 163 if ($event->advise_before()) { 164 $data['body'] = $data['body'] . ' ' . rawWiki($data['page']); 165 } 166 $event->advise_after(); 167 unset($event); 168 169 // index title 170 (new PageTitleCollection($pageIndex))->lock() 171 ->addEntity($data['page'], [$data['metadata']['title']])->unlock(); 172 unset($data['metadata']['title']); 173 174 // index fulltext 175 if ($data['metadata']['internal_index']) { 176 $words = Tokenizer::getWords($data['body']); 177 (new PageFulltextCollection($pageIndex))->lock()->addEntity($data['page'], $words)->unlock(); 178 } else { 179 $this->log("Indexer: full text indexing disabled for {$data['page']}"); 180 // clear any previously stored fulltext data 181 (new PageFulltextCollection($pageIndex))->lock()->addEntity($data['page'], [])->unlock(); 182 } 183 unset($data['metadata']['internal_index']); 184 185 // index metadata keys 186 foreach ($data['metadata'] as $key => $values) { 187 if (!is_array($values)) { 188 $values = ($values !== null && $values !== '') ? [$values] : []; 189 } 190 (new PageMetaCollection($key, $pageIndex))->lock()->addEntity($data['page'], $values)->unlock(); 191 } 192 193 // update metadata registry 194 $this->updateMetadataRegistry(array_keys($data['metadata'])); 195 196 // update index tag file 197 io_saveFile(metaFN($data['page'], '.indexed'), $this->getVersion()); 198 $this->log("Indexer: finished indexing {$data['page']}"); 199 } 200 201 /** 202 * Remove a page from the index 203 * 204 * Clears the page's data from all collections. The entity persists in page.idx. 205 * 206 * @param string $page The page to remove 207 * @param bool $force force deletion even when no .indexed tag exists 208 * 209 * @throws IndexAccessException 210 * @throws IndexLockException 211 * @throws IndexWriteException 212 */ 213 public function deletePage(string $page, bool $force = false): void 214 { 215 $idxtag = metaFN($page, '.indexed'); 216 if (!$force && !file_exists($idxtag)) { 217 $this->log("Indexer: $page.indexed file does not exist, ignoring"); 218 return; 219 } 220 221 $pageIndex = new FileIndex('page', '', true); 222 223 (new PageTitleCollection($pageIndex))->lock()->addEntity($page, [])->unlock(); 224 (new PageFulltextCollection($pageIndex))->lock()->addEntity($page, [])->unlock(); 225 226 foreach ($this->getMetadataRegistryKeys() as $key) { 227 (new PageMetaCollection($key, $pageIndex))->lock()->addEntity($page, [])->unlock(); 228 } 229 230 $this->log("Indexer: deleted $page from index"); 231 @unlink($idxtag); 232 } 233 234 /** 235 * Rename a page in the search index 236 * 237 * This renames the page's entity entry in place: its entity ID (the row in the 238 * page index) is kept and only its name is changed. Because every collection 239 * (title, fulltext and all metadata keys such as relation_references) is keyed by 240 * that entity ID, all token, frequency and reverse associations are preserved and 241 * transparently belong to the new name afterwards. 242 * 243 * In particular this keeps the renamed page's *outgoing* references intact. That is 244 * essential during multi-step operations such as namespace moves: a page renamed 245 * early on must still be discoverable as a backlink source for pages that are moved 246 * later. Re-indexing from disk instead would lose this, because the destination page 247 * has usually not been written to disk yet when this method is called. 248 * 249 * @param string $oldpage The old page name 250 * @param string $newpage The new page name 251 * 252 * @throws IndexAccessException 253 * @throws IndexLockException 254 * @throws IndexWriteException 255 */ 256 public function renamePage(string $oldpage, string $newpage): void 257 { 258 if ($oldpage === $newpage) return; 259 260 $pageIndex = new FileIndex('page', '', true); 261 262 // locate the existing entity rows; stop as soon as both are known 263 $oldId = null; 264 $newId = null; 265 foreach ($pageIndex as $rid => $value) { 266 if ($value === $oldpage) $oldId = $rid; 267 if ($value === $newpage) $newId = $rid; 268 if ($oldId !== null && $newId !== null) break; 269 } 270 271 // nothing to rename if the old page was never indexed 272 if ($oldId === null) { 273 $pageIndex->unlock(); 274 $this->log("Indexer: $oldpage is not in the index, nothing to rename"); 275 return; 276 } 277 278 // If the new name already has its own entity, drop its indexed data first. 279 // deletePage() intentionally keeps the entity row in page.idx, so we additionally 280 // blank that row - an empty entry is the index's "removed" marker (see getAllPages()). 281 // Otherwise two rows would carry the new name and a lookup could resolve to the 282 // now-empty one instead of the renamed entity that holds the data. 283 if ($newId !== null) { 284 $this->deletePage($newpage, true); 285 $pageIndex->changeRow($newId, ''); 286 } 287 288 // rename in place — keeps the entity ID and thus all index associations 289 $pageIndex->changeRow($oldId, $newpage); 290 291 $pageIndex->unlock(); 292 $this->log("Indexer: renamed $oldpage to $newpage in index"); 293 } 294 295 /** 296 * Clear all page indexes 297 */ 298 public function clear(): void 299 { 300 global $conf; 301 302 Lock::acquire('page'); 303 304 // clear metadata indexes 305 foreach ($this->getMetadataRegistryKeys() as $key) { 306 $clean = PageMetaCollection::cleanName($key); 307 @unlink($conf['indexdir'] . '/' . $clean . '_w.idx'); 308 @unlink($conf['indexdir'] . '/' . $clean . '_i.idx'); 309 @unlink($conf['indexdir'] . '/' . $clean . '_p.idx'); 310 } 311 312 // clear fulltext indexes 313 $files = glob($conf['indexdir'] . '/i*.idx'); 314 if ($files) foreach ($files as $f) @unlink($f); 315 $files = glob($conf['indexdir'] . '/w*.idx'); 316 if ($files) foreach ($files as $f) @unlink($f); 317 318 @unlink($conf['indexdir'] . '/pageword.idx'); 319 @unlink($conf['indexdir'] . '/lengths.idx'); 320 321 // clear title and page indexes 322 @unlink($conf['indexdir'] . '/title.idx'); 323 @unlink($conf['indexdir'] . '/page.idx'); 324 @unlink($conf['indexdir'] . '/metadata.idx'); 325 326 Lock::release('page'); 327 } 328 329 /** 330 * Check the structural integrity of all search indexes 331 * 332 * @throws IndexIntegrityException when a structural inconsistency is found 333 */ 334 public function checkIntegrity(): void 335 { 336 (new PageFulltextCollection())->checkIntegrity(); 337 (new PageTitleCollection())->checkIntegrity(); 338 339 foreach ($this->getMetadataRegistryKeys() as $key) { 340 (new PageMetaCollection($key))->checkIntegrity(); 341 } 342 } 343 344 /** 345 * Whether the search index is empty (no fulltext data indexed yet) 346 * 347 * @return bool 348 */ 349 public function isIndexEmpty(): bool 350 { 351 return (new PageFulltextCollection())->getTokenIndexMaximum() === 0; 352 } 353 354 /** 355 * Get the list of known metadata keys from the metadata registry 356 * 357 * @return string[] list of metadata key names 358 */ 359 protected function getMetadataRegistryKeys(): array 360 { 361 global $conf; 362 $fn = $conf['indexdir'] . '/metadata.idx'; 363 if (!file_exists($fn)) return []; 364 $keys = file($fn, FILE_IGNORE_NEW_LINES); 365 return $keys ?: []; 366 } 367 368 /** 369 * Update the metadata registry with new keys 370 * 371 * @param string[] $keys metadata key names to ensure are registered 372 * 373 * @internal Only marked public for access via LegacyIndexer 374 */ 375 public function updateMetadataRegistry(array $keys): void 376 { 377 global $conf; 378 $fn = $conf['indexdir'] . '/metadata.idx'; 379 $existing = file_exists($fn) ? file($fn, FILE_IGNORE_NEW_LINES) : []; 380 if (!$existing) $existing = []; 381 382 $added = false; 383 foreach ($keys as $key) { 384 if (!in_array($key, $existing)) { 385 $existing[] = $key; 386 $added = true; 387 } 388 } 389 390 if ($added) { 391 io_saveFile($fn, implode("\n", $existing) . "\n"); 392 } 393 } 394 395 /** 396 * Return a list of all indexed pages, optionally filtered by metadata key 397 * 398 * Kept on Indexer (not just LegacyIndexer) because several plugins call it 399 * directly on `new Indexer()` instances rather than going through 400 * idx_get_indexer(). 401 * 402 * @param string|null $key metadata key name 403 * @return string[] 404 * 405 * @deprecated 2026-04-07 use MetadataSearch::getPages() or Indexer::getAllPages() instead 406 */ 407 public function getPages($key = null) 408 { 409 DebugHelper::dbgDeprecatedFunction(MetadataSearch::class . '::getPages()'); 410 return (new MetadataSearch())->getPages($key); 411 } 412} 413