xref: /dokuwiki/inc/changelog.php (revision 8e69fd30702f1101a9c70dbe6eac6f45f9af3970)
1<?php
2/**
3 * Changelog handling functions
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 */
8
9// Constants for known core changelog line types.
10// Use these in place of string literals for more readable code.
11define('DOKU_CHANGE_TYPE_CREATE',       'C');
12define('DOKU_CHANGE_TYPE_EDIT',         'E');
13define('DOKU_CHANGE_TYPE_MINOR_EDIT',   'e');
14define('DOKU_CHANGE_TYPE_DELETE',       'D');
15define('DOKU_CHANGE_TYPE_REVERT',       'R');
16
17/**
18 * parses a changelog line into it's components
19 *
20 * @author Ben Coburn <btcoburn@silicodon.net>
21 */
22function parseChangelogLine($line) {
23    $tmp = explode("\t", $line);
24    if ($tmp!==false && count($tmp)>1) {
25        $info = array();
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)
33        return $info;
34    } else { return false; }
35}
36
37/**
38 * Add's an entry to the changelog and saves the metadata for the page
39 *
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.
46 *                             Availible flags:
47 *                             - ExternalEdit - mark as an external edit.
48 *
49 * @author Andreas Gohr <andi@splitbrain.org>
50 * @author Esther Brunner <wikidesign@gmail.com>
51 * @author Ben Coburn <btcoburn@silicodon.net>
52 */
53function addLogEntry($date, $id, $type=DOKU_CHANGE_TYPE_EDIT, $summary='', $extra='', $flags=null){
54    global $conf, $INFO;
55
56    // check for special flags as keys
57    if (!is_array($flags)) { $flags = array(); }
58    $flagExternalEdit = isset($flags['ExternalEdit']);
59
60    $id = cleanid($id);
61    $file = wikiFN($id);
62    $created = @filectime($file);
63    $minor = ($type===DOKU_CHANGE_TYPE_MINOR_EDIT);
64    $wasRemoved = ($type===DOKU_CHANGE_TYPE_DELETE);
65
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']:'';
69
70    $strip = array("\t", "\n");
71    $logline = array(
72            'date'  => $date,
73            'ip'    => $remote,
74            'type'  => str_replace($strip, '', $type),
75            'id'    => $id,
76            'user'  => $user,
77            'sum'   => str_replace($strip, '', $summary),
78            'extra' => str_replace($strip, '', $extra)
79            );
80
81    // update metadata
82    if (!$wasRemoved) {
83        $oldmeta = p_read_metadata($id);
84        $meta    = array();
85        if (!$INFO['exists'] && empty($oldmeta['persistent']['date']['created'])){ // newly created
86            $meta['date']['created'] = $created;
87            if ($user){
88                $meta['creator'] = $INFO['userinfo']['name'];
89                $meta['user']    = $user;
90            }
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'];
99        }
100        $meta['last_change'] = $logline;
101        p_set_metadata($id, $meta);
102    }
103
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
108}
109
110/**
111 * Add's an entry to the media changelog
112 *
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>
117 */
118function addMediaLogEntry($date, $id, $type=DOKU_CHANGE_TYPE_EDIT, $summary='', $extra='', $flags=null){
119    global $conf;
120
121    $id = cleanid($id);
122
123    if(!$date) $date = time(); //use current time if none supplied
124    $remote = clientIP(true);
125    $user   = $_SERVER['REMOTE_USER'];
126
127    $strip = array("\t", "\n");
128    $logline = array(
129            'date'  => $date,
130            'ip'    => $remote,
131            'type'  => str_replace($strip, '', $type),
132            'id'    => $id,
133            'user'  => $user,
134            'sum'   => str_replace($strip, '', $summary),
135            'extra' => str_replace($strip, '', $extra)
136            );
137
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
142}
143
144/**
145 * returns an array of recently changed files using the
146 * changelog
147 *
148 * The following constants can be used to control which changes are
149 * included. Add them together as needed.
150 *
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
156 *
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 bool   $flags   see above
161 *
162 * @author Ben Coburn <btcoburn@silicodon.net>
163 * @author Kate Arzamastseva <pshns@ukr.net>
164 */
165function getRecents($first,$num,$ns='',$flags=0){
166    global $conf;
167    $recent = array();
168    $count  = 0;
169
170    if(!$num)
171        return $recent;
172
173    // read all recent changes. (kept short)
174    if ($flags & RECENTS_MEDIA_CHANGES) {
175        $lines = @file($conf['media_changelog']);
176    } else {
177        $lines = @file($conf['changelog']);
178    }
179    $lines_position = count($lines)-1;
180
181    if ($flags & RECENTS_MEDIA_PAGES_MIXED) {
182        $media_lines = @file($conf['media_changelog']);
183        $media_lines_position = count($media_lines)-1;
184    }
185
186    $seen = array(); // caches seen lines, _handleRecent() skips them
187
188    // handle lines
189    while ($lines_position >= 0 || (($flags & RECENTS_MEDIA_PAGES_MIXED) && $media_lines_position >=0)) {
190        if (empty($rec) && $lines_position >= 0) {
191            $rec = _handleRecent(@$lines[$lines_position], $ns, $flags, $seen);
192            if (!$rec) {
193                $lines_position --;
194                continue;
195            }
196        }
197        if (($flags & RECENTS_MEDIA_PAGES_MIXED) && empty($media_rec) && $media_lines_position >= 0) {
198            $media_rec = _handleRecent(@$media_lines[$media_lines_position], $ns, $flags, $seen);
199            if (!$media_rec) {
200            	$media_lines_position --;
201            	continue;
202            }
203        }
204        if (($flags & RECENTS_MEDIA_PAGES_MIXED) && @$media_rec['date'] >= @$rec['date']) {
205            $media_lines_position--;
206            $x = $media_rec;
207            $media_rec = false;
208        } else {
209            $lines_position--;
210            $x = $rec;
211            $rec = false;
212        }
213        if(--$first >= 0) continue; // skip first entries
214        $recent[] = $x;
215        $count++;
216        // break when we have enough entries
217        if($count >= $num){ break; }
218    }
219    return $recent;
220}
221
222/**
223 * returns an array of files changed since a given time using the
224 * changelog
225 *
226 * The following constants can be used to control which changes are
227 * included. Add them together as needed.
228 *
229 * RECENTS_SKIP_DELETED   - don't include deleted pages
230 * RECENTS_SKIP_MINORS    - don't include minor changes
231 * RECENTS_SKIP_SUBSPACES - don't include subspaces
232 * RECENTS_MEDIA_CHANGES  - return media changes instead of page changes
233 *
234 * @param int    $from    date of the oldest entry to return
235 * @param int    $to      date of the newest entry to return (for pagination, optional)
236 * @param string $ns      restrict to given namespace (optional)
237 * @param bool   $flags   see above (optional)
238 *
239 * @author Michael Hamann <michael@content-space.de>
240 * @author Ben Coburn <btcoburn@silicodon.net>
241 */
242function getRecentsSince($from,$to=null,$ns='',$flags=0){
243    global $conf;
244    $recent = array();
245
246    if($to && $to < $from)
247        return $recent;
248
249    // read all recent changes. (kept short)
250    if ($flags & RECENTS_MEDIA_CHANGES) {
251        $lines = @file($conf['media_changelog']);
252    } else {
253        $lines = @file($conf['changelog']);
254    }
255
256    // we start searching at the end of the list
257    $lines = array_reverse($lines);
258
259    // handle lines
260    $seen = array(); // caches seen lines, _handleRecent() skips them
261
262    foreach($lines as $line){
263        $rec = _handleRecent($line, $ns, $flags, $seen);
264        if($rec !== false) {
265            if ($rec['date'] >= $from) {
266                if (!$to || $rec['date'] <= $to) {
267                    $recent[] = $rec;
268                }
269            } else {
270                break;
271            }
272        }
273    }
274
275    return array_reverse($recent);
276}
277
278/**
279 * Internal function used by getRecents
280 *
281 * don't call directly
282 *
283 * @see getRecents()
284 * @author Andreas Gohr <andi@splitbrain.org>
285 * @author Ben Coburn <btcoburn@silicodon.net>
286 */
287function _handleRecent($line,$ns,$flags,&$seen){
288    if(empty($line)) return false;   //skip empty lines
289
290    // split the line into parts
291    $recent = parseChangelogLine($line);
292    if ($recent===false) { return false; }
293
294    // skip seen ones
295    if(isset($seen[$recent['id']])) return false;
296
297    // skip minors
298    if($recent['type']===DOKU_CHANGE_TYPE_MINOR_EDIT && ($flags & RECENTS_SKIP_MINORS)) return false;
299
300    // remember in seen to skip additional sights
301    $seen[$recent['id']] = 1;
302
303    // check if it's a hidden page
304    if(isHiddenPage($recent['id'])) return false;
305
306    // filter namespace
307    if (($ns) && (strpos($recent['id'],$ns.':') !== 0)) return false;
308
309    // exclude subnamespaces
310    if (($flags & RECENTS_SKIP_SUBSPACES) && (getNS($recent['id']) != $ns)) return false;
311
312    // check ACL
313    $recent['perms'] = auth_quickaclcheck($recent['id']);
314    if ($recent['perms'] < AUTH_READ) return false;
315
316    // check existance
317    $fn = (($flags & RECENTS_MEDIA_CHANGES) ? mediaFN($recent['id']) : wikiFN($recent['id']));
318    if((!@file_exists($fn)) && ($flags & RECENTS_SKIP_DELETED)) return false;
319
320    return $recent;
321}
322
323/**
324 * Get the changelog information for a specific page id
325 * and revision (timestamp). Adjacent changelog lines
326 * are optimistically parsed and cached to speed up
327 * consecutive calls to getRevisionInfo. For large
328 * changelog files, only the chunk containing the
329 * requested changelog line is read.
330 *
331 * @author Ben Coburn <btcoburn@silicodon.net>
332 * @author Kate Arzamastseva <pshns@ukr.net>
333 */
334function getRevisionInfo($id, $rev, $chunk_size=8192, $media=false) {
335    global $cache_revinfo;
336    $cache =& $cache_revinfo;
337    if (!isset($cache[$id])) { $cache[$id] = array(); }
338    $rev = max($rev, 0);
339
340    // check if it's already in the memory cache
341    if (isset($cache[$id]) && isset($cache[$id][$rev])) {
342        return $cache[$id][$rev];
343    }
344
345    if ($media) {
346        $file = mediaMetaFN($id, '.changes');
347    } else {
348        $file = metaFN($id, '.changes');
349    }
350    if (!@file_exists($file)) { return false; }
351    if (filesize($file)<$chunk_size || $chunk_size==0) {
352        // read whole file
353        $lines = file($file);
354        if ($lines===false) { return false; }
355    } else {
356        // read by chunk
357        $fp = fopen($file, 'rb'); // "file pointer"
358        if ($fp===false) { return false; }
359        $head = 0;
360        fseek($fp, 0, SEEK_END);
361        $tail = ftell($fp);
362        $finger = 0;
363        $finger_rev = 0;
364
365        // find chunk
366        while ($tail-$head>$chunk_size) {
367            $finger = $head+floor(($tail-$head)/2.0);
368            fseek($fp, $finger);
369            fgets($fp); // slip the finger forward to a new line
370            $finger = ftell($fp);
371            $tmp = fgets($fp); // then read at that location
372            $tmp = parseChangelogLine($tmp);
373            $finger_rev = $tmp['date'];
374            if ($finger==$head || $finger==$tail) { break; }
375            if ($finger_rev>$rev) {
376                $tail = $finger;
377            } else {
378                $head = $finger;
379            }
380        }
381
382        if ($tail-$head<1) {
383            // cound not find chunk, assume requested rev is missing
384            fclose($fp);
385            return false;
386        }
387
388        // read chunk
389        $chunk = '';
390        $chunk_size = max($tail-$head, 0); // found chunk size
391        $got = 0;
392        fseek($fp, $head);
393        while ($got<$chunk_size && !feof($fp)) {
394            $tmp = @fread($fp, max($chunk_size-$got, 0));
395            if ($tmp===false) { break; } //error state
396            $got += strlen($tmp);
397            $chunk .= $tmp;
398        }
399        $lines = explode("\n", $chunk);
400        array_pop($lines); // remove trailing newline
401        fclose($fp);
402    }
403
404    // parse and cache changelog lines
405    foreach ($lines as $value) {
406        $tmp = parseChangelogLine($value);
407        if ($tmp!==false) {
408            $cache[$id][$tmp['date']] = $tmp;
409        }
410    }
411    if (!isset($cache[$id][$rev])) { return false; }
412    return $cache[$id][$rev];
413}
414
415/**
416 * Return a list of page revisions numbers
417 * Does not guarantee that the revision exists in the attic,
418 * only that a line with the date exists in the changelog.
419 * By default the current revision is skipped.
420 *
421 * id:    the page of interest
422 * first: skip the first n changelog lines
423 * num:   number of revisions to return
424 *
425 * The current revision is automatically skipped when the page exists.
426 * See $INFO['meta']['last_change'] for the current revision.
427 *
428 * For efficiency, the log lines are parsed and cached for later
429 * calls to getRevisionInfo. Large changelog files are read
430 * backwards in chunks until the requested number of changelog
431 * lines are recieved.
432 *
433 * @author Ben Coburn <btcoburn@silicodon.net>
434 * @author Kate Arzamastseva <pshns@ukr.net>
435 */
436function getRevisions($id, $first, $num, $chunk_size=8192, $media=false) {
437    global $cache_revinfo;
438    $cache =& $cache_revinfo;
439    if (!isset($cache[$id])) { $cache[$id] = array(); }
440
441    $revs = array();
442    $lines = array();
443    $count  = 0;
444    if ($media) {
445        $file = mediaMetaFN($id, '.changes');
446    } else {
447        $file = metaFN($id, '.changes');
448    }
449    $num = max($num, 0);
450    $chunk_size = max($chunk_size, 0);
451    if ($first<0) { $first = 0; }
452    else if (!$media && @file_exists(wikiFN($id)) || $media && @file_exists(mediaFN($id))) {
453        // skip current revision if the page exists
454        $first = max($first+1, 0);
455    }
456
457    if (!@file_exists($file)) { return $revs; }
458    if (filesize($file)<$chunk_size || $chunk_size==0) {
459        // read whole file
460        $lines = file($file);
461        if ($lines===false) { return $revs; }
462    } else {
463        // read chunks backwards
464        $fp = fopen($file, 'rb'); // "file pointer"
465        if ($fp===false) { return $revs; }
466        fseek($fp, 0, SEEK_END);
467        $tail = ftell($fp);
468
469        // chunk backwards
470        $finger = max($tail-$chunk_size, 0);
471        while ($count<$num+$first) {
472            fseek($fp, $finger);
473            if ($finger>0) {
474                fgets($fp); // slip the finger forward to a new line
475                $finger = ftell($fp);
476            }
477
478            // read chunk
479            if ($tail<=$finger) { break; }
480            $chunk = '';
481            $read_size = max($tail-$finger, 0); // found chunk size
482            $got = 0;
483            while ($got<$read_size && !feof($fp)) {
484                $tmp = @fread($fp, max($read_size-$got, 0));
485                if ($tmp===false) { break; } //error state
486                $got += strlen($tmp);
487                $chunk .= $tmp;
488            }
489            $tmp = explode("\n", $chunk);
490            array_pop($tmp); // remove trailing newline
491
492            // combine with previous chunk
493            $count += count($tmp);
494            $lines = array_merge($tmp, $lines);
495
496            // next chunk
497            if ($finger==0) { break; } // already read all the lines
498            else {
499                $tail = $finger;
500                $finger = max($tail-$chunk_size, 0);
501            }
502        }
503        fclose($fp);
504    }
505
506    // skip parsing extra lines
507    $num = max(min(count($lines)-$first, $num), 0);
508    if      ($first>0 && $num>0)  { $lines = array_slice($lines, max(count($lines)-$first-$num, 0), $num); }
509    else if ($first>0 && $num==0) { $lines = array_slice($lines, 0, max(count($lines)-$first, 0)); }
510    else if ($first==0 && $num>0) { $lines = array_slice($lines, max(count($lines)-$num, 0)); }
511
512    // handle lines in reverse order
513    for ($i = count($lines)-1; $i >= 0; $i--) {
514        $tmp = parseChangelogLine($lines[$i]);
515        if ($tmp!==false) {
516            $cache[$id][$tmp['date']] = $tmp;
517            $revs[] = $tmp['date'];
518        }
519    }
520
521    return $revs;
522}
523
524
525