xref: /dokuwiki/inc/changelog.php (revision cbe26ad6152c998c9a3290b0d321030c61dc7f1b)
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 *
156 * @param int    $first   number of first entry returned (for paginating
157 * @param int    $num     return $num entries
158 * @param string $ns      restrict to given namespace
159 * @param bool   $flags   see above
160 *
161 * @author Ben Coburn <btcoburn@silicodon.net>
162 */
163function getRecents($first,$num,$ns='',$flags=0){
164    global $conf;
165    $recent = array();
166    $count  = 0;
167
168    if(!$num)
169        return $recent;
170
171    // read all recent changes. (kept short)
172    if ($flags & RECENTS_MEDIA_CHANGES) {
173        $lines = @file($conf['media_changelog']);
174    } else {
175        $lines = @file($conf['changelog']);
176    }
177
178    // handle lines
179    $seen = array(); // caches seen lines, _handleRecent() skips them
180    for($i = count($lines)-1; $i >= 0; $i--){
181        $rec = _handleRecent($lines[$i], $ns, $flags, $seen);
182        if($rec !== false) {
183            if(--$first >= 0) continue; // skip first entries
184            $recent[] = $rec;
185            $count++;
186            // break when we have enough entries
187            if($count >= $num){ break; }
188        }
189    }
190
191    return $recent;
192}
193
194/**
195 * returns an array of files changed since a given time using the
196 * changelog
197 *
198 * The following constants can be used to control which changes are
199 * included. Add them together as needed.
200 *
201 * RECENTS_SKIP_DELETED   - don't include deleted pages
202 * RECENTS_SKIP_MINORS    - don't include minor changes
203 * RECENTS_SKIP_SUBSPACES - don't include subspaces
204 * RECENTS_MEDIA_CHANGES  - return media changes instead of page changes
205 *
206 * @param int    $from    date of the oldest entry to return
207 * @param int    $to      date of the newest entry to return (for pagination, optional)
208 * @param string $ns      restrict to given namespace (optional)
209 * @param bool   $flags   see above (optional)
210 *
211 * @author Michael Hamann <michael@content-space.de>
212 * @author Ben Coburn <btcoburn@silicodon.net>
213 */
214function getRecentsSince($from,$to=null,$ns='',$flags=0){
215    global $conf;
216    $recent = array();
217
218    if($to && $to < $from)
219        return $recent;
220
221    // read all recent changes. (kept short)
222    if ($flags & RECENTS_MEDIA_CHANGES) {
223        $lines = @file($conf['media_changelog']);
224    } else {
225        $lines = @file($conf['changelog']);
226    }
227
228    // we start searching at the end of the list
229    $lines = array_reverse($lines);
230
231    // handle lines
232    $seen = array(); // caches seen lines, _handleRecent() skips them
233
234    foreach($lines as $line){
235        $rec = _handleRecent($line, $ns, $flags, $seen);
236        if($rec !== false) {
237            if ($rec['date'] >= $from) {
238                if (!$to || $rec['date'] <= $to) {
239                    $recent[] = $rec;
240                }
241            } else {
242                break;
243            }
244        }
245    }
246
247    return array_reverse($recent);
248}
249
250/**
251 * Internal function used by getRecents
252 *
253 * don't call directly
254 *
255 * @see getRecents()
256 * @author Andreas Gohr <andi@splitbrain.org>
257 * @author Ben Coburn <btcoburn@silicodon.net>
258 */
259function _handleRecent($line,$ns,$flags,&$seen){
260    if(empty($line)) return false;   //skip empty lines
261
262    // split the line into parts
263    $recent = parseChangelogLine($line);
264    if ($recent===false) { return false; }
265
266    // skip seen ones
267    if(isset($seen[$recent['id']])) return false;
268
269    // skip minors
270    if($recent['type']===DOKU_CHANGE_TYPE_MINOR_EDIT && ($flags & RECENTS_SKIP_MINORS)) return false;
271
272    // remember in seen to skip additional sights
273    $seen[$recent['id']] = 1;
274
275    // check if it's a hidden page
276    if(isHiddenPage($recent['id'])) return false;
277
278    // filter namespace
279    if (($ns) && (strpos($recent['id'],$ns.':') !== 0)) return false;
280
281    // exclude subnamespaces
282    if (($flags & RECENTS_SKIP_SUBSPACES) && (getNS($recent['id']) != $ns)) return false;
283
284    // check ACL
285    $recent['perms'] = auth_quickaclcheck($recent['id']);
286    if ($recent['perms'] < AUTH_READ) return false;
287
288    // check existance
289    $fn = (($flags & RECENTS_MEDIA_CHANGES) ? mediaFN($recent['id']) : wikiFN($recent['id']));
290    if((!@file_exists($fn)) && ($flags & RECENTS_SKIP_DELETED)) return false;
291
292    return $recent;
293}
294
295/**
296 * Get the changelog information for a specific page id
297 * and revision (timestamp). Adjacent changelog lines
298 * are optimistically parsed and cached to speed up
299 * consecutive calls to getRevisionInfo. For large
300 * changelog files, only the chunk containing the
301 * requested changelog line is read.
302 *
303 * @author Ben Coburn <btcoburn@silicodon.net>
304 */
305function getRevisionInfo($id, $rev, $chunk_size=8192, $media=false) {
306    global $cache_revinfo;
307    $cache =& $cache_revinfo;
308    if (!isset($cache[$id])) { $cache[$id] = array(); }
309    $rev = max($rev, 0);
310
311    // check if it's already in the memory cache
312    if (isset($cache[$id]) && isset($cache[$id][$rev])) {
313        return $cache[$id][$rev];
314    }
315
316    if ($media) {
317        $file = mediaMetaFN($id, '.changes');
318    } else {
319        $file = metaFN($id, '.changes');
320    }
321    if (!@file_exists($file)) { return false; }
322    if (filesize($file)<$chunk_size || $chunk_size==0) {
323        // read whole file
324        $lines = file($file);
325        if ($lines===false) { return false; }
326    } else {
327        // read by chunk
328        $fp = fopen($file, 'rb'); // "file pointer"
329        if ($fp===false) { return false; }
330        $head = 0;
331        fseek($fp, 0, SEEK_END);
332        $tail = ftell($fp);
333        $finger = 0;
334        $finger_rev = 0;
335
336        // find chunk
337        while ($tail-$head>$chunk_size) {
338            $finger = $head+floor(($tail-$head)/2.0);
339            fseek($fp, $finger);
340            fgets($fp); // slip the finger forward to a new line
341            $finger = ftell($fp);
342            $tmp = fgets($fp); // then read at that location
343            $tmp = parseChangelogLine($tmp);
344            $finger_rev = $tmp['date'];
345            if ($finger==$head || $finger==$tail) { break; }
346            if ($finger_rev>$rev) {
347                $tail = $finger;
348            } else {
349                $head = $finger;
350            }
351        }
352
353        if ($tail-$head<1) {
354            // cound not find chunk, assume requested rev is missing
355            fclose($fp);
356            return false;
357        }
358
359        // read chunk
360        $chunk = '';
361        $chunk_size = max($tail-$head, 0); // found chunk size
362        $got = 0;
363        fseek($fp, $head);
364        while ($got<$chunk_size && !feof($fp)) {
365            $tmp = @fread($fp, max($chunk_size-$got, 0));
366            if ($tmp===false) { break; } //error state
367            $got += strlen($tmp);
368            $chunk .= $tmp;
369        }
370        $lines = explode("\n", $chunk);
371        array_pop($lines); // remove trailing newline
372        fclose($fp);
373    }
374
375    // parse and cache changelog lines
376    foreach ($lines as $value) {
377        $tmp = parseChangelogLine($value);
378        if ($tmp!==false) {
379            $cache[$id][$tmp['date']] = $tmp;
380        }
381    }
382    if (!isset($cache[$id][$rev])) { return false; }
383    return $cache[$id][$rev];
384}
385
386/**
387 * Return a list of page revisions numbers
388 * Does not guarantee that the revision exists in the attic,
389 * only that a line with the date exists in the changelog.
390 * By default the current revision is skipped.
391 *
392 * id:    the page of interest
393 * first: skip the first n changelog lines
394 * num:   number of revisions to return
395 *
396 * The current revision is automatically skipped when the page exists.
397 * See $INFO['meta']['last_change'] for the current revision.
398 *
399 * For efficiency, the log lines are parsed and cached for later
400 * calls to getRevisionInfo. Large changelog files are read
401 * backwards in chunks until the requested number of changelog
402 * lines are recieved.
403 *
404 * @author Ben Coburn <btcoburn@silicodon.net>
405 */
406function getRevisions($id, $first, $num, $chunk_size=8192, $media=false) {
407    global $cache_revinfo;
408    $cache =& $cache_revinfo;
409    if (!isset($cache[$id])) { $cache[$id] = array(); }
410
411    $revs = array();
412    $lines = array();
413    $count  = 0;
414    if ($media) {
415        $file = mediaMetaFN($id, '.changes');
416    } else {
417        $file = metaFN($id, '.changes');
418    }
419    $num = max($num, 0);
420    $chunk_size = max($chunk_size, 0);
421    if ($first<0) { $first = 0; }
422    else if (!$media && @file_exists(wikiFN($id)) || $media && @file_exists(mediaFN($id))) {
423        // skip current revision if the page exists
424        $first = max($first+1, 0);
425    }
426
427    if (!@file_exists($file)) { return $revs; }
428    if (filesize($file)<$chunk_size || $chunk_size==0) {
429        // read whole file
430        $lines = file($file);
431        if ($lines===false) { return $revs; }
432    } else {
433        // read chunks backwards
434        $fp = fopen($file, 'rb'); // "file pointer"
435        if ($fp===false) { return $revs; }
436        fseek($fp, 0, SEEK_END);
437        $tail = ftell($fp);
438
439        // chunk backwards
440        $finger = max($tail-$chunk_size, 0);
441        while ($count<$num+$first) {
442            fseek($fp, $finger);
443            if ($finger>0) {
444                fgets($fp); // slip the finger forward to a new line
445                $finger = ftell($fp);
446            }
447
448            // read chunk
449            if ($tail<=$finger) { break; }
450            $chunk = '';
451            $read_size = max($tail-$finger, 0); // found chunk size
452            $got = 0;
453            while ($got<$read_size && !feof($fp)) {
454                $tmp = @fread($fp, max($read_size-$got, 0));
455                if ($tmp===false) { break; } //error state
456                $got += strlen($tmp);
457                $chunk .= $tmp;
458            }
459            $tmp = explode("\n", $chunk);
460            array_pop($tmp); // remove trailing newline
461
462            // combine with previous chunk
463            $count += count($tmp);
464            $lines = array_merge($tmp, $lines);
465
466            // next chunk
467            if ($finger==0) { break; } // already read all the lines
468            else {
469                $tail = $finger;
470                $finger = max($tail-$chunk_size, 0);
471            }
472        }
473        fclose($fp);
474    }
475
476    // skip parsing extra lines
477    $num = max(min(count($lines)-$first, $num), 0);
478    if      ($first>0 && $num>0)  { $lines = array_slice($lines, max(count($lines)-$first-$num, 0), $num); }
479    else if ($first>0 && $num==0) { $lines = array_slice($lines, 0, max(count($lines)-$first, 0)); }
480    else if ($first==0 && $num>0) { $lines = array_slice($lines, max(count($lines)-$num, 0)); }
481
482    // handle lines in reverse order
483    for ($i = count($lines)-1; $i >= 0; $i--) {
484        $tmp = parseChangelogLine($lines[$i]);
485        if ($tmp!==false) {
486            $cache[$id][$tmp['date']] = $tmp;
487            $revs[] = $tmp['date'];
488        }
489    }
490
491    return $revs;
492}
493
494
495