xref: /dokuwiki/inc/ChangeLog/ChangeLog.php (revision 63b227866ea0b85ebdda774ff73181e683443a0d)
1<?php
2
3namespace dokuwiki\ChangeLog;
4
5use dokuwiki\Logger;
6
7/**
8 * ChangeLog Prototype; methods for handling changelog
9 */
10abstract class ChangeLog
11{
12    use ChangeLogTrait;
13
14    /** @var string */
15    protected $id;
16    /** @var false|int */
17    protected $currentRevision;
18    /** @var array */
19    protected $cache = [];
20
21    /**
22     * Constructor
23     *
24     * @param string $id page id
25     * @param int $chunk_size maximum block size read from file
26     */
27    public function __construct($id, $chunk_size = 8192)
28    {
29        global $cache_revinfo;
30
31        $this->cache =& $cache_revinfo;
32        if (!isset($this->cache[$id])) {
33            $this->cache[$id] = [];
34        }
35
36        $this->id = $id;
37        $this->setChunkSize($chunk_size);
38    }
39
40    /**
41     * Returns path to current page/media
42     *
43     * @param string|int $rev empty string or revision timestamp
44     * @return string path to file
45     */
46    abstract protected function getFilename($rev = '');
47
48    /**
49     * Returns mode
50     *
51     * @return string RevisionInfo::MODE_MEDIA or RevisionInfo::MODE_PAGE
52     */
53    abstract protected function getMode();
54
55    /**
56     * Returns path to the global changelog file (the cross-page recent-changes feed)
57     *
58     * @return string path to file
59     */
60    abstract protected function getGlobalChangelogFilename();
61
62    /**
63     * Check whether given revision is the current page
64     *
65     * @param int $rev timestamp of current page
66     * @return bool true if $rev is current revision, otherwise false
67     */
68    public function isCurrentRevision($rev)
69    {
70        return $rev == $this->currentRevision();
71    }
72
73    /**
74     * Checks if the revision is last revision
75     *
76     * @param int $rev revision timestamp
77     * @return bool true if $rev is last revision, otherwise false
78     */
79    public function isLastRevision($rev = null)
80    {
81        return $rev === $this->lastRevision();
82    }
83
84    /**
85     * Return the current revision identifier
86     *
87     * The "current" revision means current version of the page or media file. It is either
88     * identical with or newer than the "last" revision, that depends on whether the file
89     * has modified, created or deleted outside of DokuWiki.
90     * The value of identifier can be determined by timestamp as far as the file exists,
91     * otherwise it must be assigned larger than any other revisions to keep them sortable.
92     *
93     * @return int|false revision timestamp
94     */
95    public function currentRevision()
96    {
97        if (!isset($this->currentRevision)) {
98            // set ChangeLog::currentRevision property
99            $this->getCurrentRevisionInfo();
100        }
101        return $this->currentRevision;
102    }
103
104    /**
105     * Return the last revision identifier, date value of the last entry of the changelog
106     *
107     * @return int|false revision timestamp
108     */
109    public function lastRevision()
110    {
111        $revs = $this->getRevisions(-1, 1);
112        return empty($revs) ? false : $revs[0];
113    }
114
115    /**
116     * Parses a changelog line into its components and save revision info to the cache pool
117     *
118     * @param string $value changelog line
119     * @return array|bool parsed line or false
120     */
121    protected function parseAndCacheLogLine($value)
122    {
123        $info = static::parseLogLine($value);
124        if (is_array($info)) {
125            $info['mode'] = $this->getMode();
126            $this->cache[$this->id][$info['date']] ??= $info;
127            return $info;
128        }
129        return false;
130    }
131
132    /**
133     * Get the changelog information for a specific revision (timestamp)
134     *
135     * Adjacent changelog lines are optimistically parsed and cached to speed up
136     * consecutive calls to getRevisionInfo. For large changelog files, only the chunk
137     * containing the requested changelog line is read.
138     *
139     * @param int $rev revision timestamp
140     * @param bool $retrieveCurrentRevInfo allows to skip for getting other revision info in the
141     *                                     getCurrentRevisionInfo() where $currentRevision is not yet determined
142     * @return bool|array false or array with entries:
143     *      - date:  unix timestamp
144     *      - ip:    IPv4 address (127.0.0.1)
145     *      - type:  log line type
146     *      - id:    page id
147     *      - user:  user name
148     *      - sum:   edit summary (or action reason)
149     *      - extra: extra data (varies by line type)
150     *      - sizechange: change of filesize
151     *    additional:
152     *      - mode: page or media
153     *
154     * @author Ben Coburn <btcoburn@silicodon.net>
155     * @author Kate Arzamastseva <pshns@ukr.net>
156     */
157    public function getRevisionInfo($rev, $retrieveCurrentRevInfo = true)
158    {
159        $rev = max(0, $rev);
160        if (!$rev) return false;
161
162        //ensure the external edits are cached as well
163        if (!isset($this->currentRevision) && $retrieveCurrentRevInfo) {
164            $this->getCurrentRevisionInfo();
165        }
166
167        // check if it's already in the memory cache
168        if (isset($this->cache[$this->id][$rev])) {
169            return $this->cache[$this->id][$rev];
170        }
171
172        //read lines from changelog
173        $result = $this->readloglines($rev);
174        if ($result === false) return false;
175        [$fp, $lines] = $result;
176        if ($fp) {
177            fclose($fp);
178        }
179        if (empty($lines)) return false;
180
181        // parse and cache changelog lines
182        foreach ($lines as $line) {
183            $this->parseAndCacheLogLine($line);
184        }
185
186        return $this->cache[$this->id][$rev] ?? false;
187    }
188
189    /**
190     * Return a list of page revisions numbers
191     *
192     * Does not guarantee that the revision exists in the attic,
193     * only that a line with the date exists in the changelog.
194     * By default the current revision is skipped.
195     *
196     * The current revision is automatically skipped when the page exists.
197     * See $INFO['meta']['last_change'] for the current revision.
198     * A negative $first let read the current revision too.
199     *
200     * For efficiency, the log lines are parsed and cached for later
201     * calls to getRevisionInfo. Large changelog files are read
202     * backwards in chunks until the requested number of changelog
203     * lines are received.
204     *
205     * @param int $first skip the first n changelog lines
206     * @param int $num number of revisions to return
207     * @return array with the revision timestamps
208     *
209     * @author Ben Coburn <btcoburn@silicodon.net>
210     * @author Kate Arzamastseva <pshns@ukr.net>
211     */
212    public function getRevisions($first, $num)
213    {
214        $revs = [];
215        $lines = [];
216        $count = 0;
217
218        $logfile = $this->getChangelogFilename();
219        if (!file_exists($logfile)) return $revs;
220
221        $num = max($num, 0);
222        if ($num == 0) {
223            return $revs;
224        }
225
226        if ($first < 0) {
227            $first = 0;
228        } else {
229            $fileLastMod = $this->getFilename();
230            if (file_exists($fileLastMod) && $this->isLastRevision(filemtime($fileLastMod))) {
231                // skip last revision if the page exists
232                $first = max($first + 1, 0);
233            }
234        }
235
236        if (filesize($logfile) < $this->chunk_size || $this->chunk_size == 0) {
237            // read whole file
238            $lines = file($logfile);
239            if ($lines === false) {
240                return $revs;
241            }
242        } else {
243            // read chunks backwards
244            $fp = fopen($logfile, 'rb'); // "file pointer"
245            if ($fp === false) {
246                return $revs;
247            }
248            fseek($fp, 0, SEEK_END);
249            $tail = ftell($fp);
250
251            // chunk backwards
252            $finger = max($tail - $this->chunk_size, 0);
253            while ($count < $num + $first) {
254                $nl = $this->getNewlinepointer($fp, $finger);
255
256                // was the chunk big enough? if not, take another bite
257                if ($nl > 0 && $tail <= $nl) {
258                    $finger = max($finger - $this->chunk_size, 0);
259                    continue;
260                } else {
261                    $finger = $nl;
262                }
263
264                // read chunk
265                $chunk = '';
266                $read_size = max($tail - $finger, 0); // found chunk size
267                $got = 0;
268                while ($got < $read_size && !feof($fp)) {
269                    $tmp = @fread($fp, max(min($this->chunk_size, $read_size - $got), 0));
270                    if ($tmp === false) {
271                        break;
272                    } //error state
273                    $got += strlen($tmp);
274                    $chunk .= $tmp;
275                }
276                $tmp = explode("\n", $chunk);
277                array_pop($tmp); // remove trailing newline
278
279                // combine with previous chunk
280                $count += count($tmp);
281                $lines = [...$tmp, ...$lines];
282
283                // next chunk
284                if ($finger == 0) {
285                    break;
286                } else { // already read all the lines
287                    $tail = $finger;
288                    $finger = max($tail - $this->chunk_size, 0);
289                }
290            }
291            fclose($fp);
292        }
293
294        // skip parsing extra lines
295        $num = max(min(count($lines) - $first, $num), 0);
296        if ($first > 0 && $num > 0) {
297            $lines = array_slice($lines, max(count($lines) - $first - $num, 0), $num);
298        } elseif ($first > 0 && $num == 0) {
299            $lines = array_slice($lines, 0, max(count($lines) - $first, 0));
300        } elseif ($first == 0 && $num > 0) {
301            $lines = array_slice($lines, max(count($lines) - $num, 0));
302        }
303
304        // handle lines in reverse order
305        for ($i = count($lines) - 1; $i >= 0; $i--) {
306            $info = $this->parseAndCacheLogLine($lines[$i]);
307            if (is_array($info)) {
308                $revs[] = $info['date'];
309            }
310        }
311
312        return $revs;
313    }
314
315    /**
316     * Get the nth revision left or right-hand side  for a specific page id and revision (timestamp)
317     *
318     * For large changelog files, only the chunk containing the
319     * reference revision $rev is read and sometimes a next chunk.
320     *
321     * Adjacent changelog lines are optimistically parsed and cached to speed up
322     * consecutive calls to getRevisionInfo.
323     *
324     * @param int $rev revision timestamp used as start date
325     *    (doesn't need to be exact revision number)
326     * @param int $direction give position of returned revision with respect to $rev;
327          positive=next, negative=prev
328     * @return bool|int
329     *      timestamp of the requested revision
330     *      otherwise false
331     */
332    public function getRelativeRevision($rev, $direction)
333    {
334        $rev = max($rev, 0);
335        $direction = (int)$direction;
336
337        //no direction given or last rev, so no follow-up
338        if (!$direction || ($direction > 0 && $this->isCurrentRevision($rev))) {
339            return false;
340        }
341
342        //get lines from changelog
343        $result = $this->readloglines($rev);
344        if ($result === false) return false;
345        [$fp, $lines, $head, $tail, $eof] = $result;
346        if (empty($lines)) return false;
347
348        // look for revisions later/earlier than $rev, when founded count till the wanted revision is reached
349        // also parse and cache changelog lines for getRevisionInfo().
350        $revCounter = 0;
351        $relativeRev = false;
352        $checkOtherChunk = true; //always runs once
353        while (!$relativeRev && $checkOtherChunk) {
354            $info = [];
355            //parse in normal or reverse order
356            $count = count($lines);
357            if ($direction > 0) {
358                $start = 0;
359                $step = 1;
360            } else {
361                $start = $count - 1;
362                $step = -1;
363            }
364            for ($i = $start; $i >= 0 && $i < $count; $i += $step) {
365                $info = $this->parseAndCacheLogLine($lines[$i]);
366                if (is_array($info)) {
367                    //look for revs older/earlier then reference $rev and select $direction-th one
368                    if (($direction > 0 && $info['date'] > $rev) || ($direction < 0 && $info['date'] < $rev)) {
369                        $revCounter++;
370                        if ($revCounter == abs($direction)) {
371                            $relativeRev = $info['date'];
372                        }
373                    }
374                }
375            }
376
377            //true when $rev is found, but not the wanted follow-up.
378            $checkOtherChunk = $fp
379                && ($info['date'] == $rev || ($revCounter > 0 && !$relativeRev))
380                && (!($tail == $eof && $direction > 0) && !($head == 0 && $direction < 0));
381
382            if ($checkOtherChunk) {
383                [$lines, $head, $tail] = $this->readAdjacentChunk($fp, $head, $tail, $direction);
384
385                if (empty($lines)) break;
386            }
387        }
388        if ($fp) {
389            fclose($fp);
390        }
391
392        return $relativeRev;
393    }
394
395    /**
396     * Returns revisions around rev1 and rev2
397     * When available it returns $max entries for each revision
398     *
399     * @param int $rev1 oldest revision timestamp
400     * @param int $rev2 newest revision timestamp (0 looks up last revision)
401     * @param int $max maximum number of revisions returned
402     * @return array with two arrays with revisions surrounding rev1 respectively rev2
403     */
404    public function getRevisionsAround($rev1, $rev2, $max = 50)
405    {
406        $max = (int) (abs($max) / 2) * 2 + 1;
407        $rev1 = max($rev1, 0);
408        $rev2 = max($rev2, 0);
409
410        if ($rev2) {
411            if ($rev2 < $rev1) {
412                $rev = $rev2;
413                $rev2 = $rev1;
414                $rev1 = $rev;
415            }
416        } else {
417            //empty right side means a removed page. Look up last revision.
418            $rev2 = $this->currentRevision();
419        }
420        //collect revisions around rev2
421        $result2 = $this->retrieveRevisionsAround($rev2, $max);
422        if ($result2 === false) return [[], []];
423        [$revs2, $allRevs, $fp, $lines, $head, $tail] = $result2;
424
425        if (empty($revs2)) return [[], []];
426
427        //collect revisions around rev1
428        $index = array_search($rev1, $allRevs);
429        if ($index === false) {
430            //no overlapping revisions
431            $result1 = $this->retrieveRevisionsAround($rev1, $max);
432            if ($result1 === false) {
433                $revs1 = [];
434            } else {
435                [$revs1, , , , , ] = $result1;
436                if (empty($revs1)) $revs1 = [];
437            }
438        } else {
439            //revisions overlaps, reuse revisions around rev2
440            $lastRev = array_pop($allRevs); //keep last entry that could be external edit
441            $revs1 = $allRevs;
442            while ($head > 0) {
443                for ($i = count($lines) - 1; $i >= 0; $i--) {
444                    $info = $this->parseAndCacheLogLine($lines[$i]);
445                    if (is_array($info)) {
446                        $revs1[] = $info['date'];
447                        $index++;
448
449                        if ($index > (int) ($max / 2)) {
450                            break 2;
451                        }
452                    }
453                }
454
455                [$lines, $head, $tail] = $this->readAdjacentChunk($fp, $head, $tail, -1);
456            }
457            sort($revs1);
458            $revs1[] = $lastRev; //push back last entry
459
460            //return wanted selection
461            $revs1 = array_slice($revs1, max($index - (int) ($max / 2), 0), $max);
462        }
463
464        return [array_reverse($revs1), array_reverse($revs2)];
465    }
466
467    /**
468     * Return an existing revision for a specific date which is
469     * the current one or younger or equal then the date
470     *
471     * @param number $date_at timestamp
472     * @return string revision ('' for current)
473     */
474    public function getLastRevisionAt($date_at)
475    {
476        $fileLastMod = $this->getFilename();
477        //requested date_at(timestamp) younger or equal then modified_time($this->id) => load current
478        if (file_exists($fileLastMod) && $date_at >= @filemtime($fileLastMod)) {
479            return '';
480        } elseif ($rev = $this->getRelativeRevision($date_at + 1, -1)) {
481            //+1 to get also the requested date revision
482            return $rev;
483        } else {
484            return false;
485        }
486    }
487
488    /**
489     * Collect the $max revisions near to the timestamp $rev
490     *
491     * Ideally, half of retrieved timestamps are older than $rev, another half are newer.
492     * The returned array $requestedRevs may not contain the reference timestamp $rev
493     * when it does not match any revision value recorded in changelog.
494     *
495     * @param int $rev revision timestamp
496     * @param int $max maximum number of revisions to be returned
497     * @return bool|array
498     *     return array with entries:
499     *       - $requestedRevs: array of with $max revision timestamps
500     *       - $revs: all parsed revision timestamps
501     *       - $fp: file pointer only defined for chuck reading, needs closing.
502     *       - $lines: non-parsed changelog lines before the parsed revisions
503     *       - $head: position of first read changelog line
504     *       - $lastTail: position of end of last read changelog line
505     *     otherwise false
506     */
507    protected function retrieveRevisionsAround($rev, $max)
508    {
509        $revs = [];
510        $afterCount = 0;
511        $beforeCount = 0;
512
513        //get lines from changelog
514        $result = $this->readloglines($rev);
515        if ($result === false) return false;
516        [$fp, $lines, $startHead, $startTail, $eof] = $result;
517        if (empty($lines)) return false;
518
519        //parse changelog lines in chunk, and read forward more chunks until $max/2 is reached
520        $head = $startHead;
521        $tail = $startTail;
522        while (count($lines) > 0) {
523            foreach ($lines as $line) {
524                $info = $this->parseAndCacheLogLine($line);
525                if (is_array($info)) {
526                    $revs[] = $info['date'];
527                    if ($info['date'] >= $rev) {
528                        //count revs after reference $rev
529                        $afterCount++;
530                        if ($afterCount == 1) {
531                            $beforeCount = count($revs);
532                        }
533                    }
534                    //enough revs after reference $rev?
535                    if ($afterCount > (int) ($max / 2)) {
536                        break 2;
537                    }
538                }
539            }
540            //retrieve next chunk
541            [$lines, $head, $tail] = $this->readAdjacentChunk($fp, $head, $tail, 1);
542        }
543        $lastTail = $tail;
544
545        // add a possible revision of external edit, create or deletion
546        if (
547            $lastTail == $eof && $afterCount <= (int) ($max / 2) &&
548            count($revs) && !$this->isCurrentRevision($revs[count($revs) - 1])
549        ) {
550            $revs[] = $this->currentRevision;
551            $afterCount++;
552        }
553
554        if ($afterCount == 0) {
555            //given timestamp $rev is newer than the most recent line in chunk
556            return false; //FIXME: or proceed to collect older revisions?
557        }
558
559        //read more chunks backward until $max/2 is reached and total number of revs is equal to $max
560        $lines = [];
561        $i = 0;
562        $head = $startHead;
563        $tail = $startTail;
564        while ($head > 0) {
565            [$lines, $head, $tail] = $this->readAdjacentChunk($fp, $head, $tail, -1);
566
567            for ($i = count($lines) - 1; $i >= 0; $i--) {
568                $info = $this->parseAndCacheLogLine($lines[$i]);
569                if (is_array($info)) {
570                    $revs[] = $info['date'];
571                    $beforeCount++;
572                    //enough revs before reference $rev?
573                    if ($beforeCount > max((int) ($max / 2), $max - $afterCount)) {
574                        break 2;
575                    }
576                }
577            }
578        }
579        //keep only non-parsed lines
580        $lines = array_slice($lines, 0, $i);
581
582        sort($revs);
583
584        //trunk desired selection
585        $requestedRevs = array_slice($revs, -$max, $max);
586
587        return [$requestedRevs, $revs, $fp, $lines, $head, $lastTail];
588    }
589
590    /**
591     * Get the current revision information, considering external edit, create or deletion
592     *
593     * When the file has not modified since its last revision, the information of the last
594     * change that had already recorded in the changelog is returned as current change info.
595     * Otherwise, the change information since the last revision caused outside DokuWiki
596     * should be returned, which is referred as "external revision".
597     *
598     * External revisions are persisted to the changelog on first detection so subsequent reads
599     * see one canonical entry instead of recomputing a synthesized one (and, where the revision
600     * scheme keeps it, the content is snapshotted to the attic). If persistence fails (e.g. the
601     * data dir is not writable in the current process context), the in-memory synthesized entry
602     * is still returned so the read path keeps working.
603     *
604     * @return bool|array false when page had never existed or array with entries:
605     *      - date:  revision identifier (timestamp or last revision +1)
606     *      - ip:    IPv4 address (127.0.0.1)
607     *      - type:  log line type
608     *      - id:    id of page or media
609     *      - user:  user name
610     *      - sum:   edit summary (or action reason)
611     *      - extra: extra data (varies by line type)
612     *      - sizechange: change of filesize
613     *      - timestamp: unix timestamp or false (key set only for external edit occurred)
614     *   additional:
615     *      - mode:  page or media
616     *
617     * @author  Satoshi Sahara <sahara.satoshi@gmail.com>
618     */
619    public function getCurrentRevisionInfo()
620    {
621        if (isset($this->currentRevision)) {
622            return $this->getRevisionInfo($this->currentRevision);
623        }
624
625        // the current revision id is the item file's mtime; reconcile it against the changelog
626        $filename = $this->getFilename();
627        $fileRev = @filemtime($filename); // false when the file does not exist
628        $recordedRev = $this->lastRevision(); // false when there is no changelog
629
630        // file and changelog agree (or the item never existed): the recorded state is current
631        if ($fileRev === $recordedRev) {
632            $this->currentRevision = $recordedRev;
633            return $recordedRev === false ? false : $this->getRevisionInfo($recordedRev);
634        }
635
636        // they disagree, so an external change happened. Classify it and synthesize the missing entry.
637        if (!$fileRev) {
638            // the file is gone: external deletion
639            $revInfo = $this->synthesizeExternalDeletion($recordedRev);
640        } elseif ($recordedRev === false || $this->getRevisionInfo($recordedRev, false)['type'] == DOKU_CHANGE_TYPE_DELETE) {
641            // no changelog, or it logged a delete: (re)creation
642            $revInfo = $this->synthesizeExternalCreate($filename, $fileRev, $recordedRev);
643        } else {
644            // the file changed against a recorded live page: external edit
645            $revInfo = $this->synthesizeExternalEdit($filename, $fileRev, $recordedRev);
646        }
647        if ($revInfo === null) {
648            // null means the external change was a no-op (content unchanged), so keep the recorded revision as current
649            $this->currentRevision = $recordedRev;
650            return $this->getRevisionInfo($recordedRev);
651        }
652
653        // persist the synthesized entry so subsequent reads see it as a real changelog entry
654        $this->persistCurrentRevisionInfo($revInfo);
655        $this->currentRevision = $revInfo['date'];
656        $this->cache[$this->id][$this->currentRevision] = $revInfo;
657        return $this->getRevisionInfo($this->currentRevision);
658    }
659
660    /**
661     * Synthesize the changelog entry for an external deletion: the item file is gone while the
662     * changelog still holds entries.
663     *
664     * @param int $recordedRev date of the newest recorded changelog revision
665     * @return array|null revision info to persist, or null when the deletion is already recorded
666     *                    at $recordedRev (that revision stays current, nothing to synthesize)
667     */
668    protected function synthesizeExternalDeletion($recordedRev)
669    {
670        global $lang;
671
672        if ($this->getRevisionInfo($recordedRev, false)['type'] == DOKU_CHANGE_TYPE_DELETE) {
673            return null;
674        }
675
676        // date the deletion as late as possible: 1 sec before now, or newest revision +1
677        return [
678            'date' => max($recordedRev + 1, time() - 1),
679            'ip'   => '127.0.0.1',
680            'type' => DOKU_CHANGE_TYPE_DELETE,
681            'id'   => $this->id,
682            'user' => '',
683            'sum'  => $lang['deleted'] . ' - ' . $lang['external_edit'] . ' (' . $lang['unknowndate'] . ')',
684            'extra' => '',
685            'sizechange' => -$this->lastRevisionSize($recordedRev),
686            'timestamp' => false,
687            'mode' => $this->getMode()
688        ];
689    }
690
691    /**
692     * Synthesize the changelog entry for an external edit: the item file exists and its mtime
693     * differs from the newest recorded revision, which is a live (non-deleted) page.
694     *
695     * @param string $filename path to the current item file
696     * @param int    $fileRev  mtime of the current item file
697     * @param int    $recordedRev  date of the newest recorded changelog revision
698     * @return array|null revision info to persist, or null when the file was only touched (content
699     *                    unchanged): the mtime is reset to $recordedRev and that revision stays current
700     */
701    protected function synthesizeExternalEdit($filename, $fileRev, $recordedRev)
702    {
703        global $lang;
704
705        // A file mtime can move without the content changing (backup restore, git checkout, ...).
706        // When the content still matches $recordedRev nothing was really edited: reset the mtime to the
707        // recorded date and keep that revision.
708        if ($this->currentContentMatchesRevision($recordedRev)) {
709            @touch($filename, $recordedRev);
710            clearstatcache(false, $filename);
711            return null;
712        }
713
714        if ($fileRev > $recordedRev) {
715            $timestamp = $fileRev;
716            $sum = $lang['external_edit'];
717        } else {
718            // $fileRev is older than $recordedRev, that is an erroneous/incorrect occurrence
719            $msg = "Warning: current file modification time is older than last revision date";
720            $details = 'File revision: ' . $fileRev . ' ' . dformat($fileRev, "%Y-%m-%d %H:%M:%S") . "\n"
721                      . 'Last revision: ' . $recordedRev . ' ' . dformat($recordedRev, "%Y-%m-%d %H:%M:%S");
722            Logger::error($msg, $details, $filename);
723            $timestamp = false;
724            $sum = $lang['external_edit'] . ' (' . $lang['unknowndate'] . ')';
725        }
726
727        return [
728            'date' => $timestamp ?: $recordedRev + 1,
729            'ip'   => '127.0.0.1',
730            'type' => DOKU_CHANGE_TYPE_EDIT,
731            'id'   => $this->id,
732            'user' => '',
733            'sum'  => $sum,
734            'extra' => '',
735            'sizechange' => filesize($filename) - $this->lastRevisionSize($recordedRev),
736            'timestamp' => $timestamp,
737            'mode' => $this->getMode()
738        ];
739    }
740
741    /**
742     * Synthesize the changelog entry for an external creation: the item file exists but nothing
743     * live was recorded at $recordedRev (no changelog at all, or the newest revision is a DELETE), so
744     * the file is a fresh (re)creation.
745     *
746     * @param string    $filename path to the current item file
747     * @param int       $fileRev  mtime of the current item file
748     * @param int|false $recordedRev  date of the newest recorded changelog revision, or false when none
749     * @return array revision info to persist
750     */
751    protected function synthesizeExternalCreate($filename, $fileRev, $recordedRev)
752    {
753        global $lang;
754
755        // trust the file mtime as the creation date only when it postdates any prior delete; a
756        // backup restored with an older mtime (cp -p) can't date the creation before the deletion,
757        // so record it just after, with an unknown date.
758        $datedByFile = $recordedRev === false || $fileRev > $recordedRev;
759        $timestamp = $datedByFile ? $fileRev : false;
760        $sum = $lang['created'] . ' - ' . $lang['external_edit']
761             . ($datedByFile ? '' : ' (' . $lang['unknowndate'] . ')');
762
763        return [
764            'date' => $timestamp ?: $recordedRev + 1,
765            'ip'   => '127.0.0.1',
766            'type' => DOKU_CHANGE_TYPE_CREATE,
767            'id'   => $this->id,
768            'user' => '',
769            'sum'  => $sum,
770            'extra' => '',
771            'sizechange' => filesize($filename),
772            'timestamp' => $timestamp,
773            'mode' => $this->getMode()
774        ];
775    }
776
777    /**
778     * Adds an entry to the changelog
779     *
780     * Locks the local changelog file for the duration of the write so concurrent writers
781     * serialize through the same key. Subclasses provide the actual append logic via
782     * writeLogEntry() so persistCurrentRevisionInfo() can append while already holding
783     * the lock without re-entering it.
784     *
785     * Best-effort: if writeLogEntry() throws, surfaces the error via msg() and still
786     * returns the info dict so existing callers (saveWikiText etc.) keep working.
787     *
788     * @param array $info    Revision info structure of a page or media file
789     * @param int $timestamp log line date (optional)
790     * @return array revision info of added log line
791     */
792    public function addLogEntry(array $info, $timestamp = null)
793    {
794        $logfile = $this->getChangelogFilename();
795        io_lock($logfile);
796        try {
797            return $this->writeLogEntry($info, $timestamp);
798        } catch (\RuntimeException $e) {
799            msg($e->getMessage(), -1);
800            $info['mode'] = $this->getMode();
801            return $info;
802        } finally {
803            io_unlock($logfile);
804        }
805    }
806
807    /**
808     * Append a log entry to the local and global changelog and update the in-memory cache.
809     *
810     * Locking is the caller's responsibility: this method appends to the local changelog
811     * directly and assumes the caller already holds io_lock() on it.
812     *
813     * This method is currently used by addLogEntry() for normal edits and by persistCurrentRevisionInfo()
814     * for detected external edits, both of which hold the local changelog lock around the call.
815     *
816     * Writing the global changelog is triggered from here via writeGlobalLogEntry(); being a separate
817     * file it has its own locking, which is handled by io_saveFile() rather than by the
818     * local lock above.
819     *
820     * @param array $info    Revision info structure
821     * @param int $timestamp log line date (optional)
822     * @param bool $external entry is a detected external edit (kept out of the global feed when out of order)
823     * @return array revision info of added log line
824     * @throws \RuntimeException if the local changelog write fails
825     */
826    protected function writeLogEntry(array $info, $timestamp = null, $external = false)
827    {
828        global $conf;
829
830        if (isset($timestamp)) unset($this->cache[$this->id][$info['date']]);
831
832        $logline = static::buildLogLine($info, $timestamp);
833
834        // append to local changelog without re-locking (caller holds the lock)
835        $localFile = $this->getChangelogFilename();
836        io_makeFileDir($localFile);
837        $fileexists = file_exists($localFile);
838        $fh = @fopen($localFile, 'ab');
839        if (!$fh || @fwrite($fh, $logline) === false) {
840            if ($fh) @fclose($fh);
841            throw new \RuntimeException("Writing $localFile failed");
842        }
843        fclose($fh);
844        if (!$fileexists && !empty($conf['fperm'])) chmod($localFile, $conf['fperm']);
845
846        $this->writeGlobalLogEntry($logline, $info['date'], $external);
847
848        $this->currentRevision = $info['date'];
849        $info['mode'] = $this->getMode();
850        $this->cache[$this->id][$this->currentRevision] = $info;
851        return $info;
852    }
853
854    /**
855     * Append a log line to the global changelog (the cross-page recent-changes feed).
856     *
857     * The write goes through io_saveFile(), which locks the global changelog and reports
858     * errors via msg(). That locking is independent of the local changelog lock the caller
859     * holds, as the global changelog is a separate file.
860     *
861     * A detected external edit ($external) is skipped here when its date is older than the
862     * feed's most recent change: appending it would place it at the top of recent changes
863     * with an old date (issue #4634). Skipping does not lose the entry — writeLogEntry() has
864     * already recorded it in the page's own changelog; it is only kept out of the cross-page
865     * feed. Normal edits are always appended.
866     *
867     * @param string $logline the changelog line to append
868     * @param int $date revision date of the entry, compared against the feed's last change
869     * @param bool $external entry is a detected external edit
870     */
871    protected function writeGlobalLogEntry($logline, $date, $external)
872    {
873        $globalFile = $this->getGlobalChangelogFilename();
874
875        // skip an out-of-order external edit
876        if ($external) {
877            clearstatcache(false, $globalFile);
878            $globalMtime = @filemtime($globalFile);
879            if ($globalMtime !== false && $date < $globalMtime) return;
880        }
881
882        io_saveFile($globalFile, $logline, true);
883    }
884
885    /**
886     * Persist a synthesized external-revision entry to the changelog
887     *
888     * Holds the local changelog lock around the entire detect-and-write critical section
889     * (idempotency check, mtime repair, optional attic snapshot, log append) so it serializes
890     * against any other writer that goes through addLogEntry(). The append uses writeLogEntry()
891     * to avoid re-entering the lock we already hold.
892     *
893     * Returns false (without raising) when the attic write fails or another request
894     * already persisted the entry. The caller falls back to the in-memory synthesized
895     * entry.
896     *
897     * @param array $revInfo synthesized revision info
898     * @return bool true if newly persisted, false otherwise
899     */
900    protected function persistCurrentRevisionInfo(array $revInfo)
901    {
902        // only the synthesized branches carry the 'timestamp' key
903        if (!array_key_exists('timestamp', $revInfo)) return false;
904
905        $logfile = $this->getChangelogFilename();
906        io_lock($logfile);
907        try {
908            // re-read lastRev under the lock — another request may have just persisted
909            $lastRev = $this->lastRevision();
910            if ($lastRev !== false && $lastRev >= $revInfo['date']) {
911                return false;
912            }
913
914            if ($revInfo['type'] !== DOKU_CHANGE_TYPE_DELETE) {
915                if (!$this->repairExternalMtime($revInfo)) return false;
916                if (!$this->saveExternalAttic($revInfo)) return false;
917            }
918
919            $this->writeLogEntry($revInfo, null, true);
920            return true;
921        } catch (\RuntimeException) {
922            // silent fallback to in-memory synthesis
923            return false;
924        } finally {
925            io_unlock($logfile);
926        }
927    }
928
929    /**
930     * Move the current file's modification time forward to the synthesized revision date when
931     * the detected external change had an unreliable date (its file mtime was older than the
932     * last revision, so it was dated just after that revision instead). Without this the file
933     * mtime would still disagree with the changelog on the next read and the same external
934     * change would be re-detected on every request.
935     *
936     * Only relevant for non-delete changes (a deletion has no file); the persist flow calls it
937     * only in that case.
938     *
939     * @param array $revInfo synthesized revision info with 'date' and 'timestamp' set
940     * @return bool false only if the file exists but could not be touched
941     */
942    protected function repairExternalMtime(array $revInfo)
943    {
944        // a set timestamp means the date is the real file mtime — nothing to repair
945        if (!empty($revInfo['timestamp'])) return true;
946
947        $file = $this->getFilename();
948        if (!file_exists($file)) return true;
949
950        if (!@touch($file, $revInfo['date'])) return false;
951        clearstatcache(false, $file);
952        return true;
953    }
954
955    /**
956     * Snapshot the externally-modified content to the attic before the synthesized log entry
957     * is persisted, so the revision stays retrievable. Called only for non-delete changes.
958     *
959     * Whether this is done depends on the item's revision scheme: pages archive every
960     * revision, so they snapshot; media never archive the current revision, so they do not.
961     *
962     * @param array $revInfo synthesized revision info with 'date' set
963     * @return bool true on success or no-op, false to abort persistence
964     */
965    abstract protected function saveExternalAttic(array $revInfo);
966
967    /**
968     * Byte size of the last recorded revision, used as the "before" size when computing the
969     * size change of a synthesized external edit or deletion. Reads the size from that
970     * revision's attic copy.
971     *
972     * @param int $recordedRev timestamp of the last recorded revision
973     * @return int size in bytes (0 when it cannot be determined)
974     */
975    protected function lastRevisionSize($recordedRev)
976    {
977        return io_getSizeFile($this->getFilename($recordedRev));
978    }
979
980    /**
981     * Whether the current item file's content is byte-identical to the stored content
982     * of the given revision.
983     *
984     * Used to tell a real external edit apart from a mere mtime bump: when the content
985     * is unchanged the file was only touched, not edited. Returns false when either file
986     * is missing so detection falls back to treating the change as external.
987     *
988     * @param int $rev revision timestamp to compare the current file against
989     * @return bool true if the content is identical
990     */
991    abstract protected function currentContentMatchesRevision($rev);
992
993    /**
994     * Mechanism to trace no-actual external current revision
995     * @param int $rev
996     */
997    public function traceCurrentRevision($rev)
998    {
999        if ($rev > $this->lastRevision()) {
1000            $rev = $this->currentRevision();
1001        }
1002        return $rev;
1003    }
1004}
1005