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 * Check whether given revision is the current page 57 * 58 * @param int $rev timestamp of current page 59 * @return bool true if $rev is current revision, otherwise false 60 */ 61 public function isCurrentRevision($rev) 62 { 63 return $rev == $this->currentRevision(); 64 } 65 66 /** 67 * Checks if the revision is last revision 68 * 69 * @param int $rev revision timestamp 70 * @return bool true if $rev is last revision, otherwise false 71 */ 72 public function isLastRevision($rev = null) 73 { 74 return $rev === $this->lastRevision(); 75 } 76 77 /** 78 * Return the current revision identifier 79 * 80 * The "current" revision means current version of the page or media file. It is either 81 * identical with or newer than the "last" revision, that depends on whether the file 82 * has modified, created or deleted outside of DokuWiki. 83 * The value of identifier can be determined by timestamp as far as the file exists, 84 * otherwise it must be assigned larger than any other revisions to keep them sortable. 85 * 86 * @return int|false revision timestamp 87 */ 88 public function currentRevision() 89 { 90 if (!isset($this->currentRevision)) { 91 // set ChangeLog::currentRevision property 92 $this->getCurrentRevisionInfo(); 93 } 94 return $this->currentRevision; 95 } 96 97 /** 98 * Return the last revision identifier, date value of the last entry of the changelog 99 * 100 * @return int|false revision timestamp 101 */ 102 public function lastRevision() 103 { 104 $revs = $this->getRevisions(-1, 1); 105 return empty($revs) ? false : $revs[0]; 106 } 107 108 /** 109 * Parses a changelog line into its components and save revision info to the cache pool 110 * 111 * @param string $value changelog line 112 * @return array|bool parsed line or false 113 */ 114 protected function parseAndCacheLogLine($value) 115 { 116 $info = static::parseLogLine($value); 117 if(is_array($info)) { 118 $info['mode'] = $this->getMode(); 119 $this->cache[$this->id][$info['date']] ??= $info; 120 return $info; 121 } 122 return false; 123 } 124 125 /** 126 * Get the changelog information for a specific revision (timestamp) 127 * 128 * Adjacent changelog lines are optimistically parsed and cached to speed up 129 * consecutive calls to getRevisionInfo. For large changelog files, only the chunk 130 * containing the requested changelog line is read. 131 * 132 * @param int $rev revision timestamp 133 * @param bool $retrieveCurrentRevInfo allows to skip for getting other revision info in the 134 * getCurrentRevisionInfo() where $currentRevision is not yet determined 135 * @return bool|array false or array with entries: 136 * - date: unix timestamp 137 * - ip: IPv4 address (127.0.0.1) 138 * - type: log line type 139 * - id: page id 140 * - user: user name 141 * - sum: edit summary (or action reason) 142 * - extra: extra data (varies by line type) 143 * - sizechange: change of filesize 144 * additional: 145 * - mode: page or media 146 * 147 * @author Ben Coburn <btcoburn@silicodon.net> 148 * @author Kate Arzamastseva <pshns@ukr.net> 149 */ 150 public function getRevisionInfo($rev, $retrieveCurrentRevInfo = true) 151 { 152 $rev = max(0, $rev); 153 if (!$rev) return false; 154 155 //ensure the external edits are cached as well 156 if (!isset($this->currentRevision) && $retrieveCurrentRevInfo) { 157 $this->getCurrentRevisionInfo(); 158 } 159 160 // check if it's already in the memory cache 161 if (isset($this->cache[$this->id]) && isset($this->cache[$this->id][$rev])) { 162 return $this->cache[$this->id][$rev]; 163 } 164 165 //read lines from changelog 166 [$fp, $lines] = $this->readloglines($rev); 167 if ($fp) { 168 fclose($fp); 169 } 170 if (empty($lines)) return false; 171 172 // parse and cache changelog lines 173 foreach ($lines as $line) { 174 $this->parseAndCacheLogLine($line); 175 } 176 if (!isset($this->cache[$this->id][$rev])) { 177 return false; 178 } 179 return $this->cache[$this->id][$rev]; 180 } 181 182 /** 183 * Return a list of page revisions numbers 184 * 185 * Does not guarantee that the revision exists in the attic, 186 * only that a line with the date exists in the changelog. 187 * By default the current revision is skipped. 188 * 189 * The current revision is automatically skipped when the page exists. 190 * See $INFO['meta']['last_change'] for the current revision. 191 * A negative $first let read the current revision too. 192 * 193 * For efficiency, the log lines are parsed and cached for later 194 * calls to getRevisionInfo. Large changelog files are read 195 * backwards in chunks until the requested number of changelog 196 * lines are received. 197 * 198 * @param int $first skip the first n changelog lines 199 * @param int $num number of revisions to return 200 * @return array with the revision timestamps 201 * 202 * @author Ben Coburn <btcoburn@silicodon.net> 203 * @author Kate Arzamastseva <pshns@ukr.net> 204 */ 205 public function getRevisions($first, $num) 206 { 207 $revs = []; 208 $lines = []; 209 $count = 0; 210 211 $logfile = $this->getChangelogFilename(); 212 if (!file_exists($logfile)) return $revs; 213 214 $num = max($num, 0); 215 if ($num == 0) { 216 return $revs; 217 } 218 219 if ($first < 0) { 220 $first = 0; 221 } else { 222 $fileLastMod = $this->getFilename(); 223 if (file_exists($fileLastMod) && $this->isLastRevision(filemtime($fileLastMod))) { 224 // skip last revision if the page exists 225 $first = max($first + 1, 0); 226 } 227 } 228 229 if (filesize($logfile) < $this->chunk_size || $this->chunk_size == 0) { 230 // read whole file 231 $lines = file($logfile); 232 if ($lines === false) { 233 return $revs; 234 } 235 } else { 236 // read chunks backwards 237 $fp = fopen($logfile, 'rb'); // "file pointer" 238 if ($fp === false) { 239 return $revs; 240 } 241 fseek($fp, 0, SEEK_END); 242 $tail = ftell($fp); 243 244 // chunk backwards 245 $finger = max($tail - $this->chunk_size, 0); 246 while ($count < $num + $first) { 247 $nl = $this->getNewlinepointer($fp, $finger); 248 249 // was the chunk big enough? if not, take another bite 250 if ($nl > 0 && $tail <= $nl) { 251 $finger = max($finger - $this->chunk_size, 0); 252 continue; 253 } else { 254 $finger = $nl; 255 } 256 257 // read chunk 258 $chunk = ''; 259 $read_size = max($tail - $finger, 0); // found chunk size 260 $got = 0; 261 while ($got < $read_size && !feof($fp)) { 262 $tmp = @fread($fp, max(min($this->chunk_size, $read_size - $got), 0)); 263 if ($tmp === false) { 264 break; 265 } //error state 266 $got += strlen($tmp); 267 $chunk .= $tmp; 268 } 269 $tmp = explode("\n", $chunk); 270 array_pop($tmp); // remove trailing newline 271 272 // combine with previous chunk 273 $count += count($tmp); 274 $lines = [...$tmp, ...$lines]; 275 276 // next chunk 277 if ($finger == 0) { 278 break; 279 } else { // already read all the lines 280 $tail = $finger; 281 $finger = max($tail - $this->chunk_size, 0); 282 } 283 } 284 fclose($fp); 285 } 286 287 // skip parsing extra lines 288 $num = max(min(count($lines) - $first, $num), 0); 289 if ($first > 0 && $num > 0) { 290 $lines = array_slice($lines, max(count($lines) - $first - $num, 0), $num); 291 } elseif ($first > 0 && $num == 0) { 292 $lines = array_slice($lines, 0, max(count($lines) - $first, 0)); 293 } elseif ($first == 0 && $num > 0) { 294 $lines = array_slice($lines, max(count($lines) - $num, 0)); 295 } 296 297 // handle lines in reverse order 298 for ($i = count($lines) - 1; $i >= 0; $i--) { 299 $info = $this->parseAndCacheLogLine($lines[$i]); 300 if (is_array($info)) { 301 $revs[] = $info['date']; 302 } 303 } 304 305 return $revs; 306 } 307 308 /** 309 * Get the nth revision left or right-hand side for a specific page id and revision (timestamp) 310 * 311 * For large changelog files, only the chunk containing the 312 * reference revision $rev is read and sometimes a next chunk. 313 * 314 * Adjacent changelog lines are optimistically parsed and cached to speed up 315 * consecutive calls to getRevisionInfo. 316 * 317 * @param int $rev revision timestamp used as start date 318 * (doesn't need to be exact revision number) 319 * @param int $direction give position of returned revision with respect to $rev; 320 positive=next, negative=prev 321 * @return bool|int 322 * timestamp of the requested revision 323 * otherwise false 324 */ 325 public function getRelativeRevision($rev, $direction) 326 { 327 $rev = max($rev, 0); 328 $direction = (int)$direction; 329 330 //no direction given or last rev, so no follow-up 331 if (!$direction || ($direction > 0 && $this->isCurrentRevision($rev))) { 332 return false; 333 } 334 335 //get lines from changelog 336 [$fp, $lines, $head, $tail, $eof] = $this->readloglines($rev); 337 if (empty($lines)) return false; 338 339 // look for revisions later/earlier than $rev, when founded count till the wanted revision is reached 340 // also parse and cache changelog lines for getRevisionInfo(). 341 $revCounter = 0; 342 $relativeRev = false; 343 $checkOtherChunk = true; //always runs once 344 while (!$relativeRev && $checkOtherChunk) { 345 $info = []; 346 //parse in normal or reverse order 347 $count = count($lines); 348 if ($direction > 0) { 349 $start = 0; 350 $step = 1; 351 } else { 352 $start = $count - 1; 353 $step = -1; 354 } 355 for ($i = $start; $i >= 0 && $i < $count; $i += $step) { 356 $info = $this->parseAndCacheLogLine($lines[$i]); 357 if (is_array($info)) { 358 //look for revs older/earlier then reference $rev and select $direction-th one 359 if (($direction > 0 && $info['date'] > $rev) || ($direction < 0 && $info['date'] < $rev)) { 360 $revCounter++; 361 if ($revCounter == abs($direction)) { 362 $relativeRev = $info['date']; 363 } 364 } 365 } 366 } 367 368 //true when $rev is found, but not the wanted follow-up. 369 $checkOtherChunk = $fp 370 && ($info['date'] == $rev || ($revCounter > 0 && !$relativeRev)) 371 && (!($tail == $eof && $direction > 0) && !($head == 0 && $direction < 0)); 372 373 if ($checkOtherChunk) { 374 [$lines, $head, $tail] = $this->readAdjacentChunk($fp, $head, $tail, $direction); 375 376 if (empty($lines)) break; 377 } 378 } 379 if ($fp) { 380 fclose($fp); 381 } 382 383 return $relativeRev; 384 } 385 386 /** 387 * Returns revisions around rev1 and rev2 388 * When available it returns $max entries for each revision 389 * 390 * @param int $rev1 oldest revision timestamp 391 * @param int $rev2 newest revision timestamp (0 looks up last revision) 392 * @param int $max maximum number of revisions returned 393 * @return array with two arrays with revisions surrounding rev1 respectively rev2 394 */ 395 public function getRevisionsAround($rev1, $rev2, $max = 50) 396 { 397 $max = (int) (abs($max) / 2) * 2 + 1; 398 $rev1 = max($rev1, 0); 399 $rev2 = max($rev2, 0); 400 401 if ($rev2) { 402 if ($rev2 < $rev1) { 403 $rev = $rev2; 404 $rev2 = $rev1; 405 $rev1 = $rev; 406 } 407 } else { 408 //empty right side means a removed page. Look up last revision. 409 $rev2 = $this->currentRevision(); 410 } 411 //collect revisions around rev2 412 [$revs2, $allRevs, $fp, $lines, $head, $tail] = $this->retrieveRevisionsAround($rev2, $max); 413 414 if (empty($revs2)) return [[], []]; 415 416 //collect revisions around rev1 417 $index = array_search($rev1, $allRevs); 418 if ($index === false) { 419 //no overlapping revisions 420 [$revs1, , , , , ] = $this->retrieveRevisionsAround($rev1, $max); 421 if (empty($revs1)) $revs1 = []; 422 } else { 423 //revisions overlaps, reuse revisions around rev2 424 $lastRev = array_pop($allRevs); //keep last entry that could be external edit 425 $revs1 = $allRevs; 426 while ($head > 0) { 427 for ($i = count($lines) - 1; $i >= 0; $i--) { 428 $info = $this->parseAndCacheLogLine($lines[$i]); 429 if (is_array($info)) { 430 $revs1[] = $info['date']; 431 $index++; 432 433 if ($index > (int) ($max / 2)) break 2; 434 } 435 } 436 437 [$lines, $head, $tail] = $this->readAdjacentChunk($fp, $head, $tail, -1); 438 } 439 sort($revs1); 440 $revs1[] = $lastRev; //push back last entry 441 442 //return wanted selection 443 $revs1 = array_slice($revs1, max($index - (int) ($max / 2), 0), $max); 444 } 445 446 return [array_reverse($revs1), array_reverse($revs2)]; 447 } 448 449 /** 450 * Return an existing revision for a specific date which is 451 * the current one or younger or equal then the date 452 * 453 * @param number $date_at timestamp 454 * @return string revision ('' for current) 455 */ 456 public function getLastRevisionAt($date_at) 457 { 458 $fileLastMod = $this->getFilename(); 459 //requested date_at(timestamp) younger or equal then modified_time($this->id) => load current 460 if (file_exists($fileLastMod) && $date_at >= @filemtime($fileLastMod)) { 461 return ''; 462 } elseif ($rev = $this->getRelativeRevision($date_at + 1, -1)) { 463 //+1 to get also the requested date revision 464 return $rev; 465 } else { 466 return false; 467 } 468 } 469 470 /** 471 * Collect the $max revisions near to the timestamp $rev 472 * 473 * Ideally, half of retrieved timestamps are older than $rev, another half are newer. 474 * The returned array $requestedRevs may not contain the reference timestamp $rev 475 * when it does not match any revision value recorded in changelog. 476 * 477 * @param int $rev revision timestamp 478 * @param int $max maximum number of revisions to be returned 479 * @return bool|array 480 * return array with entries: 481 * - $requestedRevs: array of with $max revision timestamps 482 * - $revs: all parsed revision timestamps 483 * - $fp: file pointer only defined for chuck reading, needs closing. 484 * - $lines: non-parsed changelog lines before the parsed revisions 485 * - $head: position of first read changelog line 486 * - $lastTail: position of end of last read changelog line 487 * otherwise false 488 */ 489 protected function retrieveRevisionsAround($rev, $max) 490 { 491 $revs = []; 492 $afterCount = 0; 493 $beforeCount = 0; 494 495 //get lines from changelog 496 [$fp, $lines, $startHead, $startTail, $eof] = $this->readloglines($rev); 497 if (empty($lines)) return false; 498 499 //parse changelog lines in chunk, and read forward more chunks until $max/2 is reached 500 $head = $startHead; 501 $tail = $startTail; 502 while (count($lines) > 0) { 503 foreach ($lines as $line) { 504 $info = $this->parseAndCacheLogLine($line); 505 if (is_array($info)) { 506 $revs[] = $info['date']; 507 if ($info['date'] >= $rev) { 508 //count revs after reference $rev 509 $afterCount++; 510 if ($afterCount == 1) $beforeCount = count($revs); 511 } 512 //enough revs after reference $rev? 513 if ($afterCount > (int) ($max / 2)) break 2; 514 } 515 } 516 //retrieve next chunk 517 [$lines, $head, $tail] = $this->readAdjacentChunk($fp, $head, $tail, 1); 518 } 519 $lastTail = $tail; 520 521 // add a possible revision of external edit, create or deletion 522 if ( 523 $lastTail == $eof && $afterCount <= (int) ($max / 2) && 524 count($revs) && !$this->isCurrentRevision($revs[count($revs) - 1]) 525 ) { 526 $revs[] = $this->currentRevision; 527 $afterCount++; 528 } 529 530 if ($afterCount == 0) { 531 //given timestamp $rev is newer than the most recent line in chunk 532 return false; //FIXME: or proceed to collect older revisions? 533 } 534 535 //read more chunks backward until $max/2 is reached and total number of revs is equal to $max 536 $lines = []; 537 $i = 0; 538 $head = $startHead; 539 $tail = $startTail; 540 while ($head > 0) { 541 [$lines, $head, $tail] = $this->readAdjacentChunk($fp, $head, $tail, -1); 542 543 for ($i = count($lines) - 1; $i >= 0; $i--) { 544 $info = $this->parseAndCacheLogLine($lines[$i]); 545 if (is_array($info)) { 546 $revs[] = $info['date']; 547 $beforeCount++; 548 //enough revs before reference $rev? 549 if ($beforeCount > max((int) ($max / 2), $max - $afterCount)) break 2; 550 } 551 } 552 } 553 //keep only non-parsed lines 554 $lines = array_slice($lines, 0, $i); 555 556 sort($revs); 557 558 //trunk desired selection 559 $requestedRevs = array_slice($revs, -$max, $max); 560 561 return [$requestedRevs, $revs, $fp, $lines, $head, $lastTail]; 562 } 563 564 /** 565 * Get the current revision information, considering external edit, create or deletion 566 * 567 * When the file has not modified since its last revision, the information of the last 568 * change that had already recorded in the changelog is returned as current change info. 569 * Otherwise, the change information since the last revision caused outside DokuWiki 570 * should be returned, which is referred as "external revision". 571 * 572 * The change date of the file can be determined by timestamp as far as the file exists, 573 * however this is not possible when the file has already deleted outside of DokuWiki. 574 * In such case we assign 1 sec before current time() for the external deletion. 575 * As a result, the value of current revision identifier may change each time because: 576 * 1) the file has again modified outside of DokuWiki, or 577 * 2) the value is essentially volatile for deleted but once existed files. 578 * 579 * @return bool|array false when page had never existed or array with entries: 580 * - date: revision identifier (timestamp or last revision +1) 581 * - ip: IPv4 address (127.0.0.1) 582 * - type: log line type 583 * - id: id of page or media 584 * - user: user name 585 * - sum: edit summary (or action reason) 586 * - extra: extra data (varies by line type) 587 * - sizechange: change of filesize 588 * - timestamp: unix timestamp or false (key set only for external edit occurred) 589 * additional: 590 * - mode: page or media 591 * 592 * @author Satoshi Sahara <sahara.satoshi@gmail.com> 593 */ 594 public function getCurrentRevisionInfo() 595 { 596 global $lang; 597 598 if (isset($this->currentRevision)) return $this->getRevisionInfo($this->currentRevision); 599 600 // get revision id from the item file timestamp and changelog 601 $fileLastMod = $this->getFilename(); 602 $fileRev = @filemtime($fileLastMod); // false when the file not exist 603 $lastRev = $this->lastRevision(); // false when no changelog 604 605 if (!$fileRev && !$lastRev) { // has never existed 606 $this->currentRevision = false; 607 return false; 608 } elseif ($fileRev === $lastRev) { // not external edit 609 $this->currentRevision = $lastRev; 610 return $this->getRevisionInfo($lastRev); 611 } 612 613 if (!$fileRev && $lastRev) { // item file does not exist 614 // check consistency against changelog 615 $revInfo = $this->getRevisionInfo($lastRev, false); 616 if ($revInfo['type'] == DOKU_CHANGE_TYPE_DELETE) { 617 $this->currentRevision = $lastRev; 618 return $revInfo; 619 } 620 621 // externally deleted, set revision date as late as possible 622 $revInfo = [ 623 'date' => max($lastRev + 1, time() - 1), // 1 sec before now or new page save 624 'ip' => '127.0.0.1', 625 'type' => DOKU_CHANGE_TYPE_DELETE, 626 'id' => $this->id, 627 'user' => '', 628 'sum' => $lang['deleted'] . ' - ' . $lang['external_edit'] . ' (' . $lang['unknowndate'] . ')', 629 'extra' => '', 630 'sizechange' => -io_getSizeFile($this->getFilename($lastRev)), 631 'timestamp' => false, 632 'mode' => $this->getMode() 633 ]; 634 } else { // item file exists, with timestamp $fileRev 635 // here, file timestamp $fileRev is different with last revision timestamp $lastRev in changelog 636 $isJustCreated = $lastRev === false || ( 637 $fileRev > $lastRev && 638 $this->getRevisionInfo($lastRev, false)['type'] == DOKU_CHANGE_TYPE_DELETE 639 ); 640 $filesize_new = filesize($this->getFilename()); 641 $filesize_old = $isJustCreated ? 0 : io_getSizeFile($this->getFilename($lastRev)); 642 $sizechange = $filesize_new - $filesize_old; 643 644 if ($isJustCreated) { 645 $timestamp = $fileRev; 646 $sum = $lang['created'] . ' - ' . $lang['external_edit']; 647 } elseif ($fileRev > $lastRev) { 648 $timestamp = $fileRev; 649 $sum = $lang['external_edit']; 650 } else { 651 // $fileRev is older than $lastRev, that is erroneous/incorrect occurrence. 652 $msg = "Warning: current file modification time is older than last revision date"; 653 $details = 'File revision: ' . $fileRev . ' ' . dformat($fileRev, "%Y-%m-%d %H:%M:%S") . "\n" 654 . 'Last revision: ' . $lastRev . ' ' . dformat($lastRev, "%Y-%m-%d %H:%M:%S"); 655 Logger::error($msg, $details, $this->getFilename()); 656 $timestamp = false; 657 $sum = $lang['external_edit'] . ' (' . $lang['unknowndate'] . ')'; 658 } 659 660 // externally created or edited 661 $revInfo = [ 662 'date' => $timestamp ?: $lastRev + 1, 663 'ip' => '127.0.0.1', 664 'type' => $isJustCreated ? DOKU_CHANGE_TYPE_CREATE : DOKU_CHANGE_TYPE_EDIT, 665 'id' => $this->id, 666 'user' => '', 667 'sum' => $sum, 668 'extra' => '', 669 'sizechange' => $sizechange, 670 'timestamp' => $timestamp, 671 'mode' => $this->getMode() 672 ]; 673 } 674 675 // cache current revision information of external edition 676 $this->currentRevision = $revInfo['date']; 677 $this->cache[$this->id][$this->currentRevision] = $revInfo; 678 return $this->getRevisionInfo($this->currentRevision); 679 } 680 681 /** 682 * Mechanism to trace no-actual external current revision 683 * @param int $rev 684 */ 685 public function traceCurrentRevision($rev) 686 { 687 if ($rev > $this->lastRevision()) { 688 $rev = $this->currentRevision(); 689 } 690 return $rev; 691 } 692} 693