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