3 * Changelog handling functions
5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author Andreas Gohr <andi@splitbrain.org>
9 // Constants for known core changelog line types.
10 // Use these in place of string literals for more readable code.
11 define('DOKU_CHANGE_TYPE_CREATE', 'C');
12 define('DOKU_CHANGE_TYPE_EDIT', 'E');
13 define('DOKU_CHANGE_TYPE_MINOR_EDIT', 'e');
14 define('DOKU_CHANGE_TYPE_DELETE', 'D');
15 define('DOKU_CHANGE_TYPE_REVERT', 'R');
18 * parses a changelog line into it's components
20 * @author Ben Coburn <btcoburn@silicodon.net>
22 function parseChangelogLine($line) {
23 $tmp = explode("\t", $line);
24 if ($tmp!==false && count($tmp)>1) {
26 $info['date'] = (int)$tmp[0]; // unix timestamp
27 $info['ip'] = $tmp[1]; // IPv4 address (127.0.0.1)
28 $info['type'] = $tmp[2]; // log line type
29 $info['id'] = $tmp[3]; // page id
30 $info['user'] = $tmp[4]; // user name
31 $info['sum'] = $tmp[5]; // edit summary (or action reason)
32 $info['extra'] = rtrim($tmp[6], "\n"); // extra data (varies by line type)
34 } else { return false; }
38 * Add's an entry to the changelog and saves the metadata for the page
40 * @param int $date Timestamp of the change
41 * @param String $id Name of the affected page
42 * @param String $type Type of the change see DOKU_CHANGE_TYPE_*
43 * @param String $summary Summary of the change
44 * @param mixed $extra In case of a revert the revision (timestmp) of the reverted page
45 * @param array $flags Additional flags in a key value array.
47 * - ExternalEdit - mark as an external edit.
49 * @author Andreas Gohr <andi@splitbrain.org>
50 * @author Esther Brunner <wikidesign@gmail.com>
51 * @author Ben Coburn <btcoburn@silicodon.net>
53 function addLogEntry($date, $id, $type=DOKU_CHANGE_TYPE_EDIT
, $summary='', $extra='', $flags=null){
56 // check for special flags as keys
57 if (!is_array($flags)) { $flags = array(); }
58 $flagExternalEdit = isset($flags['ExternalEdit']);
62 $created = @filectime
($file);
63 $minor = ($type===DOKU_CHANGE_TYPE_MINOR_EDIT
);
64 $wasRemoved = ($type===DOKU_CHANGE_TYPE_DELETE
);
66 if(!$date) $date = time(); //use current time if none supplied
67 $remote = (!$flagExternalEdit)?
clientIP(true):'127.0.0.1';
68 $user = (!$flagExternalEdit)?
$_SERVER['REMOTE_USER']:'';
70 $strip = array("\t", "\n");
74 'type' => str_replace($strip, '', $type),
77 'sum' => utf8_substr(str_replace($strip, '', $summary),0,255),
78 'extra' => str_replace($strip, '', $extra)
83 $oldmeta = p_read_metadata($id);
85 if (!$INFO['exists'] && empty($oldmeta['persistent']['date']['created'])){ // newly created
86 $meta['date']['created'] = $created;
88 $meta['creator'] = $INFO['userinfo']['name'];
89 $meta['user'] = $user;
91 } elseif (!$INFO['exists'] && !empty($oldmeta['persistent']['date']['created'])) { // re-created / restored
92 $meta['date']['created'] = $oldmeta['persistent']['date']['created'];
93 $meta['date']['modified'] = $created; // use the files ctime here
94 $meta['creator'] = $oldmeta['persistent']['creator'];
95 if ($user) $meta['contributor'][$user] = $INFO['userinfo']['name'];
96 } elseif (!$minor) { // non-minor modification
97 $meta['date']['modified'] = $date;
98 if ($user) $meta['contributor'][$user] = $INFO['userinfo']['name'];
100 $meta['last_change'] = $logline;
101 p_set_metadata($id, $meta);
104 // add changelog lines
105 $logline = implode("\t", $logline)."\n";
106 io_saveFile(metaFN($id,'.changes'),$logline,true); //page changelog
107 io_saveFile($conf['changelog'],$logline,true); //global changelog cache
111 * Add's an entry to the media changelog
113 * @author Michael Hamann <michael@content-space.de>
114 * @author Andreas Gohr <andi@splitbrain.org>
115 * @author Esther Brunner <wikidesign@gmail.com>
116 * @author Ben Coburn <btcoburn@silicodon.net>
118 function addMediaLogEntry($date, $id, $type=DOKU_CHANGE_TYPE_EDIT
, $summary='', $extra='', $flags=null){
123 if(!$date) $date = time(); //use current time if none supplied
124 $remote = clientIP(true);
125 $user = $_SERVER['REMOTE_USER'];
127 $strip = array("\t", "\n");
131 'type' => str_replace($strip, '', $type),
134 'sum' => utf8_substr(str_replace($strip, '', $summary),0,255),
135 'extra' => str_replace($strip, '', $extra)
138 // add changelog lines
139 $logline = implode("\t", $logline)."\n";
140 io_saveFile($conf['media_changelog'],$logline,true); //global media changelog cache
141 io_saveFile(mediaMetaFN($id,'.changes'),$logline,true); //media file's changelog
145 * returns an array of recently changed files using the
148 * The following constants can be used to control which changes are
149 * included. Add them together as needed.
151 * RECENTS_SKIP_DELETED - don't include deleted pages
152 * RECENTS_SKIP_MINORS - don't include minor changes
153 * RECENTS_SKIP_SUBSPACES - don't include subspaces
154 * RECENTS_MEDIA_CHANGES - return media changes instead of page changes
155 * RECENTS_MEDIA_PAGES_MIXED - return both media changes and page changes
157 * @param int $first number of first entry returned (for paginating
158 * @param int $num return $num entries
159 * @param string $ns restrict to given namespace
160 * @param int $flags see above
161 * @return array recently changed files
163 * @author Ben Coburn <btcoburn@silicodon.net>
164 * @author Kate Arzamastseva <pshns@ukr.net>
166 function getRecents($first,$num,$ns='',$flags=0){
174 // read all recent changes. (kept short)
175 if ($flags & RECENTS_MEDIA_CHANGES
) {
176 $lines = @file
($conf['media_changelog']);
178 $lines = @file
($conf['changelog']);
180 $lines_position = count($lines)-1;
181 $media_lines_position = 0;
182 $media_lines = array();
184 if ($flags & RECENTS_MEDIA_PAGES_MIXED
) {
185 $media_lines = @file
($conf['media_changelog']);
186 $media_lines_position = count($media_lines)-1;
189 $seen = array(); // caches seen lines, _handleRecent() skips them
192 while ($lines_position >= 0 ||
(($flags & RECENTS_MEDIA_PAGES_MIXED
) && $media_lines_position >=0)) {
193 if (empty($rec) && $lines_position >= 0) {
194 $rec = _handleRecent(@$lines[$lines_position], $ns, $flags, $seen);
200 if (($flags & RECENTS_MEDIA_PAGES_MIXED
) && empty($media_rec) && $media_lines_position >= 0) {
201 $media_rec = _handleRecent(@$media_lines[$media_lines_position], $ns, $flags | RECENTS_MEDIA_CHANGES
, $seen);
203 $media_lines_position --;
207 if (($flags & RECENTS_MEDIA_PAGES_MIXED
) && @$media_rec['date'] >= @$rec['date']) {
208 $media_lines_position--;
215 if ($flags & RECENTS_MEDIA_CHANGES
) $x['media'] = true;
218 if(--$first >= 0) continue; // skip first entries
221 // break when we have enough entries
222 if($count >= $num){ break; }
228 * returns an array of files changed since a given time using the
231 * The following constants can be used to control which changes are
232 * included. Add them together as needed.
234 * RECENTS_SKIP_DELETED - don't include deleted pages
235 * RECENTS_SKIP_MINORS - don't include minor changes
236 * RECENTS_SKIP_SUBSPACES - don't include subspaces
237 * RECENTS_MEDIA_CHANGES - return media changes instead of page changes
239 * @param int $from date of the oldest entry to return
240 * @param int $to date of the newest entry to return (for pagination, optional)
241 * @param string $ns restrict to given namespace (optional)
242 * @param int $flags see above (optional)
243 * @return array of files
245 * @author Michael Hamann <michael@content-space.de>
246 * @author Ben Coburn <btcoburn@silicodon.net>
248 function getRecentsSince($from,$to=null,$ns='',$flags=0){
252 if($to && $to < $from)
255 // read all recent changes. (kept short)
256 if ($flags & RECENTS_MEDIA_CHANGES
) {
257 $lines = @file
($conf['media_changelog']);
259 $lines = @file
($conf['changelog']);
261 if(!$lines) return $recent;
263 // we start searching at the end of the list
264 $lines = array_reverse($lines);
267 $seen = array(); // caches seen lines, _handleRecent() skips them
269 foreach($lines as $line){
270 $rec = _handleRecent($line, $ns, $flags, $seen);
272 if ($rec['date'] >= $from) {
273 if (!$to ||
$rec['date'] <= $to) {
282 return array_reverse($recent);
286 * Internal function used by getRecents
288 * don't call directly
291 * @author Andreas Gohr <andi@splitbrain.org>
292 * @author Ben Coburn <btcoburn@silicodon.net>
294 function _handleRecent($line,$ns,$flags,&$seen){
295 if(empty($line)) return false; //skip empty lines
297 // split the line into parts
298 $recent = parseChangelogLine($line);
299 if ($recent===false) { return false; }
302 if(isset($seen[$recent['id']])) return false;
305 if($recent['type']===DOKU_CHANGE_TYPE_MINOR_EDIT
&& ($flags & RECENTS_SKIP_MINORS
)) return false;
307 // remember in seen to skip additional sights
308 $seen[$recent['id']] = 1;
310 // check if it's a hidden page
311 if(isHiddenPage($recent['id'])) return false;
314 if (($ns) && (strpos($recent['id'],$ns.':') !== 0)) return false;
316 // exclude subnamespaces
317 if (($flags & RECENTS_SKIP_SUBSPACES
) && (getNS($recent['id']) != $ns)) return false;
320 if ($flags & RECENTS_MEDIA_CHANGES
) {
321 $recent['perms'] = auth_quickaclcheck(getNS($recent['id']).':*');
323 $recent['perms'] = auth_quickaclcheck($recent['id']);
325 if ($recent['perms'] < AUTH_READ
) return false;
328 if($flags & RECENTS_SKIP_DELETED
){
329 $fn = (($flags & RECENTS_MEDIA_CHANGES
) ?
mediaFN($recent['id']) : wikiFN($recent['id']));
330 if(!@file_exists
($fn)) return false;
337 * Get the changelog information for a specific page id
338 * and revision (timestamp). Adjacent changelog lines
339 * are optimistically parsed and cached to speed up
340 * consecutive calls to getRevisionInfo. For large
341 * changelog files, only the chunk containing the
342 * requested changelog line is read.
344 * @author Ben Coburn <btcoburn@silicodon.net>
345 * @author Kate Arzamastseva <pshns@ukr.net>
347 function getRevisionInfo($id, $rev, $chunk_size=8192, $media=false) {
348 global $cache_revinfo;
349 $cache =& $cache_revinfo;
350 if (!isset($cache[$id])) { $cache[$id] = array(); }
353 // check if it's already in the memory cache
354 if (isset($cache[$id]) && isset($cache[$id][$rev])) {
355 return $cache[$id][$rev];
359 $file = mediaMetaFN($id, '.changes');
361 $file = metaFN($id, '.changes');
363 if (!@file_exists
($file)) { return false; }
364 if (filesize($file)<$chunk_size ||
$chunk_size==0) {
366 $lines = file($file);
367 if ($lines===false) { return false; }
370 $fp = fopen($file, 'rb'); // "file pointer"
371 if ($fp===false) { return false; }
373 fseek($fp, 0, SEEK_END
);
379 while ($tail-$head>$chunk_size) {
380 $finger = $head+
floor(($tail-$head)/2.0);
382 fgets($fp); // slip the finger forward to a new line
383 $finger = ftell($fp);
384 $tmp = fgets($fp); // then read at that location
385 $tmp = parseChangelogLine($tmp);
386 $finger_rev = $tmp['date'];
387 if ($finger==$head ||
$finger==$tail) { break; }
388 if ($finger_rev>$rev) {
396 // cound not find chunk, assume requested rev is missing
403 $chunk_size = max($tail-$head, 0); // found chunk size
406 while ($got<$chunk_size && !feof($fp)) {
407 $tmp = @fread
($fp, max($chunk_size-$got, 0));
408 if ($tmp===false) { break; } //error state
409 $got +
= strlen($tmp);
412 $lines = explode("\n", $chunk);
413 array_pop($lines); // remove trailing newline
417 // parse and cache changelog lines
418 foreach ($lines as $value) {
419 $tmp = parseChangelogLine($value);
421 $cache[$id][$tmp['date']] = $tmp;
424 if (!isset($cache[$id][$rev])) { return false; }
425 return $cache[$id][$rev];
429 * Return a list of page revisions numbers
430 * Does not guarantee that the revision exists in the attic,
431 * only that a line with the date exists in the changelog.
432 * By default the current revision is skipped.
434 * id: the page of interest
435 * first: skip the first n changelog lines
436 * num: number of revisions to return
438 * The current revision is automatically skipped when the page exists.
439 * See $INFO['meta']['last_change'] for the current revision.
441 * For efficiency, the log lines are parsed and cached for later
442 * calls to getRevisionInfo. Large changelog files are read
443 * backwards in chunks until the requested number of changelog
444 * lines are recieved.
446 * @author Ben Coburn <btcoburn@silicodon.net>
447 * @author Kate Arzamastseva <pshns@ukr.net>
449 function getRevisions($id, $first, $num, $chunk_size=8192, $media=false) {
450 global $cache_revinfo;
451 $cache =& $cache_revinfo;
452 if (!isset($cache[$id])) { $cache[$id] = array(); }
458 $file = mediaMetaFN($id, '.changes');
460 $file = metaFN($id, '.changes');
463 $chunk_size = max($chunk_size, 0);
466 } else if (!$media && @file_exists
(wikiFN($id)) ||
$media && @file_exists
(mediaFN($id))) {
467 // skip current revision if the page exists
468 $first = max($first+
1, 0);
471 if (!@file_exists
($file)) { return $revs; }
472 if (filesize($file)<$chunk_size ||
$chunk_size==0) {
474 $lines = file($file);
475 if ($lines===false) { return $revs; }
477 // read chunks backwards
478 $fp = fopen($file, 'rb'); // "file pointer"
479 if ($fp===false) { return $revs; }
480 fseek($fp, 0, SEEK_END
);
484 $finger = max($tail-$chunk_size, 0);
485 while ($count<$num+
$first) {
489 fgets($fp); // slip the finger forward to a new line
493 // was the chunk big enough? if not, take another bite
494 if($nl > 0 && $tail <= $nl){
495 $finger = max($finger-$chunk_size, 0);
503 $read_size = max($tail-$finger, 0); // found chunk size
505 while ($got<$read_size && !feof($fp)) {
506 $tmp = @fread
($fp, max($read_size-$got, 0));
507 if ($tmp===false) { break; } //error state
508 $got +
= strlen($tmp);
511 $tmp = explode("\n", $chunk);
512 array_pop($tmp); // remove trailing newline
514 // combine with previous chunk
515 $count +
= count($tmp);
516 $lines = array_merge($tmp, $lines);
519 if ($finger==0) { break; } // already read all the lines
522 $finger = max($tail-$chunk_size, 0);
528 // skip parsing extra lines
529 $num = max(min(count($lines)-$first, $num), 0);
530 if ($first>0 && $num>0) { $lines = array_slice($lines, max(count($lines)-$first-$num, 0), $num); }
531 else if ($first>0 && $num==0) { $lines = array_slice($lines, 0, max(count($lines)-$first, 0)); }
532 else if ($first==0 && $num>0) { $lines = array_slice($lines, max(count($lines)-$num, 0)); }
534 // handle lines in reverse order
535 for ($i = count($lines)-1; $i >= 0; $i--) {
536 $tmp = parseChangelogLine($lines[$i]);
538 $cache[$id][$tmp['date']] = $tmp;
539 $revs[] = $tmp['date'];
547 * Get the nth revision left or right handside for a specific page id
548 * and revision (timestamp). For large changelog files, only the chunk containing the
549 * reference revision $rev is read and sometimes a next chunck.
551 * Adjacent changelog lines are optimistically parsed and cached to speed up
552 * consecutive calls to getRevisionInfo.
554 * @author Gerrit Uitslag <klapinklapin@gmail.com>
556 * based on getRevisionInfo by
557 * @author Ben Coburn <btcoburn@silicodon.net>
558 * @author Kate Arzamastseva <pshns@ukr.net>
560 * @param string $id pageid
561 * @param int $rev revision timestamp used as startdate (doesn't need to be revisionnumber)
562 * @param int $direction give position of returned revision with respect to $rev; positive=next, negative=prev
563 * @param int $chunk_size maximum block size
565 * @return bool|string
567 function getRelativeRevision($id, $rev, $direction, $chunk_size = 8192, $media = false) {
568 global $cache_revinfo;
570 $cache =& $cache_revinfo;
571 if(!isset($cache[$id])) {
572 $cache[$id] = array();
576 //no direction given or last rev, so no follow-up
577 if(!$direction ||
($direction > 0 && $rev == $INFO['meta']['last_change']['date'])) {
582 $file = mediaMetaFN($id, '.changes');
584 $file = metaFN($id, '.changes');
586 if(!@file_exists
($file)) {
590 //get $lines from changelog
596 if(filesize($file) < $chunk_size ||
$chunk_size == 0) {
598 $uses_chuncks = false;
599 $lines = file($file);
600 if($lines === false) {
605 $uses_chuncks = true;
606 $fp = fopen($file, 'rb'); // "file pointer"
611 fseek($fp, 0, SEEK_END
); //set file position indicator 0 byte from end.
612 $tail = ftell($fp); //return current position of pointer as integer
618 while($tail - $head > $chunk_size) {
619 $finger = $head +
floor(($tail - $head) / 2.0);
620 $finger = getNewlinepointer($fp, $finger);
621 $tmp = fgets($fp); // then read at that location
622 $tmp = parseChangelogLine($tmp);
623 $finger_rev = $tmp['date'];
624 if($finger == $head ||
$finger == $tail) {
627 if($finger_rev > $rev) {
634 if($tail - $head < 1) {
635 // cound not find chunk, assume requested rev is missing
640 $lines = readChunk($fp, $head, $tail);
643 // look for revisions later then $rev, when founded count till the wanted revision is reached
644 // also parse and cache changelog lines that pass
648 $checkotherchunck = true; //always runs once
649 while(!$relrev && $checkotherchunck) {
652 foreach($lines as $value) {
653 $tmp = parseChangelogLine($value);
655 $cache[$id][$tmp['date']] = $tmp;
656 //look for revs older then reference $rev and select $direction-th one
657 if($tmp['date'] > $rev) {
659 if($revcounter == $direction) {
660 $relrev = $tmp['date'];
666 //parse in reverse order
667 for($i = count($lines) - 1; $i >= 0; $i--) {
668 $tmp = parseChangelogLine($lines[$i]);
670 $cache[$id][$tmp['date']] = $tmp;
671 //look for revs older then reference $rev and select $direction-th one
672 if($tmp['date'] < $rev) {
674 if($revcounter == abs($direction)) {
675 $relrev = $tmp['date'];
682 //true when $rev is found, but not the wanted follow-up.
683 $checkotherchunck = $uses_chuncks
684 && ($tmp['date'] == $rev ||
($revcounter > 0 && !$relrev))
687 if($checkotherchunck) {
689 //get interval of next chunck, smaller than $chunck_size
692 $tail = $head +
floor($chunk_size * (2 / 3));
693 while($lookpointer) {
694 $tail = min($tail, $eof);
695 $tail = getNewlinepointer($fp, $tail);
696 $lookpointer = $tail - $head > $chunk_size;
698 $tail = $head +
floor(($tail - $head) / 2);
703 $head = max($tail - $chunk_size, 0);
704 $head = getNewlinepointer($fp, $head);
708 $lines = readChunk($fp, $head, $tail);
715 if($relrev == $INFO['meta']['last_change']['date']) {
722 * Read chunk and return array with lines of given chunck.
723 * Has no check if $head and $tail are really at a new line
725 * @param $fp resource filepointer
726 * @param $head int start point chunck
727 * @param $tail int end point chunck
728 * @return array lines read from chunck
730 function readChunk($fp, $head, $tail) {
732 $chunk_size = max($tail - $head, 0); // found chunk size
735 while($got < $chunk_size && !feof($fp)) {
736 $tmp = @fread
($fp, max($chunk_size - $got, 0));
740 $got +
= strlen($tmp);
743 $lines = explode("\n", $chunk);
744 array_pop($lines); // remove trailing newline
749 * Set pointer to first new line after $finger and return its position
751 * @param $fp resource filepointer
752 * @param $finger int a pointer
753 * @return int pointer
755 function getNewlinepointer($fp, $finger) {
757 fgets($fp); // slip the finger forward to a new line