xref: /dokuwiki/inc/Search/Index/MemoryIndex.php (revision 9369b4a991666bc911474806b106d8958e79f4c1)
19bd7d62fSAndreas Gohr<?php
29bd7d62fSAndreas Gohr
39bd7d62fSAndreas Gohrnamespace dokuwiki\Search\Index;
49bd7d62fSAndreas Gohr
5db8be586SAndreas Gohruse dokuwiki\Logger;
67fcedc39SAndreas Gohruse dokuwiki\Search\Exception\IndexLockException;
79bd7d62fSAndreas Gohruse dokuwiki\Search\Exception\IndexWriteException;
89bd7d62fSAndreas Gohr
99bd7d62fSAndreas Gohr/**
109bd7d62fSAndreas Gohr * Access to a single index file
119bd7d62fSAndreas Gohr *
129bd7d62fSAndreas Gohr * Access using this class always happens by loading the full index into memory.
13db8be586SAndreas Gohr * Changes can be made permanent explicitly via save(), but will also be
14db8be586SAndreas Gohr * auto-saved on destruction to prevent data loss when indexes are used in tandem
15db8be586SAndreas Gohr * (a new RID in one index may already be referenced by another).
169bd7d62fSAndreas Gohr * Should be used for small indexes that receive many changes at once.
179bd7d62fSAndreas Gohr */
189bd7d62fSAndreas Gohrclass MemoryIndex extends AbstractIndex
199bd7d62fSAndreas Gohr{
20*9369b4a9SAndreas Gohr    /** @var string[] the raw data lines of the index, no newlines */
21*9369b4a9SAndreas Gohr    protected array $data = [];
229bd7d62fSAndreas Gohr
23b3cb0bc3SAndreas Gohr    /** @var bool has the index been modified? */
24*9369b4a9SAndreas Gohr    protected bool $dirty = false;
25b3cb0bc3SAndreas Gohr
269bd7d62fSAndreas Gohr    /**
279bd7d62fSAndreas Gohr     * Loads the full contents of the index into memory
289bd7d62fSAndreas Gohr     *
299bd7d62fSAndreas Gohr     * @inheritdoc
309bd7d62fSAndreas Gohr     */
317fcedc39SAndreas Gohr    public function __construct($idx, $suffix = '', $isWritable = false)
329bd7d62fSAndreas Gohr    {
337fcedc39SAndreas Gohr        parent::__construct($idx, $suffix, $isWritable);
34b3cb0bc3SAndreas Gohr        if (!file_exists($this->filename)) {
35b3cb0bc3SAndreas Gohr            return;
36b3cb0bc3SAndreas Gohr        }
379bd7d62fSAndreas Gohr        $this->data = file($this->filename, FILE_IGNORE_NEW_LINES);
389bd7d62fSAndreas Gohr    }
399bd7d62fSAndreas Gohr
407fcedc39SAndreas Gohr    /**
41db8be586SAndreas Gohr     * Auto-save dirty data before releasing the lock
42db8be586SAndreas Gohr     *
43db8be586SAndreas Gohr     * When indexes are used in tandem, a new RID written to one index may already
44db8be586SAndreas Gohr     * be referenced by other indexes that were saved. Losing unsaved data here
45db8be586SAndreas Gohr     * would leave dangling references, causing silent index corruption.
46db8be586SAndreas Gohr     *
47db8be586SAndreas Gohr     * The try/catch is necessary because unlock() is called from __destruct()
48db8be586SAndreas Gohr     * (in the parent class), and PHP destructors must not throw — a throw
49db8be586SAndreas Gohr     * during exception unwinding causes a fatal error.
50c66b5ec6SAndreas Gohr     *
51c66b5ec6SAndreas Gohr     * @inheritdoc
527fcedc39SAndreas Gohr     */
53*9369b4a9SAndreas Gohr    public function unlock(): void
547fcedc39SAndreas Gohr    {
557fcedc39SAndreas Gohr        if ($this->isDirty()) {
56db8be586SAndreas Gohr            try {
57db8be586SAndreas Gohr                $this->save();
58db8be586SAndreas Gohr            } catch (\Exception $e) {
59db8be586SAndreas Gohr                Logger::error('MemoryIndex failed to save on unlock: ' . $e->getMessage());
60db8be586SAndreas Gohr            }
617fcedc39SAndreas Gohr        }
62c66b5ec6SAndreas Gohr        parent::unlock();
637fcedc39SAndreas Gohr    }
647fcedc39SAndreas Gohr
657fcedc39SAndreas Gohr    /**
667fcedc39SAndreas Gohr     * @inheritdoc
677fcedc39SAndreas Gohr     * @throws IndexLockException
687fcedc39SAndreas Gohr     */
69*9369b4a9SAndreas Gohr    public function changeRow(int $rid, string $value): void
709bd7d62fSAndreas Gohr    {
717fcedc39SAndreas Gohr        if (!$this->isWritable) throw new IndexLockException();
727fcedc39SAndreas Gohr
739bd7d62fSAndreas Gohr        if ($rid > count($this->data)) {
749bd7d62fSAndreas Gohr            $this->data = array_pad($this->data, $rid, '');
759bd7d62fSAndreas Gohr        }
769bd7d62fSAndreas Gohr        $this->data[$rid] = $value;
77b3cb0bc3SAndreas Gohr        $this->dirty = true;
789bd7d62fSAndreas Gohr    }
799bd7d62fSAndreas Gohr
807fcedc39SAndreas Gohr    /**
817fcedc39SAndreas Gohr     * @inheritdoc
827fcedc39SAndreas Gohr     * @throws IndexLockException
837fcedc39SAndreas Gohr     */
84*9369b4a9SAndreas Gohr    public function retrieveRow(int $rid): string
859bd7d62fSAndreas Gohr    {
86b3cb0bc3SAndreas Gohr        if (isset($this->data[$rid])) {
87b3cb0bc3SAndreas Gohr            return $this->data[$rid];
88b3cb0bc3SAndreas Gohr        }
897fcedc39SAndreas Gohr        if ($this->isWritable) {
90dec26820SAndreas Gohr            $this->changeRow($rid, ''); // add to index
917fcedc39SAndreas Gohr        }
929bd7d62fSAndreas Gohr        return '';
939bd7d62fSAndreas Gohr    }
949bd7d62fSAndreas Gohr
95d6396b6dSAndreas Gohr    /** @inheritdoc */
96*9369b4a9SAndreas Gohr    public function retrieveRows(array $rids): array
979f63f003SAndreas Gohr    {
989f63f003SAndreas Gohr        $result = [];
999f63f003SAndreas Gohr        foreach ($rids as $rid) {
1009f63f003SAndreas Gohr            if (isset($this->data[$rid])) $result[$rid] = $this->data[$rid];
1019f63f003SAndreas Gohr        }
1029f63f003SAndreas Gohr
1039f63f003SAndreas Gohr        return $result;
1049f63f003SAndreas Gohr    }
1059f63f003SAndreas Gohr
1069f63f003SAndreas Gohr    /** @inheritdoc */
107*9369b4a9SAndreas Gohr    public function getRowIDs(array $values): array
108d6396b6dSAndreas Gohr    {
109*9369b4a9SAndreas Gohr        $values = array_map(trim(...), $values);
110d6396b6dSAndreas Gohr        $values = array_fill_keys($values, 1); // easier access as associative array
111d6396b6dSAndreas Gohr
112d6396b6dSAndreas Gohr        $result = [];
113d6396b6dSAndreas Gohr        $count = count($this->data);
114d6396b6dSAndreas Gohr        for ($ln = 0; $ln < $count; $ln++) {
115d6396b6dSAndreas Gohr            $line = $this->data[$ln];
116d6396b6dSAndreas Gohr            if (isset($values[$line])) {
117d6396b6dSAndreas Gohr                $result[$line] = $ln;
118d6396b6dSAndreas Gohr                unset($values[$line]);
119d6396b6dSAndreas Gohr            }
120d6396b6dSAndreas Gohr        }
121d6396b6dSAndreas Gohr
1227fcedc39SAndreas Gohr        if (!$this->isWritable) return $result;
1237fcedc39SAndreas Gohr
124d6396b6dSAndreas Gohr        // if there are still values, they have not been found and will be appended
125d6396b6dSAndreas Gohr        foreach (array_keys($values) as $value) {
126d6396b6dSAndreas Gohr            $this->data[] = $value;
127d6396b6dSAndreas Gohr            $result[$value] = $ln++;
128b3cb0bc3SAndreas Gohr            $this->dirty = true;
129d6396b6dSAndreas Gohr        }
130d6396b6dSAndreas Gohr
131d6396b6dSAndreas Gohr        return $result;
132d6396b6dSAndreas Gohr    }
133d6396b6dSAndreas Gohr
13403a35633SAndreas Gohr    /** @inheritdoc */
135*9369b4a9SAndreas Gohr    public function search(string $re): array
13603a35633SAndreas Gohr    {
13703a35633SAndreas Gohr        return preg_grep($re, $this->data);
13803a35633SAndreas Gohr    }
13903a35633SAndreas Gohr
1409bd7d62fSAndreas Gohr    /**
1419bd7d62fSAndreas Gohr     * Save the changed index back to its file
1429bd7d62fSAndreas Gohr     *
143b3cb0bc3SAndreas Gohr     * The method will check the internal dirty state and will only write when the index has actually been changed
144b3cb0bc3SAndreas Gohr     *
1459bd7d62fSAndreas Gohr     * @throws IndexWriteException
1467fcedc39SAndreas Gohr     * @throws IndexLockException
1479bd7d62fSAndreas Gohr     */
148*9369b4a9SAndreas Gohr    public function save(): void
1499bd7d62fSAndreas Gohr    {
1509bd7d62fSAndreas Gohr        global $conf;
1519bd7d62fSAndreas Gohr
152b3cb0bc3SAndreas Gohr        if (!$this->isDirty()) {
153b3cb0bc3SAndreas Gohr            return;
154b3cb0bc3SAndreas Gohr        }
155b3cb0bc3SAndreas Gohr
1567fcedc39SAndreas Gohr        if (!$this->isWritable) throw new IndexLockException();
1577fcedc39SAndreas Gohr
1589bd7d62fSAndreas Gohr        $tempname = $this->filename . '.tmp';
1599bd7d62fSAndreas Gohr
1609bd7d62fSAndreas Gohr        $fh = @fopen($tempname, 'w');
1619bd7d62fSAndreas Gohr        if (!$fh) {
1629bd7d62fSAndreas Gohr            throw new IndexWriteException("Failed to write $tempname");
1639bd7d62fSAndreas Gohr        }
1649bd7d62fSAndreas Gohr        fwrite($fh, implode("\n", $this->data));
165*9369b4a9SAndreas Gohr        if ($this->data !== []) {
1669bd7d62fSAndreas Gohr            fwrite($fh, "\n");
1679bd7d62fSAndreas Gohr        }
1689bd7d62fSAndreas Gohr        fclose($fh);
1699bd7d62fSAndreas Gohr
1709bd7d62fSAndreas Gohr        if ($conf['fperm']) {
1719bd7d62fSAndreas Gohr            chmod($tempname, $conf['fperm']);
1729bd7d62fSAndreas Gohr        }
1739bd7d62fSAndreas Gohr
1749bd7d62fSAndreas Gohr        if (!io_rename($tempname, $this->filename)) {
175*9369b4a9SAndreas Gohr            throw new IndexWriteException("Failed to write $this->filename");
1769bd7d62fSAndreas Gohr        }
177b3cb0bc3SAndreas Gohr
178b3cb0bc3SAndreas Gohr        $this->dirty = false;
1799bd7d62fSAndreas Gohr    }
1809bd7d62fSAndreas Gohr
181b3cb0bc3SAndreas Gohr    /**
182b3cb0bc3SAndreas Gohr     * Check if the index has been modified and needs to be saved
183b3cb0bc3SAndreas Gohr     * @return bool
184b3cb0bc3SAndreas Gohr     */
185*9369b4a9SAndreas Gohr    public function isDirty(): bool
186b3cb0bc3SAndreas Gohr    {
187b3cb0bc3SAndreas Gohr        return $this->dirty;
188b3cb0bc3SAndreas Gohr    }
18983b3acccSAndreas Gohr
19083b3acccSAndreas Gohr    /** @inheritdoc */
19121fbd01bSAndreas Gohr    public function count(): int
19221fbd01bSAndreas Gohr    {
19321fbd01bSAndreas Gohr        return count($this->data);
19421fbd01bSAndreas Gohr    }
19521fbd01bSAndreas Gohr
19621fbd01bSAndreas Gohr    /** @inheritdoc */
19783b3acccSAndreas Gohr    public function getIterator(): \ArrayIterator
19883b3acccSAndreas Gohr    {
19983b3acccSAndreas Gohr        return new \ArrayIterator($this->data);
20083b3acccSAndreas Gohr    }
2019bd7d62fSAndreas Gohr}
202