gitweb: fix project list if PATH_INFO=="/".
[git] / gitweb / gitweb.perl
1 #!/usr/bin/perl
2
3 # gitweb - simple web interface to track changes in git repositories
4 #
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
7 #
8 # This program is licensed under the GPLv2
9
10 use strict;
11 use warnings;
12 use CGI qw(:standard :escapeHTML -nosticky);
13 use CGI::Util qw(unescape);
14 use CGI::Carp qw(fatalsToBrowser);
15 use Encode;
16 use Fcntl ':mode';
17 use File::Find qw();
18 binmode STDOUT, ':utf8';
19
20 our $cgi = new CGI;
21 our $version = "++GIT_VERSION++";
22 our $my_url = $cgi->url();
23 our $my_uri = $cgi->url(-absolute => 1);
24
25 # core git executable to use
26 # this can just be "git" if your webserver has a sensible PATH
27 our $GIT = "++GIT_BINDIR++/git";
28
29 # absolute fs-path which will be prepended to the project path
30 #our $projectroot = "/pub/scm";
31 our $projectroot = "++GITWEB_PROJECTROOT++";
32
33 # location for temporary files needed for diffs
34 our $git_temp = "/tmp/gitweb";
35
36 # target of the home link on top of all pages
37 our $home_link = $my_uri || "/";
38
39 # string of the home link on top of all pages
40 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
41
42 # name of your site or organization to appear in page titles
43 # replace this with something more descriptive for clearer bookmarks
44 our $site_name = "++GITWEB_SITENAME++" || $ENV{'SERVER_NAME'} || "Untitled";
45
46 # html text to include at home page
47 our $home_text = "++GITWEB_HOMETEXT++";
48
49 # URI of default stylesheet
50 our $stylesheet = "++GITWEB_CSS++";
51 # URI of GIT logo
52 our $logo = "++GITWEB_LOGO++";
53
54 # source of projects list
55 our $projects_list = "++GITWEB_LIST++";
56
57 # list of git base URLs used for URL to where fetch project from,
58 # i.e. full URL is "$git_base_url/$project"
59 our @git_base_url_list = ("++GITWEB_BASE_URL++");
60
61 # default blob_plain mimetype and default charset for text/plain blob
62 our $default_blob_plain_mimetype = 'text/plain';
63 our $default_text_plain_charset  = undef;
64
65 # file to use for guessing MIME types before trying /etc/mime.types
66 # (relative to the current git repository)
67 our $mimetypes_file = undef;
68
69 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
70 require $GITWEB_CONFIG if -e $GITWEB_CONFIG;
71
72 # version of the core git binary
73 our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
74
75 $projects_list ||= $projectroot;
76 if (! -d $git_temp) {
77         mkdir($git_temp, 0700) || die_error(undef, "Couldn't mkdir $git_temp");
78 }
79
80 # ======================================================================
81 # input validation and dispatch
82 our $action = $cgi->param('a');
83 if (defined $action) {
84         if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
85                 die_error(undef, "Invalid action parameter");
86         }
87         # action which does not check rest of parameters
88         if ($action eq "opml") {
89                 git_opml();
90                 exit;
91         }
92 }
93
94 our $project = ($cgi->param('p') || $ENV{'PATH_INFO'});
95 if (defined $project) {
96         $project =~ s|^/||;
97         $project =~ s|/$||;
98         $project = undef unless $project;
99 }
100 if (defined $project) {
101         if (!validate_input($project)) {
102                 die_error(undef, "Invalid project parameter");
103         }
104         if (!(-d "$projectroot/$project")) {
105                 die_error(undef, "No such directory");
106         }
107         if (!(-e "$projectroot/$project/HEAD")) {
108                 die_error(undef, "No such project");
109         }
110         $ENV{'GIT_DIR'} = "$projectroot/$project";
111 } else {
112         git_project_list();
113         exit;
114 }
115
116 our $file_name = $cgi->param('f');
117 if (defined $file_name) {
118         if (!validate_input($file_name)) {
119                 die_error(undef, "Invalid file parameter");
120         }
121 }
122
123 our $file_parent = $cgi->param('fp');
124 if (defined $file_parent) {
125         if (!validate_input($file_parent)) {
126                 die_error(undef, "Invalid file parent parameter");
127         }
128 }
129
130 our $hash = $cgi->param('h');
131 if (defined $hash) {
132         if (!validate_input($hash)) {
133                 die_error(undef, "Invalid hash parameter");
134         }
135 }
136
137 our $hash_parent = $cgi->param('hp');
138 if (defined $hash_parent) {
139         if (!validate_input($hash_parent)) {
140                 die_error(undef, "Invalid hash parent parameter");
141         }
142 }
143
144 our $hash_base = $cgi->param('hb');
145 if (defined $hash_base) {
146         if (!validate_input($hash_base)) {
147                 die_error(undef, "Invalid hash base parameter");
148         }
149 }
150
151 our $page = $cgi->param('pg');
152 if (defined $page) {
153         if ($page =~ m/[^0-9]$/) {
154                 die_error(undef, "Invalid page parameter");
155         }
156 }
157
158 our $searchtext = $cgi->param('s');
159 if (defined $searchtext) {
160         if ($searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
161                 die_error(undef, "Invalid search parameter");
162         }
163         $searchtext = quotemeta $searchtext;
164 }
165
166 # dispatch
167 my %actions = (
168         "blame" => \&git_blame2,
169         "blobdiff" => \&git_blobdiff,
170         "blobdiff_plain" => \&git_blobdiff_plain,
171         "blob" => \&git_blob,
172         "blob_plain" => \&git_blob_plain,
173         "commitdiff" => \&git_commitdiff,
174         "commitdiff_plain" => \&git_commitdiff_plain,
175         "commit" => \&git_commit,
176         "heads" => \&git_heads,
177         "history" => \&git_history,
178         "log" => \&git_log,
179         "rss" => \&git_rss,
180         "search" => \&git_search,
181         "shortlog" => \&git_shortlog,
182         "summary" => \&git_summary,
183         "tag" => \&git_tag,
184         "tags" => \&git_tags,
185         "tree" => \&git_tree,
186 );
187
188 $action = 'summary' if (!defined($action));
189 if (!defined($actions{$action})) {
190         die_error(undef, "Unknown action");
191 }
192 $actions{$action}->();
193 exit;
194
195 ## ======================================================================
196 ## action links
197
198 sub href(%) {
199         my %mapping = (
200                 action => "a",
201                 project => "p",
202                 file_name => "f",
203                 file_parent => "fp",
204                 hash => "h",
205                 hash_parent => "hp",
206                 hash_base => "hb",
207                 page => "pg",
208                 searchtext => "s",
209         );
210
211         my %params = @_;
212         $params{"project"} ||= $project;
213
214         my $href = "$my_uri?";
215         $href .= esc_param( join(";",
216                 map {
217                         "$mapping{$_}=$params{$_}" if defined $params{$_}
218                 } keys %params
219         ) );
220
221         return $href;
222 }
223
224
225 ## ======================================================================
226 ## validation, quoting/unquoting and escaping
227
228 sub validate_input {
229         my $input = shift;
230
231         if ($input =~ m/^[0-9a-fA-F]{40}$/) {
232                 return $input;
233         }
234         if ($input =~ m/(^|\/)(|\.|\.\.)($|\/)/) {
235                 return undef;
236         }
237         if ($input =~ m/[^a-zA-Z0-9_\x80-\xff\ \t\.\/\-\+\#\~\%]/) {
238                 return undef;
239         }
240         return $input;
241 }
242
243 # quote unsafe chars, but keep the slash, even when it's not
244 # correct, but quoted slashes look too horrible in bookmarks
245 sub esc_param {
246         my $str = shift;
247         $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
248         $str =~ s/\+/%2B/g;
249         $str =~ s/ /\+/g;
250         return $str;
251 }
252
253 # replace invalid utf8 character with SUBSTITUTION sequence
254 sub esc_html {
255         my $str = shift;
256         $str = decode("utf8", $str, Encode::FB_DEFAULT);
257         $str = escapeHTML($str);
258         $str =~ s/\014/^L/g; # escape FORM FEED (FF) character (e.g. in COPYING file)
259         return $str;
260 }
261
262 # git may return quoted and escaped filenames
263 sub unquote {
264         my $str = shift;
265         if ($str =~ m/^"(.*)"$/) {
266                 $str = $1;
267                 $str =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
268         }
269         return $str;
270 }
271
272 # escape tabs (convert tabs to spaces)
273 sub untabify {
274         my $line = shift;
275
276         while ((my $pos = index($line, "\t")) != -1) {
277                 if (my $count = (8 - ($pos % 8))) {
278                         my $spaces = ' ' x $count;
279                         $line =~ s/\t/$spaces/;
280                 }
281         }
282
283         return $line;
284 }
285
286 ## ----------------------------------------------------------------------
287 ## HTML aware string manipulation
288
289 sub chop_str {
290         my $str = shift;
291         my $len = shift;
292         my $add_len = shift || 10;
293
294         # allow only $len chars, but don't cut a word if it would fit in $add_len
295         # if it doesn't fit, cut it if it's still longer than the dots we would add
296         $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
297         my $body = $1;
298         my $tail = $2;
299         if (length($tail) > 4) {
300                 $tail = " ...";
301                 $body =~ s/&[^;]*$//; # remove chopped character entities
302         }
303         return "$body$tail";
304 }
305
306 ## ----------------------------------------------------------------------
307 ## functions returning short strings
308
309 # CSS class for given age value (in seconds)
310 sub age_class {
311         my $age = shift;
312
313         if ($age < 60*60*2) {
314                 return "age0";
315         } elsif ($age < 60*60*24*2) {
316                 return "age1";
317         } else {
318                 return "age2";
319         }
320 }
321
322 # convert age in seconds to "nn units ago" string
323 sub age_string {
324         my $age = shift;
325         my $age_str;
326
327         if ($age > 60*60*24*365*2) {
328                 $age_str = (int $age/60/60/24/365);
329                 $age_str .= " years ago";
330         } elsif ($age > 60*60*24*(365/12)*2) {
331                 $age_str = int $age/60/60/24/(365/12);
332                 $age_str .= " months ago";
333         } elsif ($age > 60*60*24*7*2) {
334                 $age_str = int $age/60/60/24/7;
335                 $age_str .= " weeks ago";
336         } elsif ($age > 60*60*24*2) {
337                 $age_str = int $age/60/60/24;
338                 $age_str .= " days ago";
339         } elsif ($age > 60*60*2) {
340                 $age_str = int $age/60/60;
341                 $age_str .= " hours ago";
342         } elsif ($age > 60*2) {
343                 $age_str = int $age/60;
344                 $age_str .= " min ago";
345         } elsif ($age > 2) {
346                 $age_str = int $age;
347                 $age_str .= " sec ago";
348         } else {
349                 $age_str .= " right now";
350         }
351         return $age_str;
352 }
353
354 # convert file mode in octal to symbolic file mode string
355 sub mode_str {
356         my $mode = oct shift;
357
358         if (S_ISDIR($mode & S_IFMT)) {
359                 return 'drwxr-xr-x';
360         } elsif (S_ISLNK($mode)) {
361                 return 'lrwxrwxrwx';
362         } elsif (S_ISREG($mode)) {
363                 # git cares only about the executable bit
364                 if ($mode & S_IXUSR) {
365                         return '-rwxr-xr-x';
366                 } else {
367                         return '-rw-r--r--';
368                 };
369         } else {
370                 return '----------';
371         }
372 }
373
374 # convert file mode in octal to file type string
375 sub file_type {
376         my $mode = oct shift;
377
378         if (S_ISDIR($mode & S_IFMT)) {
379                 return "directory";
380         } elsif (S_ISLNK($mode)) {
381                 return "symlink";
382         } elsif (S_ISREG($mode)) {
383                 return "file";
384         } else {
385                 return "unknown";
386         }
387 }
388
389 ## ----------------------------------------------------------------------
390 ## functions returning short HTML fragments, or transforming HTML fragments
391 ## which don't beling to other sections
392
393 # format line of commit message or tag comment
394 sub format_log_line_html {
395         my $line = shift;
396
397         $line = esc_html($line);
398         $line =~ s/ /&nbsp;/g;
399         if ($line =~ m/([0-9a-fA-F]{40})/) {
400                 my $hash_text = $1;
401                 if (git_get_type($hash_text) eq "commit") {
402                         my $link = $cgi->a({-class => "text", -href => href(action=>"commit", hash=>$hash_text)}, $hash_text);
403                         $line =~ s/$hash_text/$link/;
404                 }
405         }
406         return $line;
407 }
408
409 # format marker of refs pointing to given object
410 sub format_ref_marker {
411         my ($refs, $id) = @_;
412         my $markers = '';
413
414         if (defined $refs->{$id}) {
415                 foreach my $ref (@{$refs->{$id}}) {
416                         my ($type, $name) = qw();
417                         # e.g. tags/v2.6.11 or heads/next
418                         if ($ref =~ m!^(.*?)s?/(.*)$!) {
419                                 $type = $1;
420                                 $name = $2;
421                         } else {
422                                 $type = "ref";
423                                 $name = $ref;
424                         }
425
426                         $markers .= " <span class=\"$type\">" . esc_html($name) . "</span>";
427                 }
428         }
429
430         if ($markers) {
431                 return ' <span class="refs">'. $markers . '</span>';
432         } else {
433                 return "";
434         }
435 }
436
437 # format, perhaps shortened and with markers, title line
438 sub format_subject_html {
439         my ($long, $short, $href, $extra) = @_;
440         $extra = '' unless defined($extra);
441
442         if (length($short) < length($long)) {
443                 return $cgi->a({-href => $href, -class => "list",
444                                 -title => $long},
445                        esc_html($short) . $extra);
446         } else {
447                 return $cgi->a({-href => $href, -class => "list"},
448                        esc_html($long)  . $extra);
449         }
450 }
451
452 ## ----------------------------------------------------------------------
453 ## git utility subroutines, invoking git commands
454
455 # get HEAD ref of given project as hash
456 sub git_get_head_hash {
457         my $project = shift;
458         my $oENV = $ENV{'GIT_DIR'};
459         my $retval = undef;
460         $ENV{'GIT_DIR'} = "$projectroot/$project";
461         if (open my $fd, "-|", $GIT, "rev-parse", "--verify", "HEAD") {
462                 my $head = <$fd>;
463                 close $fd;
464                 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
465                         $retval = $1;
466                 }
467         }
468         if (defined $oENV) {
469                 $ENV{'GIT_DIR'} = $oENV;
470         }
471         return $retval;
472 }
473
474 # get type of given object
475 sub git_get_type {
476         my $hash = shift;
477
478         open my $fd, "-|", $GIT, "cat-file", '-t', $hash or return;
479         my $type = <$fd>;
480         close $fd or return;
481         chomp $type;
482         return $type;
483 }
484
485 sub git_get_project_config {
486         my $key = shift;
487
488         return unless ($key);
489         $key =~ s/^gitweb\.//;
490         return if ($key =~ m/\W/);
491
492         my $val = qx($GIT repo-config --get gitweb.$key);
493         return ($val);
494 }
495
496 sub git_get_project_config_bool {
497         my $val = git_get_project_config (@_);
498         if ($val and $val =~ m/true|yes|on/) {
499                 return (1);
500         }
501         return; # implicit false
502 }
503
504 # get hash of given path at given ref
505 sub git_get_hash_by_path {
506         my $base = shift;
507         my $path = shift || return undef;
508
509         my $tree = $base;
510
511         open my $fd, "-|", $GIT, "ls-tree", $base, "--", $path
512                 or die_error(undef, "Open git-ls-tree failed");
513         my $line = <$fd>;
514         close $fd or return undef;
515
516         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
517         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
518         return $3;
519 }
520
521 ## ......................................................................
522 ## git utility functions, directly accessing git repository
523
524 # assumes that PATH is not symref
525 sub git_get_hash_by_ref {
526         my $path = shift;
527
528         open my $fd, "$projectroot/$path" or return undef;
529         my $head = <$fd>;
530         close $fd;
531         chomp $head;
532         if ($head =~ m/^[0-9a-fA-F]{40}$/) {
533                 return $head;
534         }
535 }
536
537 sub git_get_project_description {
538         my $path = shift;
539
540         open my $fd, "$projectroot/$path/description" or return undef;
541         my $descr = <$fd>;
542         close $fd;
543         chomp $descr;
544         return $descr;
545 }
546
547 sub git_get_project_url_list {
548         my $path = shift;
549
550         open my $fd, "$projectroot/$path/cloneurl" or return undef;
551         my @git_project_url_list = map { chomp; $_ } <$fd>;
552         close $fd;
553
554         return wantarray ? @git_project_url_list : \@git_project_url_list;
555 }
556
557 sub git_get_projects_list {
558         my @list;
559
560         if (-d $projects_list) {
561                 # search in directory
562                 my $dir = $projects_list;
563                 opendir my ($dh), $dir or return undef;
564                 while (my $dir = readdir($dh)) {
565                         if (-e "$projectroot/$dir/HEAD") {
566                                 my $pr = {
567                                         path => $dir,
568                                 };
569                                 push @list, $pr
570                         }
571                 }
572                 closedir($dh);
573         } elsif (-f $projects_list) {
574                 # read from file(url-encoded):
575                 # 'git%2Fgit.git Linus+Torvalds'
576                 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
577                 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
578                 open my ($fd), $projects_list or return undef;
579                 while (my $line = <$fd>) {
580                         chomp $line;
581                         my ($path, $owner) = split ' ', $line;
582                         $path = unescape($path);
583                         $owner = unescape($owner);
584                         if (!defined $path) {
585                                 next;
586                         }
587                         if (-e "$projectroot/$path/HEAD") {
588                                 my $pr = {
589                                         path => $path,
590                                         owner => decode("utf8", $owner, Encode::FB_DEFAULT),
591                                 };
592                                 push @list, $pr
593                         }
594                 }
595                 close $fd;
596         }
597         @list = sort {$a->{'path'} cmp $b->{'path'}} @list;
598         return @list;
599 }
600
601 sub git_get_project_owner {
602         my $project = shift;
603         my $owner;
604
605         return undef unless $project;
606
607         # read from file (url-encoded):
608         # 'git%2Fgit.git Linus+Torvalds'
609         # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
610         # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
611         if (-f $projects_list) {
612                 open (my $fd , $projects_list);
613                 while (my $line = <$fd>) {
614                         chomp $line;
615                         my ($pr, $ow) = split ' ', $line;
616                         $pr = unescape($pr);
617                         $ow = unescape($ow);
618                         if ($pr eq $project) {
619                                 $owner = decode("utf8", $ow, Encode::FB_DEFAULT);
620                                 last;
621                         }
622                 }
623                 close $fd;
624         }
625         if (!defined $owner) {
626                 $owner = get_file_owner("$projectroot/$project");
627         }
628
629         return $owner;
630 }
631
632 sub git_get_references {
633         my $type = shift || "";
634         my %refs;
635         my $fd;
636         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c      refs/tags/v2.6.11
637         # c39ae07f393806ccf406ef966e9a15afc43cc36a      refs/tags/v2.6.11^{}
638         if (-f "$projectroot/$project/info/refs") {
639                 open $fd, "$projectroot/$project/info/refs"
640                         or return;
641         } else {
642                 open $fd, "-|", $GIT, "ls-remote", "."
643                         or return;
644         }
645
646         while (my $line = <$fd>) {
647                 chomp $line;
648                 if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?[^\^]+)/) {
649                         if (defined $refs{$1}) {
650                                 push @{$refs{$1}}, $2;
651                         } else {
652                                 $refs{$1} = [ $2 ];
653                         }
654                 }
655         }
656         close $fd or return;
657         return \%refs;
658 }
659
660 ## ----------------------------------------------------------------------
661 ## parse to hash functions
662
663 sub parse_date {
664         my $epoch = shift;
665         my $tz = shift || "-0000";
666
667         my %date;
668         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
669         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
670         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
671         $date{'hour'} = $hour;
672         $date{'minute'} = $min;
673         $date{'mday'} = $mday;
674         $date{'day'} = $days[$wday];
675         $date{'month'} = $months[$mon];
676         $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000", $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
677         $date{'mday-time'} = sprintf "%d %s %02d:%02d", $mday, $months[$mon], $hour ,$min;
678
679         $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
680         my $local = $epoch + ((int $1 + ($2/60)) * 3600);
681         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
682         $date{'hour_local'} = $hour;
683         $date{'minute_local'} = $min;
684         $date{'tz_local'} = $tz;
685         return %date;
686 }
687
688 sub parse_tag {
689         my $tag_id = shift;
690         my %tag;
691         my @comment;
692
693         open my $fd, "-|", $GIT, "cat-file", "tag", $tag_id or return;
694         $tag{'id'} = $tag_id;
695         while (my $line = <$fd>) {
696                 chomp $line;
697                 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
698                         $tag{'object'} = $1;
699                 } elsif ($line =~ m/^type (.+)$/) {
700                         $tag{'type'} = $1;
701                 } elsif ($line =~ m/^tag (.+)$/) {
702                         $tag{'name'} = $1;
703                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
704                         $tag{'author'} = $1;
705                         $tag{'epoch'} = $2;
706                         $tag{'tz'} = $3;
707                 } elsif ($line =~ m/--BEGIN/) {
708                         push @comment, $line;
709                         last;
710                 } elsif ($line eq "") {
711                         last;
712                 }
713         }
714         push @comment, <$fd>;
715         $tag{'comment'} = \@comment;
716         close $fd or return;
717         if (!defined $tag{'name'}) {
718                 return
719         };
720         return %tag
721 }
722
723 sub parse_commit {
724         my $commit_id = shift;
725         my $commit_text = shift;
726
727         my @commit_lines;
728         my %co;
729
730         if (defined $commit_text) {
731                 @commit_lines = @$commit_text;
732         } else {
733                 $/ = "\0";
734                 open my $fd, "-|", $GIT, "rev-list", "--header", "--parents", "--max-count=1", $commit_id or return;
735                 @commit_lines = split '\n', <$fd>;
736                 close $fd or return;
737                 $/ = "\n";
738                 pop @commit_lines;
739         }
740         my $header = shift @commit_lines;
741         if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
742                 return;
743         }
744         ($co{'id'}, my @parents) = split ' ', $header;
745         $co{'parents'} = \@parents;
746         $co{'parent'} = $parents[0];
747         while (my $line = shift @commit_lines) {
748                 last if $line eq "\n";
749                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
750                         $co{'tree'} = $1;
751                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
752                         $co{'author'} = $1;
753                         $co{'author_epoch'} = $2;
754                         $co{'author_tz'} = $3;
755                         if ($co{'author'} =~ m/^([^<]+) </) {
756                                 $co{'author_name'} = $1;
757                         } else {
758                                 $co{'author_name'} = $co{'author'};
759                         }
760                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
761                         $co{'committer'} = $1;
762                         $co{'committer_epoch'} = $2;
763                         $co{'committer_tz'} = $3;
764                         $co{'committer_name'} = $co{'committer'};
765                         $co{'committer_name'} =~ s/ <.*//;
766                 }
767         }
768         if (!defined $co{'tree'}) {
769                 return;
770         };
771
772         foreach my $title (@commit_lines) {
773                 $title =~ s/^    //;
774                 if ($title ne "") {
775                         $co{'title'} = chop_str($title, 80, 5);
776                         # remove leading stuff of merges to make the interesting part visible
777                         if (length($title) > 50) {
778                                 $title =~ s/^Automatic //;
779                                 $title =~ s/^merge (of|with) /Merge ... /i;
780                                 if (length($title) > 50) {
781                                         $title =~ s/(http|rsync):\/\///;
782                                 }
783                                 if (length($title) > 50) {
784                                         $title =~ s/(master|www|rsync)\.//;
785                                 }
786                                 if (length($title) > 50) {
787                                         $title =~ s/kernel.org:?//;
788                                 }
789                                 if (length($title) > 50) {
790                                         $title =~ s/\/pub\/scm//;
791                                 }
792                         }
793                         $co{'title_short'} = chop_str($title, 50, 5);
794                         last;
795                 }
796         }
797         # remove added spaces
798         foreach my $line (@commit_lines) {
799                 $line =~ s/^    //;
800         }
801         $co{'comment'} = \@commit_lines;
802
803         my $age = time - $co{'committer_epoch'};
804         $co{'age'} = $age;
805         $co{'age_string'} = age_string($age);
806         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
807         if ($age > 60*60*24*7*2) {
808                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
809                 $co{'age_string_age'} = $co{'age_string'};
810         } else {
811                 $co{'age_string_date'} = $co{'age_string'};
812                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
813         }
814         return %co;
815 }
816
817 # parse ref from ref_file, given by ref_id, with given type
818 sub parse_ref {
819         my $ref_file = shift;
820         my $ref_id = shift;
821         my $type = shift || git_get_type($ref_id);
822         my %ref_item;
823
824         $ref_item{'type'} = $type;
825         $ref_item{'id'} = $ref_id;
826         $ref_item{'epoch'} = 0;
827         $ref_item{'age'} = "unknown";
828         if ($type eq "tag") {
829                 my %tag = parse_tag($ref_id);
830                 $ref_item{'comment'} = $tag{'comment'};
831                 if ($tag{'type'} eq "commit") {
832                         my %co = parse_commit($tag{'object'});
833                         $ref_item{'epoch'} = $co{'committer_epoch'};
834                         $ref_item{'age'} = $co{'age_string'};
835                 } elsif (defined($tag{'epoch'})) {
836                         my $age = time - $tag{'epoch'};
837                         $ref_item{'epoch'} = $tag{'epoch'};
838                         $ref_item{'age'} = age_string($age);
839                 }
840                 $ref_item{'reftype'} = $tag{'type'};
841                 $ref_item{'name'} = $tag{'name'};
842                 $ref_item{'refid'} = $tag{'object'};
843         } elsif ($type eq "commit"){
844                 my %co = parse_commit($ref_id);
845                 $ref_item{'reftype'} = "commit";
846                 $ref_item{'name'} = $ref_file;
847                 $ref_item{'title'} = $co{'title'};
848                 $ref_item{'refid'} = $ref_id;
849                 $ref_item{'epoch'} = $co{'committer_epoch'};
850                 $ref_item{'age'} = $co{'age_string'};
851         } else {
852                 $ref_item{'reftype'} = $type;
853                 $ref_item{'name'} = $ref_file;
854                 $ref_item{'refid'} = $ref_id;
855         }
856
857         return %ref_item;
858 }
859
860 ## ......................................................................
861 ## parse to array of hashes functions
862
863 sub git_get_refs_list {
864         my $ref_dir = shift;
865         my @reflist;
866
867         my @refs;
868         my $pfxlen = length("$projectroot/$project/$ref_dir");
869         File::Find::find(sub {
870                 return if (/^\./);
871                 if (-f $_) {
872                         push @refs, substr($File::Find::name, $pfxlen + 1);
873                 }
874         }, "$projectroot/$project/$ref_dir");
875
876         foreach my $ref_file (@refs) {
877                 my $ref_id = git_get_hash_by_ref("$project/$ref_dir/$ref_file");
878                 my $type = git_get_type($ref_id) || next;
879                 my %ref_item = parse_ref($ref_file, $ref_id, $type);
880
881                 push @reflist, \%ref_item;
882         }
883         # sort refs by age
884         @reflist = sort {$b->{'epoch'} <=> $a->{'epoch'}} @reflist;
885         return \@reflist;
886 }
887
888 ## ----------------------------------------------------------------------
889 ## filesystem-related functions
890
891 sub get_file_owner {
892         my $path = shift;
893
894         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
895         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
896         if (!defined $gcos) {
897                 return undef;
898         }
899         my $owner = $gcos;
900         $owner =~ s/[,;].*$//;
901         return decode("utf8", $owner, Encode::FB_DEFAULT);
902 }
903
904 ## ......................................................................
905 ## mimetype related functions
906
907 sub mimetype_guess_file {
908         my $filename = shift;
909         my $mimemap = shift;
910         -r $mimemap or return undef;
911
912         my %mimemap;
913         open(MIME, $mimemap) or return undef;
914         while (<MIME>) {
915                 next if m/^#/; # skip comments
916                 my ($mime, $exts) = split(/\t+/);
917                 if (defined $exts) {
918                         my @exts = split(/\s+/, $exts);
919                         foreach my $ext (@exts) {
920                                 $mimemap{$ext} = $mime;
921                         }
922                 }
923         }
924         close(MIME);
925
926         $filename =~ /\.(.*?)$/;
927         return $mimemap{$1};
928 }
929
930 sub mimetype_guess {
931         my $filename = shift;
932         my $mime;
933         $filename =~ /\./ or return undef;
934
935         if ($mimetypes_file) {
936                 my $file = $mimetypes_file;
937                 if ($file !~ m!^/!) { # if it is relative path
938                         # it is relative to project
939                         $file = "$projectroot/$project/$file";
940                 }
941                 $mime = mimetype_guess_file($filename, $file);
942         }
943         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
944         return $mime;
945 }
946
947 sub blob_mimetype {
948         my $fd = shift;
949         my $filename = shift;
950
951         if ($filename) {
952                 my $mime = mimetype_guess($filename);
953                 $mime and return $mime;
954         }
955
956         # just in case
957         return $default_blob_plain_mimetype unless $fd;
958
959         if (-T $fd) {
960                 return 'text/plain' .
961                        ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
962         } elsif (! $filename) {
963                 return 'application/octet-stream';
964         } elsif ($filename =~ m/\.png$/i) {
965                 return 'image/png';
966         } elsif ($filename =~ m/\.gif$/i) {
967                 return 'image/gif';
968         } elsif ($filename =~ m/\.jpe?g$/i) {
969                 return 'image/jpeg';
970         } else {
971                 return 'application/octet-stream';
972         }
973 }
974
975 ## ======================================================================
976 ## functions printing HTML: header, footer, error page
977
978 sub git_header_html {
979         my $status = shift || "200 OK";
980         my $expires = shift;
981
982         my $title = "$site_name git";
983         if (defined $project) {
984                 $title .= " - $project";
985                 if (defined $action) {
986                         $title .= "/$action";
987                         if (defined $file_name) {
988                                 $title .= " - $file_name";
989                                 if ($action eq "tree" && $file_name !~ m|/$|) {
990                                         $title .= "/";
991                                 }
992                         }
993                 }
994         }
995         my $content_type;
996         # require explicit support from the UA if we are to send the page as
997         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
998         # we have to do this because MSIE sometimes globs '*/*', pretending to
999         # support xhtml+xml but choking when it gets what it asked for.
1000         if (defined $cgi->http('HTTP_ACCEPT') && $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ && $cgi->Accept('application/xhtml+xml') != 0) {
1001                 $content_type = 'application/xhtml+xml';
1002         } else {
1003                 $content_type = 'text/html';
1004         }
1005         print $cgi->header(-type=>$content_type, -charset => 'utf-8', -status=> $status, -expires => $expires);
1006         print <<EOF;
1007 <?xml version="1.0" encoding="utf-8"?>
1008 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1009 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1010 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1011 <!-- git core binaries version $git_version -->
1012 <head>
1013 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1014 <meta name="generator" content="gitweb/$version git/$git_version"/>
1015 <meta name="robots" content="index, nofollow"/>
1016 <title>$title</title>
1017 <link rel="stylesheet" type="text/css" href="$stylesheet"/>
1018 EOF
1019         if (defined $project) {
1020                 printf('<link rel="alternate" title="%s log" '.
1021                        'href="%s" type="application/rss+xml"/>'."\n",
1022                        esc_param($project), href(action=>"rss"));
1023         }
1024
1025         print "</head>\n" .
1026               "<body>\n" .
1027               "<div class=\"page_header\">\n" .
1028               "<a href=\"http://www.kernel.org/pub/software/scm/git/docs/\" title=\"git documentation\">" .
1029               "<img src=\"$logo\" width=\"72\" height=\"27\" alt=\"git\" style=\"float:right; border-width:0px;\"/>" .
1030               "</a>\n";
1031         print $cgi->a({-href => esc_param($home_link)}, $home_link_str) . " / ";
1032         if (defined $project) {
1033                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1034                 if (defined $action) {
1035                         print " / $action";
1036                 }
1037                 print "\n";
1038                 if (!defined $searchtext) {
1039                         $searchtext = "";
1040                 }
1041                 my $search_hash;
1042                 if (defined $hash_base) {
1043                         $search_hash = $hash_base;
1044                 } elsif (defined $hash) {
1045                         $search_hash = $hash;
1046                 } else {
1047                         $search_hash = "HEAD";
1048                 }
1049                 $cgi->param("a", "search");
1050                 $cgi->param("h", $search_hash);
1051                 print $cgi->startform(-method => "get", -action => $my_uri) .
1052                       "<div class=\"search\">\n" .
1053                       $cgi->hidden(-name => "p") . "\n" .
1054                       $cgi->hidden(-name => "a") . "\n" .
1055                       $cgi->hidden(-name => "h") . "\n" .
1056                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1057                       "</div>" .
1058                       $cgi->end_form() . "\n";
1059         }
1060         print "</div>\n";
1061 }
1062
1063 sub git_footer_html {
1064         print "<div class=\"page_footer\">\n";
1065         if (defined $project) {
1066                 my $descr = git_get_project_description($project);
1067                 if (defined $descr) {
1068                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1069                 }
1070                 print $cgi->a({-href => href(action=>"rss"), -class => "rss_logo"}, "RSS") . "\n";
1071         } else {
1072                 print $cgi->a({-href => href(action=>"opml"), -class => "rss_logo"}, "OPML") . "\n";
1073         }
1074         print "</div>\n" .
1075               "</body>\n" .
1076               "</html>";
1077 }
1078
1079 sub die_error {
1080         my $status = shift || "403 Forbidden";
1081         my $error = shift || "Malformed query, file missing or permission denied";
1082
1083         git_header_html($status);
1084         print "<div class=\"page_body\">\n" .
1085               "<br/><br/>\n" .
1086               "$status - $error\n" .
1087               "<br/>\n" .
1088               "</div>\n";
1089         git_footer_html();
1090         exit;
1091 }
1092
1093 ## ----------------------------------------------------------------------
1094 ## functions printing or outputting HTML: navigation
1095
1096 sub git_print_page_nav {
1097         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1098         $extra = '' if !defined $extra; # pager or formats
1099
1100         my @navs = qw(summary shortlog log commit commitdiff tree);
1101         if ($suppress) {
1102                 @navs = grep { $_ ne $suppress } @navs;
1103         }
1104
1105         my %arg = map { $_ => {action=>$_} } @navs;
1106         if (defined $head) {
1107                 for (qw(commit commitdiff)) {
1108                         $arg{$_}{hash} = $head;
1109                 }
1110                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1111                         for (qw(shortlog log)) {
1112                                 $arg{$_}{hash} = $head;
1113                         }
1114                 }
1115         }
1116         $arg{tree}{hash} = $treehead if defined $treehead;
1117         $arg{tree}{hash_base} = $treebase if defined $treebase;
1118
1119         print "<div class=\"page_nav\">\n" .
1120                 (join " | ",
1121                  map { $_ eq $current ?
1122                        $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1123                  } @navs);
1124         print "<br/>\n$extra<br/>\n" .
1125               "</div>\n";
1126 }
1127
1128 sub format_paging_nav {
1129         my ($action, $hash, $head, $page, $nrevs) = @_;
1130         my $paging_nav;
1131
1132
1133         if ($hash ne $head || $page) {
1134                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1135         } else {
1136                 $paging_nav .= "HEAD";
1137         }
1138
1139         if ($page > 0) {
1140                 $paging_nav .= " &sdot; " .
1141                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1142                                  -accesskey => "p", -title => "Alt-p"}, "prev");
1143         } else {
1144                 $paging_nav .= " &sdot; prev";
1145         }
1146
1147         if ($nrevs >= (100 * ($page+1)-1)) {
1148                 $paging_nav .= " &sdot; " .
1149                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1150                                  -accesskey => "n", -title => "Alt-n"}, "next");
1151         } else {
1152                 $paging_nav .= " &sdot; next";
1153         }
1154
1155         return $paging_nav;
1156 }
1157
1158 ## ......................................................................
1159 ## functions printing or outputting HTML: div
1160
1161 sub git_print_header_div {
1162         my ($action, $title, $hash, $hash_base) = @_;
1163         my %args = ();
1164
1165         $args{action} = $action;
1166         $args{hash} = $hash if $hash;
1167         $args{hash_base} = $hash_base if $hash_base;
1168
1169         print "<div class=\"header\">\n" .
1170               $cgi->a({-href => href(%args), -class => "title"},
1171               $title ? $title : $action) .
1172               "\n</div>\n";
1173 }
1174
1175 sub git_print_page_path {
1176         my $name = shift;
1177         my $type = shift;
1178
1179         if (!defined $name) {
1180                 print "<div class=\"page_path\"><b>/</b></div>\n";
1181         } elsif (defined $type && $type eq 'blob') {
1182                 print "<div class=\"page_path\"><b>" .
1183                         $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name)}, esc_html($name)) . "</b><br/></div>\n";
1184         } else {
1185                 print "<div class=\"page_path\"><b>" . esc_html($name) . "</b><br/></div>\n";
1186         }
1187 }
1188
1189 ## ......................................................................
1190 ## functions printing large fragments of HTML
1191
1192 sub git_difftree_body {
1193         my ($difftree, $parent) = @_;
1194
1195         print "<div class=\"list_head\">\n";
1196         if ($#{$difftree} > 10) {
1197                 print(($#{$difftree} + 1) . " files changed:\n");
1198         }
1199         print "</div>\n";
1200
1201         print "<table class=\"diff_tree\">\n";
1202         my $alternate = 0;
1203         foreach my $line (@{$difftree}) {
1204                 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1205                 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1206                 if ($line !~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1207                         next;
1208                 }
1209                 my $from_mode = $1;
1210                 my $to_mode = $2;
1211                 my $from_id = $3;
1212                 my $to_id = $4;
1213                 my $status = $5;
1214                 my $similarity = $6; # score
1215                 my $file = validate_input(unquote($7));
1216
1217                 if ($alternate) {
1218                         print "<tr class=\"dark\">\n";
1219                 } else {
1220                         print "<tr class=\"light\">\n";
1221                 }
1222                 $alternate ^= 1;
1223
1224                 if ($status eq "A") { # created
1225                         my $mode_chng = "";
1226                         if (S_ISREG(oct $to_mode)) {
1227                                 $mode_chng = sprintf(" with mode: %04o", (oct $to_mode) & 0777);
1228                         }
1229                         print "<td>" .
1230                               $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$file),
1231                                       -class => "list"}, esc_html($file)) .
1232                               "</td>\n" .
1233                               "<td><span class=\"file_status new\">[new " . file_type($to_mode) . "$mode_chng]</span></td>\n" .
1234                               "<td class=\"link\">" .
1235                               $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$file)}, "blob") .
1236                               "</td>\n";
1237
1238                 } elsif ($status eq "D") { # deleted
1239                         print "<td>" .
1240                               $cgi->a({-href => href(action=>"blob", hash=>$from_id, hash_base=>$parent, file_name=>$file),
1241                                        -class => "list"}, esc_html($file)) . "</td>\n" .
1242                               "<td><span class=\"file_status deleted\">[deleted " . file_type($from_mode). "]</span></td>\n" .
1243                               "<td class=\"link\">" .
1244                               $cgi->a({-href => href(action=>"blob", hash=>$from_id, hash_base=>$parent, file_name=>$file)}, "blob") . " | " .
1245                               $cgi->a({-href => href(action=>"history", hash_base=>$parent, file_name=>$file)}, "history") .
1246                               "</td>\n"
1247
1248                 } elsif ($status eq "M" || $status eq "T") { # modified, or type changed
1249                         my $mode_chnge = "";
1250                         if ($from_mode != $to_mode) {
1251                                 $mode_chnge = " <span class=\"file_status mode_chnge\">[changed";
1252                                 if (((oct $from_mode) & S_IFMT) != ((oct $to_mode) & S_IFMT)) {
1253                                         $mode_chnge .= " from " . file_type($from_mode) . " to " . file_type($to_mode);
1254                                 }
1255                                 if (((oct $from_mode) & 0777) != ((oct $to_mode) & 0777)) {
1256                                         if (S_ISREG($from_mode) && S_ISREG($to_mode)) {
1257                                                 $mode_chnge .= sprintf(" mode: %04o->%04o", (oct $from_mode) & 0777, (oct $to_mode) & 0777);
1258                                         } elsif (S_ISREG($to_mode)) {
1259                                                 $mode_chnge .= sprintf(" mode: %04o", (oct $to_mode) & 0777);
1260                                         }
1261                                 }
1262                                 $mode_chnge .= "]</span>\n";
1263                         }
1264                         print "<td>";
1265                         if ($to_id ne $from_id) { # modified
1266                                 print $cgi->a({-href => href(action=>"blobdiff", hash=>$to_id, hash_parent=>$from_id, hash_base=>$hash, file_name=>$file),
1267                                               -class => "list"}, esc_html($file));
1268                         } else { # mode changed
1269                                 print $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$file),
1270                                               -class => "list"}, esc_html($file));
1271                         }
1272                         print "</td>\n" .
1273                               "<td>$mode_chnge</td>\n" .
1274                               "<td class=\"link\">" .
1275                                 $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$file)}, "blob");
1276                         if ($to_id ne $from_id) { # modified
1277                                 print " | " . $cgi->a({-href => href(action=>"blobdiff", hash=>$to_id, hash_parent=>$from_id, hash_base=>$hash, file_name=>$file)}, "diff");
1278                         }
1279                         print " | " . $cgi->a({-href => href(action=>"history", hash_base=>$hash, file_name=>$file)}, "history") . "\n";
1280                         print "</td>\n";
1281
1282                 } elsif ($status eq "R") { # renamed
1283                         my ($from_file, $to_file) = split "\t", $file;
1284                         my $mode_chng = "";
1285                         if ($from_mode != $to_mode) {
1286                                 $mode_chng = sprintf(", mode: %04o", (oct $to_mode) & 0777);
1287                         }
1288                         print "<td>" .
1289                               $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$to_file),
1290                                       -class => "list"}, esc_html($to_file)) . "</td>\n" .
1291                               "<td><span class=\"file_status moved\">[moved from " .
1292                               $cgi->a({-href => href(action=>"blob", hash=>$from_id, hash_base=>$parent, file_name=>$from_file),
1293                                       -class => "list"}, esc_html($from_file)) .
1294                               " with " . (int $similarity) . "% similarity$mode_chng]</span></td>\n" .
1295                               "<td class=\"link\">" .
1296                               $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$to_file)}, "blob");
1297                         if ($to_id ne $from_id) {
1298                                 print " | " .
1299                                       $cgi->a({-href => href(action=>"blobdiff", hash=>$to_id, hash_parent=>$from_id, hash_base=>$hash, file_name=>$to_file, file_parent=>$from_file)}, "diff");
1300                         }
1301                         print "</td>\n";
1302
1303                 } elsif ($status eq "C") { # copied
1304                         my ($from_file, $to_file) = split "\t", $file;
1305                         my $mode_chng = "";
1306                         if ($from_mode != $to_mode) {
1307                                 $mode_chng = sprintf(", mode: %04o", (oct $to_mode) & 0777);
1308                         }
1309                         print "<td>" .
1310                               $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$to_file),
1311                                       -class => "list"}, esc_html($to_file)) . "</td>\n" .
1312                               "<td><span class=\"file_status copied\">[copied from " .
1313                               $cgi->a({-href => href(action=>"blob", hash=>$from_id, hash_base=>$parent, file_name=>$from_file),
1314                                       -class => "list"}, esc_html($from_file)) .
1315                               " with " . (int $similarity) . "% similarity$mode_chng]</span></td>\n" .
1316                               "<td class=\"link\">" .
1317                               $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$to_file)}, "blob");
1318                         if ($to_id ne $from_id) {
1319                                 print " | " .
1320                                       $cgi->a({-href => href(action=>"blobdiff", hash=>$to_id, hash_parent=>$from_id, hash_base=>$hash, file_name=>$to_file, file_parent=>$from_file)}, "diff");
1321                         }
1322                         print "</td>\n";
1323                 } # we should not encounter Unmerged (U) or Unknown (X) status
1324                 print "</tr>\n";
1325         }
1326         print "</table>\n";
1327 }
1328
1329 sub git_shortlog_body {
1330         # uses global variable $project
1331         my ($revlist, $from, $to, $refs, $extra) = @_;
1332         $from = 0 unless defined $from;
1333         $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
1334
1335         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
1336         my $alternate = 0;
1337         for (my $i = $from; $i <= $to; $i++) {
1338                 my $commit = $revlist->[$i];
1339                 #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
1340                 my $ref = format_ref_marker($refs, $commit);
1341                 my %co = parse_commit($commit);
1342                 if ($alternate) {
1343                         print "<tr class=\"dark\">\n";
1344                 } else {
1345                         print "<tr class=\"light\">\n";
1346                 }
1347                 $alternate ^= 1;
1348                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
1349                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1350                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
1351                       "<td>";
1352                 print format_subject_html($co{'title'}, $co{'title_short'}, href(action=>"commit", hash=>$commit), $ref);
1353                 print "</td>\n" .
1354                       "<td class=\"link\">" .
1355                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
1356                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
1357                       "</td>\n" .
1358                       "</tr>\n";
1359         }
1360         if (defined $extra) {
1361                 print "<tr>\n" .
1362                       "<td colspan=\"4\">$extra</td>\n" .
1363                       "</tr>\n";
1364         }
1365         print "</table>\n";
1366 }
1367
1368 sub git_history_body {
1369         # Warning: assumes constant type (blob or tree) during history
1370         my ($fd, $refs, $hash_base, $ftype, $extra) = @_;
1371
1372         print "<table class=\"history\" cellspacing=\"0\">\n";
1373         my $alternate = 0;
1374         while (my $line = <$fd>) {
1375                 if ($line !~ m/^([0-9a-fA-F]{40})/) {
1376                         next;
1377                 }
1378
1379                 my $commit = $1;
1380                 my %co = parse_commit($commit);
1381                 if (!%co) {
1382                         next;
1383                 }
1384
1385                 my $ref = format_ref_marker($refs, $commit);
1386
1387                 if ($alternate) {
1388                         print "<tr class=\"dark\">\n";
1389                 } else {
1390                         print "<tr class=\"light\">\n";
1391                 }
1392                 $alternate ^= 1;
1393                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1394                       # shortlog uses      chop_str($co{'author_name'}, 10)
1395                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
1396                       "<td>";
1397                 # originally git_history used chop_str($co{'title'}, 50)
1398                 print format_subject_html($co{'title'}, $co{'title_short'}, href(action=>"commit", hash=>$commit), $ref);
1399                 print "</td>\n" .
1400                       "<td class=\"link\">" .
1401                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
1402                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
1403                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype);
1404
1405                 if ($ftype eq 'blob') {
1406                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
1407                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
1408                         if (defined $blob_current && defined $blob_parent &&
1409                                         $blob_current ne $blob_parent) {
1410                                 print " | " .
1411                                         $cgi->a({-href => href(action=>"blobdiff", hash=>$blob_current, hash_parent=>$blob_parent, hash_base=>$commit, file_name=>$file_name)},
1412                                                 "diff to current");
1413                         }
1414                 }
1415                 print "</td>\n" .
1416                       "</tr>\n";
1417         }
1418         if (defined $extra) {
1419                 print "<tr>\n" .
1420                       "<td colspan=\"4\">$extra</td>\n" .
1421                       "</tr>\n";
1422         }
1423         print "</table>\n";
1424 }
1425
1426 sub git_tags_body {
1427         # uses global variable $project
1428         my ($taglist, $from, $to, $extra) = @_;
1429         $from = 0 unless defined $from;
1430         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
1431
1432         print "<table class=\"tags\" cellspacing=\"0\">\n";
1433         my $alternate = 0;
1434         for (my $i = $from; $i <= $to; $i++) {
1435                 my $entry = $taglist->[$i];
1436                 my %tag = %$entry;
1437                 my $comment_lines = $tag{'comment'};
1438                 my $comment = shift @$comment_lines;
1439                 my $comment_short;
1440                 if (defined $comment) {
1441                         $comment_short = chop_str($comment, 30, 5);
1442                 }
1443                 if ($alternate) {
1444                         print "<tr class=\"dark\">\n";
1445                 } else {
1446                         print "<tr class=\"light\">\n";
1447                 }
1448                 $alternate ^= 1;
1449                 print "<td><i>$tag{'age'}</i></td>\n" .
1450                       "<td>" .
1451                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
1452                                -class => "list"}, "<b>" . esc_html($tag{'name'}) . "</b>") .
1453                       "</td>\n" .
1454                       "<td>";
1455                 if (defined $comment) {
1456                         print format_subject_html($comment, $comment_short, href(action=>"tag", hash=>$tag{'id'}));
1457                 }
1458                 print "</td>\n" .
1459                       "<td class=\"selflink\">";
1460                 if ($tag{'type'} eq "tag") {
1461                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
1462                 } else {
1463                         print "&nbsp;";
1464                 }
1465                 print "</td>\n" .
1466                       "<td class=\"link\">" . " | " .
1467                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
1468                 if ($tag{'reftype'} eq "commit") {
1469                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
1470                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'refid'})}, "log");
1471                 } elsif ($tag{'reftype'} eq "blob") {
1472                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
1473                 }
1474                 print "</td>\n" .
1475                       "</tr>";
1476         }
1477         if (defined $extra) {
1478                 print "<tr>\n" .
1479                       "<td colspan=\"5\">$extra</td>\n" .
1480                       "</tr>\n";
1481         }
1482         print "</table>\n";
1483 }
1484
1485 sub git_heads_body {
1486         # uses global variable $project
1487         my ($taglist, $head, $from, $to, $extra) = @_;
1488         $from = 0 unless defined $from;
1489         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
1490
1491         print "<table class=\"heads\" cellspacing=\"0\">\n";
1492         my $alternate = 0;
1493         for (my $i = $from; $i <= $to; $i++) {
1494                 my $entry = $taglist->[$i];
1495                 my %tag = %$entry;
1496                 my $curr = $tag{'id'} eq $head;
1497                 if ($alternate) {
1498                         print "<tr class=\"dark\">\n";
1499                 } else {
1500                         print "<tr class=\"light\">\n";
1501                 }
1502                 $alternate ^= 1;
1503                 print "<td><i>$tag{'age'}</i></td>\n" .
1504                       ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
1505                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'}),
1506                                -class => "list"}, "<b>" . esc_html($tag{'name'}) . "</b>") .
1507                       "</td>\n" .
1508                       "<td class=\"link\">" .
1509                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") . " | " .
1510                       $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log") .
1511                       "</td>\n" .
1512                       "</tr>";
1513         }
1514         if (defined $extra) {
1515                 print "<tr>\n" .
1516                       "<td colspan=\"3\">$extra</td>\n" .
1517                       "</tr>\n";
1518         }
1519         print "</table>\n";
1520 }
1521
1522 ## ----------------------------------------------------------------------
1523 ## functions printing large fragments, format as one of arguments
1524
1525 sub git_diff_print {
1526         my $from = shift;
1527         my $from_name = shift;
1528         my $to = shift;
1529         my $to_name = shift;
1530         my $format = shift || "html";
1531
1532         my $from_tmp = "/dev/null";
1533         my $to_tmp = "/dev/null";
1534         my $pid = $$;
1535
1536         # create tmp from-file
1537         if (defined $from) {
1538                 $from_tmp = "$git_temp/gitweb_" . $$ . "_from";
1539                 open my $fd2, "> $from_tmp";
1540                 open my $fd, "-|", $GIT, "cat-file", "blob", $from;
1541                 my @file = <$fd>;
1542                 print $fd2 @file;
1543                 close $fd2;
1544                 close $fd;
1545         }
1546
1547         # create tmp to-file
1548         if (defined $to) {
1549                 $to_tmp = "$git_temp/gitweb_" . $$ . "_to";
1550                 open my $fd2, "> $to_tmp";
1551                 open my $fd, "-|", $GIT, "cat-file", "blob", $to;
1552                 my @file = <$fd>;
1553                 print $fd2 @file;
1554                 close $fd2;
1555                 close $fd;
1556         }
1557
1558         open my $fd, "-|", "/usr/bin/diff -u -p -L \'$from_name\' -L \'$to_name\' $from_tmp $to_tmp";
1559         if ($format eq "plain") {
1560                 undef $/;
1561                 print <$fd>;
1562                 $/ = "\n";
1563         } else {
1564                 while (my $line = <$fd>) {
1565                         chomp $line;
1566                         my $char = substr($line, 0, 1);
1567                         my $diff_class = "";
1568                         if ($char eq '+') {
1569                                 $diff_class = " add";
1570                         } elsif ($char eq "-") {
1571                                 $diff_class = " rem";
1572                         } elsif ($char eq "@") {
1573                                 $diff_class = " chunk_header";
1574                         } elsif ($char eq "\\") {
1575                                 # skip errors
1576                                 next;
1577                         }
1578                         $line = untabify($line);
1579                         print "<div class=\"diff$diff_class\">" . esc_html($line) . "</div>\n";
1580                 }
1581         }
1582         close $fd;
1583
1584         if (defined $from) {
1585                 unlink($from_tmp);
1586         }
1587         if (defined $to) {
1588                 unlink($to_tmp);
1589         }
1590 }
1591
1592
1593 ## ======================================================================
1594 ## ======================================================================
1595 ## actions
1596
1597 sub git_project_list {
1598         my $order = $cgi->param('o');
1599         if (defined $order && $order !~ m/project|descr|owner|age/) {
1600                 die_error(undef, "Unknown order parameter");
1601         }
1602
1603         my @list = git_get_projects_list();
1604         my @projects;
1605         if (!@list) {
1606                 die_error(undef, "No projects found");
1607         }
1608         foreach my $pr (@list) {
1609                 my $head = git_get_head_hash($pr->{'path'});
1610                 if (!defined $head) {
1611                         next;
1612                 }
1613                 $ENV{'GIT_DIR'} = "$projectroot/$pr->{'path'}";
1614                 my %co = parse_commit($head);
1615                 if (!%co) {
1616                         next;
1617                 }
1618                 $pr->{'commit'} = \%co;
1619                 if (!defined $pr->{'descr'}) {
1620                         my $descr = git_get_project_description($pr->{'path'}) || "";
1621                         $pr->{'descr'} = chop_str($descr, 25, 5);
1622                 }
1623                 if (!defined $pr->{'owner'}) {
1624                         $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
1625                 }
1626                 push @projects, $pr;
1627         }
1628
1629         git_header_html();
1630         if (-f $home_text) {
1631                 print "<div class=\"index_include\">\n";
1632                 open (my $fd, $home_text);
1633                 print <$fd>;
1634                 close $fd;
1635                 print "</div>\n";
1636         }
1637         print "<table class=\"project_list\">\n" .
1638               "<tr>\n";
1639         $order ||= "project";
1640         if ($order eq "project") {
1641                 @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
1642                 print "<th>Project</th>\n";
1643         } else {
1644                 print "<th>" .
1645                       $cgi->a({-href => "$my_uri?" . esc_param("o=project"),
1646                                -class => "header"}, "Project") .
1647                       "</th>\n";
1648         }
1649         if ($order eq "descr") {
1650                 @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
1651                 print "<th>Description</th>\n";
1652         } else {
1653                 print "<th>" .
1654                       $cgi->a({-href => "$my_uri?" . esc_param("o=descr"),
1655                                -class => "header"}, "Description") .
1656                       "</th>\n";
1657         }
1658         if ($order eq "owner") {
1659                 @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
1660                 print "<th>Owner</th>\n";
1661         } else {
1662                 print "<th>" .
1663                       $cgi->a({-href => "$my_uri?" . esc_param("o=owner"),
1664                                -class => "header"}, "Owner") .
1665                       "</th>\n";
1666         }
1667         if ($order eq "age") {
1668                 @projects = sort {$a->{'commit'}{'age'} <=> $b->{'commit'}{'age'}} @projects;
1669                 print "<th>Last Change</th>\n";
1670         } else {
1671                 print "<th>" .
1672                       $cgi->a({-href => "$my_uri?" . esc_param("o=age"),
1673                                -class => "header"}, "Last Change") .
1674                       "</th>\n";
1675         }
1676         print "<th></th>\n" .
1677               "</tr>\n";
1678         my $alternate = 0;
1679         foreach my $pr (@projects) {
1680                 if ($alternate) {
1681                         print "<tr class=\"dark\">\n";
1682                 } else {
1683                         print "<tr class=\"light\">\n";
1684                 }
1685                 $alternate ^= 1;
1686                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
1687                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
1688                       "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
1689                       "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
1690                 print "<td class=\"". age_class($pr->{'commit'}{'age'}) . "\">" .
1691                       $pr->{'commit'}{'age_string'} . "</td>\n" .
1692                       "<td class=\"link\">" .
1693                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
1694                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
1695                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") .
1696                       "</td>\n" .
1697                       "</tr>\n";
1698         }
1699         print "</table>\n";
1700         git_footer_html();
1701 }
1702
1703 sub git_summary {
1704         my $descr = git_get_project_description($project) || "none";
1705         my $head = git_get_head_hash($project);
1706         my %co = parse_commit($head);
1707         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
1708
1709         my $owner = git_get_project_owner($project);
1710
1711         my $refs = git_get_references();
1712         git_header_html();
1713         git_print_page_nav('summary','', $head);
1714
1715         print "<div class=\"title\">&nbsp;</div>\n";
1716         print "<table cellspacing=\"0\">\n" .
1717               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
1718               "<tr><td>owner</td><td>$owner</td></tr>\n" .
1719               "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
1720         # use per project git URL list in $projectroot/$project/cloneurl
1721         # or make project git URL from git base URL and project name
1722         my $url_tag = "URL";
1723         my @url_list = git_get_project_url_list($project);
1724         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
1725         foreach my $git_url (@url_list) {
1726                 next unless $git_url;
1727                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
1728                 $url_tag = "";
1729         }
1730         print "</table>\n";
1731
1732         open my $fd, "-|", $GIT, "rev-list", "--max-count=17", git_get_head_hash($project)
1733                 or die_error(undef, "Open git-rev-list failed");
1734         my @revlist = map { chomp; $_ } <$fd>;
1735         close $fd;
1736         git_print_header_div('shortlog');
1737         git_shortlog_body(\@revlist, 0, 15, $refs,
1738                           $cgi->a({-href => href(action=>"shortlog")}, "..."));
1739
1740         my $taglist = git_get_refs_list("refs/tags");
1741         if (defined @$taglist) {
1742                 git_print_header_div('tags');
1743                 git_tags_body($taglist, 0, 15,
1744                               $cgi->a({-href => href(action=>"tags")}, "..."));
1745         }
1746
1747         my $headlist = git_get_refs_list("refs/heads");
1748         if (defined @$headlist) {
1749                 git_print_header_div('heads');
1750                 git_heads_body($headlist, $head, 0, 15,
1751                                $cgi->a({-href => href(action=>"heads")}, "..."));
1752         }
1753
1754         git_footer_html();
1755 }
1756
1757 sub git_tag {
1758         my $head = git_get_head_hash($project);
1759         git_header_html();
1760         git_print_page_nav('','', $head,undef,$head);
1761         my %tag = parse_tag($hash);
1762         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
1763         print "<div class=\"title_text\">\n" .
1764               "<table cellspacing=\"0\">\n" .
1765               "<tr>\n" .
1766               "<td>object</td>\n" .
1767               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})}, $tag{'object'}) . "</td>\n" .
1768               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})}, $tag{'type'}) . "</td>\n" .
1769               "</tr>\n";
1770         if (defined($tag{'author'})) {
1771                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
1772                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
1773                 print "<tr><td></td><td>" . $ad{'rfc2822'} . sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) . "</td></tr>\n";
1774         }
1775         print "</table>\n\n" .
1776               "</div>\n";
1777         print "<div class=\"page_body\">";
1778         my $comment = $tag{'comment'};
1779         foreach my $line (@$comment) {
1780                 print esc_html($line) . "<br/>\n";
1781         }
1782         print "</div>\n";
1783         git_footer_html();
1784 }
1785
1786 sub git_blame2 {
1787         my $fd;
1788         my $ftype;
1789         die_error(undef, "Permission denied") if (!git_get_project_config_bool ('blame'));
1790         die_error('404 Not Found', "File name not defined") if (!$file_name);
1791         $hash_base ||= git_get_head_hash($project);
1792         die_error(undef, "Couldn't find base commit") unless ($hash_base);
1793         my %co = parse_commit($hash_base)
1794                 or die_error(undef, "Reading commit failed");
1795         if (!defined $hash) {
1796                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
1797                         or die_error(undef, "Error looking up file");
1798         }
1799         $ftype = git_get_type($hash);
1800         if ($ftype !~ "blob") {
1801                 die_error("400 Bad Request", "Object is not a blob");
1802         }
1803         open ($fd, "-|", $GIT, "blame", '-l', $file_name, $hash_base)
1804                 or die_error(undef, "Open git-blame failed");
1805         git_header_html();
1806         my $formats_nav =
1807                 $cgi->a({-href => href(action=>"blobl", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)}, "blob") .
1808                 " | " . $cgi->a({-href => href(action=>"blame", file_name=>$file_name)}, "head");
1809         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
1810         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
1811         git_print_page_path($file_name, $ftype);
1812         my @rev_color = (qw(light2 dark2));
1813         my $num_colors = scalar(@rev_color);
1814         my $current_color = 0;
1815         my $last_rev;
1816         print "<div class=\"page_body\">\n";
1817         print "<table class=\"blame\">\n";
1818         print "<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n";
1819         while (<$fd>) {
1820                 /^([0-9a-fA-F]{40}).*?(\d+)\)\s{1}(\s*.*)/;
1821                 my $full_rev = $1;
1822                 my $rev = substr($full_rev, 0, 8);
1823                 my $lineno = $2;
1824                 my $data = $3;
1825
1826                 if (!defined $last_rev) {
1827                         $last_rev = $full_rev;
1828                 } elsif ($last_rev ne $full_rev) {
1829                         $last_rev = $full_rev;
1830                         $current_color = ++$current_color % $num_colors;
1831                 }
1832                 print "<tr class=\"$rev_color[$current_color]\">\n";
1833                 print "<td class=\"sha1\">" .
1834                         $cgi->a({-href => href(action=>"commit", hash=>$full_rev, file_name=>$file_name)}, esc_html($rev)) . "</td>\n";
1835                 print "<td class=\"linenr\"><a id=\"l$lineno\" href=\"#l$lineno\" class=\"linenr\">" . esc_html($lineno) . "</a></td>\n";
1836                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
1837                 print "</tr>\n";
1838         }
1839         print "</table>\n";
1840         print "</div>";
1841         close $fd or print "Reading blob failed\n";
1842         git_footer_html();
1843 }
1844
1845 sub git_blame {
1846         my $fd;
1847         die_error('403 Permission denied', "Permission denied") if (!git_get_project_config_bool ('blame'));
1848         die_error('404 Not Found', "File name not defined") if (!$file_name);
1849         $hash_base ||= git_get_head_hash($project);
1850         die_error(undef, "Couldn't find base commit") unless ($hash_base);
1851         my %co = parse_commit($hash_base)
1852                 or die_error(undef, "Reading commit failed");
1853         if (!defined $hash) {
1854                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
1855                         or die_error(undef, "Error lookup file");
1856         }
1857         open ($fd, "-|", $GIT, "annotate", '-l', '-t', '-r', $file_name, $hash_base)
1858                 or die_error(undef, "Open git-annotate failed");
1859         git_header_html();
1860         my $formats_nav =
1861                 $cgi->a({-href => href(action=>"blobl", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)}, "blob") .
1862                 " | " . $cgi->a({-href => href(action=>"blame", file_name=>$file_name)}, "head");
1863         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
1864         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
1865         git_print_page_path($file_name, 'blob');
1866         print "<div class=\"page_body\">\n";
1867         print <<HTML;
1868 <table class="blame">
1869   <tr>
1870     <th>Commit</th>
1871     <th>Age</th>
1872     <th>Author</th>
1873     <th>Line</th>
1874     <th>Data</th>
1875   </tr>
1876 HTML
1877         my @line_class = (qw(light dark));
1878         my $line_class_len = scalar (@line_class);
1879         my $line_class_num = $#line_class;
1880         while (my $line = <$fd>) {
1881                 my $long_rev;
1882                 my $short_rev;
1883                 my $author;
1884                 my $time;
1885                 my $lineno;
1886                 my $data;
1887                 my $age;
1888                 my $age_str;
1889                 my $age_class;
1890
1891                 chomp $line;
1892                 $line_class_num = ($line_class_num + 1) % $line_class_len;
1893
1894                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) \+\d\d\d\d\t(\d+)\)(.*)$/) {
1895                         $long_rev = $1;
1896                         $author   = $2;
1897                         $time     = $3;
1898                         $lineno   = $4;
1899                         $data     = $5;
1900                 } else {
1901                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
1902                         next;
1903                 }
1904                 $short_rev  = substr ($long_rev, 0, 8);
1905                 $age        = time () - $time;
1906                 $age_str    = age_string ($age);
1907                 $age_str    =~ s/ /&nbsp;/g;
1908                 $age_class  = age_class($age);
1909                 $author     = esc_html ($author);
1910                 $author     =~ s/ /&nbsp;/g;
1911
1912                 $data = untabify($data);
1913                 $data = esc_html ($data);
1914
1915                 print <<HTML;
1916   <tr class="$line_class[$line_class_num]">
1917     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
1918     <td class="$age_class">$age_str</td>
1919     <td>$author</td>
1920     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
1921     <td class="pre">$data</td>
1922   </tr>
1923 HTML
1924         } # while (my $line = <$fd>)
1925         print "</table>\n\n";
1926         close $fd or print "Reading blob failed.\n";
1927         print "</div>";
1928         git_footer_html();
1929 }
1930
1931 sub git_tags {
1932         my $head = git_get_head_hash($project);
1933         git_header_html();
1934         git_print_page_nav('','', $head,undef,$head);
1935         git_print_header_div('summary', $project);
1936
1937         my $taglist = git_get_refs_list("refs/tags");
1938         if (defined @$taglist) {
1939                 git_tags_body($taglist);
1940         }
1941         git_footer_html();
1942 }
1943
1944 sub git_heads {
1945         my $head = git_get_head_hash($project);
1946         git_header_html();
1947         git_print_page_nav('','', $head,undef,$head);
1948         git_print_header_div('summary', $project);
1949
1950         my $taglist = git_get_refs_list("refs/heads");
1951         if (defined @$taglist) {
1952                 git_heads_body($taglist, $head);
1953         }
1954         git_footer_html();
1955 }
1956
1957 sub git_blob_plain {
1958         if (!defined $hash) {
1959                 if (defined $file_name) {
1960                         my $base = $hash_base || git_get_head_hash($project);
1961                         $hash = git_get_hash_by_path($base, $file_name, "blob")
1962                                 or die_error(undef, "Error lookup file");
1963                 } else {
1964                         die_error(undef, "No file name defined");
1965                 }
1966         }
1967         my $type = shift;
1968         open my $fd, "-|", $GIT, "cat-file", "blob", $hash
1969                 or die_error(undef, "Couldn't cat $file_name, $hash");
1970
1971         $type ||= blob_mimetype($fd, $file_name);
1972
1973         # save as filename, even when no $file_name is given
1974         my $save_as = "$hash";
1975         if (defined $file_name) {
1976                 $save_as = $file_name;
1977         } elsif ($type =~ m/^text\//) {
1978                 $save_as .= '.txt';
1979         }
1980
1981         print $cgi->header(-type => "$type", '-content-disposition' => "inline; filename=\"$save_as\"");
1982         undef $/;
1983         binmode STDOUT, ':raw';
1984         print <$fd>;
1985         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
1986         $/ = "\n";
1987         close $fd;
1988 }
1989
1990 sub git_blob {
1991         if (!defined $hash) {
1992                 if (defined $file_name) {
1993                         my $base = $hash_base || git_get_head_hash($project);
1994                         $hash = git_get_hash_by_path($base, $file_name, "blob")
1995                                 or die_error(undef, "Error lookup file");
1996                 } else {
1997                         die_error(undef, "No file name defined");
1998                 }
1999         }
2000         my $have_blame = git_get_project_config_bool ('blame');
2001         open my $fd, "-|", $GIT, "cat-file", "blob", $hash
2002                 or die_error(undef, "Couldn't cat $file_name, $hash");
2003         my $mimetype = blob_mimetype($fd, $file_name);
2004         if ($mimetype !~ m/^text\//) {
2005                 close $fd;
2006                 return git_blob_plain($mimetype);
2007         }
2008         git_header_html();
2009         my $formats_nav = '';
2010         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2011                 if (defined $file_name) {
2012                         if ($have_blame) {
2013                                 $formats_nav .= $cgi->a({-href => href(action=>"blame", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)}, "blame") . " | ";
2014                         }
2015                         $formats_nav .=
2016                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash, file_name=>$file_name)}, "plain") .
2017                                 " | " . $cgi->a({-href => href(action=>"blob", hash_base=>"HEAD", file_name=>$file_name)}, "head");
2018                 } else {
2019                         $formats_nav .= $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "plain");
2020                 }
2021                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2022                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2023         } else {
2024                 print "<div class=\"page_nav\">\n" .
2025                       "<br/><br/></div>\n" .
2026                       "<div class=\"title\">$hash</div>\n";
2027         }
2028         git_print_page_path($file_name, "blob");
2029         print "<div class=\"page_body\">\n";
2030         my $nr;
2031         while (my $line = <$fd>) {
2032                 chomp $line;
2033                 $nr++;
2034                 $line = untabify($line);
2035                 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n", $nr, $nr, $nr, esc_html($line);
2036         }
2037         close $fd or print "Reading blob failed.\n";
2038         print "</div>";
2039         git_footer_html();
2040 }
2041
2042 sub git_tree {
2043         if (!defined $hash) {
2044                 $hash = git_get_head_hash($project);
2045                 if (defined $file_name) {
2046                         my $base = $hash_base || $hash;
2047                         $hash = git_get_hash_by_path($base, $file_name, "tree");
2048                 }
2049                 if (!defined $hash_base) {
2050                         $hash_base = $hash;
2051                 }
2052         }
2053         $/ = "\0";
2054         open my $fd, "-|", $GIT, "ls-tree", '-z', $hash
2055                 or die_error(undef, "Open git-ls-tree failed");
2056         my @entries = map { chomp; $_ } <$fd>;
2057         close $fd or die_error(undef, "Reading tree failed");
2058         $/ = "\n";
2059
2060         my $refs = git_get_references();
2061         my $ref = format_ref_marker($refs, $hash_base);
2062         git_header_html();
2063         my %base_key = ();
2064         my $base = "";
2065         my $have_blame = git_get_project_config_bool ('blame');
2066         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2067                 $base_key{hash_base} = $hash_base;
2068                 git_print_page_nav('tree','', $hash_base);
2069                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
2070         } else {
2071                 print "<div class=\"page_nav\">\n";
2072                 print "<br/><br/></div>\n";
2073                 print "<div class=\"title\">$hash</div>\n";
2074         }
2075         if (defined $file_name) {
2076                 $base = esc_html("$file_name/");
2077         }
2078         git_print_page_path($file_name, 'tree');
2079         print "<div class=\"page_body\">\n";
2080         print "<table cellspacing=\"0\">\n";
2081         my $alternate = 0;
2082         foreach my $line (@entries) {
2083                 #'100644        blob    0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa        panic.c'
2084                 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
2085                 my $t_mode = $1;
2086                 my $t_type = $2;
2087                 my $t_hash = $3;
2088                 my $t_name = validate_input($4);
2089                 if ($alternate) {
2090                         print "<tr class=\"dark\">\n";
2091                 } else {
2092                         print "<tr class=\"light\">\n";
2093                 }
2094                 $alternate ^= 1;
2095                 print "<td class=\"mode\">" . mode_str($t_mode) . "</td>\n";
2096                 if ($t_type eq "blob") {
2097                         print "<td class=\"list\">" .
2098                               $cgi->a({-href => href(action=>"blob", hash=>$t_hash, file_name=>"$base$t_name", %base_key), -class => "list"}, esc_html($t_name)) .
2099                               "</td>\n" .
2100                               "<td class=\"link\">" .
2101                               $cgi->a({-href => href(action=>"blob", hash=>$t_hash, file_name=>"$base$t_name", %base_key)}, "blob");
2102                         if ($have_blame) {
2103                                 print " | " . $cgi->a({-href => href(action=>"blame", hash=>$t_hash, file_name=>"$base$t_name", %base_key)}, "blame");
2104                         }
2105                         print " | " . $cgi->a({-href => href(action=>"history", hash=>$t_hash, hash_base=>$hash_base, file_name=>"$base$t_name")}, "history") .
2106                               " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$t_hash, file_name=>"$base$t_name")}, "raw") .
2107                               "</td>\n";
2108                 } elsif ($t_type eq "tree") {
2109                         print "<td class=\"list\">" .
2110                               $cgi->a({-href => href(action=>"tree", hash=>$t_hash, file_name=>"$base$t_name", %base_key)}, esc_html($t_name)) .
2111                               "</td>\n" .
2112                               "<td class=\"link\">" .
2113                               $cgi->a({-href => href(action=>"tree", hash=>$t_hash, file_name=>"$base$t_name", %base_key)}, "tree") .
2114                               " | " . $cgi->a({-href => href(action=>"history", hash_base=>$hash_base, file_name=>"$base$t_name")}, "history") .
2115                               "</td>\n";
2116                 }
2117                 print "</tr>\n";
2118         }
2119         print "</table>\n" .
2120               "</div>";
2121         git_footer_html();
2122 }
2123
2124 sub git_log {
2125         my $head = git_get_head_hash($project);
2126         if (!defined $hash) {
2127                 $hash = $head;
2128         }
2129         if (!defined $page) {
2130                 $page = 0;
2131         }
2132         my $refs = git_get_references();
2133
2134         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2135         open my $fd, "-|", $GIT, "rev-list", $limit, $hash
2136                 or die_error(undef, "Open git-rev-list failed");
2137         my @revlist = map { chomp; $_ } <$fd>;
2138         close $fd;
2139
2140         my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
2141
2142         git_header_html();
2143         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
2144
2145         if (!@revlist) {
2146                 my %co = parse_commit($hash);
2147
2148                 git_print_header_div('summary', $project);
2149                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
2150         }
2151         for (my $i = ($page * 100); $i <= $#revlist; $i++) {
2152                 my $commit = $revlist[$i];
2153                 my $ref = format_ref_marker($refs, $commit);
2154                 my %co = parse_commit($commit);
2155                 next if !%co;
2156                 my %ad = parse_date($co{'author_epoch'});
2157                 git_print_header_div('commit',
2158                                "<span class=\"age\">$co{'age_string'}</span>" .
2159                                esc_html($co{'title'}) . $ref,
2160                                $commit);
2161                 print "<div class=\"title_text\">\n" .
2162                       "<div class=\"log_link\">\n" .
2163                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
2164                       " | " . $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
2165                       "<br/>\n" .
2166                       "</div>\n" .
2167                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
2168                       "</div>\n" .
2169                       "<div class=\"log_body\">\n";
2170                 my $comment = $co{'comment'};
2171                 my $empty = 0;
2172                 foreach my $line (@$comment) {
2173                         if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
2174                                 next;
2175                         }
2176                         if ($line eq "") {
2177                                 if ($empty) {
2178                                         next;
2179                                 }
2180                                 $empty = 1;
2181                         } else {
2182                                 $empty = 0;
2183                         }
2184                         print format_log_line_html($line) . "<br/>\n";
2185                 }
2186                 if (!$empty) {
2187                         print "<br/>\n";
2188                 }
2189                 print "</div>\n";
2190         }
2191         git_footer_html();
2192 }
2193
2194 sub git_commit {
2195         my %co = parse_commit($hash);
2196         if (!%co) {
2197                 die_error(undef, "Unknown commit object");
2198         }
2199         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2200         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2201
2202         my $parent = $co{'parent'};
2203         if (!defined $parent) {
2204                 $parent = "--root";
2205         }
2206         open my $fd, "-|", $GIT, "diff-tree", '-r', '-M', $parent, $hash
2207                 or die_error(undef, "Open git-diff-tree failed");
2208         my @difftree = map { chomp; $_ } <$fd>;
2209         close $fd or die_error(undef, "Reading git-diff-tree failed");
2210
2211         # non-textual hash id's can be cached
2212         my $expires;
2213         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2214                 $expires = "+1d";
2215         }
2216         my $refs = git_get_references();
2217         my $ref = format_ref_marker($refs, $co{'id'});
2218         my $formats_nav = '';
2219         if (defined $file_name && defined $co{'parent'}) {
2220                 my $parent = $co{'parent'};
2221                 $formats_nav .= $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)}, "blame");
2222         }
2223         git_header_html(undef, $expires);
2224         git_print_page_nav('commit', defined $co{'parent'} ? '' : 'commitdiff',
2225                      $hash, $co{'tree'}, $hash,
2226                      $formats_nav);
2227
2228         if (defined $co{'parent'}) {
2229                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
2230         } else {
2231                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
2232         }
2233         print "<div class=\"title_text\">\n" .
2234               "<table cellspacing=\"0\">\n";
2235         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
2236               "<tr>" .
2237               "<td></td><td> $ad{'rfc2822'}";
2238         if ($ad{'hour_local'} < 6) {
2239                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2240         } else {
2241                 printf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2242         }
2243         print "</td>" .
2244               "</tr>\n";
2245         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
2246         print "<tr><td></td><td> $cd{'rfc2822'}" . sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) . "</td></tr>\n";
2247         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
2248         print "<tr>" .
2249               "<td>tree</td>" .
2250               "<td class=\"sha1\">" .
2251               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash), class => "list"}, $co{'tree'}) .
2252               "</td>" .
2253               "<td class=\"link\">" . $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)}, "tree") .
2254               "</td>" .
2255               "</tr>\n";
2256         my $parents = $co{'parents'};
2257         foreach my $par (@$parents) {
2258                 print "<tr>" .
2259                       "<td>parent</td>" .
2260                       "<td class=\"sha1\">" . $cgi->a({-href => href(action=>"commit", hash=>$par), class => "list"}, $par) . "</td>" .
2261                       "<td class=\"link\">" .
2262                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
2263                       " | " . $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "commitdiff") .
2264                       "</td>" .
2265                       "</tr>\n";
2266         }
2267         print "</table>".
2268               "</div>\n";
2269         print "<div class=\"page_body\">\n";
2270         my $comment = $co{'comment'};
2271         my $empty = 0;
2272         my $signed = 0;
2273         foreach my $line (@$comment) {
2274                 # print only one empty line
2275                 if ($line eq "") {
2276                         if ($empty || $signed) {
2277                                 next;
2278                         }
2279                         $empty = 1;
2280                 } else {
2281                         $empty = 0;
2282                 }
2283                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
2284                         $signed = 1;
2285                         print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
2286                 } else {
2287                         $signed = 0;
2288                         print format_log_line_html($line) . "<br/>\n";
2289                 }
2290         }
2291         print "</div>\n";
2292
2293         git_difftree_body(\@difftree, $parent);
2294
2295         git_footer_html();
2296 }
2297
2298 sub git_blobdiff {
2299         mkdir($git_temp, 0700);
2300         git_header_html();
2301         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2302                 my $formats_nav =
2303                         $cgi->a({-href => href(action=>"blobdiff_plain", hash=>$hash, hash_parent=>$hash_parent)}, "plain");
2304                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2305                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2306         } else {
2307                 print "<div class=\"page_nav\">\n" .
2308                       "<br/><br/></div>\n" .
2309                       "<div class=\"title\">$hash vs $hash_parent</div>\n";
2310         }
2311         git_print_page_path($file_name, "blob");
2312         print "<div class=\"page_body\">\n" .
2313               "<div class=\"diff_info\">blob:" .
2314               $cgi->a({-href => href(action=>"blob", hash=>$hash_parent, hash_base=>$hash_base, file_name=>($file_parent || $file_name))}, $hash_parent) .
2315               " -> blob:" .
2316               $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)}, $hash) .
2317               "</div>\n";
2318         git_diff_print($hash_parent, $file_name || $hash_parent, $hash, $file_name || $hash);
2319         print "</div>";
2320         git_footer_html();
2321 }
2322
2323 sub git_blobdiff_plain {
2324         mkdir($git_temp, 0700);
2325         print $cgi->header(-type => "text/plain", -charset => 'utf-8');
2326         git_diff_print($hash_parent, $file_name || $hash_parent, $hash, $file_name || $hash, "plain");
2327 }
2328
2329 sub git_commitdiff {
2330         mkdir($git_temp, 0700);
2331         my %co = parse_commit($hash);
2332         if (!%co) {
2333                 die_error(undef, "Unknown commit object");
2334         }
2335         if (!defined $hash_parent) {
2336                 $hash_parent = $co{'parent'} || '--root';
2337         }
2338         open my $fd, "-|", $GIT, "diff-tree", '-r', $hash_parent, $hash
2339                 or die_error(undef, "Open git-diff-tree failed");
2340         my @difftree = map { chomp; $_ } <$fd>;
2341         close $fd or die_error(undef, "Reading git-diff-tree failed");
2342
2343         # non-textual hash id's can be cached
2344         my $expires;
2345         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2346                 $expires = "+1d";
2347         }
2348         my $refs = git_get_references();
2349         my $ref = format_ref_marker($refs, $co{'id'});
2350         my $formats_nav =
2351                 $cgi->a({-href => href(action=>"commitdiff_plain", hash=>$hash, hash_parent=>$hash_parent)}, "plain");
2352         git_header_html(undef, $expires);
2353         git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
2354         git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
2355         print "<div class=\"page_body\">\n";
2356         my $comment = $co{'comment'};
2357         my $empty = 0;
2358         my $signed = 0;
2359         my @log = @$comment;
2360         # remove first and empty lines after that
2361         shift @log;
2362         while (defined $log[0] && $log[0] eq "") {
2363                 shift @log;
2364         }
2365         foreach my $line (@log) {
2366                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
2367                         next;
2368                 }
2369                 if ($line eq "") {
2370                         if ($empty) {
2371                                 next;
2372                         }
2373                         $empty = 1;
2374                 } else {
2375                         $empty = 0;
2376                 }
2377                 print format_log_line_html($line) . "<br/>\n";
2378         }
2379         print "<br/>\n";
2380         foreach my $line (@difftree) {
2381                 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M      ls-files.c'
2382                 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M      rev-tree.c'
2383                 if ($line !~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
2384                         next;
2385                 }
2386                 my $from_mode = $1;
2387                 my $to_mode = $2;
2388                 my $from_id = $3;
2389                 my $to_id = $4;
2390                 my $status = $5;
2391                 my $file = validate_input(unquote($6));
2392                 if ($status eq "A") {
2393                         print "<div class=\"diff_info\">" . file_type($to_mode) . ":" .
2394                               $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$file)}, $to_id) . "(new)" .
2395                               "</div>\n";
2396                         git_diff_print(undef, "/dev/null", $to_id, "b/$file");
2397                 } elsif ($status eq "D") {
2398                         print "<div class=\"diff_info\">" . file_type($from_mode) . ":" .
2399                               $cgi->a({-href => href(action=>"blob", hash=>$from_id, hash_base=>$hash_parent, file_name=>$file)}, $from_id) . "(deleted)" .
2400                               "</div>\n";
2401                         git_diff_print($from_id, "a/$file", undef, "/dev/null");
2402                 } elsif ($status eq "M") {
2403                         if ($from_id ne $to_id) {
2404                                 print "<div class=\"diff_info\">" .
2405                                       file_type($from_mode) . ":" .
2406                                       $cgi->a({-href => href(action=>"blob", hash=>$from_id, hash_base=>$hash_parent, file_name=>$file)}, $from_id) .
2407                                       " -> " .
2408                                       file_type($to_mode) . ":" .
2409                                       $cgi->a({-href => href(action=>"blob", hash=>$to_id, hash_base=>$hash, file_name=>$file)}, $to_id) .
2410                                 print "</div>\n";
2411                                 git_diff_print($from_id, "a/$file",  $to_id, "b/$file");
2412                         }
2413                 }
2414         }
2415         print "<br/>\n" .
2416               "</div>";
2417         git_footer_html();
2418 }
2419
2420 sub git_commitdiff_plain {
2421         mkdir($git_temp, 0700);
2422         my %co = parse_commit($hash);
2423         if (!%co) {
2424                 die_error(undef, "Unknown commit object");
2425         }
2426         if (!defined $hash_parent) {
2427                 $hash_parent = $co{'parent'} || '--root';
2428         }
2429         open my $fd, "-|", $GIT, "diff-tree", '-r', $hash_parent, $hash
2430                 or die_error(undef, "Open git-diff-tree failed");
2431         my @difftree = map { chomp; $_ } <$fd>;
2432         close $fd or die_error(undef, "Reading diff-tree failed");
2433
2434         # try to figure out the next tag after this commit
2435         my $tagname;
2436         my $refs = git_get_references("tags");
2437         open $fd, "-|", $GIT, "rev-list", "HEAD";
2438         my @commits = map { chomp; $_ } <$fd>;
2439         close $fd;
2440         foreach my $commit (@commits) {
2441                 if (defined $refs->{$commit}) {
2442                         $tagname = $refs->{$commit}
2443                 }
2444                 if ($commit eq $hash) {
2445                         last;
2446                 }
2447         }
2448
2449         print $cgi->header(-type => "text/plain", -charset => 'utf-8', '-content-disposition' => "inline; filename=\"git-$hash.patch\"");
2450         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2451         my $comment = $co{'comment'};
2452         print "From: $co{'author'}\n" .
2453               "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n".
2454               "Subject: $co{'title'}\n";
2455         if (defined $tagname) {
2456                 print "X-Git-Tag: $tagname\n";
2457         }
2458         print "X-Git-Url: $my_url?p=$project;a=commitdiff;h=$hash\n" .
2459               "\n";
2460
2461         foreach my $line (@$comment) {;
2462                 print "$line\n";
2463         }
2464         print "---\n\n";
2465
2466         foreach my $line (@difftree) {
2467                 if ($line !~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
2468                         next;
2469                 }
2470                 my $from_id = $3;
2471                 my $to_id = $4;
2472                 my $status = $5;
2473                 my $file = $6;
2474                 if ($status eq "A") {
2475                         git_diff_print(undef, "/dev/null", $to_id, "b/$file", "plain");
2476                 } elsif ($status eq "D") {
2477                         git_diff_print($from_id, "a/$file", undef, "/dev/null", "plain");
2478                 } elsif ($status eq "M") {
2479                         git_diff_print($from_id, "a/$file",  $to_id, "b/$file", "plain");
2480                 }
2481         }
2482 }
2483
2484 sub git_history {
2485         if (!defined $hash_base) {
2486                 $hash_base = git_get_head_hash($project);
2487         }
2488         my $ftype;
2489         my %co = parse_commit($hash_base);
2490         if (!%co) {
2491                 die_error(undef, "Unknown commit object");
2492         }
2493         my $refs = git_get_references();
2494         git_header_html();
2495         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base);
2496         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2497         if (!defined $hash && defined $file_name) {
2498                 $hash = git_get_hash_by_path($hash_base, $file_name);
2499         }
2500         if (defined $hash) {
2501                 $ftype = git_get_type($hash);
2502         }
2503         git_print_page_path($file_name, $ftype);
2504
2505         open my $fd, "-|",
2506                 $GIT, "rev-list", "--full-history", $hash_base, "--", $file_name;
2507         git_history_body($fd, $refs, $hash_base, $ftype);
2508
2509         close $fd;
2510         git_footer_html();
2511 }
2512
2513 sub git_search {
2514         if (!defined $searchtext) {
2515                 die_error(undef, "Text field empty");
2516         }
2517         if (!defined $hash) {
2518                 $hash = git_get_head_hash($project);
2519         }
2520         my %co = parse_commit($hash);
2521         if (!%co) {
2522                 die_error(undef, "Unknown commit object");
2523         }
2524         # pickaxe may take all resources of your box and run for several minutes
2525         # with every query - so decide by yourself how public you make this feature :)
2526         my $commit_search = 1;
2527         my $author_search = 0;
2528         my $committer_search = 0;
2529         my $pickaxe_search = 0;
2530         if ($searchtext =~ s/^author\\://i) {
2531                 $author_search = 1;
2532         } elsif ($searchtext =~ s/^committer\\://i) {
2533                 $committer_search = 1;
2534         } elsif ($searchtext =~ s/^pickaxe\\://i) {
2535                 $commit_search = 0;
2536                 $pickaxe_search = 1;
2537         }
2538         git_header_html();
2539         git_print_page_nav('','', $hash,$co{'tree'},$hash);
2540         git_print_header_div('commit', esc_html($co{'title'}), $hash);
2541
2542         print "<table cellspacing=\"0\">\n";
2543         my $alternate = 0;
2544         if ($commit_search) {
2545                 $/ = "\0";
2546                 open my $fd, "-|", $GIT, "rev-list", "--header", "--parents", $hash or next;
2547                 while (my $commit_text = <$fd>) {
2548                         if (!grep m/$searchtext/i, $commit_text) {
2549                                 next;
2550                         }
2551                         if ($author_search && !grep m/\nauthor .*$searchtext/i, $commit_text) {
2552                                 next;
2553                         }
2554                         if ($committer_search && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
2555                                 next;
2556                         }
2557                         my @commit_lines = split "\n", $commit_text;
2558                         my %co = parse_commit(undef, \@commit_lines);
2559                         if (!%co) {
2560                                 next;
2561                         }
2562                         if ($alternate) {
2563                                 print "<tr class=\"dark\">\n";
2564                         } else {
2565                                 print "<tr class=\"light\">\n";
2566                         }
2567                         $alternate ^= 1;
2568                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2569                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
2570                               "<td>" .
2571                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}) -class => "list"}, "<b>" . esc_html(chop_str($co{'title'}, 50)) . "</b><br/>");
2572                         my $comment = $co{'comment'};
2573                         foreach my $line (@$comment) {
2574                                 if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
2575                                         my $lead = esc_html($1) || "";
2576                                         $lead = chop_str($lead, 30, 10);
2577                                         my $match = esc_html($2) || "";
2578                                         my $trail = esc_html($3) || "";
2579                                         $trail = chop_str($trail, 30, 10);
2580                                         my $text = "$lead<span class=\"match\">$match</span>$trail";
2581                                         print chop_str($text, 80, 5) . "<br/>\n";
2582                                 }
2583                         }
2584                         print "</td>\n" .
2585                               "<td class=\"link\">" .
2586                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
2587                               " | " . $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
2588                         print "</td>\n" .
2589                               "</tr>\n";
2590                 }
2591                 close $fd;
2592         }
2593
2594         if ($pickaxe_search) {
2595                 $/ = "\n";
2596                 open my $fd, "-|", "$GIT rev-list $hash | $GIT diff-tree -r --stdin -S\'$searchtext\'";
2597                 undef %co;
2598                 my @files;
2599                 while (my $line = <$fd>) {
2600                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
2601                                 my %set;
2602                                 $set{'file'} = $6;
2603                                 $set{'from_id'} = $3;
2604                                 $set{'to_id'} = $4;
2605                                 $set{'id'} = $set{'to_id'};
2606                                 if ($set{'id'} =~ m/0{40}/) {
2607                                         $set{'id'} = $set{'from_id'};
2608                                 }
2609                                 if ($set{'id'} =~ m/0{40}/) {
2610                                         next;
2611                                 }
2612                                 push @files, \%set;
2613                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
2614                                 if (%co) {
2615                                         if ($alternate) {
2616                                                 print "<tr class=\"dark\">\n";
2617                                         } else {
2618                                                 print "<tr class=\"light\">\n";
2619                                         }
2620                                         $alternate ^= 1;
2621                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2622                                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
2623                                               "<td>" .
2624                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list"}, "<b>" .
2625                                               esc_html(chop_str($co{'title'}, 50)) . "</b><br/>");
2626                                         while (my $setref = shift @files) {
2627                                                 my %set = %$setref;
2628                                                 print $cgi->a({-href => href(action=>"blob", hash=>$set{'id'}, hash_base=>$co{'id'}, file_name=>$set{'file'}), class => "list"},
2629                                                       "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
2630                                                       "<br/>\n";
2631                                         }
2632                                         print "</td>\n" .
2633                                               "<td class=\"link\">" .
2634                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
2635                                               " | " . $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
2636                                         print "</td>\n" .
2637                                               "</tr>\n";
2638                                 }
2639                                 %co = parse_commit($1);
2640                         }
2641                 }
2642                 close $fd;
2643         }
2644         print "</table>\n";
2645         git_footer_html();
2646 }
2647
2648 sub git_shortlog {
2649         my $head = git_get_head_hash($project);
2650         if (!defined $hash) {
2651                 $hash = $head;
2652         }
2653         if (!defined $page) {
2654                 $page = 0;
2655         }
2656         my $refs = git_get_references();
2657
2658         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2659         open my $fd, "-|", $GIT, "rev-list", $limit, $hash
2660                 or die_error(undef, "Open git-rev-list failed");
2661         my @revlist = map { chomp; $_ } <$fd>;
2662         close $fd;
2663
2664         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
2665         my $next_link = '';
2666         if ($#revlist >= (100 * ($page+1)-1)) {
2667                 $next_link =
2668                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
2669                                  -title => "Alt-n"}, "next");
2670         }
2671
2672
2673         git_header_html();
2674         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
2675         git_print_header_div('summary', $project);
2676
2677         git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
2678
2679         git_footer_html();
2680 }
2681
2682 ## ......................................................................
2683 ## feeds (RSS, OPML)
2684
2685 sub git_rss {
2686         # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
2687         open my $fd, "-|", $GIT, "rev-list", "--max-count=150", git_get_head_hash($project)
2688                 or die_error(undef, "Open git-rev-list failed");
2689         my @revlist = map { chomp; $_ } <$fd>;
2690         close $fd or die_error(undef, "Reading git-rev-list failed");
2691         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
2692         print "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".
2693               "<rss version=\"2.0\" xmlns:content=\"http://purl.org/rss/1.0/modules/content/\">\n";
2694         print "<channel>\n";
2695         print "<title>$project</title>\n".
2696               "<link>" . esc_html("$my_url?p=$project;a=summary") . "</link>\n".
2697               "<description>$project log</description>\n".
2698               "<language>en</language>\n";
2699
2700         for (my $i = 0; $i <= $#revlist; $i++) {
2701                 my $commit = $revlist[$i];
2702                 my %co = parse_commit($commit);
2703                 # we read 150, we always show 30 and the ones more recent than 48 hours
2704                 if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
2705                         last;
2706                 }
2707                 my %cd = parse_date($co{'committer_epoch'});
2708                 open $fd, "-|", $GIT, "diff-tree", '-r', $co{'parent'}, $co{'id'} or next;
2709                 my @difftree = map { chomp; $_ } <$fd>;
2710                 close $fd or next;
2711                 print "<item>\n" .
2712                       "<title>" .
2713                       sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
2714                       "</title>\n" .
2715                       "<author>" . esc_html($co{'author'}) . "</author>\n" .
2716                       "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
2717                       "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
2718                       "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
2719                       "<description>" . esc_html($co{'title'}) . "</description>\n" .
2720                       "<content:encoded>" .
2721                       "<![CDATA[\n";
2722                 my $comment = $co{'comment'};
2723                 foreach my $line (@$comment) {
2724                         $line = decode("utf8", $line, Encode::FB_DEFAULT);
2725                         print "$line<br/>\n";
2726                 }
2727                 print "<br/>\n";
2728                 foreach my $line (@difftree) {
2729                         if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
2730                                 next;
2731                         }
2732                         my $file = validate_input(unquote($7));
2733                         $file = decode("utf8", $file, Encode::FB_DEFAULT);
2734                         print "$file<br/>\n";
2735                 }
2736                 print "]]>\n" .
2737                       "</content:encoded>\n" .
2738                       "</item>\n";
2739         }
2740         print "</channel></rss>";
2741 }
2742
2743 sub git_opml {
2744         my @list = git_get_projects_list();
2745
2746         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
2747         print "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".
2748               "<opml version=\"1.0\">\n".
2749               "<head>".
2750               "  <title>$site_name Git OPML Export</title>\n".
2751               "</head>\n".
2752               "<body>\n".
2753               "<outline text=\"git RSS feeds\">\n";
2754
2755         foreach my $pr (@list) {
2756                 my %proj = %$pr;
2757                 my $head = git_get_head_hash($proj{'path'});
2758                 if (!defined $head) {
2759                         next;
2760                 }
2761                 $ENV{'GIT_DIR'} = "$projectroot/$proj{'path'}";
2762                 my %co = parse_commit($head);
2763                 if (!%co) {
2764                         next;
2765                 }
2766
2767                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
2768                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
2769                 my $html = "$my_url?p=$proj{'path'};a=summary";
2770                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
2771         }
2772         print "</outline>\n".
2773               "</body>\n".
2774               "</opml>\n";
2775 }