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