xref: /dokuwiki/inc/changelog.php (revision 040f0e135c37c5b544f16277ff69205369df5f1f)
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'   => utf8_substr(str_replace($strip, '', $summary),0,255),
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'   => utf8_substr(str_replace($strip, '', $summary),0,255),
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 int    $flags   see above
161 * @return array recently changed files
162 *
163 * @author Ben Coburn <btcoburn@silicodon.net>
164 * @author Kate Arzamastseva <pshns@ukr.net>
165 */
166function getRecents($first,$num,$ns='',$flags=0){
167    global $conf;
168    $recent = array();
169    $count  = 0;
170
171    if(!$num)
172        return $recent;
173
174    // read all recent changes. (kept short)
175    if ($flags & RECENTS_MEDIA_CHANGES) {
176        $lines = @file($conf['media_changelog']);
177    } else {
178        $lines = @file($conf['changelog']);
179    }
180    $lines_position = count($lines)-1;
181    $media_lines_position = 0;
182    $media_lines = array();
183
184    if ($flags & RECENTS_MEDIA_PAGES_MIXED) {
185        $media_lines = @file($conf['media_changelog']);
186        $media_lines_position = count($media_lines)-1;
187    }
188
189    $seen = array(); // caches seen lines, _handleRecent() skips them
190
191    // handle lines
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);
195            if (!$rec) {
196                $lines_position --;
197                continue;
198            }
199        }
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);
202            if (!$media_rec) {
203                $media_lines_position --;
204                continue;
205            }
206        }
207        if (($flags & RECENTS_MEDIA_PAGES_MIXED) && @$media_rec['date'] >= @$rec['date']) {
208            $media_lines_position--;
209            $x = $media_rec;
210            $x['media'] = true;
211            $media_rec = false;
212        } else {
213            $lines_position--;
214            $x = $rec;
215            if ($flags & RECENTS_MEDIA_CHANGES) $x['media'] = true;
216            $rec = false;
217        }
218        if(--$first >= 0) continue; // skip first entries
219        $recent[] = $x;
220        $count++;
221        // break when we have enough entries
222        if($count >= $num){ break; }
223    }
224    return $recent;
225}
226
227/**
228 * returns an array of files changed since a given time using the
229 * changelog
230 *
231 * The following constants can be used to control which changes are
232 * included. Add them together as needed.
233 *
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
238 *
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
244 *
245 * @author Michael Hamann <michael@content-space.de>
246 * @author Ben Coburn <btcoburn@silicodon.net>
247 */
248function getRecentsSince($from,$to=null,$ns='',$flags=0){
249    global $conf;
250    $recent = array();
251
252    if($to && $to < $from)
253        return $recent;
254
255    // read all recent changes. (kept short)
256    if ($flags & RECENTS_MEDIA_CHANGES) {
257        $lines = @file($conf['media_changelog']);
258    } else {
259        $lines = @file($conf['changelog']);
260    }
261    if(!$lines) return $recent;
262
263    // we start searching at the end of the list
264    $lines = array_reverse($lines);
265
266    // handle lines
267    $seen = array(); // caches seen lines, _handleRecent() skips them
268
269    foreach($lines as $line){
270        $rec = _handleRecent($line, $ns, $flags, $seen);
271        if($rec !== false) {
272            if ($rec['date'] >= $from) {
273                if (!$to || $rec['date'] <= $to) {
274                    $recent[] = $rec;
275                }
276            } else {
277                break;
278            }
279        }
280    }
281
282    return array_reverse($recent);
283}
284
285/**
286 * Internal function used by getRecents
287 *
288 * don't call directly
289 *
290 * @see getRecents()
291 * @author Andreas Gohr <andi@splitbrain.org>
292 * @author Ben Coburn <btcoburn@silicodon.net>
293 */
294function _handleRecent($line,$ns,$flags,&$seen){
295    if(empty($line)) return false;   //skip empty lines
296
297    // split the line into parts
298    $recent = parseChangelogLine($line);
299    if ($recent===false) { return false; }
300
301    // skip seen ones
302    if(isset($seen[$recent['id']])) return false;
303
304    // skip minors
305    if($recent['type']===DOKU_CHANGE_TYPE_MINOR_EDIT && ($flags & RECENTS_SKIP_MINORS)) return false;
306
307    // remember in seen to skip additional sights
308    $seen[$recent['id']] = 1;
309
310    // check if it's a hidden page
311    if(isHiddenPage($recent['id'])) return false;
312
313    // filter namespace
314    if (($ns) && (strpos($recent['id'],$ns.':') !== 0)) return false;
315
316    // exclude subnamespaces
317    if (($flags & RECENTS_SKIP_SUBSPACES) && (getNS($recent['id']) != $ns)) return false;
318
319    // check ACL
320    if ($flags & RECENTS_MEDIA_CHANGES) {
321        $recent['perms'] = auth_quickaclcheck(getNS($recent['id']).':*');
322    } else {
323        $recent['perms'] = auth_quickaclcheck($recent['id']);
324    }
325    if ($recent['perms'] < AUTH_READ) return false;
326
327    // check existance
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;
331    }
332
333    return $recent;
334}
335
336/**
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.
343 *
344 * @author Ben Coburn <btcoburn@silicodon.net>
345 * @author Kate Arzamastseva <pshns@ukr.net>
346 */
347function getRevisionInfo($id, $rev, $chunk_size=8192, $media=false) {
348    global $cache_revinfo;
349    $cache =& $cache_revinfo;
350    if (!isset($cache[$id])) { $cache[$id] = array(); }
351    $rev = max($rev, 0);
352
353    // check if it's already in the memory cache
354    if (isset($cache[$id]) && isset($cache[$id][$rev])) {
355        return $cache[$id][$rev];
356    }
357
358    if ($media) {
359        $file = mediaMetaFN($id, '.changes');
360    } else {
361        $file = metaFN($id, '.changes');
362    }
363
364    //read lines from changelog
365    list($fp, $lines) = _readloglines($file, $rev, $chunk_size);
366    if($fp) {
367        fclose($fp);
368    }
369    if(empty($lines)) return false;
370
371    // parse and cache changelog lines
372    foreach ($lines as $value) {
373        $tmp = parseChangelogLine($value);
374        if ($tmp!==false) {
375            $cache[$id][$tmp['date']] = $tmp;
376        }
377    }
378    if (!isset($cache[$id][$rev])) { return false; }
379    return $cache[$id][$rev];
380}
381
382/**
383 * Return a list of page revisions numbers
384 * Does not guarantee that the revision exists in the attic,
385 * only that a line with the date exists in the changelog.
386 * By default the current revision is skipped.
387 *
388 * id:    the page of interest
389 * first: skip the first n changelog lines
390 * num:   number of revisions to return
391 *
392 * The current revision is automatically skipped when the page exists.
393 * See $INFO['meta']['last_change'] for the current revision.
394 *
395 * For efficiency, the log lines are parsed and cached for later
396 * calls to getRevisionInfo. Large changelog files are read
397 * backwards in chunks until the requested number of changelog
398 * lines are recieved.
399 *
400 * @author Ben Coburn <btcoburn@silicodon.net>
401 * @author Kate Arzamastseva <pshns@ukr.net>
402 */
403function getRevisions($id, $first, $num, $chunk_size=8192, $media=false) {
404    global $cache_revinfo;
405    $cache =& $cache_revinfo;
406    if (!isset($cache[$id])) { $cache[$id] = array(); }
407
408    $revs = array();
409    $lines = array();
410    $count  = 0;
411    if ($media) {
412        $file = mediaMetaFN($id, '.changes');
413    } else {
414        $file = metaFN($id, '.changes');
415    }
416    $num = max($num, 0);
417    $chunk_size = max($chunk_size, 0);
418    if ($first<0) {
419        $first = 0;
420    } else if (!$media && @file_exists(wikiFN($id)) || $media && @file_exists(mediaFN($id))) {
421        // skip current revision if the page exists
422        $first = max($first+1, 0);
423    }
424
425    if (!@file_exists($file)) { return $revs; }
426    if (filesize($file)<$chunk_size || $chunk_size==0) {
427        // read whole file
428        $lines = file($file);
429        if ($lines===false) { return $revs; }
430    } else {
431        // read chunks backwards
432        $fp = fopen($file, 'rb'); // "file pointer"
433        if ($fp===false) { return $revs; }
434        fseek($fp, 0, SEEK_END);
435        $tail = ftell($fp);
436
437        // chunk backwards
438        $finger = max($tail-$chunk_size, 0);
439        while ($count<$num+$first) {
440            fseek($fp, $finger);
441            $nl = $finger;
442            if ($finger>0) {
443                fgets($fp); // slip the finger forward to a new line
444                $nl = ftell($fp);
445            }
446
447            // was the chunk big enough? if not, take another bite
448            if($nl > 0 && $tail <= $nl){
449                $finger = max($finger-$chunk_size, 0);
450                continue;
451            }else{
452                $finger = $nl;
453            }
454
455            // read chunk
456            $chunk = '';
457            $read_size = max($tail-$finger, 0); // found chunk size
458            $got = 0;
459            while ($got<$read_size && !feof($fp)) {
460                $tmp = @fread($fp, max($read_size-$got, 0));
461                if ($tmp===false) { break; } //error state
462                $got += strlen($tmp);
463                $chunk .= $tmp;
464            }
465            $tmp = explode("\n", $chunk);
466            array_pop($tmp); // remove trailing newline
467
468            // combine with previous chunk
469            $count += count($tmp);
470            $lines = array_merge($tmp, $lines);
471
472            // next chunk
473            if ($finger==0) { break; } // already read all the lines
474            else {
475                $tail = $finger;
476                $finger = max($tail-$chunk_size, 0);
477            }
478        }
479        fclose($fp);
480    }
481
482    // skip parsing extra lines
483    $num = max(min(count($lines)-$first, $num), 0);
484    if      ($first>0 && $num>0)  { $lines = array_slice($lines, max(count($lines)-$first-$num, 0), $num); }
485    else if ($first>0 && $num==0) { $lines = array_slice($lines, 0, max(count($lines)-$first, 0)); }
486    else if ($first==0 && $num>0) { $lines = array_slice($lines, max(count($lines)-$num, 0)); }
487
488    // handle lines in reverse order
489    for ($i = count($lines)-1; $i >= 0; $i--) {
490        $tmp = parseChangelogLine($lines[$i]);
491        if ($tmp!==false) {
492            $cache[$id][$tmp['date']] = $tmp;
493            $revs[] = $tmp['date'];
494        }
495    }
496
497    return $revs;
498}
499
500/**
501 * Get the nth revision left or right handside  for a specific page id
502 * and revision (timestamp). For large changelog files, only the chunk containing the
503 * reference revision $rev is read and sometimes a next chunck.
504 *
505 * Adjacent changelog lines are optimistically parsed and cached to speed up
506 * consecutive calls to getRevisionInfo.
507 *
508 * @author Gerrit Uitslag <klapinklapin@gmail.com>
509 *
510 * based on getRevisionInfo by
511 * @author Ben Coburn <btcoburn@silicodon.net>
512 * @author Kate Arzamastseva <pshns@ukr.net>
513 *
514 * @param string     $id pageid
515 * @param int        $rev revision timestamp used as startdate (doesn't need to be revisionnumber)
516 * @param int        $direction give position of returned revision with respect to $rev; positive=next, negative=prev
517 * @param int        $chunk_size maximum block size
518 * @param bool       $media
519 * @return bool|string
520 */
521function getRelativeRevision($id, $rev, $direction, $chunk_size = 8192, $media = false) {
522    global $cache_revinfo;
523    global $INFO;
524    $cache =& $cache_revinfo;
525    if(!isset($cache[$id])) {
526        $cache[$id] = array();
527    }
528    $rev = max($rev, 0);
529    $direction = (int) $direction;
530
531    //no direction given or last rev, so no follow-up
532    if(!$direction ||
533        ($direction > 0
534         && isset($INFO['meta']['last_change']['date'])
535         && $rev == $INFO['meta']['last_change']['date'])) {
536        return false;
537    }
538
539    if($media) {
540        $file = mediaMetaFN($id, '.changes');
541    } else {
542        $file = metaFN($id, '.changes');
543    }
544
545    //get lines from changelog
546    list($fp, $lines, $head, $tail, $eof) = _readloglines($file, $rev, $chunk_size);
547    if(empty($lines)) return false;
548
549    // look for revisions later/earlier then $rev, when founded count till the wanted revision is reached
550    // also parse and cache changelog lines for getRevisionInfo().
551    $revcounter       = 0;
552    $relativerev      = false;
553    $checkotherchunck = true; //always runs once
554    while(!$relativerev && $checkotherchunck) {
555        $tmp = array();
556        //parse in normal or reverse order
557        $count = count($lines);
558        if($direction > 0) {
559            $start = 0;
560            $step  = 1;
561        } else {
562            $start = $count - 1;
563            $step  = -1;
564        }
565        for($i = $start; $i >= 0 && $i < $count; $i = $i + $step) {
566            $tmp = parseChangelogLine($lines[$i]);
567            if($tmp !== false) {
568                $cache[$id][$tmp['date']] = $tmp;
569                //look for revs older/earlier then reference $rev and select $direction-th one
570                if(($direction > 0 && $tmp['date'] > $rev) || ($direction < 0 && $tmp['date'] < $rev)) {
571                    $revcounter++;
572                    if($revcounter == abs($direction)) {
573                        $relativerev = $tmp['date'];
574                    }
575                }
576            }
577        }
578
579        //true when $rev is found, but not the wanted follow-up.
580        $checkotherchunck = $fp
581                            && ($tmp['date'] == $rev || ($revcounter > 0 && !$relativerev))
582                            && !(($tail == $eof && $direction > 0) || ($head == 0 && $direction < 0));
583
584        if($checkotherchunck) {
585            //search bounds of chunck, rounded on new line, but smaller than $chunck_size
586            if($direction > 0) {
587                $head        = $tail;
588                $lookpointer = true;
589                $tail        = $head + floor($chunk_size * (2 / 3));
590                while($lookpointer) {
591                    $tail        = min($tail, $eof);
592                    $tail        = _getNewlinepointer($fp, $tail);
593                    $lookpointer = $tail - $head > $chunk_size;
594                    if($lookpointer) {
595                        $tail = $head + floor(($tail - $head) / 2);
596                    }
597                    if($tail == $head) break;
598                }
599            } else {
600                $tail = $head;
601                $head = max($tail - $chunk_size, 0);
602                $head = _getNewlinepointer($fp, $head);
603            }
604
605            //load next chunck
606            $lines = _readChunk($fp, $head, $tail);
607            if(empty($lines)) break;
608        }
609    }
610    if($fp) {
611        fclose($fp);
612    }
613
614    if(isset($INFO['meta']['last_change']) && $relativerev == $INFO['meta']['last_change']['date']) {
615        return 'current';
616    }
617    return $relativerev;
618}
619
620/**
621 * get lines from changelog.
622 * If file larger than $chuncksize, only chunck is read that could contain $rev.
623 *
624 * @param int $file         path to changelog file
625 * @param int $rev          revision timestamp
626 * @param int $chunk_size   maximum block size read from file
627 * @return array(fp, array(changeloglines), $head, $tail, $eof)|bool
628 *     returns false when not succeed. fp only defined for chuck reading, needs closing.
629 */
630function _readloglines($file, $rev, $chunk_size) {
631    if(!@file_exists($file)) {
632        return false;
633    }
634
635    $fp    = null;
636    $head  = 0;
637    $tail  = 0;
638    $eof   = 0;
639    if(filesize($file) < $chunk_size || $chunk_size == 0) {
640        // read whole file
641        $lines = file($file);
642        if($lines === false) {
643            return false;
644        }
645    } else {
646        // read by chunk
647        $fp = fopen($file, 'rb'); // "file pointer"
648        if($fp === false) {
649            return false;
650        }
651        $head = 0;
652        fseek($fp, 0, SEEK_END);
653        $eof        = ftell($fp);
654        $tail       = $eof;
655        $finger     = 0;
656        $finger_rev = 0;
657
658        // find chunk
659        while($tail - $head > $chunk_size) {
660            $finger     = $head + floor(($tail - $head) / 2.0);
661            $finger     = _getNewlinepointer($fp, $finger);
662            $tmp        = fgets($fp);
663            $tmp        = parseChangelogLine($tmp);
664            $finger_rev = $tmp['date'];
665            if($finger == $head || $finger == $tail) {
666                break;
667            }
668            if($finger_rev > $rev) {
669                $tail = $finger;
670            } else {
671                $head = $finger;
672            }
673        }
674
675        if($tail - $head < 1) {
676            // cound not find chunk, assume requested rev is missing
677            fclose($fp);
678            return false;
679        }
680
681        $lines = _readChunk($fp, $head, $tail);
682    }
683    return array(
684        $fp,
685        $lines,
686        $head,
687        $tail,
688        $eof
689    );
690}
691
692/**
693 * Read chunk and return array with lines of given chunck.
694 * Has no check if $head and $tail are really at a new line
695 *
696 * @param $fp resource filepointer
697 * @param $head int start point chunck
698 * @param $tail int end point chunck
699 * @return array lines read from chunck
700 */
701function _readChunk($fp, $head, $tail) {
702    $chunk      = '';
703    $chunk_size = max($tail - $head, 0); // found chunk size
704    $got        = 0;
705    fseek($fp, $head);
706    while($got < $chunk_size && !feof($fp)) {
707        $tmp = @fread($fp, max($chunk_size - $got, 0));
708        if($tmp === false) { //error state
709            break;
710        }
711        $got += strlen($tmp);
712        $chunk .= $tmp;
713    }
714    $lines = explode("\n", $chunk);
715    array_pop($lines); // remove trailing newline
716    return $lines;
717}
718
719/**
720 * Set pointer to first new line after $finger and return its position
721 *
722 * @param $fp resource filepointer
723 * @param $finger int a pointer
724 * @return int pointer
725 */
726function _getNewlinepointer($fp, $finger) {
727    fseek($fp, $finger);
728    fgets($fp); // slip the finger forward to a new line
729    return ftell($fp);
730}
731