xref: /dokuwiki/inc/Search/Indexer.php (revision 6e39b4e379a661a3abd765df49fa679d2119741c)
16225b270SMichael Große<?php
26225b270SMichael Große
36225b270SMichael Großenamespace dokuwiki\Search;
46225b270SMichael Große
5e1272c08SAndreas Gohruse dokuwiki\Debug\DebugHelper;
66225b270SMichael Großeuse dokuwiki\Extension\Event;
783b3acccSAndreas Gohruse dokuwiki\Search\Collection\PageFulltextCollection;
883b3acccSAndreas Gohruse dokuwiki\Search\Collection\PageMetaCollection;
983b3acccSAndreas Gohruse dokuwiki\Search\Collection\PageTitleCollection;
1015f699acSAndreas Gohruse dokuwiki\Search\Exception\IndexAccessException;
1121fbd01bSAndreas Gohruse dokuwiki\Search\Exception\IndexIntegrityException;
12a16bd548SSatoshi Saharause dokuwiki\Search\Exception\IndexLockException;
13a16bd548SSatoshi Saharause dokuwiki\Search\Exception\IndexWriteException;
1483b3acccSAndreas Gohruse dokuwiki\Search\Index\FileIndex;
1583b3acccSAndreas Gohruse dokuwiki\Search\Index\Lock;
16e1272c08SAndreas Gohruse dokuwiki\Search\Index\MemoryIndex;
174027a91aSSatoshi Sahara
184027a91aSSatoshi Sahara// Version tag used to force rebuild on upgrade
195d034a75SAndreas Gohrconst INDEXER_VERSION = 9;
206225b270SMichael Große
216225b270SMichael Große/**
22a32da6ddSSatoshi Sahara * Class DokuWiki Indexer
236225b270SMichael Große *
2483b3acccSAndreas Gohr * Manages the page search index by delegating to Collection classes.
2583b3acccSAndreas Gohr *
264027a91aSSatoshi Sahara * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
276225b270SMichael Große * @author     Andreas Gohr <andi@splitbrain.org>
284027a91aSSatoshi Sahara * @author Tom N Harris <tnharris@whoopdedo.org>
296225b270SMichael Große */
3083b3acccSAndreas Gohrclass Indexer
314027a91aSSatoshi Sahara{
3283b3acccSAndreas Gohr    /** @var callable|null Logging callback, receives a string message */
3383b3acccSAndreas Gohr    protected $logger;
346225b270SMichael Große
354027a91aSSatoshi Sahara    /**
3683b3acccSAndreas Gohr     * Set a logging callback
374027a91aSSatoshi Sahara     *
3883b3acccSAndreas Gohr     * The callback receives a single string message. Use this to integrate
3983b3acccSAndreas Gohr     * with different output mechanisms (TaskRunner echo, CLI output, Logger, etc.)
4083b3acccSAndreas Gohr     *
4183b3acccSAndreas Gohr     * @param callable $logger
4283b3acccSAndreas Gohr     * @return static
434027a91aSSatoshi Sahara     */
4483b3acccSAndreas Gohr    public function setLogger(callable $logger): static
454027a91aSSatoshi Sahara    {
4683b3acccSAndreas Gohr        $this->logger = $logger;
4783b3acccSAndreas Gohr        return $this;
486225b270SMichael Große    }
496225b270SMichael Große
506225b270SMichael Große    /**
5183b3acccSAndreas Gohr     * Send a message to the registered logger
526225b270SMichael Große     *
5383b3acccSAndreas Gohr     * @param string $message
546225b270SMichael Große     */
5583b3acccSAndreas Gohr    protected function log(string $message): void
564027a91aSSatoshi Sahara    {
5783b3acccSAndreas Gohr        if ($this->logger)($this->logger)($message);
586225b270SMichael Große    }
596225b270SMichael Große
606225b270SMichael Große    /**
614027a91aSSatoshi Sahara     * Version of the indexer taking into consideration the external tokenizer.
624027a91aSSatoshi Sahara     * The indexer is only compatible with data written by the same version.
636225b270SMichael Große     *
644027a91aSSatoshi Sahara     * @triggers INDEXER_VERSION_GET
654027a91aSSatoshi Sahara     * Plugins that modify what gets indexed should hook this event and
664027a91aSSatoshi Sahara     * add their version info to the event data like so:
674027a91aSSatoshi Sahara     *     $data[$plugin_name] = $plugin_version;
686225b270SMichael Große     *
694027a91aSSatoshi Sahara     * @return int|string
706225b270SMichael Große     */
719369b4a9SAndreas Gohr    public function getVersion(): int|string
724027a91aSSatoshi Sahara    {
734027a91aSSatoshi Sahara        static $indexer_version = null;
744027a91aSSatoshi Sahara        if ($indexer_version == null) {
754027a91aSSatoshi Sahara            $version = INDEXER_VERSION;
764027a91aSSatoshi Sahara
7783b3acccSAndreas Gohr            $data = ['dokuwiki' => $version];
784027a91aSSatoshi Sahara            Event::createAndTrigger('INDEXER_VERSION_GET', $data, null, false);
794027a91aSSatoshi Sahara            unset($data['dokuwiki']); // this needs to be first
804027a91aSSatoshi Sahara            ksort($data);
814027a91aSSatoshi Sahara            foreach ($data as $plugin => $vers) {
824027a91aSSatoshi Sahara                $version .= '+' . $plugin . '=' . $vers;
834027a91aSSatoshi Sahara            }
844027a91aSSatoshi Sahara            $indexer_version = $version;
854027a91aSSatoshi Sahara        }
864027a91aSSatoshi Sahara        return $indexer_version;
876225b270SMichael Große    }
886225b270SMichael Große
894027a91aSSatoshi Sahara    /**
9083b3acccSAndreas Gohr     * Return a list of all indexed pages
9183b3acccSAndreas Gohr     *
9283b3acccSAndreas Gohr     * @param bool $existsFilter only return pages that exist on disk
9383b3acccSAndreas Gohr     * @return string[] list of page names (keys are the RIDs in the page index)
9483b3acccSAndreas Gohr     */
9583b3acccSAndreas Gohr    public function getAllPages(bool $existsFilter = false): array
9683b3acccSAndreas Gohr    {
979369b4a9SAndreas Gohr        $pageIndex = new MemoryIndex('page');
9883b3acccSAndreas Gohr        return array_filter(
9983b3acccSAndreas Gohr            iterator_to_array($pageIndex),
10083b3acccSAndreas Gohr            static fn($v) => $v !== '' && (!$existsFilter || page_exists($v, '', false))
10183b3acccSAndreas Gohr        );
10283b3acccSAndreas Gohr    }
10383b3acccSAndreas Gohr
10483b3acccSAndreas Gohr    /**
10583b3acccSAndreas Gohr     * Check if a page needs (re-)indexing
10683b3acccSAndreas Gohr     *
10783b3acccSAndreas Gohr     * @param string $page
10883b3acccSAndreas Gohr     * @param bool $force
10983b3acccSAndreas Gohr     * @return bool true if indexing is needed
11083b3acccSAndreas Gohr     */
11183b3acccSAndreas Gohr    public function needsIndexing(string $page, bool $force = false): bool
11283b3acccSAndreas Gohr    {
11383b3acccSAndreas Gohr        $idxtag = metaFN($page, '.indexed');
11483b3acccSAndreas Gohr        if ($force || !file_exists($idxtag)) return true;
11583b3acccSAndreas Gohr
11683b3acccSAndreas Gohr        if (trim(io_readFile($idxtag)) != $this->getVersion()) return true;
11783b3acccSAndreas Gohr
11883b3acccSAndreas Gohr        $last = @filemtime($idxtag);
11983b3acccSAndreas Gohr        return $last <= @filemtime(wikiFN($page));
12083b3acccSAndreas Gohr    }
12183b3acccSAndreas Gohr
12283b3acccSAndreas Gohr    /**
12383b3acccSAndreas Gohr     * Add/update the search index for a page
1244027a91aSSatoshi Sahara     *
1254027a91aSSatoshi Sahara     * Locking is handled internally.
1264027a91aSSatoshi Sahara     *
12783b3acccSAndreas Gohr     * @param string $page The page to index
1284027a91aSSatoshi Sahara     * @param bool $force force reindexing even when the index is up to date
1294027a91aSSatoshi Sahara     *
130a32da6ddSSatoshi Sahara     * @throws IndexAccessException
131a16bd548SSatoshi Sahara     * @throws IndexLockException
132a16bd548SSatoshi Sahara     * @throws IndexWriteException
1334027a91aSSatoshi Sahara     */
13483b3acccSAndreas Gohr    public function addPage(string $page, bool $force = false): void
1354027a91aSSatoshi Sahara    {
13683b3acccSAndreas Gohr        if (!$this->needsIndexing($page, $force)) {
1379369b4a9SAndreas Gohr            $this->log("Indexer: index for $page up to date");
13883b3acccSAndreas Gohr            return;
139a32da6ddSSatoshi Sahara        }
140a32da6ddSSatoshi Sahara
14183b3acccSAndreas Gohr        // create shared writable page index early so we can resolve the PID for plugins
14283b3acccSAndreas Gohr        $pageIndex = new FileIndex('page', '', true);
1436225b270SMichael Große
14483b3acccSAndreas Gohr        // prepare event data
14583b3acccSAndreas Gohr        $data = [
14683b3acccSAndreas Gohr            'page' => $page,
14783b3acccSAndreas Gohr            'body' => '',
14883b3acccSAndreas Gohr            'metadata' => [
14983b3acccSAndreas Gohr                'title' => p_get_metadata($page, 'title', METADATA_RENDER_UNLIMITED),
15083b3acccSAndreas Gohr                'relation_references' => array_keys(
15183b3acccSAndreas Gohr                    p_get_metadata($page, 'relation references', METADATA_RENDER_UNLIMITED) ?? []
15283b3acccSAndreas Gohr                ),
15383b3acccSAndreas Gohr                'relation_media' => array_keys(
15483b3acccSAndreas Gohr                    p_get_metadata($page, 'relation media', METADATA_RENDER_UNLIMITED) ?? []
15583b3acccSAndreas Gohr                ),
15683b3acccSAndreas Gohr                'internal_index' => p_get_metadata($page, 'internal index', METADATA_RENDER_UNLIMITED) !== false,
15783b3acccSAndreas Gohr            ],
15883b3acccSAndreas Gohr            'pid' => $pageIndex->accessCachedValue($page),
15983b3acccSAndreas Gohr        ];
1606225b270SMichael Große
16183b3acccSAndreas Gohr        // let plugins modify the data
1624027a91aSSatoshi Sahara        $event = new Event('INDEXER_PAGE_ADD', $data);
16383b3acccSAndreas Gohr        if ($event->advise_before()) {
16483b3acccSAndreas Gohr            $data['body'] = $data['body'] . ' ' . rawWiki($data['page']);
16583b3acccSAndreas Gohr        }
1664027a91aSSatoshi Sahara        $event->advise_after();
1674027a91aSSatoshi Sahara        unset($event);
1686225b270SMichael Große
16983b3acccSAndreas Gohr        // index title
17083b3acccSAndreas Gohr        (new PageTitleCollection($pageIndex))->lock()
17183b3acccSAndreas Gohr            ->addEntity($data['page'], [$data['metadata']['title']])->unlock();
17283b3acccSAndreas Gohr        unset($data['metadata']['title']);
1736225b270SMichael Große
17483b3acccSAndreas Gohr        // index fulltext
17583b3acccSAndreas Gohr        if ($data['metadata']['internal_index']) {
17683b3acccSAndreas Gohr            $words = Tokenizer::getWords($data['body']);
17783b3acccSAndreas Gohr            (new PageFulltextCollection($pageIndex))->lock()->addEntity($data['page'], $words)->unlock();
1786225b270SMichael Große        } else {
17983b3acccSAndreas Gohr            $this->log("Indexer: full text indexing disabled for {$data['page']}");
18083b3acccSAndreas Gohr            // clear any previously stored fulltext data
18183b3acccSAndreas Gohr            (new PageFulltextCollection($pageIndex))->lock()->addEntity($data['page'], [])->unlock();
1826225b270SMichael Große        }
18383b3acccSAndreas Gohr        unset($data['metadata']['internal_index']);
18483b3acccSAndreas Gohr
18583b3acccSAndreas Gohr        // index metadata keys
18683b3acccSAndreas Gohr        foreach ($data['metadata'] as $key => $values) {
18783b3acccSAndreas Gohr            if (!is_array($values)) {
18883b3acccSAndreas Gohr                $values = ($values !== null && $values !== '') ? [$values] : [];
1896225b270SMichael Große            }
19083b3acccSAndreas Gohr            (new PageMetaCollection($key, $pageIndex))->lock()->addEntity($data['page'], $values)->unlock();
19183b3acccSAndreas Gohr        }
19283b3acccSAndreas Gohr
19383b3acccSAndreas Gohr        // update metadata registry
19483b3acccSAndreas Gohr        $this->updateMetadataRegistry(array_keys($data['metadata']));
1956225b270SMichael Große
1964027a91aSSatoshi Sahara        // update index tag file
19783b3acccSAndreas Gohr        io_saveFile(metaFN($data['page'], '.indexed'), $this->getVersion());
19883b3acccSAndreas Gohr        $this->log("Indexer: finished indexing {$data['page']}");
1996225b270SMichael Große    }
2006225b270SMichael Große
2016225b270SMichael Große    /**
2025f9bd525SSatoshi Sahara     * Remove a page from the index
2036225b270SMichael Große     *
20483b3acccSAndreas Gohr     * Clears the page's data from all collections. The entity persists in page.idx.
2056225b270SMichael Große     *
20683b3acccSAndreas Gohr     * @param string $page The page to remove
20783b3acccSAndreas Gohr     * @param bool $force force deletion even when no .indexed tag exists
2086225b270SMichael Große     *
209a32da6ddSSatoshi Sahara     * @throws IndexAccessException
210a16bd548SSatoshi Sahara     * @throws IndexLockException
211a16bd548SSatoshi Sahara     * @throws IndexWriteException
2126225b270SMichael Große     */
21383b3acccSAndreas Gohr    public function deletePage(string $page, bool $force = false): void
2144027a91aSSatoshi Sahara    {
2154027a91aSSatoshi Sahara        $idxtag = metaFN($page, '.indexed');
2164027a91aSSatoshi Sahara        if (!$force && !file_exists($idxtag)) {
2179369b4a9SAndreas Gohr            $this->log("Indexer: $page.indexed file does not exist, ignoring");
21883b3acccSAndreas Gohr            return;
2194027a91aSSatoshi Sahara        }
2206225b270SMichael Große
22183b3acccSAndreas Gohr        $pageIndex = new FileIndex('page', '', true);
222725e8e5fSSatoshi Sahara
22383b3acccSAndreas Gohr        (new PageTitleCollection($pageIndex))->lock()->addEntity($page, [])->unlock();
22483b3acccSAndreas Gohr        (new PageFulltextCollection($pageIndex))->lock()->addEntity($page, [])->unlock();
22583b3acccSAndreas Gohr
22683b3acccSAndreas Gohr        foreach ($this->getMetadataRegistryKeys() as $key) {
22783b3acccSAndreas Gohr            (new PageMetaCollection($key, $pageIndex))->lock()->addEntity($page, [])->unlock();
2284027a91aSSatoshi Sahara        }
2296225b270SMichael Große
2309369b4a9SAndreas Gohr        $this->log("Indexer: deleted $page from index");
2314027a91aSSatoshi Sahara        @unlink($idxtag);
2324027a91aSSatoshi Sahara    }
2334027a91aSSatoshi Sahara
2344027a91aSSatoshi Sahara    /**
23583b3acccSAndreas Gohr     * Rename a page in the search index
23683b3acccSAndreas Gohr     *
23783b3acccSAndreas Gohr     * The page must already have been moved on disk before calling this.
23883b3acccSAndreas Gohr     * Clears the old page's data and re-indexes under the new name.
2394027a91aSSatoshi Sahara     *
2404027a91aSSatoshi Sahara     * @param string $oldpage The old page name
2414027a91aSSatoshi Sahara     * @param string $newpage The new page name
24283b3acccSAndreas Gohr     *
24383b3acccSAndreas Gohr     * @throws IndexAccessException
244a16bd548SSatoshi Sahara     * @throws IndexLockException
245a16bd548SSatoshi Sahara     * @throws IndexWriteException
2464027a91aSSatoshi Sahara     */
24783b3acccSAndreas Gohr    public function renamePage(string $oldpage, string $newpage): void
2484027a91aSSatoshi Sahara    {
24983b3acccSAndreas Gohr        $this->deletePage($oldpage, true);
25083b3acccSAndreas Gohr        $this->addPage($newpage, true);
2516225b270SMichael Große    }
2526225b270SMichael Große
2536225b270SMichael Große    /**
25483b3acccSAndreas Gohr     * Clear all page indexes
2556225b270SMichael Große     */
25683b3acccSAndreas Gohr    public function clear(): void
2574027a91aSSatoshi Sahara    {
2586225b270SMichael Große        global $conf;
2596225b270SMichael Große
26083b3acccSAndreas Gohr        Lock::acquire('page');
2614027a91aSSatoshi Sahara
26283b3acccSAndreas Gohr        // clear metadata indexes
26383b3acccSAndreas Gohr        foreach ($this->getMetadataRegistryKeys() as $key) {
26483b3acccSAndreas Gohr            $clean = PageMetaCollection::cleanName($key);
26583b3acccSAndreas Gohr            @unlink($conf['indexdir'] . '/' . $clean . '_w.idx');
26683b3acccSAndreas Gohr            @unlink($conf['indexdir'] . '/' . $clean . '_i.idx');
26783b3acccSAndreas Gohr            @unlink($conf['indexdir'] . '/' . $clean . '_p.idx');
2686225b270SMichael Große        }
2696225b270SMichael Große
27083b3acccSAndreas Gohr        // clear fulltext indexes
27183b3acccSAndreas Gohr        $files = glob($conf['indexdir'] . '/i*.idx');
27283b3acccSAndreas Gohr        if ($files) foreach ($files as $f) @unlink($f);
27383b3acccSAndreas Gohr        $files = glob($conf['indexdir'] . '/w*.idx');
27483b3acccSAndreas Gohr        if ($files) foreach ($files as $f) @unlink($f);
27583b3acccSAndreas Gohr
27683b3acccSAndreas Gohr        @unlink($conf['indexdir'] . '/pageword.idx');
27783b3acccSAndreas Gohr        @unlink($conf['indexdir'] . '/lengths.idx');
27883b3acccSAndreas Gohr
27983b3acccSAndreas Gohr        // clear title and page indexes
28083b3acccSAndreas Gohr        @unlink($conf['indexdir'] . '/title.idx');
28183b3acccSAndreas Gohr        @unlink($conf['indexdir'] . '/page.idx');
28283b3acccSAndreas Gohr        @unlink($conf['indexdir'] . '/metadata.idx');
28383b3acccSAndreas Gohr
28483b3acccSAndreas Gohr        Lock::release('page');
28583b3acccSAndreas Gohr    }
28683b3acccSAndreas Gohr
28783b3acccSAndreas Gohr    /**
28821fbd01bSAndreas Gohr     * Check the structural integrity of all search indexes
28921fbd01bSAndreas Gohr     *
29021fbd01bSAndreas Gohr     * @throws IndexIntegrityException when a structural inconsistency is found
29121fbd01bSAndreas Gohr     */
29221fbd01bSAndreas Gohr    public function checkIntegrity(): void
29321fbd01bSAndreas Gohr    {
29421fbd01bSAndreas Gohr        (new PageFulltextCollection())->checkIntegrity();
29521fbd01bSAndreas Gohr        (new PageTitleCollection())->checkIntegrity();
29621fbd01bSAndreas Gohr
29721fbd01bSAndreas Gohr        foreach ($this->getMetadataRegistryKeys() as $key) {
29821fbd01bSAndreas Gohr            (new PageMetaCollection($key))->checkIntegrity();
29921fbd01bSAndreas Gohr        }
30021fbd01bSAndreas Gohr    }
30121fbd01bSAndreas Gohr
30221fbd01bSAndreas Gohr    /**
30321fbd01bSAndreas Gohr     * Whether the search index is empty (no fulltext data indexed yet)
30421fbd01bSAndreas Gohr     *
30521fbd01bSAndreas Gohr     * @return bool
30621fbd01bSAndreas Gohr     */
30721fbd01bSAndreas Gohr    public function isIndexEmpty(): bool
30821fbd01bSAndreas Gohr    {
30921fbd01bSAndreas Gohr        return (new PageFulltextCollection())->getTokenIndexMaximum() === 0;
31021fbd01bSAndreas Gohr    }
31121fbd01bSAndreas Gohr
31221fbd01bSAndreas Gohr    /**
31383b3acccSAndreas Gohr     * Get the list of known metadata keys from the metadata registry
31483b3acccSAndreas Gohr     *
31583b3acccSAndreas Gohr     * @return string[] list of metadata key names
31683b3acccSAndreas Gohr     */
31783b3acccSAndreas Gohr    protected function getMetadataRegistryKeys(): array
31883b3acccSAndreas Gohr    {
31983b3acccSAndreas Gohr        global $conf;
32083b3acccSAndreas Gohr        $fn = $conf['indexdir'] . '/metadata.idx';
32183b3acccSAndreas Gohr        if (!file_exists($fn)) return [];
32283b3acccSAndreas Gohr        $keys = file($fn, FILE_IGNORE_NEW_LINES);
32383b3acccSAndreas Gohr        return $keys ?: [];
32483b3acccSAndreas Gohr    }
32583b3acccSAndreas Gohr
32683b3acccSAndreas Gohr    /**
32783b3acccSAndreas Gohr     * Update the metadata registry with new keys
32883b3acccSAndreas Gohr     *
32983b3acccSAndreas Gohr     * @param string[] $keys metadata key names to ensure are registered
330*6e39b4e3SAndreas Gohr     *
331*6e39b4e3SAndreas Gohr     * @internal Only marked public for access via LegacyIndexer
33283b3acccSAndreas Gohr     */
333*6e39b4e3SAndreas Gohr    public function updateMetadataRegistry(array $keys): void
33483b3acccSAndreas Gohr    {
33583b3acccSAndreas Gohr        global $conf;
33683b3acccSAndreas Gohr        $fn = $conf['indexdir'] . '/metadata.idx';
33783b3acccSAndreas Gohr        $existing = file_exists($fn) ? file($fn, FILE_IGNORE_NEW_LINES) : [];
33883b3acccSAndreas Gohr        if (!$existing) $existing = [];
33983b3acccSAndreas Gohr
34083b3acccSAndreas Gohr        $added = false;
34183b3acccSAndreas Gohr        foreach ($keys as $key) {
34283b3acccSAndreas Gohr            if (!in_array($key, $existing)) {
34383b3acccSAndreas Gohr                $existing[] = $key;
34483b3acccSAndreas Gohr                $added = true;
34583b3acccSAndreas Gohr            }
34683b3acccSAndreas Gohr        }
34783b3acccSAndreas Gohr
34883b3acccSAndreas Gohr        if ($added) {
34983b3acccSAndreas Gohr            io_saveFile($fn, implode("\n", $existing) . "\n");
35083b3acccSAndreas Gohr        }
35183b3acccSAndreas Gohr    }
352e1272c08SAndreas Gohr
353e1272c08SAndreas Gohr    /**
354e1272c08SAndreas Gohr     * Return a list of all indexed pages, optionally filtered by metadata key
355e1272c08SAndreas Gohr     *
356*6e39b4e3SAndreas Gohr     * Kept on Indexer (not just LegacyIndexer) because several plugins call it
357*6e39b4e3SAndreas Gohr     * directly on `new Indexer()` instances rather than going through
358*6e39b4e3SAndreas Gohr     * idx_get_indexer().
359*6e39b4e3SAndreas Gohr     *
360e1272c08SAndreas Gohr     * @param string|null $key metadata key name
361e1272c08SAndreas Gohr     * @return string[]
362e1272c08SAndreas Gohr     *
363e1272c08SAndreas Gohr     * @deprecated 2026-04-07 use MetadataSearch::getPages() or Indexer::getAllPages() instead
364e1272c08SAndreas Gohr     */
365e1272c08SAndreas Gohr    public function getPages($key = null)
366e1272c08SAndreas Gohr    {
367e1272c08SAndreas Gohr        DebugHelper::dbgDeprecatedFunction(MetadataSearch::class . '::getPages()');
368e1272c08SAndreas Gohr        return (new MetadataSearch())->getPages($key);
369e1272c08SAndreas Gohr    }
3706225b270SMichael Große}
371