xref: /dokuwiki/inc/ChangeLog/ChangeLog.php (revision a835c93a8c9175f580c05a0aeb56b7664f5e8435)
10c3a5702SAndreas Gohr<?php
20c3a5702SAndreas Gohr
30c3a5702SAndreas Gohrnamespace dokuwiki\ChangeLog;
40c3a5702SAndreas Gohr
566f4cdd4SSatoshi Saharause dokuwiki\Logger;
666f4cdd4SSatoshi Sahara
70c3a5702SAndreas Gohr/**
81d11f1d3SSatoshi Sahara * ChangeLog Prototype; methods for handling changelog
90c3a5702SAndreas Gohr */
100c3a5702SAndreas Gohrabstract class ChangeLog
110c3a5702SAndreas Gohr{
121d11f1d3SSatoshi Sahara    use ChangeLogTrait;
131d11f1d3SSatoshi Sahara
140c3a5702SAndreas Gohr    /** @var string */
150c3a5702SAndreas Gohr    protected $id;
1679a2d784SGerrit Uitslag    /** @var false|int */
17bd17ac90SSatoshi Sahara    protected $currentRevision;
180c3a5702SAndreas Gohr    /** @var array */
190603e565SAndreas Gohr    protected $cache = [];
200c3a5702SAndreas Gohr
210c3a5702SAndreas Gohr    /**
220c3a5702SAndreas Gohr     * Constructor
230c3a5702SAndreas Gohr     *
240c3a5702SAndreas Gohr     * @param string $id page id
250c3a5702SAndreas Gohr     * @param int $chunk_size maximum block size read from file
260c3a5702SAndreas Gohr     */
270c3a5702SAndreas Gohr    public function __construct($id, $chunk_size = 8192)
280c3a5702SAndreas Gohr    {
290c3a5702SAndreas Gohr        global $cache_revinfo;
300c3a5702SAndreas Gohr
310c3a5702SAndreas Gohr        $this->cache =& $cache_revinfo;
320c3a5702SAndreas Gohr        if (!isset($this->cache[$id])) {
330603e565SAndreas Gohr            $this->cache[$id] = [];
340c3a5702SAndreas Gohr        }
350c3a5702SAndreas Gohr
360c3a5702SAndreas Gohr        $this->id = $id;
370c3a5702SAndreas Gohr        $this->setChunkSize($chunk_size);
380c3a5702SAndreas Gohr    }
390c3a5702SAndreas Gohr
400c3a5702SAndreas Gohr    /**
410c3a5702SAndreas Gohr     * Returns path to current page/media
420c3a5702SAndreas Gohr     *
4383bec475SAndreas Gohr     * @param string|int $rev empty string or revision timestamp
440c3a5702SAndreas Gohr     * @return string path to file
450c3a5702SAndreas Gohr     */
4683bec475SAndreas Gohr    abstract protected function getFilename($rev = '');
470c3a5702SAndreas Gohr
48df7627d6SSatoshi Sahara    /**
49*a835c93aSGerrit Uitslag     * Returns mode
50*a835c93aSGerrit Uitslag     *
51*a835c93aSGerrit Uitslag     * @return string RevisionInfo::MODE_MEDIA or RevisionInfo::MODE_PAGE
52*a835c93aSGerrit Uitslag     */
53*a835c93aSGerrit Uitslag    abstract protected function getMode();
54*a835c93aSGerrit Uitslag
55*a835c93aSGerrit Uitslag    /**
56df7627d6SSatoshi Sahara     * Check whether given revision is the current page
57df7627d6SSatoshi Sahara     *
58df7627d6SSatoshi Sahara     * @param int $rev timestamp of current page
59df7627d6SSatoshi Sahara     * @return bool true if $rev is current revision, otherwise false
60df7627d6SSatoshi Sahara     */
61df7627d6SSatoshi Sahara    public function isCurrentRevision($rev)
62df7627d6SSatoshi Sahara    {
63df7627d6SSatoshi Sahara        return $rev == $this->currentRevision();
64df7627d6SSatoshi Sahara    }
65df7627d6SSatoshi Sahara
66df7627d6SSatoshi Sahara    /**
67df7627d6SSatoshi Sahara     * Checks if the revision is last revision
68df7627d6SSatoshi Sahara     *
69df7627d6SSatoshi Sahara     * @param int $rev revision timestamp
70df7627d6SSatoshi Sahara     * @return bool true if $rev is last revision, otherwise false
71df7627d6SSatoshi Sahara     */
72df7627d6SSatoshi Sahara    public function isLastRevision($rev = null)
73df7627d6SSatoshi Sahara    {
74df7627d6SSatoshi Sahara        return $rev === $this->lastRevision();
75df7627d6SSatoshi Sahara    }
76df7627d6SSatoshi Sahara
77df7627d6SSatoshi Sahara    /**
78eeda7adaSGerrit Uitslag     * Return the current revision identifier
7905282e9fSSatoshi Sahara     *
8005282e9fSSatoshi Sahara     * The "current" revision means current version of the page or media file. It is either
8105282e9fSSatoshi Sahara     * identical with or newer than the "last" revision, that depends on whether the file
8205282e9fSSatoshi Sahara     * has modified, created or deleted outside of DokuWiki.
8305282e9fSSatoshi Sahara     * The value of identifier can be determined by timestamp as far as the file exists,
8405282e9fSSatoshi Sahara     * otherwise it must be assigned larger than any other revisions to keep them sortable.
8505282e9fSSatoshi Sahara     *
8605282e9fSSatoshi Sahara     * @return int|false revision timestamp
87df7627d6SSatoshi Sahara     */
88df7627d6SSatoshi Sahara    public function currentRevision()
89df7627d6SSatoshi Sahara    {
90df7627d6SSatoshi Sahara        if (!isset($this->currentRevision)) {
91df7627d6SSatoshi Sahara            // set ChangeLog::currentRevision property
92df7627d6SSatoshi Sahara            $this->getCurrentRevisionInfo();
93df7627d6SSatoshi Sahara        }
94df7627d6SSatoshi Sahara        return $this->currentRevision;
95df7627d6SSatoshi Sahara    }
96df7627d6SSatoshi Sahara
97df7627d6SSatoshi Sahara    /**
98eeda7adaSGerrit Uitslag     * Return the last revision identifier, date value of the last entry of the changelog
99d154755dSSatoshi Sahara     *
10005282e9fSSatoshi Sahara     * @return int|false revision timestamp
101df7627d6SSatoshi Sahara     */
102df7627d6SSatoshi Sahara    public function lastRevision()
103df7627d6SSatoshi Sahara    {
104df7627d6SSatoshi Sahara        $revs = $this->getRevisions(-1, 1);
105df7627d6SSatoshi Sahara        return empty($revs) ? false : $revs[0];
106df7627d6SSatoshi Sahara    }
107df7627d6SSatoshi Sahara
1080c3a5702SAndreas Gohr    /**
109*a835c93aSGerrit Uitslag     * Parses a changelog line into its components and save revision info to the cache pool
110b82f2411SSatoshi Sahara     *
111*a835c93aSGerrit Uitslag     * @param string $value changelog line
112*a835c93aSGerrit Uitslag     * @return array|bool parsed line or false
113b82f2411SSatoshi Sahara     */
114*a835c93aSGerrit Uitslag    protected function parseAndCacheLogLine($value)
115b82f2411SSatoshi Sahara    {
116*a835c93aSGerrit Uitslag        $info = static::parseLogLine($value);
117*a835c93aSGerrit Uitslag        if(is_array($info)) {
118*a835c93aSGerrit Uitslag            $info['mode'] = $this->getMode();
1190603e565SAndreas Gohr            $this->cache[$this->id][$info['date']] ??= $info;
120*a835c93aSGerrit Uitslag            return $info;
121*a835c93aSGerrit Uitslag        }
122*a835c93aSGerrit Uitslag        return false;
123b82f2411SSatoshi Sahara    }
124b82f2411SSatoshi Sahara
125b82f2411SSatoshi Sahara    /**
126d154755dSSatoshi Sahara     * Get the changelog information for a specific revision (timestamp)
1270c3a5702SAndreas Gohr     *
1280c3a5702SAndreas Gohr     * Adjacent changelog lines are optimistically parsed and cached to speed up
1290c3a5702SAndreas Gohr     * consecutive calls to getRevisionInfo. For large changelog files, only the chunk
1300c3a5702SAndreas Gohr     * containing the requested changelog line is read.
1310c3a5702SAndreas Gohr     *
1320c3a5702SAndreas Gohr     * @param int $rev revision timestamp
13386216bf0SGerrit Uitslag     * @param bool $retrieveCurrentRevInfo allows to skip for getting other revision info in the
13486216bf0SGerrit Uitslag     *                                     getCurrentRevisionInfo() where $currentRevision is not yet determined
1350c3a5702SAndreas Gohr     * @return bool|array false or array with entries:
1360c3a5702SAndreas Gohr     *      - date:  unix timestamp
1370c3a5702SAndreas Gohr     *      - ip:    IPv4 address (127.0.0.1)
1380c3a5702SAndreas Gohr     *      - type:  log line type
1390c3a5702SAndreas Gohr     *      - id:    page id
1400c3a5702SAndreas Gohr     *      - user:  user name
1410c3a5702SAndreas Gohr     *      - sum:   edit summary (or action reason)
1420c3a5702SAndreas Gohr     *      - extra: extra data (varies by line type)
143bd17ac90SSatoshi Sahara     *      - sizechange: change of filesize
144*a835c93aSGerrit Uitslag     *    additional:
145*a835c93aSGerrit Uitslag     *      - mode: page or media
1460c3a5702SAndreas Gohr     *
1470c3a5702SAndreas Gohr     * @author Ben Coburn <btcoburn@silicodon.net>
1480c3a5702SAndreas Gohr     * @author Kate Arzamastseva <pshns@ukr.net>
1490c3a5702SAndreas Gohr     */
15086216bf0SGerrit Uitslag    public function getRevisionInfo($rev, $retrieveCurrentRevInfo = true)
1510c3a5702SAndreas Gohr    {
152a3984ddfSSatoshi Sahara        $rev = max(0, $rev);
153a3984ddfSSatoshi Sahara        if (!$rev) return false;
1540c3a5702SAndreas Gohr
15586216bf0SGerrit Uitslag        //ensure the external edits are cached as well
15686216bf0SGerrit Uitslag        if (!isset($this->currentRevision) && $retrieveCurrentRevInfo) {
15786216bf0SGerrit Uitslag            $this->getCurrentRevisionInfo();
15886216bf0SGerrit Uitslag        }
15986216bf0SGerrit Uitslag
1600c3a5702SAndreas Gohr        // check if it's already in the memory cache
1610c3a5702SAndreas Gohr        if (isset($this->cache[$this->id]) && isset($this->cache[$this->id][$rev])) {
1620c3a5702SAndreas Gohr            return $this->cache[$this->id][$rev];
1630c3a5702SAndreas Gohr        }
1640c3a5702SAndreas Gohr
1650c3a5702SAndreas Gohr        //read lines from changelog
1660603e565SAndreas Gohr        [$fp, $lines] = $this->readloglines($rev);
1670c3a5702SAndreas Gohr        if ($fp) {
1680c3a5702SAndreas Gohr            fclose($fp);
1690c3a5702SAndreas Gohr        }
1700c3a5702SAndreas Gohr        if (empty($lines)) return false;
1710c3a5702SAndreas Gohr
1720c3a5702SAndreas Gohr        // parse and cache changelog lines
173*a835c93aSGerrit Uitslag        foreach ($lines as $line) {
174*a835c93aSGerrit Uitslag            $this->parseAndCacheLogLine($line);
1750c3a5702SAndreas Gohr        }
1760c3a5702SAndreas Gohr        if (!isset($this->cache[$this->id][$rev])) {
1770c3a5702SAndreas Gohr            return false;
1780c3a5702SAndreas Gohr        }
1790c3a5702SAndreas Gohr        return $this->cache[$this->id][$rev];
1800c3a5702SAndreas Gohr    }
1810c3a5702SAndreas Gohr
1820c3a5702SAndreas Gohr    /**
1830c3a5702SAndreas Gohr     * Return a list of page revisions numbers
1840c3a5702SAndreas Gohr     *
1850c3a5702SAndreas Gohr     * Does not guarantee that the revision exists in the attic,
1860c3a5702SAndreas Gohr     * only that a line with the date exists in the changelog.
1870c3a5702SAndreas Gohr     * By default the current revision is skipped.
1880c3a5702SAndreas Gohr     *
1890c3a5702SAndreas Gohr     * The current revision is automatically skipped when the page exists.
1900c3a5702SAndreas Gohr     * See $INFO['meta']['last_change'] for the current revision.
1910c3a5702SAndreas Gohr     * A negative $first let read the current revision too.
1920c3a5702SAndreas Gohr     *
1930c3a5702SAndreas Gohr     * For efficiency, the log lines are parsed and cached for later
1940c3a5702SAndreas Gohr     * calls to getRevisionInfo. Large changelog files are read
1950c3a5702SAndreas Gohr     * backwards in chunks until the requested number of changelog
196eeda7adaSGerrit Uitslag     * lines are received.
1970c3a5702SAndreas Gohr     *
1980c3a5702SAndreas Gohr     * @param int $first skip the first n changelog lines
1990c3a5702SAndreas Gohr     * @param int $num number of revisions to return
2000c3a5702SAndreas Gohr     * @return array with the revision timestamps
2010c3a5702SAndreas Gohr     *
2020c3a5702SAndreas Gohr     * @author Ben Coburn <btcoburn@silicodon.net>
2030c3a5702SAndreas Gohr     * @author Kate Arzamastseva <pshns@ukr.net>
2040c3a5702SAndreas Gohr     */
2050c3a5702SAndreas Gohr    public function getRevisions($first, $num)
2060c3a5702SAndreas Gohr    {
2070603e565SAndreas Gohr        $revs = [];
2080603e565SAndreas Gohr        $lines = [];
2090c3a5702SAndreas Gohr        $count = 0;
2100c3a5702SAndreas Gohr
211d154755dSSatoshi Sahara        $logfile = $this->getChangelogFilename();
212d154755dSSatoshi Sahara        if (!file_exists($logfile)) return $revs;
213d154755dSSatoshi Sahara
2140c3a5702SAndreas Gohr        $num = max($num, 0);
2150c3a5702SAndreas Gohr        if ($num == 0) {
2160c3a5702SAndreas Gohr            return $revs;
2170c3a5702SAndreas Gohr        }
2180c3a5702SAndreas Gohr
2190c3a5702SAndreas Gohr        if ($first < 0) {
2200c3a5702SAndreas Gohr            $first = 0;
2210c3a5702SAndreas Gohr        } else {
222df7627d6SSatoshi Sahara            $fileLastMod = $this->getFilename();
223df7627d6SSatoshi Sahara            if (file_exists($fileLastMod) && $this->isLastRevision(filemtime($fileLastMod))) {
224df7627d6SSatoshi Sahara                // skip last revision if the page exists
2250c3a5702SAndreas Gohr                $first = max($first + 1, 0);
2260c3a5702SAndreas Gohr            }
2270c3a5702SAndreas Gohr        }
2280c3a5702SAndreas Gohr
229d154755dSSatoshi Sahara        if (filesize($logfile) < $this->chunk_size || $this->chunk_size == 0) {
2300c3a5702SAndreas Gohr            // read whole file
231d154755dSSatoshi Sahara            $lines = file($logfile);
2320c3a5702SAndreas Gohr            if ($lines === false) {
2330c3a5702SAndreas Gohr                return $revs;
2340c3a5702SAndreas Gohr            }
2350c3a5702SAndreas Gohr        } else {
2360c3a5702SAndreas Gohr            // read chunks backwards
237d154755dSSatoshi Sahara            $fp = fopen($logfile, 'rb'); // "file pointer"
2380c3a5702SAndreas Gohr            if ($fp === false) {
2390c3a5702SAndreas Gohr                return $revs;
2400c3a5702SAndreas Gohr            }
2410c3a5702SAndreas Gohr            fseek($fp, 0, SEEK_END);
2420c3a5702SAndreas Gohr            $tail = ftell($fp);
2430c3a5702SAndreas Gohr
2440c3a5702SAndreas Gohr            // chunk backwards
2450c3a5702SAndreas Gohr            $finger = max($tail - $this->chunk_size, 0);
2460c3a5702SAndreas Gohr            while ($count < $num + $first) {
2470c3a5702SAndreas Gohr                $nl = $this->getNewlinepointer($fp, $finger);
2480c3a5702SAndreas Gohr
2490c3a5702SAndreas Gohr                // was the chunk big enough? if not, take another bite
2500c3a5702SAndreas Gohr                if ($nl > 0 && $tail <= $nl) {
2510c3a5702SAndreas Gohr                    $finger = max($finger - $this->chunk_size, 0);
2520c3a5702SAndreas Gohr                    continue;
2530c3a5702SAndreas Gohr                } else {
2540c3a5702SAndreas Gohr                    $finger = $nl;
2550c3a5702SAndreas Gohr                }
2560c3a5702SAndreas Gohr
2570c3a5702SAndreas Gohr                // read chunk
2580c3a5702SAndreas Gohr                $chunk = '';
2590c3a5702SAndreas Gohr                $read_size = max($tail - $finger, 0); // found chunk size
2600c3a5702SAndreas Gohr                $got = 0;
2610c3a5702SAndreas Gohr                while ($got < $read_size && !feof($fp)) {
2620c3a5702SAndreas Gohr                    $tmp = @fread($fp, max(min($this->chunk_size, $read_size - $got), 0));
2630c3a5702SAndreas Gohr                    if ($tmp === false) {
2640c3a5702SAndreas Gohr                        break;
2650c3a5702SAndreas Gohr                    } //error state
2660c3a5702SAndreas Gohr                    $got += strlen($tmp);
2670c3a5702SAndreas Gohr                    $chunk .= $tmp;
2680c3a5702SAndreas Gohr                }
2690c3a5702SAndreas Gohr                $tmp = explode("\n", $chunk);
2700c3a5702SAndreas Gohr                array_pop($tmp); // remove trailing newline
2710c3a5702SAndreas Gohr
2720c3a5702SAndreas Gohr                // combine with previous chunk
2730c3a5702SAndreas Gohr                $count += count($tmp);
2740603e565SAndreas Gohr                $lines = [...$tmp, ...$lines];
2750c3a5702SAndreas Gohr
2760c3a5702SAndreas Gohr                // next chunk
2770c3a5702SAndreas Gohr                if ($finger == 0) {
2780c3a5702SAndreas Gohr                    break;
279e24a74c0SAndreas Gohr                } else { // already read all the lines
2800c3a5702SAndreas Gohr                    $tail = $finger;
2810c3a5702SAndreas Gohr                    $finger = max($tail - $this->chunk_size, 0);
2820c3a5702SAndreas Gohr                }
2830c3a5702SAndreas Gohr            }
2840c3a5702SAndreas Gohr            fclose($fp);
2850c3a5702SAndreas Gohr        }
2860c3a5702SAndreas Gohr
2870c3a5702SAndreas Gohr        // skip parsing extra lines
2880c3a5702SAndreas Gohr        $num = max(min(count($lines) - $first, $num), 0);
2890c3a5702SAndreas Gohr        if ($first > 0 && $num > 0) {
2900c3a5702SAndreas Gohr            $lines = array_slice($lines, max(count($lines) - $first - $num, 0), $num);
291df7627d6SSatoshi Sahara        } elseif ($first > 0 && $num == 0) {
2920c3a5702SAndreas Gohr            $lines = array_slice($lines, 0, max(count($lines) - $first, 0));
2930c3a5702SAndreas Gohr        } elseif ($first == 0 && $num > 0) {
2940c3a5702SAndreas Gohr            $lines = array_slice($lines, max(count($lines) - $num, 0));
2950c3a5702SAndreas Gohr        }
2960c3a5702SAndreas Gohr
2970c3a5702SAndreas Gohr        // handle lines in reverse order
2980c3a5702SAndreas Gohr        for ($i = count($lines) - 1; $i >= 0; $i--) {
299*a835c93aSGerrit Uitslag            $info = $this->parseAndCacheLogLine($lines[$i]);
300*a835c93aSGerrit Uitslag            if (is_array($info)) {
301bd17ac90SSatoshi Sahara                $revs[] = $info['date'];
3020c3a5702SAndreas Gohr            }
3030c3a5702SAndreas Gohr        }
3040c3a5702SAndreas Gohr
3050c3a5702SAndreas Gohr        return $revs;
3060c3a5702SAndreas Gohr    }
3070c3a5702SAndreas Gohr
3080c3a5702SAndreas Gohr    /**
309eeda7adaSGerrit Uitslag     * Get the nth revision left or right-hand side  for a specific page id and revision (timestamp)
3100c3a5702SAndreas Gohr     *
3110c3a5702SAndreas Gohr     * For large changelog files, only the chunk containing the
312eeda7adaSGerrit Uitslag     * reference revision $rev is read and sometimes a next chunk.
3130c3a5702SAndreas Gohr     *
3140c3a5702SAndreas Gohr     * Adjacent changelog lines are optimistically parsed and cached to speed up
3150c3a5702SAndreas Gohr     * consecutive calls to getRevisionInfo.
3160c3a5702SAndreas Gohr     *
317d154755dSSatoshi Sahara     * @param int $rev revision timestamp used as start date
318d154755dSSatoshi Sahara     *    (doesn't need to be exact revision number)
319d154755dSSatoshi Sahara     * @param int $direction give position of returned revision with respect to $rev;
320d154755dSSatoshi Sahara          positive=next, negative=prev
3210c3a5702SAndreas Gohr     * @return bool|int
3220c3a5702SAndreas Gohr     *      timestamp of the requested revision
3230c3a5702SAndreas Gohr     *      otherwise false
3240c3a5702SAndreas Gohr     */
3250c3a5702SAndreas Gohr    public function getRelativeRevision($rev, $direction)
3260c3a5702SAndreas Gohr    {
3270c3a5702SAndreas Gohr        $rev = max($rev, 0);
3280c3a5702SAndreas Gohr        $direction = (int)$direction;
3290c3a5702SAndreas Gohr
3300c3a5702SAndreas Gohr        //no direction given or last rev, so no follow-up
3310c3a5702SAndreas Gohr        if (!$direction || ($direction > 0 && $this->isCurrentRevision($rev))) {
3320c3a5702SAndreas Gohr            return false;
3330c3a5702SAndreas Gohr        }
3340c3a5702SAndreas Gohr
3350c3a5702SAndreas Gohr        //get lines from changelog
3360603e565SAndreas Gohr        [$fp, $lines, $head, $tail, $eof] = $this->readloglines($rev);
3370c3a5702SAndreas Gohr        if (empty($lines)) return false;
3380c3a5702SAndreas Gohr
3395d9428a0SSatoshi Sahara        // look for revisions later/earlier than $rev, when founded count till the wanted revision is reached
3400c3a5702SAndreas Gohr        // also parse and cache changelog lines for getRevisionInfo().
341eeda7adaSGerrit Uitslag        $revCounter = 0;
342eeda7adaSGerrit Uitslag        $relativeRev = false;
343eeda7adaSGerrit Uitslag        $checkOtherChunk = true; //always runs once
344eeda7adaSGerrit Uitslag        while (!$relativeRev && $checkOtherChunk) {
3450603e565SAndreas Gohr            $info = [];
3460c3a5702SAndreas Gohr            //parse in normal or reverse order
3470c3a5702SAndreas Gohr            $count = count($lines);
3480c3a5702SAndreas Gohr            if ($direction > 0) {
3490c3a5702SAndreas Gohr                $start = 0;
3500c3a5702SAndreas Gohr                $step = 1;
3510c3a5702SAndreas Gohr            } else {
3520c3a5702SAndreas Gohr                $start = $count - 1;
3530c3a5702SAndreas Gohr                $step = -1;
3540c3a5702SAndreas Gohr            }
3550603e565SAndreas Gohr            for ($i = $start; $i >= 0 && $i < $count; $i += $step) {
356*a835c93aSGerrit Uitslag                $info = $this->parseAndCacheLogLine($lines[$i]);
357*a835c93aSGerrit Uitslag                if (is_array($info)) {
3580c3a5702SAndreas Gohr                    //look for revs older/earlier then reference $rev and select $direction-th one
359bd17ac90SSatoshi Sahara                    if (($direction > 0 && $info['date'] > $rev) || ($direction < 0 && $info['date'] < $rev)) {
360eeda7adaSGerrit Uitslag                        $revCounter++;
361eeda7adaSGerrit Uitslag                        if ($revCounter == abs($direction)) {
362eeda7adaSGerrit Uitslag                            $relativeRev = $info['date'];
3630c3a5702SAndreas Gohr                        }
3640c3a5702SAndreas Gohr                    }
3650c3a5702SAndreas Gohr                }
3660c3a5702SAndreas Gohr            }
3670c3a5702SAndreas Gohr
3680c3a5702SAndreas Gohr            //true when $rev is found, but not the wanted follow-up.
369eeda7adaSGerrit Uitslag            $checkOtherChunk = $fp
370eeda7adaSGerrit Uitslag                && ($info['date'] == $rev || ($revCounter > 0 && !$relativeRev))
3710603e565SAndreas Gohr                && (!($tail == $eof && $direction > 0) && !($head == 0 && $direction < 0));
3720c3a5702SAndreas Gohr
373eeda7adaSGerrit Uitslag            if ($checkOtherChunk) {
3740603e565SAndreas Gohr                [$lines, $head, $tail] = $this->readAdjacentChunk($fp, $head, $tail, $direction);
3750c3a5702SAndreas Gohr
3760c3a5702SAndreas Gohr                if (empty($lines)) break;
3770c3a5702SAndreas Gohr            }
3780c3a5702SAndreas Gohr        }
3790c3a5702SAndreas Gohr        if ($fp) {
3800c3a5702SAndreas Gohr            fclose($fp);
3810c3a5702SAndreas Gohr        }
3820c3a5702SAndreas Gohr
383eeda7adaSGerrit Uitslag        return $relativeRev;
3840c3a5702SAndreas Gohr    }
3850c3a5702SAndreas Gohr
3860c3a5702SAndreas Gohr    /**
3870c3a5702SAndreas Gohr     * Returns revisions around rev1 and rev2
3880c3a5702SAndreas Gohr     * When available it returns $max entries for each revision
3890c3a5702SAndreas Gohr     *
3900c3a5702SAndreas Gohr     * @param int $rev1 oldest revision timestamp
3910c3a5702SAndreas Gohr     * @param int $rev2 newest revision timestamp (0 looks up last revision)
3920c3a5702SAndreas Gohr     * @param int $max maximum number of revisions returned
3930c3a5702SAndreas Gohr     * @return array with two arrays with revisions surrounding rev1 respectively rev2
3940c3a5702SAndreas Gohr     */
3950c3a5702SAndreas Gohr    public function getRevisionsAround($rev1, $rev2, $max = 50)
3960c3a5702SAndreas Gohr    {
3970603e565SAndreas Gohr        $max = (int) (abs($max) / 2) * 2 + 1;
3980c3a5702SAndreas Gohr        $rev1 = max($rev1, 0);
3990c3a5702SAndreas Gohr        $rev2 = max($rev2, 0);
4000c3a5702SAndreas Gohr
4010c3a5702SAndreas Gohr        if ($rev2) {
4020c3a5702SAndreas Gohr            if ($rev2 < $rev1) {
4030c3a5702SAndreas Gohr                $rev = $rev2;
4040c3a5702SAndreas Gohr                $rev2 = $rev1;
4050c3a5702SAndreas Gohr                $rev1 = $rev;
4060c3a5702SAndreas Gohr            }
4070c3a5702SAndreas Gohr        } else {
4080c3a5702SAndreas Gohr            //empty right side means a removed page. Look up last revision.
409bd17ac90SSatoshi Sahara            $rev2 = $this->currentRevision();
4100c3a5702SAndreas Gohr        }
4110c3a5702SAndreas Gohr        //collect revisions around rev2
4120603e565SAndreas Gohr        [$revs2, $allRevs, $fp, $lines, $head, $tail] = $this->retrieveRevisionsAround($rev2, $max);
4130c3a5702SAndreas Gohr
4140603e565SAndreas Gohr        if (empty($revs2)) return [[], []];
4150c3a5702SAndreas Gohr
4160c3a5702SAndreas Gohr        //collect revisions around rev1
4170f8604a9SAndreas Gohr        $index = array_search($rev1, $allRevs);
4180c3a5702SAndreas Gohr        if ($index === false) {
4190c3a5702SAndreas Gohr            //no overlapping revisions
4200603e565SAndreas Gohr            [$revs1, , , , , ] = $this->retrieveRevisionsAround($rev1, $max);
4210603e565SAndreas Gohr            if (empty($revs1)) $revs1 = [];
4220c3a5702SAndreas Gohr        } else {
4230c3a5702SAndreas Gohr            //revisions overlaps, reuse revisions around rev2
424eeda7adaSGerrit Uitslag            $lastRev = array_pop($allRevs); //keep last entry that could be external edit
425eeda7adaSGerrit Uitslag            $revs1 = $allRevs;
4260c3a5702SAndreas Gohr            while ($head > 0) {
4270c3a5702SAndreas Gohr                for ($i = count($lines) - 1; $i >= 0; $i--) {
428*a835c93aSGerrit Uitslag                    $info = $this->parseAndCacheLogLine($lines[$i]);
429*a835c93aSGerrit Uitslag                    if (is_array($info)) {
430bd17ac90SSatoshi Sahara                        $revs1[] = $info['date'];
4310c3a5702SAndreas Gohr                        $index++;
4320c3a5702SAndreas Gohr
4330603e565SAndreas Gohr                        if ($index > (int) ($max / 2)) break 2;
4340c3a5702SAndreas Gohr                    }
4350c3a5702SAndreas Gohr                }
4360c3a5702SAndreas Gohr
4370603e565SAndreas Gohr                [$lines, $head, $tail] = $this->readAdjacentChunk($fp, $head, $tail, -1);
4380c3a5702SAndreas Gohr            }
4390c3a5702SAndreas Gohr            sort($revs1);
440eeda7adaSGerrit Uitslag            $revs1[] = $lastRev; //push back last entry
4415d9428a0SSatoshi Sahara
4420c3a5702SAndreas Gohr            //return wanted selection
4430603e565SAndreas Gohr            $revs1 = array_slice($revs1, max($index - (int) ($max / 2), 0), $max);
4440c3a5702SAndreas Gohr        }
4450c3a5702SAndreas Gohr
4460603e565SAndreas Gohr        return [array_reverse($revs1), array_reverse($revs2)];
4470c3a5702SAndreas Gohr    }
4480c3a5702SAndreas Gohr
4490c3a5702SAndreas Gohr    /**
4500c3a5702SAndreas Gohr     * Return an existing revision for a specific date which is
4510c3a5702SAndreas Gohr     * the current one or younger or equal then the date
4520c3a5702SAndreas Gohr     *
4530c3a5702SAndreas Gohr     * @param number $date_at timestamp
4540c3a5702SAndreas Gohr     * @return string revision ('' for current)
4550c3a5702SAndreas Gohr     */
4560c3a5702SAndreas Gohr    public function getLastRevisionAt($date_at)
4570c3a5702SAndreas Gohr    {
458d154755dSSatoshi Sahara        $fileLastMod = $this->getFilename();
4590c3a5702SAndreas Gohr        //requested date_at(timestamp) younger or equal then modified_time($this->id) => load current
460d154755dSSatoshi Sahara        if (file_exists($fileLastMod) && $date_at >= @filemtime($fileLastMod)) {
4610c3a5702SAndreas Gohr            return '';
4620603e565SAndreas Gohr        } elseif ($rev = $this->getRelativeRevision($date_at + 1, -1)) {
4630603e565SAndreas Gohr            //+1 to get also the requested date revision
4640c3a5702SAndreas Gohr            return $rev;
4650c3a5702SAndreas Gohr        } else {
4660c3a5702SAndreas Gohr            return false;
4670c3a5702SAndreas Gohr        }
4680c3a5702SAndreas Gohr    }
4690c3a5702SAndreas Gohr
4700c3a5702SAndreas Gohr    /**
4710c3a5702SAndreas Gohr     * Collect the $max revisions near to the timestamp $rev
4720c3a5702SAndreas Gohr     *
473bd17ac90SSatoshi Sahara     * Ideally, half of retrieved timestamps are older than $rev, another half are newer.
474eeda7adaSGerrit Uitslag     * The returned array $requestedRevs may not contain the reference timestamp $rev
475bd17ac90SSatoshi Sahara     * when it does not match any revision value recorded in changelog.
476bd17ac90SSatoshi Sahara     *
4770c3a5702SAndreas Gohr     * @param int $rev revision timestamp
4780c3a5702SAndreas Gohr     * @param int $max maximum number of revisions to be returned
4790c3a5702SAndreas Gohr     * @return bool|array
4800c3a5702SAndreas Gohr     *     return array with entries:
481eeda7adaSGerrit Uitslag     *       - $requestedRevs: array of with $max revision timestamps
4820c3a5702SAndreas Gohr     *       - $revs: all parsed revision timestamps
4830c3a5702SAndreas Gohr     *       - $fp: file pointer only defined for chuck reading, needs closing.
4840c3a5702SAndreas Gohr     *       - $lines: non-parsed changelog lines before the parsed revisions
485eeda7adaSGerrit Uitslag     *       - $head: position of first read changelog line
486eeda7adaSGerrit Uitslag     *       - $lastTail: position of end of last read changelog line
4870c3a5702SAndreas Gohr     *     otherwise false
4880c3a5702SAndreas Gohr     */
4890c3a5702SAndreas Gohr    protected function retrieveRevisionsAround($rev, $max)
4900c3a5702SAndreas Gohr    {
4910603e565SAndreas Gohr        $revs = [];
4920603e565SAndreas Gohr        $afterCount = 0;
4930603e565SAndreas Gohr        $beforeCount = 0;
494a3984ddfSSatoshi Sahara
4950c3a5702SAndreas Gohr        //get lines from changelog
4960603e565SAndreas Gohr        [$fp, $lines, $startHead, $startTail, $eof] = $this->readloglines($rev);
497bd17ac90SSatoshi Sahara        if (empty($lines)) return false;
4980c3a5702SAndreas Gohr
499bd17ac90SSatoshi Sahara        //parse changelog lines in chunk, and read forward more chunks until $max/2 is reached
500eeda7adaSGerrit Uitslag        $head = $startHead;
501eeda7adaSGerrit Uitslag        $tail = $startTail;
5020c3a5702SAndreas Gohr        while (count($lines) > 0) {
5030c3a5702SAndreas Gohr            foreach ($lines as $line) {
504*a835c93aSGerrit Uitslag                $info = $this->parseAndCacheLogLine($line);
505*a835c93aSGerrit Uitslag                if (is_array($info)) {
506bd17ac90SSatoshi Sahara                    $revs[] = $info['date'];
507bd17ac90SSatoshi Sahara                    if ($info['date'] >= $rev) {
5080c3a5702SAndreas Gohr                        //count revs after reference $rev
509eeda7adaSGerrit Uitslag                        $afterCount++;
510eeda7adaSGerrit Uitslag                        if ($afterCount == 1) $beforeCount = count($revs);
5110c3a5702SAndreas Gohr                    }
5120c3a5702SAndreas Gohr                    //enough revs after reference $rev?
5130603e565SAndreas Gohr                    if ($afterCount > (int) ($max / 2)) break 2;
5140c3a5702SAndreas Gohr                }
5150c3a5702SAndreas Gohr            }
5160c3a5702SAndreas Gohr            //retrieve next chunk
5170603e565SAndreas Gohr            [$lines, $head, $tail] = $this->readAdjacentChunk($fp, $head, $tail, 1);
5180c3a5702SAndreas Gohr        }
519eeda7adaSGerrit Uitslag        $lastTail = $tail;
5200c3a5702SAndreas Gohr
521bd17ac90SSatoshi Sahara        // add a possible revision of external edit, create or deletion
5227d34963bSAndreas Gohr        if (
5237d34963bSAndreas Gohr            $lastTail == $eof && $afterCount <= (int) ($max / 2) &&
524df7627d6SSatoshi Sahara            count($revs) && !$this->isCurrentRevision($revs[count($revs) - 1])
525df7627d6SSatoshi Sahara        ) {
526bd17ac90SSatoshi Sahara            $revs[] = $this->currentRevision;
527eeda7adaSGerrit Uitslag            $afterCount++;
528bd17ac90SSatoshi Sahara        }
529bd17ac90SSatoshi Sahara
530eeda7adaSGerrit Uitslag        if ($afterCount == 0) {
531bd17ac90SSatoshi Sahara            //given timestamp $rev is newer than the most recent line in chunk
532bd17ac90SSatoshi Sahara            return false; //FIXME: or proceed to collect older revisions?
533bd17ac90SSatoshi Sahara        }
534bd17ac90SSatoshi Sahara
535bd17ac90SSatoshi Sahara        //read more chunks backward until $max/2 is reached and total number of revs is equal to $max
5360603e565SAndreas Gohr        $lines = [];
5370c3a5702SAndreas Gohr        $i = 0;
538eeda7adaSGerrit Uitslag        $head = $startHead;
539eeda7adaSGerrit Uitslag        $tail = $startTail;
5400c3a5702SAndreas Gohr        while ($head > 0) {
5410603e565SAndreas Gohr            [$lines, $head, $tail] = $this->readAdjacentChunk($fp, $head, $tail, -1);
5420c3a5702SAndreas Gohr
5430c3a5702SAndreas Gohr            for ($i = count($lines) - 1; $i >= 0; $i--) {
544*a835c93aSGerrit Uitslag                $info = $this->parseAndCacheLogLine($lines[$i]);
545*a835c93aSGerrit Uitslag                if (is_array($info)) {
546bd17ac90SSatoshi Sahara                    $revs[] = $info['date'];
547eeda7adaSGerrit Uitslag                    $beforeCount++;
5480c3a5702SAndreas Gohr                    //enough revs before reference $rev?
5490603e565SAndreas Gohr                    if ($beforeCount > max((int) ($max / 2), $max - $afterCount)) break 2;
5500c3a5702SAndreas Gohr                }
5510c3a5702SAndreas Gohr            }
5520c3a5702SAndreas Gohr        }
5530c3a5702SAndreas Gohr        //keep only non-parsed lines
5540c3a5702SAndreas Gohr        $lines = array_slice($lines, 0, $i);
555bd17ac90SSatoshi Sahara
556bd17ac90SSatoshi Sahara        sort($revs);
557bd17ac90SSatoshi Sahara
5580c3a5702SAndreas Gohr        //trunk desired selection
559eeda7adaSGerrit Uitslag        $requestedRevs = array_slice($revs, -$max, $max);
5600c3a5702SAndreas Gohr
5610603e565SAndreas Gohr        return [$requestedRevs, $revs, $fp, $lines, $head, $lastTail];
5620c3a5702SAndreas Gohr    }
563a3984ddfSSatoshi Sahara
564a3984ddfSSatoshi Sahara    /**
565bd17ac90SSatoshi Sahara     * Get the current revision information, considering external edit, create or deletion
566bd17ac90SSatoshi Sahara     *
567a19054e9SSatoshi Sahara     * When the file has not modified since its last revision, the information of the last
56805282e9fSSatoshi Sahara     * change that had already recorded in the changelog is returned as current change info.
569a19054e9SSatoshi Sahara     * Otherwise, the change information since the last revision caused outside DokuWiki
57005282e9fSSatoshi Sahara     * should be returned, which is referred as "external revision".
571bd17ac90SSatoshi Sahara     *
57205282e9fSSatoshi Sahara     * The change date of the file can be determined by timestamp as far as the file exists,
57305282e9fSSatoshi Sahara     * however this is not possible when the file has already deleted outside of DokuWiki.
57466f4cdd4SSatoshi Sahara     * In such case we assign 1 sec before current time() for the external deletion.
57505282e9fSSatoshi Sahara     * As a result, the value of current revision identifier may change each time because:
57605282e9fSSatoshi Sahara     *   1) the file has again modified outside of DokuWiki, or
57705282e9fSSatoshi Sahara     *   2) the value is essentially volatile for deleted but once existed files.
578bd17ac90SSatoshi Sahara     *
579bd17ac90SSatoshi Sahara     * @return bool|array false when page had never existed or array with entries:
580bd17ac90SSatoshi Sahara     *      - date:  revision identifier (timestamp or last revision +1)
581bd17ac90SSatoshi Sahara     *      - ip:    IPv4 address (127.0.0.1)
582bd17ac90SSatoshi Sahara     *      - type:  log line type
583bd17ac90SSatoshi Sahara     *      - id:    id of page or media
584bd17ac90SSatoshi Sahara     *      - user:  user name
585bd17ac90SSatoshi Sahara     *      - sum:   edit summary (or action reason)
586bd17ac90SSatoshi Sahara     *      - extra: extra data (varies by line type)
587bd17ac90SSatoshi Sahara     *      - sizechange: change of filesize
588dbf582ddSSatoshi Sahara     *      - timestamp: unix timestamp or false (key set only for external edit occurred)
589*a835c93aSGerrit Uitslag     *   additional:
590*a835c93aSGerrit Uitslag     *      - mode:  page or media
591bd17ac90SSatoshi Sahara     *
592bd17ac90SSatoshi Sahara     * @author  Satoshi Sahara <sahara.satoshi@gmail.com>
593bd17ac90SSatoshi Sahara     */
594bd17ac90SSatoshi Sahara    public function getCurrentRevisionInfo()
595bd17ac90SSatoshi Sahara    {
596bd17ac90SSatoshi Sahara        global $lang;
597bd17ac90SSatoshi Sahara
598bd17ac90SSatoshi Sahara        if (isset($this->currentRevision)) return $this->getRevisionInfo($this->currentRevision);
599bd17ac90SSatoshi Sahara
600eeda7adaSGerrit Uitslag        // get revision id from the item file timestamp and changelog
601dbf582ddSSatoshi Sahara        $fileLastMod = $this->getFilename();
602dbf582ddSSatoshi Sahara        $fileRev = @filemtime($fileLastMod); // false when the file not exist
603df7627d6SSatoshi Sahara        $lastRev = $this->lastRevision();    // false when no changelog
604bd17ac90SSatoshi Sahara
605df7627d6SSatoshi Sahara        if (!$fileRev && !$lastRev) {                // has never existed
606df7627d6SSatoshi Sahara            $this->currentRevision = false;
607bd17ac90SSatoshi Sahara            return false;
608bd17ac90SSatoshi Sahara        } elseif ($fileRev === $lastRev) {           // not external edit
609bd17ac90SSatoshi Sahara            $this->currentRevision = $lastRev;
6105ec96136SSatoshi Sahara            return $this->getRevisionInfo($lastRev);
611bd17ac90SSatoshi Sahara        }
612bd17ac90SSatoshi Sahara
613bd17ac90SSatoshi Sahara        if (!$fileRev && $lastRev) {                 // item file does not exist
614bd17ac90SSatoshi Sahara            // check consistency against changelog
61586216bf0SGerrit Uitslag            $revInfo = $this->getRevisionInfo($lastRev, false);
616bd17ac90SSatoshi Sahara            if ($revInfo['type'] == DOKU_CHANGE_TYPE_DELETE) {
617bd17ac90SSatoshi Sahara                $this->currentRevision = $lastRev;
61854d95e36SGerrit Uitslag                return $revInfo;
619bd17ac90SSatoshi Sahara            }
620bd17ac90SSatoshi Sahara
62166f4cdd4SSatoshi Sahara            // externally deleted, set revision date as late as possible
622bd17ac90SSatoshi Sahara            $revInfo = [
62366f4cdd4SSatoshi Sahara                'date' => max($lastRev + 1, time() - 1), // 1 sec before now or new page save
624bd17ac90SSatoshi Sahara                'ip'   => '127.0.0.1',
625bd17ac90SSatoshi Sahara                'type' => DOKU_CHANGE_TYPE_DELETE,
626bd17ac90SSatoshi Sahara                'id'   => $this->id,
627bd17ac90SSatoshi Sahara                'user' => '',
628df7627d6SSatoshi Sahara                'sum'  => $lang['deleted'] . ' - ' . $lang['external_edit'] . ' (' . $lang['unknowndate'] . ')',
629bd17ac90SSatoshi Sahara                'extra' => '',
6306e695190SAndreas Gohr                'sizechange' => -io_getSizeFile($this->getFilename($lastRev)),
631dbf582ddSSatoshi Sahara                'timestamp' => false,
632*a835c93aSGerrit Uitslag                'mode' => $this->getMode()
633bd17ac90SSatoshi Sahara            ];
6340b5bb6b4SGerrit Uitslag        } else {                                     // item file exists, with timestamp $fileRev
63554d95e36SGerrit Uitslag            // here, file timestamp $fileRev is different with last revision timestamp $lastRev in changelog
636df7627d6SSatoshi Sahara            $isJustCreated = $lastRev === false || (
637e39c2efbSSatoshi Sahara                    $fileRev > $lastRev &&
63886216bf0SGerrit Uitslag                    $this->getRevisionInfo($lastRev, false)['type'] == DOKU_CHANGE_TYPE_DELETE
639e39c2efbSSatoshi Sahara            );
640bd17ac90SSatoshi Sahara            $filesize_new = filesize($this->getFilename());
6416e695190SAndreas Gohr            $filesize_old = $isJustCreated ? 0 : io_getSizeFile($this->getFilename($lastRev));
642bd17ac90SSatoshi Sahara            $sizechange = $filesize_new - $filesize_old;
643bd17ac90SSatoshi Sahara
644dbf582ddSSatoshi Sahara            if ($isJustCreated) {
6458ff5c11aSSatoshi Sahara                $timestamp = $fileRev;
646bd17ac90SSatoshi Sahara                $sum = $lang['created'] . ' - ' . $lang['external_edit'];
647bd17ac90SSatoshi Sahara            } elseif ($fileRev > $lastRev) {
6488ff5c11aSSatoshi Sahara                $timestamp = $fileRev;
649bd17ac90SSatoshi Sahara                $sum = $lang['external_edit'];
650bd17ac90SSatoshi Sahara            } else {
651eeda7adaSGerrit Uitslag                // $fileRev is older than $lastRev, that is erroneous/incorrect occurrence.
65266f4cdd4SSatoshi Sahara                $msg = "Warning: current file modification time is older than last revision date";
65310f359adSAndreas Gohr                $details = 'File revision: ' . $fileRev . ' ' . dformat($fileRev, "%Y-%m-%d %H:%M:%S") . "\n"
65410f359adSAndreas Gohr                          . 'Last revision: ' . $lastRev . ' ' . dformat($lastRev, "%Y-%m-%d %H:%M:%S");
65566f4cdd4SSatoshi Sahara                Logger::error($msg, $details, $this->getFilename());
65666f4cdd4SSatoshi Sahara                $timestamp = false;
657df7627d6SSatoshi Sahara                $sum = $lang['external_edit'] . ' (' . $lang['unknowndate'] . ')';
658bd17ac90SSatoshi Sahara            }
659bd17ac90SSatoshi Sahara
660bd17ac90SSatoshi Sahara            // externally created or edited
661bd17ac90SSatoshi Sahara            $revInfo = [
66266f4cdd4SSatoshi Sahara                'date' => $timestamp ?: $lastRev + 1,
663bd17ac90SSatoshi Sahara                'ip'   => '127.0.0.1',
664bd17ac90SSatoshi Sahara                'type' => $isJustCreated ? DOKU_CHANGE_TYPE_CREATE : DOKU_CHANGE_TYPE_EDIT,
665bd17ac90SSatoshi Sahara                'id'   => $this->id,
666bd17ac90SSatoshi Sahara                'user' => '',
667bd17ac90SSatoshi Sahara                'sum'  => $sum,
668bd17ac90SSatoshi Sahara                'extra' => '',
669bd17ac90SSatoshi Sahara                'sizechange' => $sizechange,
670bd17ac90SSatoshi Sahara                'timestamp' => $timestamp,
671*a835c93aSGerrit Uitslag                'mode' => $this->getMode()
672bd17ac90SSatoshi Sahara            ];
673bd17ac90SSatoshi Sahara        }
674bd17ac90SSatoshi Sahara
675bd17ac90SSatoshi Sahara        // cache current revision information of external edition
676bd17ac90SSatoshi Sahara        $this->currentRevision = $revInfo['date'];
677bd17ac90SSatoshi Sahara        $this->cache[$this->id][$this->currentRevision] = $revInfo;
678bd17ac90SSatoshi Sahara        return $this->getRevisionInfo($this->currentRevision);
679bd17ac90SSatoshi Sahara    }
680312e7095SSatoshi Sahara
681312e7095SSatoshi Sahara    /**
682312e7095SSatoshi Sahara     * Mechanism to trace no-actual external current revision
683312e7095SSatoshi Sahara     * @param int $rev
684312e7095SSatoshi Sahara     */
685312e7095SSatoshi Sahara    public function traceCurrentRevision($rev)
686312e7095SSatoshi Sahara    {
687312e7095SSatoshi Sahara        if ($rev > $this->lastRevision()) {
688312e7095SSatoshi Sahara            $rev = $this->currentRevision();
689312e7095SSatoshi Sahara        }
690312e7095SSatoshi Sahara        return $rev;
691312e7095SSatoshi Sahara    }
6920c3a5702SAndreas Gohr}
693