Merge branch 'maint'
[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 use File::Basename qw(basename);
19 binmode STDOUT, ':utf8';
20
21 our $cgi = new CGI;
22 our $version = "++GIT_VERSION++";
23 our $my_url = $cgi->url();
24 our $my_uri = $cgi->url(-absolute => 1);
25
26 # core git executable to use
27 # this can just be "git" if your webserver has a sensible PATH
28 our $GIT = "++GIT_BINDIR++/git";
29
30 # absolute fs-path which will be prepended to the project path
31 #our $projectroot = "/pub/scm";
32 our $projectroot = "++GITWEB_PROJECTROOT++";
33
34 # target of the home link on top of all pages
35 our $home_link = $my_uri || "/";
36
37 # string of the home link on top of all pages
38 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
39
40 # name of your site or organization to appear in page titles
41 # replace this with something more descriptive for clearer bookmarks
42 our $site_name = "++GITWEB_SITENAME++" || $ENV{'SERVER_NAME'} || "Untitled";
43
44 # html text to include at home page
45 our $home_text = "++GITWEB_HOMETEXT++";
46
47 # URI of default stylesheet
48 our $stylesheet = "++GITWEB_CSS++";
49 # URI of GIT logo (72x27 size)
50 our $logo = "++GITWEB_LOGO++";
51 # URI of GIT favicon, assumed to be image/png type
52 our $favicon = "++GITWEB_FAVICON++";
53
54 # URI and label (title) of GIT logo link
55 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
56 #our $logo_label = "git documentation";
57 our $logo_url = "http://git.or.cz/";
58 our $logo_label = "git homepage";
59
60 # source of projects list
61 our $projects_list = "++GITWEB_LIST++";
62
63 # show repository only if this file exists
64 # (only effective if this variable evaluates to true)
65 our $export_ok = "++GITWEB_EXPORT_OK++";
66
67 # only allow viewing of repositories also shown on the overview page
68 our $strict_export = "++GITWEB_STRICT_EXPORT++";
69
70 # list of git base URLs used for URL to where fetch project from,
71 # i.e. full URL is "$git_base_url/$project"
72 our @git_base_url_list = ("++GITWEB_BASE_URL++");
73
74 # default blob_plain mimetype and default charset for text/plain blob
75 our $default_blob_plain_mimetype = 'text/plain';
76 our $default_text_plain_charset  = undef;
77
78 # file to use for guessing MIME types before trying /etc/mime.types
79 # (relative to the current git repository)
80 our $mimetypes_file = undef;
81
82 # You define site-wide feature defaults here; override them with
83 # $GITWEB_CONFIG as necessary.
84 our %feature = (
85         # feature => {
86         #       'sub' => feature-sub (subroutine),
87         #       'override' => allow-override (boolean),
88         #       'default' => [ default options...] (array reference)}
89         #
90         # if feature is overridable (it means that allow-override has true value,
91         # then feature-sub will be called with default options as parameters;
92         # return value of feature-sub indicates if to enable specified feature
93         #
94         # use gitweb_check_feature(<feature>) to check if <feature> is enabled
95
96         # Enable the 'blame' blob view, showing the last commit that modified
97         # each line in the file. This can be very CPU-intensive.
98
99         # To enable system wide have in $GITWEB_CONFIG
100         # $feature{'blame'}{'default'} = [1];
101         # To have project specific config enable override in $GITWEB_CONFIG
102         # $feature{'blame'}{'override'} = 1;
103         # and in project config gitweb.blame = 0|1;
104         'blame' => {
105                 'sub' => \&feature_blame,
106                 'override' => 0,
107                 'default' => [0]},
108
109         # Enable the 'snapshot' link, providing a compressed tarball of any
110         # tree. This can potentially generate high traffic if you have large
111         # project.
112
113         # To disable system wide have in $GITWEB_CONFIG
114         # $feature{'snapshot'}{'default'} = [undef];
115         # To have project specific config enable override in $GITWEB_CONFIG
116         # $feature{'blame'}{'override'} = 1;
117         # and in project config gitweb.snapshot = none|gzip|bzip2;
118         'snapshot' => {
119                 'sub' => \&feature_snapshot,
120                 'override' => 0,
121                 #         => [content-encoding, suffix, program]
122                 'default' => ['x-gzip', 'gz', 'gzip']},
123
124         # Enable the pickaxe search, which will list the commits that modified
125         # a given string in a file. This can be practical and quite faster
126         # alternative to 'blame', but still potentially CPU-intensive.
127
128         # To enable system wide have in $GITWEB_CONFIG
129         # $feature{'pickaxe'}{'default'} = [1];
130         # To have project specific config enable override in $GITWEB_CONFIG
131         # $feature{'pickaxe'}{'override'} = 1;
132         # and in project config gitweb.pickaxe = 0|1;
133         'pickaxe' => {
134                 'sub' => \&feature_pickaxe,
135                 'override' => 0,
136                 'default' => [1]},
137
138         # Make gitweb use an alternative format of the URLs which can be
139         # more readable and natural-looking: project name is embedded
140         # directly in the path and the query string contains other
141         # auxiliary information. All gitweb installations recognize
142         # URL in either format; this configures in which formats gitweb
143         # generates links.
144
145         # To enable system wide have in $GITWEB_CONFIG
146         # $feature{'pathinfo'}{'default'} = [1];
147         # Project specific override is not supported.
148
149         # Note that you will need to change the default location of CSS,
150         # favicon, logo and possibly other files to an absolute URL. Also,
151         # if gitweb.cgi serves as your indexfile, you will need to force
152         # $my_uri to contain the script name in your $GITWEB_CONFIG.
153         'pathinfo' => {
154                 'override' => 0,
155                 'default' => [0]},
156 );
157
158 sub gitweb_check_feature {
159         my ($name) = @_;
160         return unless exists $feature{$name};
161         my ($sub, $override, @defaults) = (
162                 $feature{$name}{'sub'},
163                 $feature{$name}{'override'},
164                 @{$feature{$name}{'default'}});
165         if (!$override) { return @defaults; }
166         if (!defined $sub) {
167                 warn "feature $name is not overrideable";
168                 return @defaults;
169         }
170         return $sub->(@defaults);
171 }
172
173 sub feature_blame {
174         my ($val) = git_get_project_config('blame', '--bool');
175
176         if ($val eq 'true') {
177                 return 1;
178         } elsif ($val eq 'false') {
179                 return 0;
180         }
181
182         return $_[0];
183 }
184
185 sub feature_snapshot {
186         my ($ctype, $suffix, $command) = @_;
187
188         my ($val) = git_get_project_config('snapshot');
189
190         if ($val eq 'gzip') {
191                 return ('x-gzip', 'gz', 'gzip');
192         } elsif ($val eq 'bzip2') {
193                 return ('x-bzip2', 'bz2', 'bzip2');
194         } elsif ($val eq 'none') {
195                 return ();
196         }
197
198         return ($ctype, $suffix, $command);
199 }
200
201 sub gitweb_have_snapshot {
202         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
203         my $have_snapshot = (defined $ctype && defined $suffix);
204
205         return $have_snapshot;
206 }
207
208 sub feature_pickaxe {
209         my ($val) = git_get_project_config('pickaxe', '--bool');
210
211         if ($val eq 'true') {
212                 return (1);
213         } elsif ($val eq 'false') {
214                 return (0);
215         }
216
217         return ($_[0]);
218 }
219
220 # rename detection options for git-diff and git-diff-tree
221 # - default is '-M', with the cost proportional to
222 #   (number of removed files) * (number of new files).
223 # - more costly is '-C' (or '-C', '-M'), with the cost proportional to
224 #   (number of changed files + number of removed files) * (number of new files)
225 # - even more costly is '-C', '--find-copies-harder' with cost
226 #   (number of files in the original tree) * (number of new files)
227 # - one might want to include '-B' option, e.g. '-B', '-M'
228 our @diff_opts = ('-M'); # taken from git_commit
229
230 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
231 do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
232
233 # version of the core git binary
234 our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
235
236 $projects_list ||= $projectroot;
237
238 # ======================================================================
239 # input validation and dispatch
240 our $action = $cgi->param('a');
241 if (defined $action) {
242         if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
243                 die_error(undef, "Invalid action parameter");
244         }
245 }
246
247 # parameters which are pathnames
248 our $project = $cgi->param('p');
249 if (defined $project) {
250         if (!validate_pathname($project) ||
251             !(-d "$projectroot/$project") ||
252             !(-e "$projectroot/$project/HEAD") ||
253             ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
254             ($strict_export && !project_in_list($project))) {
255                 undef $project;
256                 die_error(undef, "No such project");
257         }
258 }
259
260 our $file_name = $cgi->param('f');
261 if (defined $file_name) {
262         if (!validate_pathname($file_name)) {
263                 die_error(undef, "Invalid file parameter");
264         }
265 }
266
267 our $file_parent = $cgi->param('fp');
268 if (defined $file_parent) {
269         if (!validate_pathname($file_parent)) {
270                 die_error(undef, "Invalid file parent parameter");
271         }
272 }
273
274 # parameters which are refnames
275 our $hash = $cgi->param('h');
276 if (defined $hash) {
277         if (!validate_refname($hash)) {
278                 die_error(undef, "Invalid hash parameter");
279         }
280 }
281
282 our $hash_parent = $cgi->param('hp');
283 if (defined $hash_parent) {
284         if (!validate_refname($hash_parent)) {
285                 die_error(undef, "Invalid hash parent parameter");
286         }
287 }
288
289 our $hash_base = $cgi->param('hb');
290 if (defined $hash_base) {
291         if (!validate_refname($hash_base)) {
292                 die_error(undef, "Invalid hash base parameter");
293         }
294 }
295
296 our $hash_parent_base = $cgi->param('hpb');
297 if (defined $hash_parent_base) {
298         if (!validate_refname($hash_parent_base)) {
299                 die_error(undef, "Invalid hash parent base parameter");
300         }
301 }
302
303 # other parameters
304 our $page = $cgi->param('pg');
305 if (defined $page) {
306         if ($page =~ m/[^0-9]/) {
307                 die_error(undef, "Invalid page parameter");
308         }
309 }
310
311 our $searchtext = $cgi->param('s');
312 if (defined $searchtext) {
313         if ($searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
314                 die_error(undef, "Invalid search parameter");
315         }
316         $searchtext = quotemeta $searchtext;
317 }
318
319 # now read PATH_INFO and use it as alternative to parameters
320 sub evaluate_path_info {
321         return if defined $project;
322         my $path_info = $ENV{"PATH_INFO"};
323         return if !$path_info;
324         $path_info =~ s,^/+,,;
325         return if !$path_info;
326         # find which part of PATH_INFO is project
327         $project = $path_info;
328         $project =~ s,/+$,,;
329         while ($project && !-e "$projectroot/$project/HEAD") {
330                 $project =~ s,/*[^/]*$,,;
331         }
332         # validate project
333         $project = validate_pathname($project);
334         if (!$project ||
335             ($export_ok && !-e "$projectroot/$project/$export_ok") ||
336             ($strict_export && !project_in_list($project))) {
337                 undef $project;
338                 return;
339         }
340         # do not change any parameters if an action is given using the query string
341         return if $action;
342         $path_info =~ s,^$project/*,,;
343         my ($refname, $pathname) = split(/:/, $path_info, 2);
344         if (defined $pathname) {
345                 # we got "project.git/branch:filename" or "project.git/branch:dir/"
346                 # we could use git_get_type(branch:pathname), but it needs $git_dir
347                 $pathname =~ s,^/+,,;
348                 if (!$pathname || substr($pathname, -1) eq "/") {
349                         $action  ||= "tree";
350                         $pathname =~ s,/$,,;
351                 } else {
352                         $action  ||= "blob_plain";
353                 }
354                 $hash_base ||= validate_refname($refname);
355                 $file_name ||= validate_pathname($pathname);
356         } elsif (defined $refname) {
357                 # we got "project.git/branch"
358                 $action ||= "shortlog";
359                 $hash   ||= validate_refname($refname);
360         }
361 }
362 evaluate_path_info();
363
364 # path to the current git repository
365 our $git_dir;
366 $git_dir = "$projectroot/$project" if $project;
367
368 # dispatch
369 my %actions = (
370         "blame" => \&git_blame2,
371         "blobdiff" => \&git_blobdiff,
372         "blobdiff_plain" => \&git_blobdiff_plain,
373         "blob" => \&git_blob,
374         "blob_plain" => \&git_blob_plain,
375         "commitdiff" => \&git_commitdiff,
376         "commitdiff_plain" => \&git_commitdiff_plain,
377         "commit" => \&git_commit,
378         "heads" => \&git_heads,
379         "history" => \&git_history,
380         "log" => \&git_log,
381         "rss" => \&git_rss,
382         "search" => \&git_search,
383         "shortlog" => \&git_shortlog,
384         "summary" => \&git_summary,
385         "tag" => \&git_tag,
386         "tags" => \&git_tags,
387         "tree" => \&git_tree,
388         "snapshot" => \&git_snapshot,
389         # those below don't need $project
390         "opml" => \&git_opml,
391         "project_list" => \&git_project_list,
392         "project_index" => \&git_project_index,
393 );
394
395 if (defined $project) {
396         $action ||= 'summary';
397 } else {
398         $action ||= 'project_list';
399 }
400 if (!defined($actions{$action})) {
401         die_error(undef, "Unknown action");
402 }
403 if ($action !~ m/^(opml|project_list|project_index)$/ &&
404     !$project) {
405         die_error(undef, "Project needed");
406 }
407 $actions{$action}->();
408 exit;
409
410 ## ======================================================================
411 ## action links
412
413 sub href(%) {
414         my %params = @_;
415         my $href = $my_uri;
416
417         # XXX: Warning: If you touch this, check the search form for updating,
418         # too.
419
420         my @mapping = (
421                 project => "p",
422                 action => "a",
423                 file_name => "f",
424                 file_parent => "fp",
425                 hash => "h",
426                 hash_parent => "hp",
427                 hash_base => "hb",
428                 hash_parent_base => "hpb",
429                 page => "pg",
430                 order => "o",
431                 searchtext => "s",
432         );
433         my %mapping = @mapping;
434
435         $params{'project'} = $project unless exists $params{'project'};
436
437         my ($use_pathinfo) = gitweb_check_feature('pathinfo');
438         if ($use_pathinfo) {
439                 # use PATH_INFO for project name
440                 $href .= "/$params{'project'}" if defined $params{'project'};
441                 delete $params{'project'};
442
443                 # Summary just uses the project path URL
444                 if (defined $params{'action'} && $params{'action'} eq 'summary') {
445                         delete $params{'action'};
446                 }
447         }
448
449         # now encode the parameters explicitly
450         my @result = ();
451         for (my $i = 0; $i < @mapping; $i += 2) {
452                 my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
453                 if (defined $params{$name}) {
454                         push @result, $symbol . "=" . esc_param($params{$name});
455                 }
456         }
457         $href .= "?" . join(';', @result) if scalar @result;
458
459         return $href;
460 }
461
462
463 ## ======================================================================
464 ## validation, quoting/unquoting and escaping
465
466 sub validate_pathname {
467         my $input = shift || return undef;
468
469         # no '.' or '..' as elements of path, i.e. no '.' nor '..'
470         # at the beginning, at the end, and between slashes.
471         # also this catches doubled slashes
472         if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
473                 return undef;
474         }
475         # no null characters
476         if ($input =~ m!\0!) {
477                 return undef;
478         }
479         return $input;
480 }
481
482 sub validate_refname {
483         my $input = shift || return undef;
484
485         # textual hashes are O.K.
486         if ($input =~ m/^[0-9a-fA-F]{40}$/) {
487                 return $input;
488         }
489         # it must be correct pathname
490         $input = validate_pathname($input)
491                 or return undef;
492         # restrictions on ref name according to git-check-ref-format
493         if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
494                 return undef;
495         }
496         return $input;
497 }
498
499 # very thin wrapper for decode("utf8", $str, Encode::FB_DEFAULT);
500 sub to_utf8 {
501         my $str = shift;
502         return decode("utf8", $str, Encode::FB_DEFAULT);
503 }
504
505 # quote unsafe chars, but keep the slash, even when it's not
506 # correct, but quoted slashes look too horrible in bookmarks
507 sub esc_param {
508         my $str = shift;
509         $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
510         $str =~ s/\+/%2B/g;
511         $str =~ s/ /\+/g;
512         return $str;
513 }
514
515 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
516 sub esc_url {
517         my $str = shift;
518         $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
519         $str =~ s/\+/%2B/g;
520         $str =~ s/ /\+/g;
521         return $str;
522 }
523
524 # replace invalid utf8 character with SUBSTITUTION sequence
525 sub esc_html {
526         my $str = shift;
527         $str = to_utf8($str);
528         $str = escapeHTML($str);
529         $str =~ s/\014/^L/g; # escape FORM FEED (FF) character (e.g. in COPYING file)
530         $str =~ s/\033/^[/g; # "escape" ESCAPE (\e) character (e.g. commit 20a3847d8a5032ce41f90dcc68abfb36e6fee9b1)
531         return $str;
532 }
533
534 # git may return quoted and escaped filenames
535 sub unquote {
536         my $str = shift;
537         if ($str =~ m/^"(.*)"$/) {
538                 $str = $1;
539                 $str =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
540         }
541         return $str;
542 }
543
544 # escape tabs (convert tabs to spaces)
545 sub untabify {
546         my $line = shift;
547
548         while ((my $pos = index($line, "\t")) != -1) {
549                 if (my $count = (8 - ($pos % 8))) {
550                         my $spaces = ' ' x $count;
551                         $line =~ s/\t/$spaces/;
552                 }
553         }
554
555         return $line;
556 }
557
558 sub project_in_list {
559         my $project = shift;
560         my @list = git_get_projects_list();
561         return @list && scalar(grep { $_->{'path'} eq $project } @list);
562 }
563
564 ## ----------------------------------------------------------------------
565 ## HTML aware string manipulation
566
567 sub chop_str {
568         my $str = shift;
569         my $len = shift;
570         my $add_len = shift || 10;
571
572         # allow only $len chars, but don't cut a word if it would fit in $add_len
573         # if it doesn't fit, cut it if it's still longer than the dots we would add
574         $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
575         my $body = $1;
576         my $tail = $2;
577         if (length($tail) > 4) {
578                 $tail = " ...";
579                 $body =~ s/&[^;]*$//; # remove chopped character entities
580         }
581         return "$body$tail";
582 }
583
584 ## ----------------------------------------------------------------------
585 ## functions returning short strings
586
587 # CSS class for given age value (in seconds)
588 sub age_class {
589         my $age = shift;
590
591         if ($age < 60*60*2) {
592                 return "age0";
593         } elsif ($age < 60*60*24*2) {
594                 return "age1";
595         } else {
596                 return "age2";
597         }
598 }
599
600 # convert age in seconds to "nn units ago" string
601 sub age_string {
602         my $age = shift;
603         my $age_str;
604
605         if ($age > 60*60*24*365*2) {
606                 $age_str = (int $age/60/60/24/365);
607                 $age_str .= " years ago";
608         } elsif ($age > 60*60*24*(365/12)*2) {
609                 $age_str = int $age/60/60/24/(365/12);
610                 $age_str .= " months ago";
611         } elsif ($age > 60*60*24*7*2) {
612                 $age_str = int $age/60/60/24/7;
613                 $age_str .= " weeks ago";
614         } elsif ($age > 60*60*24*2) {
615                 $age_str = int $age/60/60/24;
616                 $age_str .= " days ago";
617         } elsif ($age > 60*60*2) {
618                 $age_str = int $age/60/60;
619                 $age_str .= " hours ago";
620         } elsif ($age > 60*2) {
621                 $age_str = int $age/60;
622                 $age_str .= " min ago";
623         } elsif ($age > 2) {
624                 $age_str = int $age;
625                 $age_str .= " sec ago";
626         } else {
627                 $age_str .= " right now";
628         }
629         return $age_str;
630 }
631
632 # convert file mode in octal to symbolic file mode string
633 sub mode_str {
634         my $mode = oct shift;
635
636         if (S_ISDIR($mode & S_IFMT)) {
637                 return 'drwxr-xr-x';
638         } elsif (S_ISLNK($mode)) {
639                 return 'lrwxrwxrwx';
640         } elsif (S_ISREG($mode)) {
641                 # git cares only about the executable bit
642                 if ($mode & S_IXUSR) {
643                         return '-rwxr-xr-x';
644                 } else {
645                         return '-rw-r--r--';
646                 };
647         } else {
648                 return '----------';
649         }
650 }
651
652 # convert file mode in octal to file type string
653 sub file_type {
654         my $mode = shift;
655
656         if ($mode !~ m/^[0-7]+$/) {
657                 return $mode;
658         } else {
659                 $mode = oct $mode;
660         }
661
662         if (S_ISDIR($mode & S_IFMT)) {
663                 return "directory";
664         } elsif (S_ISLNK($mode)) {
665                 return "symlink";
666         } elsif (S_ISREG($mode)) {
667                 return "file";
668         } else {
669                 return "unknown";
670         }
671 }
672
673 ## ----------------------------------------------------------------------
674 ## functions returning short HTML fragments, or transforming HTML fragments
675 ## which don't beling to other sections
676
677 # format line of commit message or tag comment
678 sub format_log_line_html {
679         my $line = shift;
680
681         $line = esc_html($line);
682         $line =~ s/ /&nbsp;/g;
683         if ($line =~ m/([0-9a-fA-F]{40})/) {
684                 my $hash_text = $1;
685                 if (git_get_type($hash_text) eq "commit") {
686                         my $link =
687                                 $cgi->a({-href => href(action=>"commit", hash=>$hash_text),
688                                         -class => "text"}, $hash_text);
689                         $line =~ s/$hash_text/$link/;
690                 }
691         }
692         return $line;
693 }
694
695 # format marker of refs pointing to given object
696 sub format_ref_marker {
697         my ($refs, $id) = @_;
698         my $markers = '';
699
700         if (defined $refs->{$id}) {
701                 foreach my $ref (@{$refs->{$id}}) {
702                         my ($type, $name) = qw();
703                         # e.g. tags/v2.6.11 or heads/next
704                         if ($ref =~ m!^(.*?)s?/(.*)$!) {
705                                 $type = $1;
706                                 $name = $2;
707                         } else {
708                                 $type = "ref";
709                                 $name = $ref;
710                         }
711
712                         $markers .= " <span class=\"$type\">" . esc_html($name) . "</span>";
713                 }
714         }
715
716         if ($markers) {
717                 return ' <span class="refs">'. $markers . '</span>';
718         } else {
719                 return "";
720         }
721 }
722
723 # format, perhaps shortened and with markers, title line
724 sub format_subject_html {
725         my ($long, $short, $href, $extra) = @_;
726         $extra = '' unless defined($extra);
727
728         if (length($short) < length($long)) {
729                 return $cgi->a({-href => $href, -class => "list subject",
730                                 -title => to_utf8($long)},
731                        esc_html($short) . $extra);
732         } else {
733                 return $cgi->a({-href => $href, -class => "list subject"},
734                        esc_html($long)  . $extra);
735         }
736 }
737
738 sub format_diff_line {
739         my $line = shift;
740         my $char = substr($line, 0, 1);
741         my $diff_class = "";
742
743         chomp $line;
744
745         if ($char eq '+') {
746                 $diff_class = " add";
747         } elsif ($char eq "-") {
748                 $diff_class = " rem";
749         } elsif ($char eq "@") {
750                 $diff_class = " chunk_header";
751         } elsif ($char eq "\\") {
752                 $diff_class = " incomplete";
753         }
754         $line = untabify($line);
755         return "<div class=\"diff$diff_class\">" . esc_html($line) . "</div>\n";
756 }
757
758 ## ----------------------------------------------------------------------
759 ## git utility subroutines, invoking git commands
760
761 # returns path to the core git executable and the --git-dir parameter as list
762 sub git_cmd {
763         return $GIT, '--git-dir='.$git_dir;
764 }
765
766 # returns path to the core git executable and the --git-dir parameter as string
767 sub git_cmd_str {
768         return join(' ', git_cmd());
769 }
770
771 # get HEAD ref of given project as hash
772 sub git_get_head_hash {
773         my $project = shift;
774         my $o_git_dir = $git_dir;
775         my $retval = undef;
776         $git_dir = "$projectroot/$project";
777         if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
778                 my $head = <$fd>;
779                 close $fd;
780                 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
781                         $retval = $1;
782                 }
783         }
784         if (defined $o_git_dir) {
785                 $git_dir = $o_git_dir;
786         }
787         return $retval;
788 }
789
790 # get type of given object
791 sub git_get_type {
792         my $hash = shift;
793
794         open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
795         my $type = <$fd>;
796         close $fd or return;
797         chomp $type;
798         return $type;
799 }
800
801 sub git_get_project_config {
802         my ($key, $type) = @_;
803
804         return unless ($key);
805         $key =~ s/^gitweb\.//;
806         return if ($key =~ m/\W/);
807
808         my @x = (git_cmd(), 'repo-config');
809         if (defined $type) { push @x, $type; }
810         push @x, "--get";
811         push @x, "gitweb.$key";
812         my $val = qx(@x);
813         chomp $val;
814         return ($val);
815 }
816
817 # get hash of given path at given ref
818 sub git_get_hash_by_path {
819         my $base = shift;
820         my $path = shift || return undef;
821         my $type = shift;
822
823         $path =~ s,/+$,,;
824
825         open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
826                 or die_error(undef, "Open git-ls-tree failed");
827         my $line = <$fd>;
828         close $fd or return undef;
829
830         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
831         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
832         if (defined $type && $type ne $2) {
833                 # type doesn't match
834                 return undef;
835         }
836         return $3;
837 }
838
839 ## ......................................................................
840 ## git utility functions, directly accessing git repository
841
842 sub git_get_project_description {
843         my $path = shift;
844
845         open my $fd, "$projectroot/$path/description" or return undef;
846         my $descr = <$fd>;
847         close $fd;
848         chomp $descr;
849         return $descr;
850 }
851
852 sub git_get_project_url_list {
853         my $path = shift;
854
855         open my $fd, "$projectroot/$path/cloneurl" or return;
856         my @git_project_url_list = map { chomp; $_ } <$fd>;
857         close $fd;
858
859         return wantarray ? @git_project_url_list : \@git_project_url_list;
860 }
861
862 sub git_get_projects_list {
863         my @list;
864
865         if (-d $projects_list) {
866                 # search in directory
867                 my $dir = $projects_list;
868                 my $pfxlen = length("$dir");
869
870                 File::Find::find({
871                         follow_fast => 1, # follow symbolic links
872                         dangling_symlinks => 0, # ignore dangling symlinks, silently
873                         wanted => sub {
874                                 # skip project-list toplevel, if we get it.
875                                 return if (m!^[/.]$!);
876                                 # only directories can be git repositories
877                                 return unless (-d $_);
878
879                                 my $subdir = substr($File::Find::name, $pfxlen + 1);
880                                 # we check related file in $projectroot
881                                 if (-e "$projectroot/$subdir/HEAD" && (!$export_ok ||
882                                     -e "$projectroot/$subdir/$export_ok")) {
883                                         push @list, { path => $subdir };
884                                         $File::Find::prune = 1;
885                                 }
886                         },
887                 }, "$dir");
888
889         } elsif (-f $projects_list) {
890                 # read from file(url-encoded):
891                 # 'git%2Fgit.git Linus+Torvalds'
892                 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
893                 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
894                 open my ($fd), $projects_list or return;
895                 while (my $line = <$fd>) {
896                         chomp $line;
897                         my ($path, $owner) = split ' ', $line;
898                         $path = unescape($path);
899                         $owner = unescape($owner);
900                         if (!defined $path) {
901                                 next;
902                         }
903                         if (-e "$projectroot/$path/HEAD" && (!$export_ok ||
904                             -e "$projectroot/$path/$export_ok")) {
905                                 my $pr = {
906                                         path => $path,
907                                         owner => to_utf8($owner),
908                                 };
909                                 push @list, $pr
910                         }
911                 }
912                 close $fd;
913         }
914         @list = sort {$a->{'path'} cmp $b->{'path'}} @list;
915         return @list;
916 }
917
918 sub git_get_project_owner {
919         my $project = shift;
920         my $owner;
921
922         return undef unless $project;
923
924         # read from file (url-encoded):
925         # 'git%2Fgit.git Linus+Torvalds'
926         # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
927         # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
928         if (-f $projects_list) {
929                 open (my $fd , $projects_list);
930                 while (my $line = <$fd>) {
931                         chomp $line;
932                         my ($pr, $ow) = split ' ', $line;
933                         $pr = unescape($pr);
934                         $ow = unescape($ow);
935                         if ($pr eq $project) {
936                                 $owner = to_utf8($ow);
937                                 last;
938                         }
939                 }
940                 close $fd;
941         }
942         if (!defined $owner) {
943                 $owner = get_file_owner("$projectroot/$project");
944         }
945
946         return $owner;
947 }
948
949 sub git_get_references {
950         my $type = shift || "";
951         my %refs;
952         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c      refs/tags/v2.6.11
953         # c39ae07f393806ccf406ef966e9a15afc43cc36a      refs/tags/v2.6.11^{}
954         open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
955                 or return;
956
957         while (my $line = <$fd>) {
958                 chomp $line;
959                 if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?[^\^]+)/) {
960                         if (defined $refs{$1}) {
961                                 push @{$refs{$1}}, $2;
962                         } else {
963                                 $refs{$1} = [ $2 ];
964                         }
965                 }
966         }
967         close $fd or return;
968         return \%refs;
969 }
970
971 sub git_get_rev_name_tags {
972         my $hash = shift || return undef;
973
974         open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
975                 or return;
976         my $name_rev = <$fd>;
977         close $fd;
978
979         if ($name_rev =~ m|^$hash tags/(.*)$|) {
980                 return $1;
981         } else {
982                 # catches also '$hash undefined' output
983                 return undef;
984         }
985 }
986
987 ## ----------------------------------------------------------------------
988 ## parse to hash functions
989
990 sub parse_date {
991         my $epoch = shift;
992         my $tz = shift || "-0000";
993
994         my %date;
995         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
996         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
997         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
998         $date{'hour'} = $hour;
999         $date{'minute'} = $min;
1000         $date{'mday'} = $mday;
1001         $date{'day'} = $days[$wday];
1002         $date{'month'} = $months[$mon];
1003         $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
1004                            $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
1005         $date{'mday-time'} = sprintf "%d %s %02d:%02d",
1006                              $mday, $months[$mon], $hour ,$min;
1007
1008         $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
1009         my $local = $epoch + ((int $1 + ($2/60)) * 3600);
1010         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
1011         $date{'hour_local'} = $hour;
1012         $date{'minute_local'} = $min;
1013         $date{'tz_local'} = $tz;
1014         return %date;
1015 }
1016
1017 sub parse_tag {
1018         my $tag_id = shift;
1019         my %tag;
1020         my @comment;
1021
1022         open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
1023         $tag{'id'} = $tag_id;
1024         while (my $line = <$fd>) {
1025                 chomp $line;
1026                 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
1027                         $tag{'object'} = $1;
1028                 } elsif ($line =~ m/^type (.+)$/) {
1029                         $tag{'type'} = $1;
1030                 } elsif ($line =~ m/^tag (.+)$/) {
1031                         $tag{'name'} = $1;
1032                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
1033                         $tag{'author'} = $1;
1034                         $tag{'epoch'} = $2;
1035                         $tag{'tz'} = $3;
1036                 } elsif ($line =~ m/--BEGIN/) {
1037                         push @comment, $line;
1038                         last;
1039                 } elsif ($line eq "") {
1040                         last;
1041                 }
1042         }
1043         push @comment, <$fd>;
1044         $tag{'comment'} = \@comment;
1045         close $fd or return;
1046         if (!defined $tag{'name'}) {
1047                 return
1048         };
1049         return %tag
1050 }
1051
1052 sub parse_commit {
1053         my $commit_id = shift;
1054         my $commit_text = shift;
1055
1056         my @commit_lines;
1057         my %co;
1058
1059         if (defined $commit_text) {
1060                 @commit_lines = @$commit_text;
1061         } else {
1062                 $/ = "\0";
1063                 open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", "--max-count=1", $commit_id
1064                         or return;
1065                 @commit_lines = split '\n', <$fd>;
1066                 close $fd or return;
1067                 $/ = "\n";
1068                 pop @commit_lines;
1069         }
1070         my $header = shift @commit_lines;
1071         if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
1072                 return;
1073         }
1074         ($co{'id'}, my @parents) = split ' ', $header;
1075         $co{'parents'} = \@parents;
1076         $co{'parent'} = $parents[0];
1077         while (my $line = shift @commit_lines) {
1078                 last if $line eq "\n";
1079                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1080                         $co{'tree'} = $1;
1081                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1082                         $co{'author'} = $1;
1083                         $co{'author_epoch'} = $2;
1084                         $co{'author_tz'} = $3;
1085                         if ($co{'author'} =~ m/^([^<]+) </) {
1086                                 $co{'author_name'} = $1;
1087                         } else {
1088                                 $co{'author_name'} = $co{'author'};
1089                         }
1090                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1091                         $co{'committer'} = $1;
1092                         $co{'committer_epoch'} = $2;
1093                         $co{'committer_tz'} = $3;
1094                         $co{'committer_name'} = $co{'committer'};
1095                         $co{'committer_name'} =~ s/ <.*//;
1096                 }
1097         }
1098         if (!defined $co{'tree'}) {
1099                 return;
1100         };
1101
1102         foreach my $title (@commit_lines) {
1103                 $title =~ s/^    //;
1104                 if ($title ne "") {
1105                         $co{'title'} = chop_str($title, 80, 5);
1106                         # remove leading stuff of merges to make the interesting part visible
1107                         if (length($title) > 50) {
1108                                 $title =~ s/^Automatic //;
1109                                 $title =~ s/^merge (of|with) /Merge ... /i;
1110                                 if (length($title) > 50) {
1111                                         $title =~ s/(http|rsync):\/\///;
1112                                 }
1113                                 if (length($title) > 50) {
1114                                         $title =~ s/(master|www|rsync)\.//;
1115                                 }
1116                                 if (length($title) > 50) {
1117                                         $title =~ s/kernel.org:?//;
1118                                 }
1119                                 if (length($title) > 50) {
1120                                         $title =~ s/\/pub\/scm//;
1121                                 }
1122                         }
1123                         $co{'title_short'} = chop_str($title, 50, 5);
1124                         last;
1125                 }
1126         }
1127         if ($co{'title'} eq "") {
1128                 $co{'title'} = $co{'title_short'} = '(no commit message)';
1129         }
1130         # remove added spaces
1131         foreach my $line (@commit_lines) {
1132                 $line =~ s/^    //;
1133         }
1134         $co{'comment'} = \@commit_lines;
1135
1136         my $age = time - $co{'committer_epoch'};
1137         $co{'age'} = $age;
1138         $co{'age_string'} = age_string($age);
1139         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1140         if ($age > 60*60*24*7*2) {
1141                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1142                 $co{'age_string_age'} = $co{'age_string'};
1143         } else {
1144                 $co{'age_string_date'} = $co{'age_string'};
1145                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1146         }
1147         return %co;
1148 }
1149
1150 # parse ref from ref_file, given by ref_id, with given type
1151 sub parse_ref {
1152         my $ref_file = shift;
1153         my $ref_id = shift;
1154         my $type = shift || git_get_type($ref_id);
1155         my %ref_item;
1156
1157         $ref_item{'type'} = $type;
1158         $ref_item{'id'} = $ref_id;
1159         $ref_item{'epoch'} = 0;
1160         $ref_item{'age'} = "unknown";
1161         if ($type eq "tag") {
1162                 my %tag = parse_tag($ref_id);
1163                 $ref_item{'comment'} = $tag{'comment'};
1164                 if ($tag{'type'} eq "commit") {
1165                         my %co = parse_commit($tag{'object'});
1166                         $ref_item{'epoch'} = $co{'committer_epoch'};
1167                         $ref_item{'age'} = $co{'age_string'};
1168                 } elsif (defined($tag{'epoch'})) {
1169                         my $age = time - $tag{'epoch'};
1170                         $ref_item{'epoch'} = $tag{'epoch'};
1171                         $ref_item{'age'} = age_string($age);
1172                 }
1173                 $ref_item{'reftype'} = $tag{'type'};
1174                 $ref_item{'name'} = $tag{'name'};
1175                 $ref_item{'refid'} = $tag{'object'};
1176         } elsif ($type eq "commit"){
1177                 my %co = parse_commit($ref_id);
1178                 $ref_item{'reftype'} = "commit";
1179                 $ref_item{'name'} = $ref_file;
1180                 $ref_item{'title'} = $co{'title'};
1181                 $ref_item{'refid'} = $ref_id;
1182                 $ref_item{'epoch'} = $co{'committer_epoch'};
1183                 $ref_item{'age'} = $co{'age_string'};
1184         } else {
1185                 $ref_item{'reftype'} = $type;
1186                 $ref_item{'name'} = $ref_file;
1187                 $ref_item{'refid'} = $ref_id;
1188         }
1189
1190         return %ref_item;
1191 }
1192
1193 # parse line of git-diff-tree "raw" output
1194 sub parse_difftree_raw_line {
1195         my $line = shift;
1196         my %res;
1197
1198         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1199         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1200         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1201                 $res{'from_mode'} = $1;
1202                 $res{'to_mode'} = $2;
1203                 $res{'from_id'} = $3;
1204                 $res{'to_id'} = $4;
1205                 $res{'status'} = $5;
1206                 $res{'similarity'} = $6;
1207                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1208                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1209                 } else {
1210                         $res{'file'} = unquote($7);
1211                 }
1212         }
1213         # 'c512b523472485aef4fff9e57b229d9d243c967f'
1214         elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1215                 $res{'commit'} = $1;
1216         }
1217
1218         return wantarray ? %res : \%res;
1219 }
1220
1221 # parse line of git-ls-tree output
1222 sub parse_ls_tree_line ($;%) {
1223         my $line = shift;
1224         my %opts = @_;
1225         my %res;
1226
1227         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1228         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
1229
1230         $res{'mode'} = $1;
1231         $res{'type'} = $2;
1232         $res{'hash'} = $3;
1233         if ($opts{'-z'}) {
1234                 $res{'name'} = $4;
1235         } else {
1236                 $res{'name'} = unquote($4);
1237         }
1238
1239         return wantarray ? %res : \%res;
1240 }
1241
1242 ## ......................................................................
1243 ## parse to array of hashes functions
1244
1245 sub git_get_refs_list {
1246         my $type = shift || "";
1247         my %refs;
1248         my @reflist;
1249
1250         my @refs;
1251         open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
1252                 or return;
1253         while (my $line = <$fd>) {
1254                 chomp $line;
1255                 if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?([^\^]+))(\^\{\})?$/) {
1256                         if (defined $refs{$1}) {
1257                                 push @{$refs{$1}}, $2;
1258                         } else {
1259                                 $refs{$1} = [ $2 ];
1260                         }
1261
1262                         if (! $4) { # unpeeled, direct reference
1263                                 push @refs, { hash => $1, name => $3 }; # without type
1264                         } elsif ($3 eq $refs[-1]{'name'}) {
1265                                 # most likely a tag is followed by its peeled
1266                                 # (deref) one, and when that happens we know the
1267                                 # previous one was of type 'tag'.
1268                                 $refs[-1]{'type'} = "tag";
1269                         }
1270                 }
1271         }
1272         close $fd;
1273
1274         foreach my $ref (@refs) {
1275                 my $ref_file = $ref->{'name'};
1276                 my $ref_id   = $ref->{'hash'};
1277
1278                 my $type = $ref->{'type'} || git_get_type($ref_id) || next;
1279                 my %ref_item = parse_ref($ref_file, $ref_id, $type);
1280
1281                 push @reflist, \%ref_item;
1282         }
1283         # sort refs by age
1284         @reflist = sort {$b->{'epoch'} <=> $a->{'epoch'}} @reflist;
1285         return (\@reflist, \%refs);
1286 }
1287
1288 ## ----------------------------------------------------------------------
1289 ## filesystem-related functions
1290
1291 sub get_file_owner {
1292         my $path = shift;
1293
1294         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1295         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1296         if (!defined $gcos) {
1297                 return undef;
1298         }
1299         my $owner = $gcos;
1300         $owner =~ s/[,;].*$//;
1301         return to_utf8($owner);
1302 }
1303
1304 ## ......................................................................
1305 ## mimetype related functions
1306
1307 sub mimetype_guess_file {
1308         my $filename = shift;
1309         my $mimemap = shift;
1310         -r $mimemap or return undef;
1311
1312         my %mimemap;
1313         open(MIME, $mimemap) or return undef;
1314         while (<MIME>) {
1315                 next if m/^#/; # skip comments
1316                 my ($mime, $exts) = split(/\t+/);
1317                 if (defined $exts) {
1318                         my @exts = split(/\s+/, $exts);
1319                         foreach my $ext (@exts) {
1320                                 $mimemap{$ext} = $mime;
1321                         }
1322                 }
1323         }
1324         close(MIME);
1325
1326         $filename =~ /\.([^.]*)$/;
1327         return $mimemap{$1};
1328 }
1329
1330 sub mimetype_guess {
1331         my $filename = shift;
1332         my $mime;
1333         $filename =~ /\./ or return undef;
1334
1335         if ($mimetypes_file) {
1336                 my $file = $mimetypes_file;
1337                 if ($file !~ m!^/!) { # if it is relative path
1338                         # it is relative to project
1339                         $file = "$projectroot/$project/$file";
1340                 }
1341                 $mime = mimetype_guess_file($filename, $file);
1342         }
1343         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1344         return $mime;
1345 }
1346
1347 sub blob_mimetype {
1348         my $fd = shift;
1349         my $filename = shift;
1350
1351         if ($filename) {
1352                 my $mime = mimetype_guess($filename);
1353                 $mime and return $mime;
1354         }
1355
1356         # just in case
1357         return $default_blob_plain_mimetype unless $fd;
1358
1359         if (-T $fd) {
1360                 return 'text/plain' .
1361                        ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1362         } elsif (! $filename) {
1363                 return 'application/octet-stream';
1364         } elsif ($filename =~ m/\.png$/i) {
1365                 return 'image/png';
1366         } elsif ($filename =~ m/\.gif$/i) {
1367                 return 'image/gif';
1368         } elsif ($filename =~ m/\.jpe?g$/i) {
1369                 return 'image/jpeg';
1370         } else {
1371                 return 'application/octet-stream';
1372         }
1373 }
1374
1375 ## ======================================================================
1376 ## functions printing HTML: header, footer, error page
1377
1378 sub git_header_html {
1379         my $status = shift || "200 OK";
1380         my $expires = shift;
1381
1382         my $title = "$site_name git";
1383         if (defined $project) {
1384                 $title .= " - $project";
1385                 if (defined $action) {
1386                         $title .= "/$action";
1387                         if (defined $file_name) {
1388                                 $title .= " - " . esc_html($file_name);
1389                                 if ($action eq "tree" && $file_name !~ m|/$|) {
1390                                         $title .= "/";
1391                                 }
1392                         }
1393                 }
1394         }
1395         my $content_type;
1396         # require explicit support from the UA if we are to send the page as
1397         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1398         # we have to do this because MSIE sometimes globs '*/*', pretending to
1399         # support xhtml+xml but choking when it gets what it asked for.
1400         if (defined $cgi->http('HTTP_ACCEPT') &&
1401             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1402             $cgi->Accept('application/xhtml+xml') != 0) {
1403                 $content_type = 'application/xhtml+xml';
1404         } else {
1405                 $content_type = 'text/html';
1406         }
1407         print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1408                            -status=> $status, -expires => $expires);
1409         print <<EOF;
1410 <?xml version="1.0" encoding="utf-8"?>
1411 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1412 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1413 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1414 <!-- git core binaries version $git_version -->
1415 <head>
1416 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1417 <meta name="generator" content="gitweb/$version git/$git_version"/>
1418 <meta name="robots" content="index, nofollow"/>
1419 <title>$title</title>
1420 <link rel="stylesheet" type="text/css" href="$stylesheet"/>
1421 EOF
1422         if (defined $project) {
1423                 printf('<link rel="alternate" title="%s log" '.
1424                        'href="%s" type="application/rss+xml"/>'."\n",
1425                        esc_param($project), href(action=>"rss"));
1426         } else {
1427                 printf('<link rel="alternate" title="%s projects list" '.
1428                        'href="%s" type="text/plain; charset=utf-8"/>'."\n",
1429                        $site_name, href(project=>undef, action=>"project_index"));
1430                 printf('<link rel="alternate" title="%s projects logs" '.
1431                        'href="%s" type="text/x-opml"/>'."\n",
1432                        $site_name, href(project=>undef, action=>"opml"));
1433         }
1434         if (defined $favicon) {
1435                 print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
1436         }
1437
1438         print "</head>\n" .
1439               "<body>\n" .
1440               "<div class=\"page_header\">\n" .
1441               $cgi->a({-href => esc_url($logo_url),
1442                        -title => $logo_label},
1443                       qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
1444         print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
1445         if (defined $project) {
1446                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1447                 if (defined $action) {
1448                         print " / $action";
1449                 }
1450                 print "\n";
1451                 if (!defined $searchtext) {
1452                         $searchtext = "";
1453                 }
1454                 my $search_hash;
1455                 if (defined $hash_base) {
1456                         $search_hash = $hash_base;
1457                 } elsif (defined $hash) {
1458                         $search_hash = $hash;
1459                 } else {
1460                         $search_hash = "HEAD";
1461                 }
1462                 $cgi->param("a", "search");
1463                 $cgi->param("h", $search_hash);
1464                 $cgi->param("p", $project);
1465                 print $cgi->startform(-method => "get", -action => $my_uri) .
1466                       "<div class=\"search\">\n" .
1467                       $cgi->hidden(-name => "p") . "\n" .
1468                       $cgi->hidden(-name => "a") . "\n" .
1469                       $cgi->hidden(-name => "h") . "\n" .
1470                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1471                       "</div>" .
1472                       $cgi->end_form() . "\n";
1473         }
1474         print "</div>\n";
1475 }
1476
1477 sub git_footer_html {
1478         print "<div class=\"page_footer\">\n";
1479         if (defined $project) {
1480                 my $descr = git_get_project_description($project);
1481                 if (defined $descr) {
1482                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1483                 }
1484                 print $cgi->a({-href => href(action=>"rss"),
1485                               -class => "rss_logo"}, "RSS") . "\n";
1486         } else {
1487                 print $cgi->a({-href => href(project=>undef, action=>"opml"),
1488                               -class => "rss_logo"}, "OPML") . " ";
1489                 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
1490                               -class => "rss_logo"}, "TXT") . "\n";
1491         }
1492         print "</div>\n" .
1493               "</body>\n" .
1494               "</html>";
1495 }
1496
1497 sub die_error {
1498         my $status = shift || "403 Forbidden";
1499         my $error = shift || "Malformed query, file missing or permission denied";
1500
1501         git_header_html($status);
1502         print <<EOF;
1503 <div class="page_body">
1504 <br /><br />
1505 $status - $error
1506 <br />
1507 </div>
1508 EOF
1509         git_footer_html();
1510         exit;
1511 }
1512
1513 ## ----------------------------------------------------------------------
1514 ## functions printing or outputting HTML: navigation
1515
1516 sub git_print_page_nav {
1517         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1518         $extra = '' if !defined $extra; # pager or formats
1519
1520         my @navs = qw(summary shortlog log commit commitdiff tree);
1521         if ($suppress) {
1522                 @navs = grep { $_ ne $suppress } @navs;
1523         }
1524
1525         my %arg = map { $_ => {action=>$_} } @navs;
1526         if (defined $head) {
1527                 for (qw(commit commitdiff)) {
1528                         $arg{$_}{hash} = $head;
1529                 }
1530                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1531                         for (qw(shortlog log)) {
1532                                 $arg{$_}{hash} = $head;
1533                         }
1534                 }
1535         }
1536         $arg{tree}{hash} = $treehead if defined $treehead;
1537         $arg{tree}{hash_base} = $treebase if defined $treebase;
1538
1539         print "<div class=\"page_nav\">\n" .
1540                 (join " | ",
1541                  map { $_ eq $current ?
1542                        $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1543                  } @navs);
1544         print "<br/>\n$extra<br/>\n" .
1545               "</div>\n";
1546 }
1547
1548 sub format_paging_nav {
1549         my ($action, $hash, $head, $page, $nrevs) = @_;
1550         my $paging_nav;
1551
1552
1553         if ($hash ne $head || $page) {
1554                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1555         } else {
1556                 $paging_nav .= "HEAD";
1557         }
1558
1559         if ($page > 0) {
1560                 $paging_nav .= " &sdot; " .
1561                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1562                                  -accesskey => "p", -title => "Alt-p"}, "prev");
1563         } else {
1564                 $paging_nav .= " &sdot; prev";
1565         }
1566
1567         if ($nrevs >= (100 * ($page+1)-1)) {
1568                 $paging_nav .= " &sdot; " .
1569                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1570                                  -accesskey => "n", -title => "Alt-n"}, "next");
1571         } else {
1572                 $paging_nav .= " &sdot; next";
1573         }
1574
1575         return $paging_nav;
1576 }
1577
1578 ## ......................................................................
1579 ## functions printing or outputting HTML: div
1580
1581 sub git_print_header_div {
1582         my ($action, $title, $hash, $hash_base) = @_;
1583         my %args = ();
1584
1585         $args{action} = $action;
1586         $args{hash} = $hash if $hash;
1587         $args{hash_base} = $hash_base if $hash_base;
1588
1589         print "<div class=\"header\">\n" .
1590               $cgi->a({-href => href(%args), -class => "title"},
1591               $title ? $title : $action) .
1592               "\n</div>\n";
1593 }
1594
1595 #sub git_print_authorship (\%) {
1596 sub git_print_authorship {
1597         my $co = shift;
1598
1599         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
1600         print "<div class=\"author_date\">" .
1601               esc_html($co->{'author_name'}) .
1602               " [$ad{'rfc2822'}";
1603         if ($ad{'hour_local'} < 6) {
1604                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
1605                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1606         } else {
1607                 printf(" (%02d:%02d %s)",
1608                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1609         }
1610         print "]</div>\n";
1611 }
1612
1613 sub git_print_page_path {
1614         my $name = shift;
1615         my $type = shift;
1616         my $hb = shift;
1617
1618         if (!defined $name) {
1619                 print "<div class=\"page_path\">/</div>\n";
1620         } else {
1621                 my @dirname = split '/', $name;
1622                 my $basename = pop @dirname;
1623                 my $fullname = '';
1624
1625                 print "<div class=\"page_path\">";
1626                 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
1627                               -title => 'tree root'}, "[$project]");
1628                 print " / ";
1629                 foreach my $dir (@dirname) {
1630                         $fullname .= ($fullname ? '/' : '') . $dir;
1631                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
1632                                                      hash_base=>$hb),
1633                                       -title => $fullname}, esc_html($dir));
1634                         print " / ";
1635                 }
1636                 if (defined $type && $type eq 'blob') {
1637                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
1638                                                      hash_base=>$hb),
1639                                       -title => $name}, esc_html($basename));
1640                 } elsif (defined $type && $type eq 'tree') {
1641                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
1642                                                      hash_base=>$hb),
1643                                       -title => $name}, esc_html($basename));
1644                 } else {
1645                         print esc_html($basename);
1646                 }
1647                 print "<br/></div>\n";
1648         }
1649 }
1650
1651 # sub git_print_log (\@;%) {
1652 sub git_print_log ($;%) {
1653         my $log = shift;
1654         my %opts = @_;
1655
1656         if ($opts{'-remove_title'}) {
1657                 # remove title, i.e. first line of log
1658                 shift @$log;
1659         }
1660         # remove leading empty lines
1661         while (defined $log->[0] && $log->[0] eq "") {
1662                 shift @$log;
1663         }
1664
1665         # print log
1666         my $signoff = 0;
1667         my $empty = 0;
1668         foreach my $line (@$log) {
1669                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1670                         $signoff = 1;
1671                         $empty = 0;
1672                         if (! $opts{'-remove_signoff'}) {
1673                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1674                                 next;
1675                         } else {
1676                                 # remove signoff lines
1677                                 next;
1678                         }
1679                 } else {
1680                         $signoff = 0;
1681                 }
1682
1683                 # print only one empty line
1684                 # do not print empty line after signoff
1685                 if ($line eq "") {
1686                         next if ($empty || $signoff);
1687                         $empty = 1;
1688                 } else {
1689                         $empty = 0;
1690                 }
1691
1692                 print format_log_line_html($line) . "<br/>\n";
1693         }
1694
1695         if ($opts{'-final_empty_line'}) {
1696                 # end with single empty line
1697                 print "<br/>\n" unless $empty;
1698         }
1699 }
1700
1701 sub git_print_simplified_log {
1702         my $log = shift;
1703         my $remove_title = shift;
1704
1705         git_print_log($log,
1706                 -final_empty_line=> 1,
1707                 -remove_title => $remove_title);
1708 }
1709
1710 # print tree entry (row of git_tree), but without encompassing <tr> element
1711 sub git_print_tree_entry {
1712         my ($t, $basedir, $hash_base, $have_blame) = @_;
1713
1714         my %base_key = ();
1715         $base_key{hash_base} = $hash_base if defined $hash_base;
1716
1717         # The format of a table row is: mode list link.  Where mode is
1718         # the mode of the entry, list is the name of the entry, an href,
1719         # and link is the action links of the entry.
1720
1721         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
1722         if ($t->{'type'} eq "blob") {
1723                 print "<td class=\"list\">" .
1724                         $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1725                                                file_name=>"$basedir$t->{'name'}", %base_key),
1726                                 -class => "list"}, esc_html($t->{'name'})) . "</td>\n";
1727                 print "<td class=\"link\">";
1728                 if ($have_blame) {
1729                         print $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
1730                                                            file_name=>"$basedir$t->{'name'}", %base_key)},
1731                                             "blame");
1732                 }
1733                 if (defined $hash_base) {
1734                         if ($have_blame) {
1735                                 print " | ";
1736                         }
1737                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1738                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
1739                                       "history");
1740                 }
1741                 print " | " .
1742                         $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
1743                                                file_name=>"$basedir$t->{'name'}")},
1744                                 "raw");
1745                 print "</td>\n";
1746
1747         } elsif ($t->{'type'} eq "tree") {
1748                 print "<td class=\"list\">";
1749                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1750                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1751                               esc_html($t->{'name'}));
1752                 print "</td>\n";
1753                 print "<td class=\"link\">";
1754                 if (defined $hash_base) {
1755                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1756                                                      file_name=>"$basedir$t->{'name'}")},
1757                                       "history");
1758                 }
1759                 print "</td>\n";
1760         }
1761 }
1762
1763 ## ......................................................................
1764 ## functions printing large fragments of HTML
1765
1766 sub git_difftree_body {
1767         my ($difftree, $hash, $parent) = @_;
1768
1769         print "<div class=\"list_head\">\n";
1770         if ($#{$difftree} > 10) {
1771                 print(($#{$difftree} + 1) . " files changed:\n");
1772         }
1773         print "</div>\n";
1774
1775         print "<table class=\"diff_tree\">\n";
1776         my $alternate = 1;
1777         my $patchno = 0;
1778         foreach my $line (@{$difftree}) {
1779                 my %diff = parse_difftree_raw_line($line);
1780
1781                 if ($alternate) {
1782                         print "<tr class=\"dark\">\n";
1783                 } else {
1784                         print "<tr class=\"light\">\n";
1785                 }
1786                 $alternate ^= 1;
1787
1788                 my ($to_mode_oct, $to_mode_str, $to_file_type);
1789                 my ($from_mode_oct, $from_mode_str, $from_file_type);
1790                 if ($diff{'to_mode'} ne ('0' x 6)) {
1791                         $to_mode_oct = oct $diff{'to_mode'};
1792                         if (S_ISREG($to_mode_oct)) { # only for regular file
1793                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
1794                         }
1795                         $to_file_type = file_type($diff{'to_mode'});
1796                 }
1797                 if ($diff{'from_mode'} ne ('0' x 6)) {
1798                         $from_mode_oct = oct $diff{'from_mode'};
1799                         if (S_ISREG($to_mode_oct)) { # only for regular file
1800                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
1801                         }
1802                         $from_file_type = file_type($diff{'from_mode'});
1803                 }
1804
1805                 if ($diff{'status'} eq "A") { # created
1806                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
1807                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
1808                         $mode_chng   .= "]</span>";
1809                         print "<td>";
1810                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1811                                                      hash_base=>$hash, file_name=>$diff{'file'}),
1812                                       -class => "list"}, esc_html($diff{'file'}));
1813                         print "</td>\n";
1814                         print "<td>$mode_chng</td>\n";
1815                         print "<td class=\"link\">";
1816                         if ($action eq 'commitdiff') {
1817                                 # link to patch
1818                                 $patchno++;
1819                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
1820                         }
1821                         print "</td>\n";
1822
1823                 } elsif ($diff{'status'} eq "D") { # deleted
1824                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
1825                         print "<td>";
1826                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1827                                                      hash_base=>$parent, file_name=>$diff{'file'}),
1828                                        -class => "list"}, esc_html($diff{'file'}));
1829                         print "</td>\n";
1830                         print "<td>$mode_chng</td>\n";
1831                         print "<td class=\"link\">";
1832                         if ($action eq 'commitdiff') {
1833                                 # link to patch
1834                                 $patchno++;
1835                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
1836                                 print " | ";
1837                         }
1838                         print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
1839                                                      file_name=>$diff{'file'})},
1840                                       "blame") . " | ";
1841                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1842                                                      file_name=>$diff{'file'})},
1843                                       "history");
1844                         print "</td>\n";
1845
1846                 } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
1847                         my $mode_chnge = "";
1848                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1849                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
1850                                 if ($from_file_type != $to_file_type) {
1851                                         $mode_chnge .= " from $from_file_type to $to_file_type";
1852                                 }
1853                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
1854                                         if ($from_mode_str && $to_mode_str) {
1855                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
1856                                         } elsif ($to_mode_str) {
1857                                                 $mode_chnge .= " mode: $to_mode_str";
1858                                         }
1859                                 }
1860                                 $mode_chnge .= "]</span>\n";
1861                         }
1862                         print "<td>";
1863                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1864                                                      hash_base=>$hash, file_name=>$diff{'file'}),
1865                                       -class => "list"}, esc_html($diff{'file'}));
1866                         print "</td>\n";
1867                         print "<td>$mode_chnge</td>\n";
1868                         print "<td class=\"link\">";
1869                         if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1870                                 if ($action eq 'commitdiff') {
1871                                         # link to patch
1872                                         $patchno++;
1873                                         print $cgi->a({-href => "#patch$patchno"}, "patch");
1874                                 } else {
1875                                         print $cgi->a({-href => href(action=>"blobdiff",
1876                                                                      hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1877                                                                      hash_base=>$hash, hash_parent_base=>$parent,
1878                                                                      file_name=>$diff{'file'})},
1879                                                       "diff");
1880                                 }
1881                                 print " | ";
1882                         }
1883                         print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
1884                                                      file_name=>$diff{'file'})},
1885                                       "blame") . " | ";
1886                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
1887                                                      file_name=>$diff{'file'})},
1888                                       "history");
1889                         print "</td>\n";
1890
1891                 } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
1892                         my %status_name = ('R' => 'moved', 'C' => 'copied');
1893                         my $nstatus = $status_name{$diff{'status'}};
1894                         my $mode_chng = "";
1895                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1896                                 # mode also for directories, so we cannot use $to_mode_str
1897                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
1898                         }
1899                         print "<td>" .
1900                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1901                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
1902                                       -class => "list"}, esc_html($diff{'to_file'})) . "</td>\n" .
1903                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
1904                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
1905                                                      hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
1906                                       -class => "list"}, esc_html($diff{'from_file'})) .
1907                               " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
1908                               "<td class=\"link\">";
1909                         if ($diff{'to_id'} ne $diff{'from_id'}) {
1910                                 if ($action eq 'commitdiff') {
1911                                         # link to patch
1912                                         $patchno++;
1913                                         print $cgi->a({-href => "#patch$patchno"}, "patch");
1914                                 } else {
1915                                         print $cgi->a({-href => href(action=>"blobdiff",
1916                                                                      hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1917                                                                      hash_base=>$hash, hash_parent_base=>$parent,
1918                                                                      file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
1919                                                       "diff");
1920                                 }
1921                                 print " | ";
1922                         }
1923                         print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
1924                                                      file_name=>$diff{'from_file'})},
1925                                       "blame") . " | ";
1926                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1927                                                     file_name=>$diff{'from_file'})},
1928                                       "history");
1929                         print "</td>\n";
1930
1931                 } # we should not encounter Unmerged (U) or Unknown (X) status
1932                 print "</tr>\n";
1933         }
1934         print "</table>\n";
1935 }
1936
1937 sub git_patchset_body {
1938         my ($fd, $difftree, $hash, $hash_parent) = @_;
1939
1940         my $patch_idx = 0;
1941         my $in_header = 0;
1942         my $patch_found = 0;
1943         my $diffinfo;
1944
1945         print "<div class=\"patchset\">\n";
1946
1947         LINE:
1948         while (my $patch_line = <$fd>) {
1949                 chomp $patch_line;
1950
1951                 if ($patch_line =~ m/^diff /) { # "git diff" header
1952                         # beginning of patch (in patchset)
1953                         if ($patch_found) {
1954                                 # close previous patch
1955                                 print "</div>\n"; # class="patch"
1956                         } else {
1957                                 # first patch in patchset
1958                                 $patch_found = 1;
1959                         }
1960                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
1961
1962                         if (ref($difftree->[$patch_idx]) eq "HASH") {
1963                                 $diffinfo = $difftree->[$patch_idx];
1964                         } else {
1965                                 $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
1966                         }
1967                         $patch_idx++;
1968
1969                         # for now, no extended header, hence we skip empty patches
1970                         # companion to  next LINE if $in_header;
1971                         if ($diffinfo->{'from_id'} eq $diffinfo->{'to_id'}) { # no change
1972                                 $in_header = 1;
1973                                 next LINE;
1974                         }
1975
1976                         if ($diffinfo->{'status'} eq "A") { # added
1977                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'to_mode'}) . ":" .
1978                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1979                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1980                                               $diffinfo->{'to_id'}) . " (new)" .
1981                                       "</div>\n"; # class="diff_info"
1982
1983                         } elsif ($diffinfo->{'status'} eq "D") { # deleted
1984                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'from_mode'}) . ":" .
1985                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1986                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1987                                               $diffinfo->{'from_id'}) . " (deleted)" .
1988                                       "</div>\n"; # class="diff_info"
1989
1990                         } elsif ($diffinfo->{'status'} eq "R" || # renamed
1991                                  $diffinfo->{'status'} eq "C" || # copied
1992                                  $diffinfo->{'status'} eq "2") { # with two filenames (from git_blobdiff)
1993                                 print "<div class=\"diff_info\">" .
1994                                       file_type($diffinfo->{'from_mode'}) . ":" .
1995                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1996                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'from_file'})},
1997                                               $diffinfo->{'from_id'}) .
1998                                       " -> " .
1999                                       file_type($diffinfo->{'to_mode'}) . ":" .
2000                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2001                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'to_file'})},
2002                                               $diffinfo->{'to_id'});
2003                                 print "</div>\n"; # class="diff_info"
2004
2005                         } else { # modified, mode changed, ...
2006                                 print "<div class=\"diff_info\">" .
2007                                       file_type($diffinfo->{'from_mode'}) . ":" .
2008                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
2009                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
2010                                               $diffinfo->{'from_id'}) .
2011                                       " -> " .
2012                                       file_type($diffinfo->{'to_mode'}) . ":" .
2013                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2014                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
2015                                               $diffinfo->{'to_id'});
2016                                 print "</div>\n"; # class="diff_info"
2017                         }
2018
2019                         #print "<div class=\"diff extended_header\">\n";
2020                         $in_header = 1;
2021                         next LINE;
2022                 } # start of patch in patchset
2023
2024
2025                 if ($in_header && $patch_line =~ m/^---/) {
2026                         #print "</div>\n"; # class="diff extended_header"
2027                         $in_header = 0;
2028
2029                         my $file = $diffinfo->{'from_file'};
2030                         $file  ||= $diffinfo->{'file'};
2031                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
2032                                                        hash=>$diffinfo->{'from_id'}, file_name=>$file),
2033                                         -class => "list"}, esc_html($file));
2034                         $patch_line =~ s|a/.*$|a/$file|g;
2035                         print "<div class=\"diff from_file\">$patch_line</div>\n";
2036
2037                         $patch_line = <$fd>;
2038                         chomp $patch_line;
2039
2040                         #$patch_line =~ m/^+++/;
2041                         $file    = $diffinfo->{'to_file'};
2042                         $file  ||= $diffinfo->{'file'};
2043                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2044                                                        hash=>$diffinfo->{'to_id'}, file_name=>$file),
2045                                         -class => "list"}, esc_html($file));
2046                         $patch_line =~ s|b/.*|b/$file|g;
2047                         print "<div class=\"diff to_file\">$patch_line</div>\n";
2048
2049                         next LINE;
2050                 }
2051                 next LINE if $in_header;
2052
2053                 print format_diff_line($patch_line);
2054         }
2055         print "</div>\n" if $patch_found; # class="patch"
2056
2057         print "</div>\n"; # class="patchset"
2058 }
2059
2060 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2061
2062 sub git_shortlog_body {
2063         # uses global variable $project
2064         my ($revlist, $from, $to, $refs, $extra) = @_;
2065
2066         $from = 0 unless defined $from;
2067         $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
2068
2069         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
2070         my $alternate = 1;
2071         for (my $i = $from; $i <= $to; $i++) {
2072                 my $commit = $revlist->[$i];
2073                 #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
2074                 my $ref = format_ref_marker($refs, $commit);
2075                 my %co = parse_commit($commit);
2076                 if ($alternate) {
2077                         print "<tr class=\"dark\">\n";
2078                 } else {
2079                         print "<tr class=\"light\">\n";
2080                 }
2081                 $alternate ^= 1;
2082                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
2083                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2084                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
2085                       "<td>";
2086                 print format_subject_html($co{'title'}, $co{'title_short'},
2087                                           href(action=>"commit", hash=>$commit), $ref);
2088                 print "</td>\n" .
2089                       "<td class=\"link\">" .
2090                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
2091                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
2092                 if (gitweb_have_snapshot()) {
2093                         print " | " . $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
2094                 }
2095                 print "</td>\n" .
2096                       "</tr>\n";
2097         }
2098         if (defined $extra) {
2099                 print "<tr>\n" .
2100                       "<td colspan=\"4\">$extra</td>\n" .
2101                       "</tr>\n";
2102         }
2103         print "</table>\n";
2104 }
2105
2106 sub git_history_body {
2107         # Warning: assumes constant type (blob or tree) during history
2108         my ($revlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
2109
2110         $from = 0 unless defined $from;
2111         $to = $#{$revlist} unless (defined $to && $to <= $#{$revlist});
2112
2113         print "<table class=\"history\" cellspacing=\"0\">\n";
2114         my $alternate = 1;
2115         for (my $i = $from; $i <= $to; $i++) {
2116                 if ($revlist->[$i] !~ m/^([0-9a-fA-F]{40})/) {
2117                         next;
2118                 }
2119
2120                 my $commit = $1;
2121                 my %co = parse_commit($commit);
2122                 if (!%co) {
2123                         next;
2124                 }
2125
2126                 my $ref = format_ref_marker($refs, $commit);
2127
2128                 if ($alternate) {
2129                         print "<tr class=\"dark\">\n";
2130                 } else {
2131                         print "<tr class=\"light\">\n";
2132                 }
2133                 $alternate ^= 1;
2134                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2135                       # shortlog uses      chop_str($co{'author_name'}, 10)
2136                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
2137                       "<td>";
2138                 # originally git_history used chop_str($co{'title'}, 50)
2139                 print format_subject_html($co{'title'}, $co{'title_short'},
2140                                           href(action=>"commit", hash=>$commit), $ref);
2141                 print "</td>\n" .
2142                       "<td class=\"link\">" .
2143                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
2144                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
2145
2146                 if ($ftype eq 'blob') {
2147                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
2148                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
2149                         if (defined $blob_current && defined $blob_parent &&
2150                                         $blob_current ne $blob_parent) {
2151                                 print " | " .
2152                                         $cgi->a({-href => href(action=>"blobdiff",
2153                                                                hash=>$blob_current, hash_parent=>$blob_parent,
2154                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
2155                                                                file_name=>$file_name)},
2156                                                 "diff to current");
2157                         }
2158                 }
2159                 print "</td>\n" .
2160                       "</tr>\n";
2161         }
2162         if (defined $extra) {
2163                 print "<tr>\n" .
2164                       "<td colspan=\"4\">$extra</td>\n" .
2165                       "</tr>\n";
2166         }
2167         print "</table>\n";
2168 }
2169
2170 sub git_tags_body {
2171         # uses global variable $project
2172         my ($taglist, $from, $to, $extra) = @_;
2173         $from = 0 unless defined $from;
2174         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2175
2176         print "<table class=\"tags\" cellspacing=\"0\">\n";
2177         my $alternate = 1;
2178         for (my $i = $from; $i <= $to; $i++) {
2179                 my $entry = $taglist->[$i];
2180                 my %tag = %$entry;
2181                 my $comment_lines = $tag{'comment'};
2182                 my $comment = shift @$comment_lines;
2183                 my $comment_short;
2184                 if (defined $comment) {
2185                         $comment_short = chop_str($comment, 30, 5);
2186                 }
2187                 if ($alternate) {
2188                         print "<tr class=\"dark\">\n";
2189                 } else {
2190                         print "<tr class=\"light\">\n";
2191                 }
2192                 $alternate ^= 1;
2193                 print "<td><i>$tag{'age'}</i></td>\n" .
2194                       "<td>" .
2195                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
2196                                -class => "list name"}, esc_html($tag{'name'})) .
2197                       "</td>\n" .
2198                       "<td>";
2199                 if (defined $comment) {
2200                         print format_subject_html($comment, $comment_short,
2201                                                   href(action=>"tag", hash=>$tag{'id'}));
2202                 }
2203                 print "</td>\n" .
2204                       "<td class=\"selflink\">";
2205                 if ($tag{'type'} eq "tag") {
2206                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
2207                 } else {
2208                         print "&nbsp;";
2209                 }
2210                 print "</td>\n" .
2211                       "<td class=\"link\">" . " | " .
2212                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
2213                 if ($tag{'reftype'} eq "commit") {
2214                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
2215                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'refid'})}, "log");
2216                 } elsif ($tag{'reftype'} eq "blob") {
2217                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
2218                 }
2219                 print "</td>\n" .
2220                       "</tr>";
2221         }
2222         if (defined $extra) {
2223                 print "<tr>\n" .
2224                       "<td colspan=\"5\">$extra</td>\n" .
2225                       "</tr>\n";
2226         }
2227         print "</table>\n";
2228 }
2229
2230 sub git_heads_body {
2231         # uses global variable $project
2232         my ($headlist, $head, $from, $to, $extra) = @_;
2233         $from = 0 unless defined $from;
2234         $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
2235
2236         print "<table class=\"heads\" cellspacing=\"0\">\n";
2237         my $alternate = 1;
2238         for (my $i = $from; $i <= $to; $i++) {
2239                 my $entry = $headlist->[$i];
2240                 my %tag = %$entry;
2241                 my $curr = $tag{'id'} eq $head;
2242                 if ($alternate) {
2243                         print "<tr class=\"dark\">\n";
2244                 } else {
2245                         print "<tr class=\"light\">\n";
2246                 }
2247                 $alternate ^= 1;
2248                 print "<td><i>$tag{'age'}</i></td>\n" .
2249                       ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
2250                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'}),
2251                                -class => "list name"},esc_html($tag{'name'})) .
2252                       "</td>\n" .
2253                       "<td class=\"link\">" .
2254                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") . " | " .
2255                       $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log") . " | " .
2256                       $cgi->a({-href => href(action=>"tree", hash=>$tag{'name'}, hash_base=>$tag{'name'})}, "tree") .
2257                       "</td>\n" .
2258                       "</tr>";
2259         }
2260         if (defined $extra) {
2261                 print "<tr>\n" .
2262                       "<td colspan=\"3\">$extra</td>\n" .
2263                       "</tr>\n";
2264         }
2265         print "</table>\n";
2266 }
2267
2268 ## ======================================================================
2269 ## ======================================================================
2270 ## actions
2271
2272 sub git_project_list {
2273         my $order = $cgi->param('o');
2274         if (defined $order && $order !~ m/project|descr|owner|age/) {
2275                 die_error(undef, "Unknown order parameter");
2276         }
2277
2278         my @list = git_get_projects_list();
2279         my @projects;
2280         if (!@list) {
2281                 die_error(undef, "No projects found");
2282         }
2283         foreach my $pr (@list) {
2284                 my $head = git_get_head_hash($pr->{'path'});
2285                 if (!defined $head) {
2286                         next;
2287                 }
2288                 $git_dir = "$projectroot/$pr->{'path'}";
2289                 my %co = parse_commit($head);
2290                 if (!%co) {
2291                         next;
2292                 }
2293                 $pr->{'commit'} = \%co;
2294                 if (!defined $pr->{'descr'}) {
2295                         my $descr = git_get_project_description($pr->{'path'}) || "";
2296                         $pr->{'descr'} = chop_str($descr, 25, 5);
2297                 }
2298                 if (!defined $pr->{'owner'}) {
2299                         $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2300                 }
2301                 push @projects, $pr;
2302         }
2303
2304         git_header_html();
2305         if (-f $home_text) {
2306                 print "<div class=\"index_include\">\n";
2307                 open (my $fd, $home_text);
2308                 print <$fd>;
2309                 close $fd;
2310                 print "</div>\n";
2311         }
2312         print "<table class=\"project_list\">\n" .
2313               "<tr>\n";
2314         $order ||= "project";
2315         if ($order eq "project") {
2316                 @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2317                 print "<th>Project</th>\n";
2318         } else {
2319                 print "<th>" .
2320                       $cgi->a({-href => href(project=>undef, order=>'project'),
2321                                -class => "header"}, "Project") .
2322                       "</th>\n";
2323         }
2324         if ($order eq "descr") {
2325                 @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2326                 print "<th>Description</th>\n";
2327         } else {
2328                 print "<th>" .
2329                       $cgi->a({-href => href(project=>undef, order=>'descr'),
2330                                -class => "header"}, "Description") .
2331                       "</th>\n";
2332         }
2333         if ($order eq "owner") {
2334                 @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2335                 print "<th>Owner</th>\n";
2336         } else {
2337                 print "<th>" .
2338                       $cgi->a({-href => href(project=>undef, order=>'owner'),
2339                                -class => "header"}, "Owner") .
2340                       "</th>\n";
2341         }
2342         if ($order eq "age") {
2343                 @projects = sort {$a->{'commit'}{'age'} <=> $b->{'commit'}{'age'}} @projects;
2344                 print "<th>Last Change</th>\n";
2345         } else {
2346                 print "<th>" .
2347                       $cgi->a({-href => href(project=>undef, order=>'age'),
2348                                -class => "header"}, "Last Change") .
2349                       "</th>\n";
2350         }
2351         print "<th></th>\n" .
2352               "</tr>\n";
2353         my $alternate = 1;
2354         foreach my $pr (@projects) {
2355                 if ($alternate) {
2356                         print "<tr class=\"dark\">\n";
2357                 } else {
2358                         print "<tr class=\"light\">\n";
2359                 }
2360                 $alternate ^= 1;
2361                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2362                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2363                       "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
2364                       "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2365                 print "<td class=\"". age_class($pr->{'commit'}{'age'}) . "\">" .
2366                       $pr->{'commit'}{'age_string'} . "</td>\n" .
2367                       "<td class=\"link\">" .
2368                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2369                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
2370                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
2371                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
2372                       "</td>\n" .
2373                       "</tr>\n";
2374         }
2375         print "</table>\n";
2376         git_footer_html();
2377 }
2378
2379 sub git_project_index {
2380         my @projects = git_get_projects_list();
2381
2382         print $cgi->header(
2383                 -type => 'text/plain',
2384                 -charset => 'utf-8',
2385                 -content_disposition => 'inline; filename="index.aux"');
2386
2387         foreach my $pr (@projects) {
2388                 if (!exists $pr->{'owner'}) {
2389                         $pr->{'owner'} = get_file_owner("$projectroot/$project");
2390                 }
2391
2392                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
2393                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
2394                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2395                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2396                 $path  =~ s/ /\+/g;
2397                 $owner =~ s/ /\+/g;
2398
2399                 print "$path $owner\n";
2400         }
2401 }
2402
2403 sub git_summary {
2404         my $descr = git_get_project_description($project) || "none";
2405         my $head = git_get_head_hash($project);
2406         my %co = parse_commit($head);
2407         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2408
2409         my $owner = git_get_project_owner($project);
2410
2411         my ($reflist, $refs) = git_get_refs_list();
2412
2413         my @taglist;
2414         my @headlist;
2415         foreach my $ref (@$reflist) {
2416                 if ($ref->{'name'} =~ s!^heads/!!) {
2417                         push @headlist, $ref;
2418                 } else {
2419                         $ref->{'name'} =~ s!^tags/!!;
2420                         push @taglist, $ref;
2421                 }
2422         }
2423
2424         git_header_html();
2425         git_print_page_nav('summary','', $head);
2426
2427         print "<div class=\"title\">&nbsp;</div>\n";
2428         print "<table cellspacing=\"0\">\n" .
2429               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
2430               "<tr><td>owner</td><td>$owner</td></tr>\n" .
2431               "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
2432         # use per project git URL list in $projectroot/$project/cloneurl
2433         # or make project git URL from git base URL and project name
2434         my $url_tag = "URL";
2435         my @url_list = git_get_project_url_list($project);
2436         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
2437         foreach my $git_url (@url_list) {
2438                 next unless $git_url;
2439                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
2440                 $url_tag = "";
2441         }
2442         print "</table>\n";
2443
2444         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=17",
2445                 git_get_head_hash($project)
2446                 or die_error(undef, "Open git-rev-list failed");
2447         my @revlist = map { chomp; $_ } <$fd>;
2448         close $fd;
2449         git_print_header_div('shortlog');
2450         git_shortlog_body(\@revlist, 0, 15, $refs,
2451                           $cgi->a({-href => href(action=>"shortlog")}, "..."));
2452
2453         if (@taglist) {
2454                 git_print_header_div('tags');
2455                 git_tags_body(\@taglist, 0, 15,
2456                               $cgi->a({-href => href(action=>"tags")}, "..."));
2457         }
2458
2459         if (@headlist) {
2460                 git_print_header_div('heads');
2461                 git_heads_body(\@headlist, $head, 0, 15,
2462                                $cgi->a({-href => href(action=>"heads")}, "..."));
2463         }
2464
2465         git_footer_html();
2466 }
2467
2468 sub git_tag {
2469         my $head = git_get_head_hash($project);
2470         git_header_html();
2471         git_print_page_nav('','', $head,undef,$head);
2472         my %tag = parse_tag($hash);
2473         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
2474         print "<div class=\"title_text\">\n" .
2475               "<table cellspacing=\"0\">\n" .
2476               "<tr>\n" .
2477               "<td>object</td>\n" .
2478               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2479                                $tag{'object'}) . "</td>\n" .
2480               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2481                                               $tag{'type'}) . "</td>\n" .
2482               "</tr>\n";
2483         if (defined($tag{'author'})) {
2484                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
2485                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
2486                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
2487                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
2488                         "</td></tr>\n";
2489         }
2490         print "</table>\n\n" .
2491               "</div>\n";
2492         print "<div class=\"page_body\">";
2493         my $comment = $tag{'comment'};
2494         foreach my $line (@$comment) {
2495                 print esc_html($line) . "<br/>\n";
2496         }
2497         print "</div>\n";
2498         git_footer_html();
2499 }
2500
2501 sub git_blame2 {
2502         my $fd;
2503         my $ftype;
2504
2505         my ($have_blame) = gitweb_check_feature('blame');
2506         if (!$have_blame) {
2507                 die_error('403 Permission denied', "Permission denied");
2508         }
2509         die_error('404 Not Found', "File name not defined") if (!$file_name);
2510         $hash_base ||= git_get_head_hash($project);
2511         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2512         my %co = parse_commit($hash_base)
2513                 or die_error(undef, "Reading commit failed");
2514         if (!defined $hash) {
2515                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2516                         or die_error(undef, "Error looking up file");
2517         }
2518         $ftype = git_get_type($hash);
2519         if ($ftype !~ "blob") {
2520                 die_error("400 Bad Request", "Object is not a blob");
2521         }
2522         open ($fd, "-|", git_cmd(), "blame", '-l', '--', $file_name, $hash_base)
2523                 or die_error(undef, "Open git-blame failed");
2524         git_header_html();
2525         my $formats_nav =
2526                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2527                         "blob") .
2528                 " | " .
2529                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2530                         "history") .
2531                 " | " .
2532                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2533                         "HEAD");
2534         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2535         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2536         git_print_page_path($file_name, $ftype, $hash_base);
2537         my @rev_color = (qw(light2 dark2));
2538         my $num_colors = scalar(@rev_color);
2539         my $current_color = 0;
2540         my $last_rev;
2541         print <<HTML;
2542 <div class="page_body">
2543 <table class="blame">
2544 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
2545 HTML
2546         while (<$fd>) {
2547                 /^([0-9a-fA-F]{40}).*?(\d+)\)\s{1}(\s*.*)/;
2548                 my $full_rev = $1;
2549                 my $rev = substr($full_rev, 0, 8);
2550                 my $lineno = $2;
2551                 my $data = $3;
2552
2553                 if (!defined $last_rev) {
2554                         $last_rev = $full_rev;
2555                 } elsif ($last_rev ne $full_rev) {
2556                         $last_rev = $full_rev;
2557                         $current_color = ++$current_color % $num_colors;
2558                 }
2559                 print "<tr class=\"$rev_color[$current_color]\">\n";
2560                 print "<td class=\"sha1\">" .
2561                         $cgi->a({-href => href(action=>"commit", hash=>$full_rev, file_name=>$file_name)},
2562                                 esc_html($rev)) . "</td>\n";
2563                 print "<td class=\"linenr\"><a id=\"l$lineno\" href=\"#l$lineno\" class=\"linenr\">" .
2564                       esc_html($lineno) . "</a></td>\n";
2565                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
2566                 print "</tr>\n";
2567         }
2568         print "</table>\n";
2569         print "</div>";
2570         close $fd
2571                 or print "Reading blob failed\n";
2572         git_footer_html();
2573 }
2574
2575 sub git_blame {
2576         my $fd;
2577
2578         my ($have_blame) = gitweb_check_feature('blame');
2579         if (!$have_blame) {
2580                 die_error('403 Permission denied', "Permission denied");
2581         }
2582         die_error('404 Not Found', "File name not defined") if (!$file_name);
2583         $hash_base ||= git_get_head_hash($project);
2584         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2585         my %co = parse_commit($hash_base)
2586                 or die_error(undef, "Reading commit failed");
2587         if (!defined $hash) {
2588                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2589                         or die_error(undef, "Error lookup file");
2590         }
2591         open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
2592                 or die_error(undef, "Open git-annotate failed");
2593         git_header_html();
2594         my $formats_nav =
2595                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2596                         "blob") .
2597                 " | " .
2598                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2599                         "history") .
2600                 " | " .
2601                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2602                         "HEAD");
2603         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2604         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2605         git_print_page_path($file_name, 'blob', $hash_base);
2606         print "<div class=\"page_body\">\n";
2607         print <<HTML;
2608 <table class="blame">
2609   <tr>
2610     <th>Commit</th>
2611     <th>Age</th>
2612     <th>Author</th>
2613     <th>Line</th>
2614     <th>Data</th>
2615   </tr>
2616 HTML
2617         my @line_class = (qw(light dark));
2618         my $line_class_len = scalar (@line_class);
2619         my $line_class_num = $#line_class;
2620         while (my $line = <$fd>) {
2621                 my $long_rev;
2622                 my $short_rev;
2623                 my $author;
2624                 my $time;
2625                 my $lineno;
2626                 my $data;
2627                 my $age;
2628                 my $age_str;
2629                 my $age_class;
2630
2631                 chomp $line;
2632                 $line_class_num = ($line_class_num + 1) % $line_class_len;
2633
2634                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
2635                         $long_rev = $1;
2636                         $author   = $2;
2637                         $time     = $3;
2638                         $lineno   = $4;
2639                         $data     = $5;
2640                 } else {
2641                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
2642                         next;
2643                 }
2644                 $short_rev  = substr ($long_rev, 0, 8);
2645                 $age        = time () - $time;
2646                 $age_str    = age_string ($age);
2647                 $age_str    =~ s/ /&nbsp;/g;
2648                 $age_class  = age_class($age);
2649                 $author     = esc_html ($author);
2650                 $author     =~ s/ /&nbsp;/g;
2651
2652                 $data = untabify($data);
2653                 $data = esc_html ($data);
2654
2655                 print <<HTML;
2656   <tr class="$line_class[$line_class_num]">
2657     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
2658     <td class="$age_class">$age_str</td>
2659     <td>$author</td>
2660     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
2661     <td class="pre">$data</td>
2662   </tr>
2663 HTML
2664         } # while (my $line = <$fd>)
2665         print "</table>\n\n";
2666         close $fd
2667                 or print "Reading blob failed.\n";
2668         print "</div>";
2669         git_footer_html();
2670 }
2671
2672 sub git_tags {
2673         my $head = git_get_head_hash($project);
2674         git_header_html();
2675         git_print_page_nav('','', $head,undef,$head);
2676         git_print_header_div('summary', $project);
2677
2678         my ($taglist) = git_get_refs_list("tags");
2679         if (@$taglist) {
2680                 git_tags_body($taglist);
2681         }
2682         git_footer_html();
2683 }
2684
2685 sub git_heads {
2686         my $head = git_get_head_hash($project);
2687         git_header_html();
2688         git_print_page_nav('','', $head,undef,$head);
2689         git_print_header_div('summary', $project);
2690
2691         my ($headlist) = git_get_refs_list("heads");
2692         if (@$headlist) {
2693                 git_heads_body($headlist, $head);
2694         }
2695         git_footer_html();
2696 }
2697
2698 sub git_blob_plain {
2699         my $expires;
2700
2701         if (!defined $hash) {
2702                 if (defined $file_name) {
2703                         my $base = $hash_base || git_get_head_hash($project);
2704                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2705                                 or die_error(undef, "Error lookup file");
2706                 } else {
2707                         die_error(undef, "No file name defined");
2708                 }
2709         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2710                 # blobs defined by non-textual hash id's can be cached
2711                 $expires = "+1d";
2712         }
2713
2714         my $type = shift;
2715         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2716                 or die_error(undef, "Couldn't cat $file_name, $hash");
2717
2718         $type ||= blob_mimetype($fd, $file_name);
2719
2720         # save as filename, even when no $file_name is given
2721         my $save_as = "$hash";
2722         if (defined $file_name) {
2723                 $save_as = $file_name;
2724         } elsif ($type =~ m/^text\//) {
2725                 $save_as .= '.txt';
2726         }
2727
2728         print $cgi->header(
2729                 -type => "$type",
2730                 -expires=>$expires,
2731                 -content_disposition => 'inline; filename="' . "$save_as" . '"');
2732         undef $/;
2733         binmode STDOUT, ':raw';
2734         print <$fd>;
2735         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2736         $/ = "\n";
2737         close $fd;
2738 }
2739
2740 sub git_blob {
2741         my $expires;
2742
2743         if (!defined $hash) {
2744                 if (defined $file_name) {
2745                         my $base = $hash_base || git_get_head_hash($project);
2746                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2747                                 or die_error(undef, "Error lookup file");
2748                 } else {
2749                         die_error(undef, "No file name defined");
2750                 }
2751         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2752                 # blobs defined by non-textual hash id's can be cached
2753                 $expires = "+1d";
2754         }
2755
2756         my ($have_blame) = gitweb_check_feature('blame');
2757         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2758                 or die_error(undef, "Couldn't cat $file_name, $hash");
2759         my $mimetype = blob_mimetype($fd, $file_name);
2760         if ($mimetype !~ m/^text\//) {
2761                 close $fd;
2762                 return git_blob_plain($mimetype);
2763         }
2764         git_header_html(undef, $expires);
2765         my $formats_nav = '';
2766         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2767                 if (defined $file_name) {
2768                         if ($have_blame) {
2769                                 $formats_nav .=
2770                                         $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
2771                                                                hash=>$hash, file_name=>$file_name)},
2772                                                 "blame") .
2773                                         " | ";
2774                         }
2775                         $formats_nav .=
2776                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2777                                                        hash=>$hash, file_name=>$file_name)},
2778                                         "history") .
2779                                 " | " .
2780                                 $cgi->a({-href => href(action=>"blob_plain",
2781                                                        hash=>$hash, file_name=>$file_name)},
2782                                         "raw") .
2783                                 " | " .
2784                                 $cgi->a({-href => href(action=>"blob",
2785                                                        hash_base=>"HEAD", file_name=>$file_name)},
2786                                         "HEAD");
2787                 } else {
2788                         $formats_nav .=
2789                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
2790                 }
2791                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2792                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2793         } else {
2794                 print "<div class=\"page_nav\">\n" .
2795                       "<br/><br/></div>\n" .
2796                       "<div class=\"title\">$hash</div>\n";
2797         }
2798         git_print_page_path($file_name, "blob", $hash_base);
2799         print "<div class=\"page_body\">\n";
2800         my $nr;
2801         while (my $line = <$fd>) {
2802                 chomp $line;
2803                 $nr++;
2804                 $line = untabify($line);
2805                 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
2806                        $nr, $nr, $nr, esc_html($line);
2807         }
2808         close $fd
2809                 or print "Reading blob failed.\n";
2810         print "</div>";
2811         git_footer_html();
2812 }
2813
2814 sub git_tree {
2815         my $have_snapshot = gitweb_have_snapshot();
2816
2817         if (!defined $hash_base) {
2818                 $hash_base = "HEAD";
2819         }
2820         if (!defined $hash) {
2821                 if (defined $file_name) {
2822                         $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
2823                 } else {
2824                         $hash = $hash_base;
2825                 }
2826         }
2827         $/ = "\0";
2828         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
2829                 or die_error(undef, "Open git-ls-tree failed");
2830         my @entries = map { chomp; $_ } <$fd>;
2831         close $fd or die_error(undef, "Reading tree failed");
2832         $/ = "\n";
2833
2834         my $refs = git_get_references();
2835         my $ref = format_ref_marker($refs, $hash_base);
2836         git_header_html();
2837         my $basedir = '';
2838         my ($have_blame) = gitweb_check_feature('blame');
2839         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2840                 my @views_nav = ();
2841                 if (defined $file_name) {
2842                         push @views_nav,
2843                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2844                                                        hash=>$hash, file_name=>$file_name)},
2845                                         "history"),
2846                                 $cgi->a({-href => href(action=>"tree",
2847                                                        hash_base=>"HEAD", file_name=>$file_name)},
2848                                         "HEAD"),
2849                 }
2850                 if ($have_snapshot) {
2851                         # FIXME: Should be available when we have no hash base as well.
2852                         push @views_nav,
2853                                 $cgi->a({-href => href(action=>"snapshot", hash=>$hash)},
2854                                         "snapshot");
2855                 }
2856                 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
2857                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
2858         } else {
2859                 undef $hash_base;
2860                 print "<div class=\"page_nav\">\n";
2861                 print "<br/><br/></div>\n";
2862                 print "<div class=\"title\">$hash</div>\n";
2863         }
2864         if (defined $file_name) {
2865                 $basedir = $file_name;
2866                 if ($basedir ne '' && substr($basedir, -1) ne '/') {
2867                         $basedir .= '/';
2868                 }
2869         }
2870         git_print_page_path($file_name, 'tree', $hash_base);
2871         print "<div class=\"page_body\">\n";
2872         print "<table cellspacing=\"0\">\n";
2873         my $alternate = 1;
2874         foreach my $line (@entries) {
2875                 my %t = parse_ls_tree_line($line, -z => 1);
2876
2877                 if ($alternate) {
2878                         print "<tr class=\"dark\">\n";
2879                 } else {
2880                         print "<tr class=\"light\">\n";
2881                 }
2882                 $alternate ^= 1;
2883
2884                 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
2885
2886                 print "</tr>\n";
2887         }
2888         print "</table>\n" .
2889               "</div>";
2890         git_footer_html();
2891 }
2892
2893 sub git_snapshot {
2894         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2895         my $have_snapshot = (defined $ctype && defined $suffix);
2896         if (!$have_snapshot) {
2897                 die_error('403 Permission denied', "Permission denied");
2898         }
2899
2900         if (!defined $hash) {
2901                 $hash = git_get_head_hash($project);
2902         }
2903
2904         my $filename = basename($project) . "-$hash.tar.$suffix";
2905
2906         print $cgi->header(
2907                 -type => 'application/x-tar',
2908                 -content_encoding => $ctype,
2909                 -content_disposition => 'inline; filename="' . "$filename" . '"',
2910                 -status => '200 OK');
2911
2912         my $git = git_cmd_str();
2913         my $name = $project;
2914         $name =~ s/\047/\047\\\047\047/g;
2915         open my $fd, "-|",
2916         "$git archive --format=tar --prefix=\'$name\'/ $hash | $command"
2917                 or die_error(undef, "Execute git-tar-tree failed.");
2918         binmode STDOUT, ':raw';
2919         print <$fd>;
2920         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2921         close $fd;
2922
2923 }
2924
2925 sub git_log {
2926         my $head = git_get_head_hash($project);
2927         if (!defined $hash) {
2928                 $hash = $head;
2929         }
2930         if (!defined $page) {
2931                 $page = 0;
2932         }
2933         my $refs = git_get_references();
2934
2935         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2936         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
2937                 or die_error(undef, "Open git-rev-list failed");
2938         my @revlist = map { chomp; $_ } <$fd>;
2939         close $fd;
2940
2941         my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
2942
2943         git_header_html();
2944         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
2945
2946         if (!@revlist) {
2947                 my %co = parse_commit($hash);
2948
2949                 git_print_header_div('summary', $project);
2950                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
2951         }
2952         for (my $i = ($page * 100); $i <= $#revlist; $i++) {
2953                 my $commit = $revlist[$i];
2954                 my $ref = format_ref_marker($refs, $commit);
2955                 my %co = parse_commit($commit);
2956                 next if !%co;
2957                 my %ad = parse_date($co{'author_epoch'});
2958                 git_print_header_div('commit',
2959                                "<span class=\"age\">$co{'age_string'}</span>" .
2960                                esc_html($co{'title'}) . $ref,
2961                                $commit);
2962                 print "<div class=\"title_text\">\n" .
2963                       "<div class=\"log_link\">\n" .
2964                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
2965                       " | " .
2966                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
2967                       " | " .
2968                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
2969                       "<br/>\n" .
2970                       "</div>\n" .
2971                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
2972                       "</div>\n";
2973
2974                 print "<div class=\"log_body\">\n";
2975                 git_print_simplified_log($co{'comment'});
2976                 print "</div>\n";
2977         }
2978         git_footer_html();
2979 }
2980
2981 sub git_commit {
2982         my %co = parse_commit($hash);
2983         if (!%co) {
2984                 die_error(undef, "Unknown commit object");
2985         }
2986         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2987         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2988
2989         my $parent = $co{'parent'};
2990         if (!defined $parent) {
2991                 $parent = "--root";
2992         }
2993         open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $parent, $hash
2994                 or die_error(undef, "Open git-diff-tree failed");
2995         my @difftree = map { chomp; $_ } <$fd>;
2996         close $fd or die_error(undef, "Reading git-diff-tree failed");
2997
2998         # non-textual hash id's can be cached
2999         my $expires;
3000         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3001                 $expires = "+1d";
3002         }
3003         my $refs = git_get_references();
3004         my $ref = format_ref_marker($refs, $co{'id'});
3005
3006         my $have_snapshot = gitweb_have_snapshot();
3007
3008         my @views_nav = ();
3009         if (defined $file_name && defined $co{'parent'}) {
3010                 push @views_nav,
3011                         $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)},
3012                                 "blame");
3013         }
3014         git_header_html(undef, $expires);
3015         git_print_page_nav('commit', '',
3016                            $hash, $co{'tree'}, $hash,
3017                            join (' | ', @views_nav));
3018
3019         if (defined $co{'parent'}) {
3020                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
3021         } else {
3022                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
3023         }
3024         print "<div class=\"title_text\">\n" .
3025               "<table cellspacing=\"0\">\n";
3026         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
3027               "<tr>" .
3028               "<td></td><td> $ad{'rfc2822'}";
3029         if ($ad{'hour_local'} < 6) {
3030                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3031                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3032         } else {
3033                 printf(" (%02d:%02d %s)",
3034                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3035         }
3036         print "</td>" .
3037               "</tr>\n";
3038         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
3039         print "<tr><td></td><td> $cd{'rfc2822'}" .
3040               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
3041               "</td></tr>\n";
3042         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
3043         print "<tr>" .
3044               "<td>tree</td>" .
3045               "<td class=\"sha1\">" .
3046               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
3047                        class => "list"}, $co{'tree'}) .
3048               "</td>" .
3049               "<td class=\"link\">" .
3050               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
3051                       "tree");
3052         if ($have_snapshot) {
3053                 print " | " .
3054                       $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
3055         }
3056         print "</td>" .
3057               "</tr>\n";
3058         my $parents = $co{'parents'};
3059         foreach my $par (@$parents) {
3060                 print "<tr>" .
3061                       "<td>parent</td>" .
3062                       "<td class=\"sha1\">" .
3063                       $cgi->a({-href => href(action=>"commit", hash=>$par),
3064                                class => "list"}, $par) .
3065                       "</td>" .
3066                       "<td class=\"link\">" .
3067                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
3068                       " | " .
3069                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
3070                       "</td>" .
3071                       "</tr>\n";
3072         }
3073         print "</table>".
3074               "</div>\n";
3075
3076         print "<div class=\"page_body\">\n";
3077         git_print_log($co{'comment'});
3078         print "</div>\n";
3079
3080         git_difftree_body(\@difftree, $hash, $parent);
3081
3082         git_footer_html();
3083 }
3084
3085 sub git_blobdiff {
3086         my $format = shift || 'html';
3087
3088         my $fd;
3089         my @difftree;
3090         my %diffinfo;
3091         my $expires;
3092
3093         # preparing $fd and %diffinfo for git_patchset_body
3094         # new style URI
3095         if (defined $hash_base && defined $hash_parent_base) {
3096                 if (defined $file_name) {
3097                         # read raw output
3098                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base,
3099                                 "--", $file_name
3100                                 or die_error(undef, "Open git-diff-tree failed");
3101                         @difftree = map { chomp; $_ } <$fd>;
3102                         close $fd
3103                                 or die_error(undef, "Reading git-diff-tree failed");
3104                         @difftree
3105                                 or die_error('404 Not Found', "Blob diff not found");
3106
3107                 } elsif (defined $hash &&
3108                          $hash =~ /[0-9a-fA-F]{40}/) {
3109                         # try to find filename from $hash
3110
3111                         # read filtered raw output
3112                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base
3113                                 or die_error(undef, "Open git-diff-tree failed");
3114                         @difftree =
3115                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
3116                                 # $hash == to_id
3117                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
3118                                 map { chomp; $_ } <$fd>;
3119                         close $fd
3120                                 or die_error(undef, "Reading git-diff-tree failed");
3121                         @difftree
3122                                 or die_error('404 Not Found', "Blob diff not found");
3123
3124                 } else {
3125                         die_error('404 Not Found', "Missing one of the blob diff parameters");
3126                 }
3127
3128                 if (@difftree > 1) {
3129                         die_error('404 Not Found', "Ambiguous blob diff specification");
3130                 }
3131
3132                 %diffinfo = parse_difftree_raw_line($difftree[0]);
3133                 $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
3134                 $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
3135
3136                 $hash_parent ||= $diffinfo{'from_id'};
3137                 $hash        ||= $diffinfo{'to_id'};
3138
3139                 # non-textual hash id's can be cached
3140                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
3141                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
3142                         $expires = '+1d';
3143                 }
3144
3145                 # open patch output
3146                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3147                         '-p', $hash_parent_base, $hash_base,
3148                         "--", $file_name
3149                         or die_error(undef, "Open git-diff-tree failed");
3150         }
3151
3152         # old/legacy style URI
3153         if (!%diffinfo && # if new style URI failed
3154             defined $hash && defined $hash_parent) {
3155                 # fake git-diff-tree raw output
3156                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
3157                 $diffinfo{'from_id'} = $hash_parent;
3158                 $diffinfo{'to_id'}   = $hash;
3159                 if (defined $file_name) {
3160                         if (defined $file_parent) {
3161                                 $diffinfo{'status'} = '2';
3162                                 $diffinfo{'from_file'} = $file_parent;
3163                                 $diffinfo{'to_file'}   = $file_name;
3164                         } else { # assume not renamed
3165                                 $diffinfo{'status'} = '1';
3166                                 $diffinfo{'from_file'} = $file_name;
3167                                 $diffinfo{'to_file'}   = $file_name;
3168                         }
3169                 } else { # no filename given
3170                         $diffinfo{'status'} = '2';
3171                         $diffinfo{'from_file'} = $hash_parent;
3172                         $diffinfo{'to_file'}   = $hash;
3173                 }
3174
3175                 # non-textual hash id's can be cached
3176                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
3177                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3178                         $expires = '+1d';
3179                 }
3180
3181                 # open patch output
3182                 open $fd, "-|", git_cmd(), "diff", '-p', @diff_opts, $hash_parent, $hash
3183                         or die_error(undef, "Open git-diff failed");
3184         } else  {
3185                 die_error('404 Not Found', "Missing one of the blob diff parameters")
3186                         unless %diffinfo;
3187         }
3188
3189         # header
3190         if ($format eq 'html') {
3191                 my $formats_nav =
3192                         $cgi->a({-href => href(action=>"blobdiff_plain",
3193                                                hash=>$hash, hash_parent=>$hash_parent,
3194                                                hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
3195                                                file_name=>$file_name, file_parent=>$file_parent)},
3196                                 "raw");
3197                 git_header_html(undef, $expires);
3198                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3199                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3200                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3201                 } else {
3202                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
3203                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
3204                 }
3205                 if (defined $file_name) {
3206                         git_print_page_path($file_name, "blob", $hash_base);
3207                 } else {
3208                         print "<div class=\"page_path\"></div>\n";
3209                 }
3210
3211         } elsif ($format eq 'plain') {
3212                 print $cgi->header(
3213                         -type => 'text/plain',
3214                         -charset => 'utf-8',
3215                         -expires => $expires,
3216                         -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
3217
3218                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3219
3220         } else {
3221                 die_error(undef, "Unknown blobdiff format");
3222         }
3223
3224         # patch
3225         if ($format eq 'html') {
3226                 print "<div class=\"page_body\">\n";
3227
3228                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
3229                 close $fd;
3230
3231                 print "</div>\n"; # class="page_body"
3232                 git_footer_html();
3233
3234         } else {
3235                 while (my $line = <$fd>) {
3236                         $line =~ s!a/($hash|$hash_parent)!'a/'.esc_html($diffinfo{'from_file'})!eg;
3237                         $line =~ s!b/($hash|$hash_parent)!'b/'.esc_html($diffinfo{'to_file'})!eg;
3238
3239                         print $line;
3240
3241                         last if $line =~ m!^\+\+\+!;
3242                 }
3243                 local $/ = undef;
3244                 print <$fd>;
3245                 close $fd;
3246         }
3247 }
3248
3249 sub git_blobdiff_plain {
3250         git_blobdiff('plain');
3251 }
3252
3253 sub git_commitdiff {
3254         my $format = shift || 'html';
3255         my %co = parse_commit($hash);
3256         if (!%co) {
3257                 die_error(undef, "Unknown commit object");
3258         }
3259         if (!defined $hash_parent) {
3260                 $hash_parent = $co{'parent'} || '--root';
3261         }
3262
3263         # read commitdiff
3264         my $fd;
3265         my @difftree;
3266         if ($format eq 'html') {
3267                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3268                         "--patch-with-raw", "--full-index", $hash_parent, $hash
3269                         or die_error(undef, "Open git-diff-tree failed");
3270
3271                 while (chomp(my $line = <$fd>)) {
3272                         # empty line ends raw part of diff-tree output
3273                         last unless $line;
3274                         push @difftree, $line;
3275                 }
3276
3277         } elsif ($format eq 'plain') {
3278                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3279                         '-p', $hash_parent, $hash
3280                         or die_error(undef, "Open git-diff-tree failed");
3281
3282         } else {
3283                 die_error(undef, "Unknown commitdiff format");
3284         }
3285
3286         # non-textual hash id's can be cached
3287         my $expires;
3288         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3289                 $expires = "+1d";
3290         }
3291
3292         # write commit message
3293         if ($format eq 'html') {
3294                 my $refs = git_get_references();
3295                 my $ref = format_ref_marker($refs, $co{'id'});
3296                 my $formats_nav =
3297                         $cgi->a({-href => href(action=>"commitdiff_plain",
3298                                                hash=>$hash, hash_parent=>$hash_parent)},
3299                                 "raw");
3300
3301                 git_header_html(undef, $expires);
3302                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
3303                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
3304                 git_print_authorship(\%co);
3305                 print "<div class=\"page_body\">\n";
3306                 print "<div class=\"log\">\n";
3307                 git_print_simplified_log($co{'comment'}, 1); # skip title
3308                 print "</div>\n"; # class="log"
3309
3310         } elsif ($format eq 'plain') {
3311                 my $refs = git_get_references("tags");
3312                 my $tagname = git_get_rev_name_tags($hash);
3313                 my $filename = basename($project) . "-$hash.patch";
3314
3315                 print $cgi->header(
3316                         -type => 'text/plain',
3317                         -charset => 'utf-8',
3318                         -expires => $expires,
3319                         -content_disposition => 'inline; filename="' . "$filename" . '"');
3320                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3321                 print <<TEXT;
3322 From: $co{'author'}
3323 Date: $ad{'rfc2822'} ($ad{'tz_local'})
3324 Subject: $co{'title'}
3325 TEXT
3326                 print "X-Git-Tag: $tagname\n" if $tagname;
3327                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3328
3329                 foreach my $line (@{$co{'comment'}}) {
3330                         print "$line\n";
3331                 }
3332                 print "---\n\n";
3333         }
3334
3335         # write patch
3336         if ($format eq 'html') {
3337                 git_difftree_body(\@difftree, $hash, $hash_parent);
3338                 print "<br/>\n";
3339
3340                 git_patchset_body($fd, \@difftree, $hash, $hash_parent);
3341                 close $fd;
3342                 print "</div>\n"; # class="page_body"
3343                 git_footer_html();
3344
3345         } elsif ($format eq 'plain') {
3346                 local $/ = undef;
3347                 print <$fd>;
3348                 close $fd
3349                         or print "Reading git-diff-tree failed\n";
3350         }
3351 }
3352
3353 sub git_commitdiff_plain {
3354         git_commitdiff('plain');
3355 }
3356
3357 sub git_history {
3358         if (!defined $hash_base) {
3359                 $hash_base = git_get_head_hash($project);
3360         }
3361         if (!defined $page) {
3362                 $page = 0;
3363         }
3364         my $ftype;
3365         my %co = parse_commit($hash_base);
3366         if (!%co) {
3367                 die_error(undef, "Unknown commit object");
3368         }
3369
3370         my $refs = git_get_references();
3371         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3372
3373         if (!defined $hash && defined $file_name) {
3374                 $hash = git_get_hash_by_path($hash_base, $file_name);
3375         }
3376         if (defined $hash) {
3377                 $ftype = git_get_type($hash);
3378         }
3379
3380         open my $fd, "-|",
3381                 git_cmd(), "rev-list", $limit, "--full-history", $hash_base, "--", $file_name
3382                         or die_error(undef, "Open git-rev-list-failed");
3383         my @revlist = map { chomp; $_ } <$fd>;
3384         close $fd
3385                 or die_error(undef, "Reading git-rev-list failed");
3386
3387         my $paging_nav = '';
3388         if ($page > 0) {
3389                 $paging_nav .=
3390                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3391                                                file_name=>$file_name)},
3392                                 "first");
3393                 $paging_nav .= " &sdot; " .
3394                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3395                                                file_name=>$file_name, page=>$page-1),
3396                                  -accesskey => "p", -title => "Alt-p"}, "prev");
3397         } else {
3398                 $paging_nav .= "first";
3399                 $paging_nav .= " &sdot; prev";
3400         }
3401         if ($#revlist >= (100 * ($page+1)-1)) {
3402                 $paging_nav .= " &sdot; " .
3403                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3404                                                file_name=>$file_name, page=>$page+1),
3405                                  -accesskey => "n", -title => "Alt-n"}, "next");
3406         } else {
3407                 $paging_nav .= " &sdot; next";
3408         }
3409         my $next_link = '';
3410         if ($#revlist >= (100 * ($page+1)-1)) {
3411                 $next_link =
3412                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3413                                                file_name=>$file_name, page=>$page+1),
3414                                  -title => "Alt-n"}, "next");
3415         }
3416
3417         git_header_html();
3418         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
3419         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3420         git_print_page_path($file_name, $ftype, $hash_base);
3421
3422         git_history_body(\@revlist, ($page * 100), $#revlist,
3423                          $refs, $hash_base, $ftype, $next_link);
3424
3425         git_footer_html();
3426 }
3427
3428 sub git_search {
3429         if (!defined $searchtext) {
3430                 die_error(undef, "Text field empty");
3431         }
3432         if (!defined $hash) {
3433                 $hash = git_get_head_hash($project);
3434         }
3435         my %co = parse_commit($hash);
3436         if (!%co) {
3437                 die_error(undef, "Unknown commit object");
3438         }
3439
3440         my $commit_search = 1;
3441         my $author_search = 0;
3442         my $committer_search = 0;
3443         my $pickaxe_search = 0;
3444         if ($searchtext =~ s/^author\\://i) {
3445                 $author_search = 1;
3446         } elsif ($searchtext =~ s/^committer\\://i) {
3447                 $committer_search = 1;
3448         } elsif ($searchtext =~ s/^pickaxe\\://i) {
3449                 $commit_search = 0;
3450                 $pickaxe_search = 1;
3451
3452                 # pickaxe may take all resources of your box and run for several minutes
3453                 # with every query - so decide by yourself how public you make this feature
3454                 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
3455                 if (!$have_pickaxe) {
3456                         die_error('403 Permission denied', "Permission denied");
3457                 }
3458         }
3459         git_header_html();
3460         git_print_page_nav('','', $hash,$co{'tree'},$hash);
3461         git_print_header_div('commit', esc_html($co{'title'}), $hash);
3462
3463         print "<table cellspacing=\"0\">\n";
3464         my $alternate = 1;
3465         if ($commit_search) {
3466                 $/ = "\0";
3467                 open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", $hash or next;
3468                 while (my $commit_text = <$fd>) {
3469                         if (!grep m/$searchtext/i, $commit_text) {
3470                                 next;
3471                         }
3472                         if ($author_search && !grep m/\nauthor .*$searchtext/i, $commit_text) {
3473                                 next;
3474                         }
3475                         if ($committer_search && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
3476                                 next;
3477                         }
3478                         my @commit_lines = split "\n", $commit_text;
3479                         my %co = parse_commit(undef, \@commit_lines);
3480                         if (!%co) {
3481                                 next;
3482                         }
3483                         if ($alternate) {
3484                                 print "<tr class=\"dark\">\n";
3485                         } else {
3486                                 print "<tr class=\"light\">\n";
3487                         }
3488                         $alternate ^= 1;
3489                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3490                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3491                               "<td>" .
3492                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3493                                        esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3494                         my $comment = $co{'comment'};
3495                         foreach my $line (@$comment) {
3496                                 if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
3497                                         my $lead = esc_html($1) || "";
3498                                         $lead = chop_str($lead, 30, 10);
3499                                         my $match = esc_html($2) || "";
3500                                         my $trail = esc_html($3) || "";
3501                                         $trail = chop_str($trail, 30, 10);
3502                                         my $text = "$lead<span class=\"match\">$match</span>$trail";
3503                                         print chop_str($text, 80, 5) . "<br/>\n";
3504                                 }
3505                         }
3506                         print "</td>\n" .
3507                               "<td class=\"link\">" .
3508                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3509                               " | " .
3510                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3511                         print "</td>\n" .
3512                               "</tr>\n";
3513                 }
3514                 close $fd;
3515         }
3516
3517         if ($pickaxe_search) {
3518                 $/ = "\n";
3519                 my $git_command = git_cmd_str();
3520                 open my $fd, "-|", "$git_command rev-list $hash | " .
3521                         "$git_command diff-tree -r --stdin -S\'$searchtext\'";
3522                 undef %co;
3523                 my @files;
3524                 while (my $line = <$fd>) {
3525                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
3526                                 my %set;
3527                                 $set{'file'} = $6;
3528                                 $set{'from_id'} = $3;
3529                                 $set{'to_id'} = $4;
3530                                 $set{'id'} = $set{'to_id'};
3531                                 if ($set{'id'} =~ m/0{40}/) {
3532                                         $set{'id'} = $set{'from_id'};
3533                                 }
3534                                 if ($set{'id'} =~ m/0{40}/) {
3535                                         next;
3536                                 }
3537                                 push @files, \%set;
3538                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
3539                                 if (%co) {
3540                                         if ($alternate) {
3541                                                 print "<tr class=\"dark\">\n";
3542                                         } else {
3543                                                 print "<tr class=\"light\">\n";
3544                                         }
3545                                         $alternate ^= 1;
3546                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3547                                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3548                                               "<td>" .
3549                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
3550                                                       -class => "list subject"},
3551                                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3552                                         while (my $setref = shift @files) {
3553                                                 my %set = %$setref;
3554                                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
3555                                                                              hash=>$set{'id'}, file_name=>$set{'file'}),
3556                                                               -class => "list"},
3557                                                               "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
3558                                                       "<br/>\n";
3559                                         }
3560                                         print "</td>\n" .
3561                                               "<td class=\"link\">" .
3562                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3563                                               " | " .
3564                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3565                                         print "</td>\n" .
3566                                               "</tr>\n";
3567                                 }
3568                                 %co = parse_commit($1);
3569                         }
3570                 }
3571                 close $fd;
3572         }
3573         print "</table>\n";
3574         git_footer_html();
3575 }
3576
3577 sub git_shortlog {
3578         my $head = git_get_head_hash($project);
3579         if (!defined $hash) {
3580                 $hash = $head;
3581         }
3582         if (!defined $page) {
3583                 $page = 0;
3584         }
3585         my $refs = git_get_references();
3586
3587         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3588         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
3589                 or die_error(undef, "Open git-rev-list failed");
3590         my @revlist = map { chomp; $_ } <$fd>;
3591         close $fd;
3592
3593         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
3594         my $next_link = '';
3595         if ($#revlist >= (100 * ($page+1)-1)) {
3596                 $next_link =
3597                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
3598                                  -title => "Alt-n"}, "next");
3599         }
3600
3601
3602         git_header_html();
3603         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
3604         git_print_header_div('summary', $project);
3605
3606         git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
3607
3608         git_footer_html();
3609 }
3610
3611 ## ......................................................................
3612 ## feeds (RSS, OPML)
3613
3614 sub git_rss {
3615         # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
3616         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=150", git_get_head_hash($project)
3617                 or die_error(undef, "Open git-rev-list failed");
3618         my @revlist = map { chomp; $_ } <$fd>;
3619         close $fd or die_error(undef, "Reading git-rev-list failed");
3620         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3621         print <<XML;
3622 <?xml version="1.0" encoding="utf-8"?>
3623 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
3624 <channel>
3625 <title>$project $my_uri $my_url</title>
3626 <link>${\esc_html("$my_url?p=$project;a=summary")}</link>
3627 <description>$project log</description>
3628 <language>en</language>
3629 XML
3630
3631         for (my $i = 0; $i <= $#revlist; $i++) {
3632                 my $commit = $revlist[$i];
3633                 my %co = parse_commit($commit);
3634                 # we read 150, we always show 30 and the ones more recent than 48 hours
3635                 if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
3636                         last;
3637                 }
3638                 my %cd = parse_date($co{'committer_epoch'});
3639                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3640                         $co{'parent'}, $co{'id'}
3641                         or next;
3642                 my @difftree = map { chomp; $_ } <$fd>;
3643                 close $fd
3644                         or next;
3645                 print "<item>\n" .
3646                       "<title>" .
3647                       sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
3648                       "</title>\n" .
3649                       "<author>" . esc_html($co{'author'}) . "</author>\n" .
3650                       "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
3651                       "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
3652                       "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
3653                       "<description>" . esc_html($co{'title'}) . "</description>\n" .
3654                       "<content:encoded>" .
3655                       "<![CDATA[\n";
3656                 my $comment = $co{'comment'};
3657                 foreach my $line (@$comment) {
3658                         $line = to_utf8($line);
3659                         print "$line<br/>\n";
3660                 }
3661                 print "<br/>\n";
3662                 foreach my $line (@difftree) {
3663                         if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
3664                                 next;
3665                         }
3666                         my $file = esc_html(unquote($7));
3667                         $file = to_utf8($file);
3668                         print "$file<br/>\n";
3669                 }
3670                 print "]]>\n" .
3671                       "</content:encoded>\n" .
3672                       "</item>\n";
3673         }
3674         print "</channel></rss>";
3675 }
3676
3677 sub git_opml {
3678         my @list = git_get_projects_list();
3679
3680         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3681         print <<XML;
3682 <?xml version="1.0" encoding="utf-8"?>
3683 <opml version="1.0">
3684 <head>
3685   <title>$site_name Git OPML Export</title>
3686 </head>
3687 <body>
3688 <outline text="git RSS feeds">
3689 XML
3690
3691         foreach my $pr (@list) {
3692                 my %proj = %$pr;
3693                 my $head = git_get_head_hash($proj{'path'});
3694                 if (!defined $head) {
3695                         next;
3696                 }
3697                 $git_dir = "$projectroot/$proj{'path'}";
3698                 my %co = parse_commit($head);
3699                 if (!%co) {
3700                         next;
3701                 }
3702
3703                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
3704                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
3705                 my $html = "$my_url?p=$proj{'path'};a=summary";
3706                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
3707         }
3708         print <<XML;
3709 </outline>
3710 </body>
3711 </opml>
3712 XML
3713 }