Adopting the GPL
[viewsvn.git] / includes / svnlib.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # ViewSVN [#]version[#]
5 || # Copyright ©2002-[#]year[#] Iris Studios, Inc.
6 || #
7 || # This program is free software; you can redistribute it and/or modify
8 || # it under the terms of the GNU General Public License as published by
9 || # the Free Software Foundation; version [#]gpl[#] of the License.
10 || #
11 || # This program is distributed in the hope that it will be useful, but
12 || # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 || # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 || # more details.
15 || #
16 || # You should have received a copy of the GNU General Public License along
17 || # with this program; if not, write to the Free Software Foundation, Inc.,
18 || # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
19 || ###################################################################
20 \*=====================================================================*/
21
22 /**
23 * Command line interface with the SVN commands
24 *
25 * @package ViewSVN
26 */
27
28 /**
29 * Interacts with the command line subsystem to
30 * access SVN information
31 *
32 * @package ViewSVN
33 * @version $Id$
34 */
35 class SVNLib
36 {
37 /**
38 * Path to the SVN binary
39 * @var string
40 */
41 var $svnpath;
42
43 /**
44 * Common command system
45 * @var object
46 */
47 var $common;
48
49 /**
50 * Constructor: validate SVN path
51 *
52 * @param string Path to SVN binary
53 */
54 function SVNLib($svnpath)
55 {
56 global $viewsvn;
57
58 $this->svnpath = $viewsvn->shell->cmd($svnpath);
59
60 $this->common =& new SVNCommon();
61
62 $access = $viewsvn->shell->exec($this->svnpath . ' --version');
63
64 if (!$access)
65 {
66 $viewsvn->trigger->error('svn binary could not be found');
67 }
68
69 if (!preg_match('#^svn, version (.*?)\)$#i', trim($access[0])))
70 {
71 $viewsvn->trigger->error('svn binary does not pass test');
72 }
73 }
74
75 /**
76 * Prepares data for output
77 *
78 * @access public
79 *
80 * @param string Standard data
81 *
82 * @return string Output-ready data
83 */
84 function format($string)
85 {
86 // convert entities
87 $string = htmlspecialchars($string);
88
89 // tabs to 5 spaces
90 $string = str_replace("\t", ' ', $string);
91
92 // spaces to nbsp
93 $string = str_replace(' ', '&nbsp;', $string);
94
95 // convert advanced diff
96 $string = str_replace(array('{@++}', '{@--}'), array('<span class="diff_add_bit">', '<span class="diff_del_bit">'), $string);
97 $string = str_replace(array('{/@++}', '{/@--}'), '</span>', $string);
98
99 // nl2br
100 $string = nl2br($string);
101
102 return $string;
103 }
104
105 /**
106 * Executes the SVN binary
107 *
108 * @access private
109 *
110 * @param string Command
111 *
112 * @return array Output
113 */
114 function svn($command)
115 {
116 global $viewsvn;
117
118 $output = $viewsvn->shell->exec($this->svnpath . ' ' . $command . ' 2>&1');
119 $temp = implode("\n", $output);
120 if (strpos($temp, '(apr' . '_err=') !== false)
121 {
122 $viewsvn->trigger->error(nl2br($temp));
123 }
124 return $output;
125 }
126
127 /**
128 * SVN Wrapper: standard command system
129 *
130 * @access private
131 *
132 * @param string SVN command
133 * @param string Repository
134 * @param string Path
135 * @param integer Revision
136 *
137 * @return array Lines of output
138 */
139 function std($command, $repos, $path, $revision)
140 {
141 global $viewsvn;
142
143 $revision = $this->rev($revision);
144 $repospath = $viewsvn->repos->fetch_path($repos, false);
145
146 return $this->svn($command . ' -r' . $revision . ' ' . $repospath . $path);
147 }
148
149 /**
150 * SVN Wrapper: blame
151 *
152 * @access protected
153 *
154 * @param string Repository
155 * @param string Path
156 * @param integer Revision
157 *
158 * @return array Lines of blame output
159 */
160 function blame($repos, $path, $revision)
161 {
162 return $this->std('blame', $repos, $path, $revision);
163 }
164
165 /**
166 * SVN Wrapper: cat
167 *
168 * @access protected
169 *
170 * @param string Repository
171 * @param string Path
172 * @param integer Revision
173 *
174 * @return array Lines of cat output
175 */
176 function cat($repos, $path, $revision)
177 {
178 return $this->std('cat', $repos, $path, $revision);
179 }
180
181 /**
182 * SVN Wrapper: diff
183 *
184 * @access protected
185 *
186 * @param string Repository
187 * @param string Path
188 * @param integer Lower revision
189 * @param integer Higher revision
190 *
191 * @return array Lines of diff output
192 */
193 function diff($repos, $path, $lorev, $hirev)
194 {
195 global $viewsvn;
196
197 $hirev = $this->rev($hirev);
198 $lorev = $this->rev($lorev);
199 if ($lorev == 'HEAD')
200 {
201 $lorev = 1;
202 }
203
204 if (is_integer($hirev) AND is_integer($lorev))
205 {
206 if ($lorev > $hirev)
207 {
208 $lorev = $hirev - 1;
209 }
210 if ($lorev == $hirev)
211 {
212 $lorev = 0;
213 }
214 }
215
216 $repospath = $viewsvn->repos->fetch_path($repos, false);
217
218 return $this->svn('diff -r' . $lorev . ':' . $hirev . ' ' . $repospath . $path);
219 }
220
221 /**
222 * SVN Wrapper: log
223 *
224 * @access protected
225 *
226 * @param string Repository
227 * @param string Path
228 * @param integer Lower revision
229 * @param integer Higher revision
230 *
231 * @return array Lines of log output
232 */
233 function log($repos, $path, $lorev, $hirev)
234 {
235 global $viewsvn;
236
237 $hirev = $this->rev($hirev);
238 $lorev = $this->rev($hirev);
239 if ($lorev == 'HEAD')
240 {
241 $lorev = 0;
242 }
243
244 if (is_integer($hirev) AND is_integer($lorev))
245 {
246 if ($lorev > $hirev)
247 {
248 $lorev = $hirev - 1;
249 }
250 if ($lorev == $hirev)
251 {
252 $lorev = 0;
253 }
254 }
255
256 $repospath = $viewsvn->repos->fetch_path($repos, false);
257
258 return $this->svn('log -v -r' . $hirev . ':' . $lorev . ' ' . $repospath . $path);
259 }
260
261 /**
262 * SVN Wrapper: ls (list)
263 *
264 * @access protected
265 *
266 * @param string Repository
267 * @param string Path
268 * @param integer Revision
269 *
270 * @return array Lines of list output
271 */
272 function ls($repos, $path, $revision)
273 {
274 return $this->std('list', $repos, $path, $revision);
275 }
276
277 /**
278 * Generates a clean revision number
279 *
280 * @access public
281 *
282 * @param integer Revision number
283 *
284 * @return mixed Cleaned revision or HEAD
285 */
286 function rev($revision)
287 {
288 if (($revision = intval($revision)) < 1)
289 {
290 $revision = 'HEAD';
291 }
292 return $revision;
293 }
294 }
295
296 /**
297 * Commonly executed SVN commands that return data
298 * used in many parts of the system
299 *
300 * @package ViewSVN
301 * @version $Id$
302 */
303 class SVNCommon
304 {
305 /**
306 * Registry object
307 * @var object
308 */
309 var $registry;
310
311 /**
312 * List of revisions
313 * @var array
314 */
315 var $revisions;
316
317 /**
318 * List of logs
319 * @var array
320 */
321 var $logs;
322
323 /**
324 * Constructor: bind with registry
325 */
326 function SVNCommon()
327 {
328 global $viewsvn;
329
330 $this->registry =& $viewsvn;
331 }
332
333 /**
334 * Checks to see if the given universal path is
335 * a directory
336 *
337 * @access public
338 *
339 * @param string Universal path
340 *
341 * @return bool Directory or not
342 */
343 function isdir($path)
344 {
345 $output = $this->registry->svn->std('info', $this->registry->paths->fetch_repos($path), $this->registry->paths->fetch_path($path), 'HEAD');
346
347 foreach ($output AS $line)
348 {
349 if (preg_match('#^Node Kind: (.*)#', $line, $matches))
350 {
351 if (trim(strtolower($matches[1])) == 'directory')
352 {
353 return true;
354 }
355 }
356 }
357
358 return false;
359 }
360
361 /**
362 * Get a list of revisions for a path
363 *
364 * @access public
365 *
366 * @param string Universal path
367 *
368 * @return array Key revisions
369 */
370 function fetch_revs($path)
371 {
372 if (!isset($this->revisions["$path"]))
373 {
374 $log = $this->fetch_logs($path);
375
376 $revs = array_keys($log);
377
378 $this->revisions["$path"] = array(
379 'HEAD' => $revs[0],
380 'START' => $revs[ count($revs) - 1 ],
381 'revs' => $revs
382 );
383 }
384
385 return $this->revisions["$path"];
386 }
387
388 /**
389 * Gets the revision that is marked as HEAD
390 *
391 * @access public
392 *
393 * @param string Universal path
394 *
395 * @return integer Revision
396 */
397 function fetch_head_rev($path)
398 {
399 $revs = $this->fetch_revs($path);
400 return $revs['HEAD'];
401 }
402
403 /**
404 * Returns the previous revision to the one given
405 *
406 * @access public
407 *
408 * @param string Universal path
409 * @param integer Arbitrary revision
410 *
411 * @return integer Previous revision (-1 if none)
412 */
413 function fetch_prev_rev($path, $current)
414 {
415 $revs = $this->fetch_revs($path);
416
417 if ($current == 'HEAD')
418 {
419 $current = $this->fetch_head_rev($path);
420 }
421
422 $index = array_search($current, $revs['revs']);
423 if ($current === false)
424 {
425 $message->trigger->error('revision ' . $current . ' is not in ' . $path);
426 }
427
428 if (isset($revs['revs'][ $index + 1 ]))
429 {
430 return $revs['revs'][ $index + 1 ];
431 }
432 else
433 {
434 return -1;
435 }
436 }
437
438 /**
439 * Get a list of logs
440 *
441 * @access public
442 *
443 * @param string Universal path
444 *
445 * @return array Log data
446 */
447 function fetch_logs($path)
448 {
449 if (!isset($this->logs["$path"]))
450 {
451 $log = new SVNLog($this->registry->paths->fetch_repos($path), $this->registry->paths->fetch_path($path), 0, 0);
452
453 $this->logs["$path"] = $log->fetch();
454 }
455
456 return $this->logs["$path"];
457 }
458
459 /**
460 * Returns a given log entry for a path
461 * and revision
462 *
463 * @access public
464 *
465 * @param string Universal path
466 * @param integer Arbitrary revision
467 *
468 * @return array Log entry
469 */
470 function fetch_log($path, $rev)
471 {
472 $logs = $this->fetch_logs($path);
473
474 $rev = $this->registry->svn->rev($rev);
475 if ($rev == 'HEAD')
476 {
477 $rev = $this->fetch_head_rev($path);
478 }
479
480 if (isset($logs["$rev"]))
481 {
482 return $logs["$rev"];
483 }
484 else
485 {
486 return null;
487 }
488 }
489 }
490
491 /**
492 * Annotation/blame system; constructs an array
493 * that is ready for output
494 *
495 * @package ViewSVN
496 * @version $Id$
497 */
498 class SVNBlame
499 {
500 /**
501 * Array of blame information
502 * @var array
503 */
504 var $blame = array();
505
506 /**
507 * Raw "svn blame" output
508 * @var array
509 */
510 var $rawoutput;
511
512 /**
513 * Constructor: create blame and store data
514 *
515 * @param string Repository
516 * @param string Path
517 * @param integer Revision
518 */
519 function SVNBlame($repos, $path, $revision)
520 {
521 global $viewsvn;
522
523 $this->rawoutput = $viewsvn->svn->blame($repos, $path, $revision);
524 $this->process();
525 }
526
527 /**
528 * Returns blame for display
529 *
530 * @access public
531 *
532 * @return array Blame data
533 */
534 function fetch()
535 {
536 return $this->blame;
537 }
538
539 /**
540 * Parses the blame data
541 *
542 * @access private
543 */
544 function process()
545 {
546 $lineno = 1;
547
548 foreach ($this->rawoutput AS $line)
549 {
550 if (preg_match('#^\s+([0-9]+)\s+([\w\.\-_]+)\s(.*)$#', $line, $matches))
551 {
552 $this->blame[] = array(
553 'rev' => $matches[1],
554 'author' => $matches[2],
555 'line' => $matches[3],
556 'lineno' => $lineno++
557 );
558 }
559 // a blank line
560 else if (preg_match('#^\s+([0-9]+)\s+([\w\.\-_]+)$#', $line, $matches))
561 {
562 $this->blame[] = array(
563 'rev' => $matches[1],
564 'author' => $matches[2],
565 'line' => '',
566 'lineno' => $lineno++
567 );
568 }
569 }
570 }
571 }
572
573 /**
574 * Log management system; creates a complex list
575 * of SVN log information
576 *
577 * @package ViewSVN
578 * @version $Id$
579 */
580 class SVNLog
581 {
582 /**
583 * Array of logs
584 * @var array
585 */
586 var $logs = array();
587
588 /**
589 * Raw "svn log" output
590 * @var array
591 */
592 var $rawoutput;
593
594 /**
595 * Constructor: create log store for the given file
596 *
597 * @param string Repository
598 * @param string Path
599 * @param integer Lower revision
600 * @param integer Higher revision
601 */
602 function SVNLog($repos, $path, $lorev, $hirev)
603 {
604 global $viewsvn;
605
606 $this->rawoutput = $viewsvn->svn->log($repos, $path, $lorev, $hirev);
607 $this->process();
608 }
609
610 /**
611 * Returns logs for display
612 *
613 * @access public
614 *
615 * @return array Log data
616 */
617 function fetch()
618 {
619 return $this->logs;
620 }
621
622 /**
623 * Splits up the raw output into a usable log
624 *
625 * @access private
626 */
627 function process()
628 {
629 $lastrev = 0;
630
631 for ($i = 1; $i <= count($this->rawoutput) - 1; $i++)
632 {
633 $line = $this->rawoutput["$i"];
634
635 if (preg_match('#^r([0-9]*) \| (.*?) \| (....-..-.. ..:..:..) ([0-9\-]*) \((.*?)\) \| ([0-9]*) lines?$#', $line, $matches))
636 {
637 if (isset($this->logs["$lastrev"]))
638 {
639 $this->logs["$lastrev"]['message'] = $this->strip_last_line($this->logs["$lastrev"]['message']);
640 }
641
642 $this->logs["$matches[1]"] = array(
643 'rev' => $matches[1],
644 'author' => $matches[2],
645 'date' => $matches[3],
646 'timezone' => $matches[4],
647 'lines' => $matches[6],
648 'message' => ''
649 );
650
651 $lastrev = $matches[1];
652 }
653 else if (preg_match('#^\s+([ADMR])\s(.*)#', $line, $matches))
654 {
655 $this->logs["$lastrev"]['files'][] = array(
656 'action' => $matches[1],
657 'file' => $matches[2]
658 );
659 }
660 else
661 {
662 if (trim($line) != 'Changed paths:')
663 {
664 $this->logs["$lastrev"]['message'] .= $line . "\n";
665 }
666 }
667 }
668
669 if (isset($this->logs["$lastrev"]))
670 {
671 $this->logs["$lastrev"]['message'] = $this->strip_last_line($this->logs["$lastrev"]['message']);
672 }
673 }
674
675 /**
676 * Trims the last dash line off a message
677 *
678 * @access private
679 *
680 * @param string Message with annoying-ass line
681 *
682 * @return string Clean string
683 */
684 function strip_last_line($string)
685 {
686 return trim(preg_replace("#\n(.*?)\n$#", '', $string));
687 }
688 }
689
690 /**
691 * Diff system; constructs a diff array that
692 * is ready for output
693 *
694 * @package ViewSVN
695 */
696 class SVNDiff
697 {
698 /**
699 * Array of diff information
700 * @var array
701 */
702 var $diff = array();
703
704 /**
705 * Raw "svn diff" output
706 * @var array
707 */
708 var $rawoutput;
709
710 /**
711 * Constructor: create and store diff data
712 *
713 * @param string Repository
714 * @param string Path
715 * @param integer Lower revision
716 * @param integer Higher revision
717 */
718 function SVNDiff($repos, $path, $lorev, $hirev)
719 {
720 global $viewsvn;
721
722 $this->rawoutput = $viewsvn->svn->diff($repos, $path, $lorev, $hirev);
723 $this->process();
724 }
725
726 /**
727 * Returns diffs for display
728 *
729 * @access public
730 *
731 * @return array Diff data
732 */
733 function fetch()
734 {
735 return $this->diff;
736 }
737
738 /**
739 * Processes and prepares diff data
740 *
741 * @access private
742 */
743 function process()
744 {
745 $chunk = 0;
746 $indexcounter = null;
747
748 $lastact = '';
749 $lastcontent = '';
750
751 foreach ($this->rawoutput AS $line)
752 {
753 if (preg_match('#^@@ \-([0-9]*),([0-9]*) \+([0-9]*),([0-9]*) @@$#', $line, $bits))
754 {
755 $lastact = '';
756 $lastcontent = '';
757
758 $this->diff["$index"][ ++$chunk ]['hunk'] = array('old' => array('line' => $bits[1], 'count' => $bits[2]), 'new' => array('line' => $bits[3], 'count' => $bits[4]));
759 $lines['old'] = $this->diff["$index"]["$chunk"]['hunk']['old']['line'] - 1;
760 $lines['new'] = $this->diff["$index"]["$chunk"]['hunk']['new']['line'] - 1;
761 continue;
762 }
763
764 if ($indexcounter <= 5 AND $indexcounter !== null)
765 {
766 $indexcounter++;
767 continue;
768 }
769 else if ($indexcounter == 5)
770 {
771 $indexcounter = null;
772 continue;
773 }
774
775 if (preg_match('#^([\+\- ])(.*)#', $line, $matches))
776 {
777 $act = $matches[1];
778 $content = $matches[2];
779
780 if ($act == ' ')
781 {
782 $this->diff["$index"]["$chunk"][] = array(
783 'line' => $content,
784 'act' => '',
785 'oldlineno' => ++$lines['old'],
786 'newlineno' => ++$lines['new']
787 );
788 }
789 else if ($act == '+')
790 {
791 // potential line delta
792 if ($lastact == '-')
793 {
794 if ($delta = @$this->fetch_diff_extent($lastcontent, $content))
795 {
796 // create two sets of ends for the two contents
797 $delta['endo'] = strlen($lastcontent) - $delta['end'];
798 $delta['endn'] = strlen($content) - $delta['end'];
799
800 $diffo = $delta['endo'] - $delta['start'];
801 $diffn = $delta['endn'] - $delta['start'];
802
803 if (strlen($lastcontent) > $delta['endo'] - $diffo)
804 {
805 $removed = substr($lastcontent, $delta['start'], $diffo);
806 $this->diff["$index"]["$chunk"][ count($this->diff["$index"]["$chunk"]) - 2 ]['line'] = substr_replace($lastcontent, '{@--}' . $removed . '{/@--}', $delta['start'], $diffo);
807 }
808
809 if (strlen($content) > $delta['endn'] - $diffn)
810 {
811 $added = substr($content, $delta['start'], $diffn);
812 $content = substr_replace($content, '{@++}' . $added . '{/@++}', $delta['start'], $diffn);
813 }
814 }
815 }
816
817 $this->diff["$index"]["$chunk"][] = array(
818 'line' => $content,
819 'act' => '+',
820 'oldlineno' => '',
821 'newlineno' => ++$lines['new']
822 );
823 }
824 else if ($act == '-')
825 {
826 $lastcontent = $content;
827
828 $this->diff["$index"]["$chunk"][] = array(
829 'line' => $content,
830 'act' => '-',
831 'oldlineno' => ++$lines['old'],
832 'newlineno' => ''
833 );
834 }
835
836 $lastact = $act;
837 }
838 // whitespace lines
839 else
840 {
841 if (preg_match('#^Index: (.*?)$#', $line, $matches))
842 {
843 $index = $matches[1];
844 $indexcounter = 1;
845 $chunk = 0;
846 continue;
847 }
848
849 $lastact = '';
850
851 $this->diff["$index"]["$chunk"][] = array(
852 'line' => '',
853 'act' => '',
854 'oldlineno' => ++$lines['old'],
855 'newlineno' => ++$lines['new']
856 );
857 }
858 }
859 }
860
861 /**
862 * Returns the amount of change that occured
863 * between two lines
864 *
865 * @access private
866 *
867 * @param string Old line
868 * @param string New line
869 *
870 * @return array Difference of positions
871 */
872 function fetch_diff_extent($old, $new)
873 {
874 $start = 0;
875 $min = min(strlen($old), strlen($new));
876
877 for ($start = 0; $start < $min; $start++)
878 {
879 if ($old{"$start"} != $new{"$start"})
880 {
881 break;
882 }
883 }
884
885 $max = max(strlen($old), strlen($new));
886
887 for ($end = 0; $end < $min; $end++)
888 {
889 $oldpos = strlen($old) - $end;
890 $newpos = strlen($new) - $end;
891
892 if ($old{"$oldpos"} != $new{"$newpos"})
893 {
894 break;
895 }
896 }
897
898 $end--;
899
900 if ($start == 0 AND $end == $max)
901 {
902 return false;
903 }
904
905 return array('start' => $start, 'end' => $end);
906 }
907 }
908
909 /*=====================================================================*\
910 || ###################################################################
911 || # $HeadURL$
912 || # $Id$
913 || ###################################################################
914 \*=====================================================================*/
915 ?>