gitweb: Add a few comments about %feature hash
[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 BEGIN {
22         CGI->compile() if $ENV{MOD_PERL};
23 }
24
25 our $cgi = new CGI;
26 our $version = "++GIT_VERSION++";
27 our $my_url = $cgi->url();
28 our $my_uri = $cgi->url(-absolute => 1);
29
30 # core git executable to use
31 # this can just be "git" if your webserver has a sensible PATH
32 our $GIT = "++GIT_BINDIR++/git";
33
34 # absolute fs-path which will be prepended to the project path
35 #our $projectroot = "/pub/scm";
36 our $projectroot = "++GITWEB_PROJECTROOT++";
37
38 # target of the home link on top of all pages
39 our $home_link = $my_uri || "/";
40
41 # string of the home link on top of all pages
42 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
43
44 # name of your site or organization to appear in page titles
45 # replace this with something more descriptive for clearer bookmarks
46 our $site_name = "++GITWEB_SITENAME++"
47                  || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
48
49 # filename of html text to include at top of each page
50 our $site_header = "++GITWEB_SITE_HEADER++";
51 # html text to include at home page
52 our $home_text = "++GITWEB_HOMETEXT++";
53 # filename of html text to include at bottom of each page
54 our $site_footer = "++GITWEB_SITE_FOOTER++";
55
56 # URI of stylesheets
57 our @stylesheets = ("++GITWEB_CSS++");
58 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
59 our $stylesheet = undef;
60 # URI of GIT logo (72x27 size)
61 our $logo = "++GITWEB_LOGO++";
62 # URI of GIT favicon, assumed to be image/png type
63 our $favicon = "++GITWEB_FAVICON++";
64
65 # URI and label (title) of GIT logo link
66 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
67 #our $logo_label = "git documentation";
68 our $logo_url = "http://git.or.cz/";
69 our $logo_label = "git homepage";
70
71 # source of projects list
72 our $projects_list = "++GITWEB_LIST++";
73
74 # show repository only if this file exists
75 # (only effective if this variable evaluates to true)
76 our $export_ok = "++GITWEB_EXPORT_OK++";
77
78 # only allow viewing of repositories also shown on the overview page
79 our $strict_export = "++GITWEB_STRICT_EXPORT++";
80
81 # list of git base URLs used for URL to where fetch project from,
82 # i.e. full URL is "$git_base_url/$project"
83 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
84
85 # default blob_plain mimetype and default charset for text/plain blob
86 our $default_blob_plain_mimetype = 'text/plain';
87 our $default_text_plain_charset  = undef;
88
89 # file to use for guessing MIME types before trying /etc/mime.types
90 # (relative to the current git repository)
91 our $mimetypes_file = undef;
92
93 # You define site-wide feature defaults here; override them with
94 # $GITWEB_CONFIG as necessary.
95 our %feature = (
96         # feature => {
97         #       'sub' => feature-sub (subroutine),
98         #       'override' => allow-override (boolean),
99         #       'default' => [ default options...] (array reference)}
100         #
101         # if feature is overridable (it means that allow-override has true value),
102         # then feature-sub will be called with default options as parameters;
103         # return value of feature-sub indicates if to enable specified feature
104         #
105         # if there is no 'sub' key (no feature-sub), then feature cannot be
106         # overriden
107         #
108         # use gitweb_check_feature(<feature>) to check if <feature> is enabled
109
110         # Enable the 'blame' blob view, showing the last commit that modified
111         # each line in the file. This can be very CPU-intensive.
112
113         # To enable system wide have in $GITWEB_CONFIG
114         # $feature{'blame'}{'default'} = [1];
115         # To have project specific config enable override in $GITWEB_CONFIG
116         # $feature{'blame'}{'override'} = 1;
117         # and in project config gitweb.blame = 0|1;
118         'blame' => {
119                 'sub' => \&feature_blame,
120                 'override' => 0,
121                 'default' => [0]},
122
123         # Enable the 'snapshot' link, providing a compressed tarball of any
124         # tree. This can potentially generate high traffic if you have large
125         # project.
126
127         # To disable system wide have in $GITWEB_CONFIG
128         # $feature{'snapshot'}{'default'} = [undef];
129         # To have project specific config enable override in $GITWEB_CONFIG
130         # $feature{'snapshot'}{'override'} = 1;
131         # and in project config gitweb.snapshot = none|gzip|bzip2;
132         'snapshot' => {
133                 'sub' => \&feature_snapshot,
134                 'override' => 0,
135                 #         => [content-encoding, suffix, program]
136                 'default' => ['x-gzip', 'gz', 'gzip']},
137
138         # Enable text search, which will list the commits which match author,
139         # committer or commit text to a given string.  Enabled by default.
140         # Project specific override is not supported.
141         'search' => {
142                 'override' => 0,
143                 'default' => [1]},
144
145         # Enable the pickaxe search, which will list the commits that modified
146         # a given string in a file. This can be practical and quite faster
147         # alternative to 'blame', but still potentially CPU-intensive.
148
149         # To enable system wide have in $GITWEB_CONFIG
150         # $feature{'pickaxe'}{'default'} = [1];
151         # To have project specific config enable override in $GITWEB_CONFIG
152         # $feature{'pickaxe'}{'override'} = 1;
153         # and in project config gitweb.pickaxe = 0|1;
154         'pickaxe' => {
155                 'sub' => \&feature_pickaxe,
156                 'override' => 0,
157                 'default' => [1]},
158
159         # Make gitweb use an alternative format of the URLs which can be
160         # more readable and natural-looking: project name is embedded
161         # directly in the path and the query string contains other
162         # auxiliary information. All gitweb installations recognize
163         # URL in either format; this configures in which formats gitweb
164         # generates links.
165
166         # To enable system wide have in $GITWEB_CONFIG
167         # $feature{'pathinfo'}{'default'} = [1];
168         # Project specific override is not supported.
169
170         # Note that you will need to change the default location of CSS,
171         # favicon, logo and possibly other files to an absolute URL. Also,
172         # if gitweb.cgi serves as your indexfile, you will need to force
173         # $my_uri to contain the script name in your $GITWEB_CONFIG.
174         'pathinfo' => {
175                 'override' => 0,
176                 'default' => [0]},
177
178         # Make gitweb consider projects in project root subdirectories
179         # to be forks of existing projects. Given project $projname.git,
180         # projects matching $projname/*.git will not be shown in the main
181         # projects list, instead a '+' mark will be added to $projname
182         # there and a 'forks' view will be enabled for the project, listing
183         # all the forks. This feature is supported only if project list
184         # is taken from a directory, not file.
185
186         # To enable system wide have in $GITWEB_CONFIG
187         # $feature{'forks'}{'default'} = [1];
188         # Project specific override is not supported.
189         'forks' => {
190                 'override' => 0,
191                 'default' => [0]},
192 );
193
194 sub gitweb_check_feature {
195         my ($name) = @_;
196         return unless exists $feature{$name};
197         my ($sub, $override, @defaults) = (
198                 $feature{$name}{'sub'},
199                 $feature{$name}{'override'},
200                 @{$feature{$name}{'default'}});
201         if (!$override) { return @defaults; }
202         if (!defined $sub) {
203                 warn "feature $name is not overrideable";
204                 return @defaults;
205         }
206         return $sub->(@defaults);
207 }
208
209 sub feature_blame {
210         my ($val) = git_get_project_config('blame', '--bool');
211
212         if ($val eq 'true') {
213                 return 1;
214         } elsif ($val eq 'false') {
215                 return 0;
216         }
217
218         return $_[0];
219 }
220
221 sub feature_snapshot {
222         my ($ctype, $suffix, $command) = @_;
223
224         my ($val) = git_get_project_config('snapshot');
225
226         if ($val eq 'gzip') {
227                 return ('x-gzip', 'gz', 'gzip');
228         } elsif ($val eq 'bzip2') {
229                 return ('x-bzip2', 'bz2', 'bzip2');
230         } elsif ($val eq 'none') {
231                 return ();
232         }
233
234         return ($ctype, $suffix, $command);
235 }
236
237 sub gitweb_have_snapshot {
238         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
239         my $have_snapshot = (defined $ctype && defined $suffix);
240
241         return $have_snapshot;
242 }
243
244 sub feature_pickaxe {
245         my ($val) = git_get_project_config('pickaxe', '--bool');
246
247         if ($val eq 'true') {
248                 return (1);
249         } elsif ($val eq 'false') {
250                 return (0);
251         }
252
253         return ($_[0]);
254 }
255
256 # checking HEAD file with -e is fragile if the repository was
257 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
258 # and then pruned.
259 sub check_head_link {
260         my ($dir) = @_;
261         my $headfile = "$dir/HEAD";
262         return ((-e $headfile) ||
263                 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
264 }
265
266 sub check_export_ok {
267         my ($dir) = @_;
268         return (check_head_link($dir) &&
269                 (!$export_ok || -e "$dir/$export_ok"));
270 }
271
272 # rename detection options for git-diff and git-diff-tree
273 # - default is '-M', with the cost proportional to
274 #   (number of removed files) * (number of new files).
275 # - more costly is '-C' (or '-C', '-M'), with the cost proportional to
276 #   (number of changed files + number of removed files) * (number of new files)
277 # - even more costly is '-C', '--find-copies-harder' with cost
278 #   (number of files in the original tree) * (number of new files)
279 # - one might want to include '-B' option, e.g. '-B', '-M'
280 our @diff_opts = ('-M'); # taken from git_commit
281
282 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
283 do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
284
285 # version of the core git binary
286 our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
287
288 $projects_list ||= $projectroot;
289
290 # ======================================================================
291 # input validation and dispatch
292 our $action = $cgi->param('a');
293 if (defined $action) {
294         if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
295                 die_error(undef, "Invalid action parameter");
296         }
297 }
298
299 # parameters which are pathnames
300 our $project = $cgi->param('p');
301 if (defined $project) {
302         if (!validate_pathname($project) ||
303             !(-d "$projectroot/$project") ||
304             !check_head_link("$projectroot/$project") ||
305             ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
306             ($strict_export && !project_in_list($project))) {
307                 undef $project;
308                 die_error(undef, "No such project");
309         }
310 }
311
312 our $file_name = $cgi->param('f');
313 if (defined $file_name) {
314         if (!validate_pathname($file_name)) {
315                 die_error(undef, "Invalid file parameter");
316         }
317 }
318
319 our $file_parent = $cgi->param('fp');
320 if (defined $file_parent) {
321         if (!validate_pathname($file_parent)) {
322                 die_error(undef, "Invalid file parent parameter");
323         }
324 }
325
326 # parameters which are refnames
327 our $hash = $cgi->param('h');
328 if (defined $hash) {
329         if (!validate_refname($hash)) {
330                 die_error(undef, "Invalid hash parameter");
331         }
332 }
333
334 our $hash_parent = $cgi->param('hp');
335 if (defined $hash_parent) {
336         if (!validate_refname($hash_parent)) {
337                 die_error(undef, "Invalid hash parent parameter");
338         }
339 }
340
341 our $hash_base = $cgi->param('hb');
342 if (defined $hash_base) {
343         if (!validate_refname($hash_base)) {
344                 die_error(undef, "Invalid hash base parameter");
345         }
346 }
347
348 our $hash_parent_base = $cgi->param('hpb');
349 if (defined $hash_parent_base) {
350         if (!validate_refname($hash_parent_base)) {
351                 die_error(undef, "Invalid hash parent base parameter");
352         }
353 }
354
355 # other parameters
356 our $page = $cgi->param('pg');
357 if (defined $page) {
358         if ($page =~ m/[^0-9]/) {
359                 die_error(undef, "Invalid page parameter");
360         }
361 }
362
363 our $searchtext = $cgi->param('s');
364 if (defined $searchtext) {
365         if ($searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
366                 die_error(undef, "Invalid search parameter");
367         }
368         if (length($searchtext) < 2) {
369                 die_error(undef, "At least two characters are required for search parameter");
370         }
371         $searchtext = quotemeta $searchtext;
372 }
373
374 our $searchtype = $cgi->param('st');
375 if (defined $searchtype) {
376         if ($searchtype =~ m/[^a-z]/) {
377                 die_error(undef, "Invalid searchtype parameter");
378         }
379 }
380
381 # now read PATH_INFO and use it as alternative to parameters
382 sub evaluate_path_info {
383         return if defined $project;
384         my $path_info = $ENV{"PATH_INFO"};
385         return if !$path_info;
386         $path_info =~ s,^/+,,;
387         return if !$path_info;
388         # find which part of PATH_INFO is project
389         $project = $path_info;
390         $project =~ s,/+$,,;
391         while ($project && !check_head_link("$projectroot/$project")) {
392                 $project =~ s,/*[^/]*$,,;
393         }
394         # validate project
395         $project = validate_pathname($project);
396         if (!$project ||
397             ($export_ok && !-e "$projectroot/$project/$export_ok") ||
398             ($strict_export && !project_in_list($project))) {
399                 undef $project;
400                 return;
401         }
402         # do not change any parameters if an action is given using the query string
403         return if $action;
404         $path_info =~ s,^$project/*,,;
405         my ($refname, $pathname) = split(/:/, $path_info, 2);
406         if (defined $pathname) {
407                 # we got "project.git/branch:filename" or "project.git/branch:dir/"
408                 # we could use git_get_type(branch:pathname), but it needs $git_dir
409                 $pathname =~ s,^/+,,;
410                 if (!$pathname || substr($pathname, -1) eq "/") {
411                         $action  ||= "tree";
412                         $pathname =~ s,/$,,;
413                 } else {
414                         $action  ||= "blob_plain";
415                 }
416                 $hash_base ||= validate_refname($refname);
417                 $file_name ||= validate_pathname($pathname);
418         } elsif (defined $refname) {
419                 # we got "project.git/branch"
420                 $action ||= "shortlog";
421                 $hash   ||= validate_refname($refname);
422         }
423 }
424 evaluate_path_info();
425
426 # path to the current git repository
427 our $git_dir;
428 $git_dir = "$projectroot/$project" if $project;
429
430 # dispatch
431 my %actions = (
432         "blame" => \&git_blame2,
433         "blobdiff" => \&git_blobdiff,
434         "blobdiff_plain" => \&git_blobdiff_plain,
435         "blob" => \&git_blob,
436         "blob_plain" => \&git_blob_plain,
437         "commitdiff" => \&git_commitdiff,
438         "commitdiff_plain" => \&git_commitdiff_plain,
439         "commit" => \&git_commit,
440         "forks" => \&git_forks,
441         "heads" => \&git_heads,
442         "history" => \&git_history,
443         "log" => \&git_log,
444         "rss" => \&git_rss,
445         "atom" => \&git_atom,
446         "search" => \&git_search,
447         "search_help" => \&git_search_help,
448         "shortlog" => \&git_shortlog,
449         "summary" => \&git_summary,
450         "tag" => \&git_tag,
451         "tags" => \&git_tags,
452         "tree" => \&git_tree,
453         "snapshot" => \&git_snapshot,
454         "object" => \&git_object,
455         # those below don't need $project
456         "opml" => \&git_opml,
457         "project_list" => \&git_project_list,
458         "project_index" => \&git_project_index,
459 );
460
461 if (defined $project) {
462         $action ||= 'summary';
463 } else {
464         $action ||= 'project_list';
465 }
466 if (!defined($actions{$action})) {
467         die_error(undef, "Unknown action");
468 }
469 if ($action !~ m/^(opml|project_list|project_index)$/ &&
470     !$project) {
471         die_error(undef, "Project needed");
472 }
473 $actions{$action}->();
474 exit;
475
476 ## ======================================================================
477 ## action links
478
479 sub href(%) {
480         my %params = @_;
481         # default is to use -absolute url() i.e. $my_uri
482         my $href = $params{-full} ? $my_url : $my_uri;
483
484         # XXX: Warning: If you touch this, check the search form for updating,
485         # too.
486
487         my @mapping = (
488                 project => "p",
489                 action => "a",
490                 file_name => "f",
491                 file_parent => "fp",
492                 hash => "h",
493                 hash_parent => "hp",
494                 hash_base => "hb",
495                 hash_parent_base => "hpb",
496                 page => "pg",
497                 order => "o",
498                 searchtext => "s",
499                 searchtype => "st",
500         );
501         my %mapping = @mapping;
502
503         $params{'project'} = $project unless exists $params{'project'};
504
505         my ($use_pathinfo) = gitweb_check_feature('pathinfo');
506         if ($use_pathinfo) {
507                 # use PATH_INFO for project name
508                 $href .= "/$params{'project'}" if defined $params{'project'};
509                 delete $params{'project'};
510
511                 # Summary just uses the project path URL
512                 if (defined $params{'action'} && $params{'action'} eq 'summary') {
513                         delete $params{'action'};
514                 }
515         }
516
517         # now encode the parameters explicitly
518         my @result = ();
519         for (my $i = 0; $i < @mapping; $i += 2) {
520                 my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
521                 if (defined $params{$name}) {
522                         push @result, $symbol . "=" . esc_param($params{$name});
523                 }
524         }
525         $href .= "?" . join(';', @result) if scalar @result;
526
527         return $href;
528 }
529
530
531 ## ======================================================================
532 ## validation, quoting/unquoting and escaping
533
534 sub validate_pathname {
535         my $input = shift || return undef;
536
537         # no '.' or '..' as elements of path, i.e. no '.' nor '..'
538         # at the beginning, at the end, and between slashes.
539         # also this catches doubled slashes
540         if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
541                 return undef;
542         }
543         # no null characters
544         if ($input =~ m!\0!) {
545                 return undef;
546         }
547         return $input;
548 }
549
550 sub validate_refname {
551         my $input = shift || return undef;
552
553         # textual hashes are O.K.
554         if ($input =~ m/^[0-9a-fA-F]{40}$/) {
555                 return $input;
556         }
557         # it must be correct pathname
558         $input = validate_pathname($input)
559                 or return undef;
560         # restrictions on ref name according to git-check-ref-format
561         if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
562                 return undef;
563         }
564         return $input;
565 }
566
567 # quote unsafe chars, but keep the slash, even when it's not
568 # correct, but quoted slashes look too horrible in bookmarks
569 sub esc_param {
570         my $str = shift;
571         $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
572         $str =~ s/\+/%2B/g;
573         $str =~ s/ /\+/g;
574         return $str;
575 }
576
577 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
578 sub esc_url {
579         my $str = shift;
580         $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
581         $str =~ s/\+/%2B/g;
582         $str =~ s/ /\+/g;
583         return $str;
584 }
585
586 # replace invalid utf8 character with SUBSTITUTION sequence
587 sub esc_html ($;%) {
588         my $str = shift;
589         my %opts = @_;
590
591         $str = decode_utf8($str);
592         $str = $cgi->escapeHTML($str);
593         if ($opts{'-nbsp'}) {
594                 $str =~ s/ /&nbsp;/g;
595         }
596         $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
597         return $str;
598 }
599
600 # quote control characters and escape filename to HTML
601 sub esc_path {
602         my $str = shift;
603         my %opts = @_;
604
605         $str = decode_utf8($str);
606         $str = $cgi->escapeHTML($str);
607         if ($opts{'-nbsp'}) {
608                 $str =~ s/ /&nbsp;/g;
609         }
610         $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
611         return $str;
612 }
613
614 # Make control characters "printable", using character escape codes (CEC)
615 sub quot_cec {
616         my $cntrl = shift;
617         my %es = ( # character escape codes, aka escape sequences
618                    "\t" => '\t',   # tab            (HT)
619                    "\n" => '\n',   # line feed      (LF)
620                    "\r" => '\r',   # carrige return (CR)
621                    "\f" => '\f',   # form feed      (FF)
622                    "\b" => '\b',   # backspace      (BS)
623                    "\a" => '\a',   # alarm (bell)   (BEL)
624                    "\e" => '\e',   # escape         (ESC)
625                    "\013" => '\v', # vertical tab   (VT)
626                    "\000" => '\0', # nul character  (NUL)
627                    );
628         my $chr = ( (exists $es{$cntrl})
629                     ? $es{$cntrl}
630                     : sprintf('\%03o', ord($cntrl)) );
631         return "<span class=\"cntrl\">$chr</span>";
632 }
633
634 # Alternatively use unicode control pictures codepoints,
635 # Unicode "printable representation" (PR)
636 sub quot_upr {
637         my $cntrl = shift;
638         my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
639         return "<span class=\"cntrl\">$chr</span>";
640 }
641
642 # git may return quoted and escaped filenames
643 sub unquote {
644         my $str = shift;
645
646         sub unq {
647                 my $seq = shift;
648                 my %es = ( # character escape codes, aka escape sequences
649                         't' => "\t",   # tab            (HT, TAB)
650                         'n' => "\n",   # newline        (NL)
651                         'r' => "\r",   # return         (CR)
652                         'f' => "\f",   # form feed      (FF)
653                         'b' => "\b",   # backspace      (BS)
654                         'a' => "\a",   # alarm (bell)   (BEL)
655                         'e' => "\e",   # escape         (ESC)
656                         'v' => "\013", # vertical tab   (VT)
657                 );
658
659                 if ($seq =~ m/^[0-7]{1,3}$/) {
660                         # octal char sequence
661                         return chr(oct($seq));
662                 } elsif (exists $es{$seq}) {
663                         # C escape sequence, aka character escape code
664                         return $es{$seq}
665                 }
666                 # quoted ordinary character
667                 return $seq;
668         }
669
670         if ($str =~ m/^"(.*)"$/) {
671                 # needs unquoting
672                 $str = $1;
673                 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
674         }
675         return $str;
676 }
677
678 # escape tabs (convert tabs to spaces)
679 sub untabify {
680         my $line = shift;
681
682         while ((my $pos = index($line, "\t")) != -1) {
683                 if (my $count = (8 - ($pos % 8))) {
684                         my $spaces = ' ' x $count;
685                         $line =~ s/\t/$spaces/;
686                 }
687         }
688
689         return $line;
690 }
691
692 sub project_in_list {
693         my $project = shift;
694         my @list = git_get_projects_list();
695         return @list && scalar(grep { $_->{'path'} eq $project } @list);
696 }
697
698 ## ----------------------------------------------------------------------
699 ## HTML aware string manipulation
700
701 sub chop_str {
702         my $str = shift;
703         my $len = shift;
704         my $add_len = shift || 10;
705
706         # allow only $len chars, but don't cut a word if it would fit in $add_len
707         # if it doesn't fit, cut it if it's still longer than the dots we would add
708         $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
709         my $body = $1;
710         my $tail = $2;
711         if (length($tail) > 4) {
712                 $tail = " ...";
713                 $body =~ s/&[^;]*$//; # remove chopped character entities
714         }
715         return "$body$tail";
716 }
717
718 ## ----------------------------------------------------------------------
719 ## functions returning short strings
720
721 # CSS class for given age value (in seconds)
722 sub age_class {
723         my $age = shift;
724
725         if ($age < 60*60*2) {
726                 return "age0";
727         } elsif ($age < 60*60*24*2) {
728                 return "age1";
729         } else {
730                 return "age2";
731         }
732 }
733
734 # convert age in seconds to "nn units ago" string
735 sub age_string {
736         my $age = shift;
737         my $age_str;
738
739         if ($age > 60*60*24*365*2) {
740                 $age_str = (int $age/60/60/24/365);
741                 $age_str .= " years ago";
742         } elsif ($age > 60*60*24*(365/12)*2) {
743                 $age_str = int $age/60/60/24/(365/12);
744                 $age_str .= " months ago";
745         } elsif ($age > 60*60*24*7*2) {
746                 $age_str = int $age/60/60/24/7;
747                 $age_str .= " weeks ago";
748         } elsif ($age > 60*60*24*2) {
749                 $age_str = int $age/60/60/24;
750                 $age_str .= " days ago";
751         } elsif ($age > 60*60*2) {
752                 $age_str = int $age/60/60;
753                 $age_str .= " hours ago";
754         } elsif ($age > 60*2) {
755                 $age_str = int $age/60;
756                 $age_str .= " min ago";
757         } elsif ($age > 2) {
758                 $age_str = int $age;
759                 $age_str .= " sec ago";
760         } else {
761                 $age_str .= " right now";
762         }
763         return $age_str;
764 }
765
766 # convert file mode in octal to symbolic file mode string
767 sub mode_str {
768         my $mode = oct shift;
769
770         if (S_ISDIR($mode & S_IFMT)) {
771                 return 'drwxr-xr-x';
772         } elsif (S_ISLNK($mode)) {
773                 return 'lrwxrwxrwx';
774         } elsif (S_ISREG($mode)) {
775                 # git cares only about the executable bit
776                 if ($mode & S_IXUSR) {
777                         return '-rwxr-xr-x';
778                 } else {
779                         return '-rw-r--r--';
780                 };
781         } else {
782                 return '----------';
783         }
784 }
785
786 # convert file mode in octal to file type string
787 sub file_type {
788         my $mode = shift;
789
790         if ($mode !~ m/^[0-7]+$/) {
791                 return $mode;
792         } else {
793                 $mode = oct $mode;
794         }
795
796         if (S_ISDIR($mode & S_IFMT)) {
797                 return "directory";
798         } elsif (S_ISLNK($mode)) {
799                 return "symlink";
800         } elsif (S_ISREG($mode)) {
801                 return "file";
802         } else {
803                 return "unknown";
804         }
805 }
806
807 # convert file mode in octal to file type description string
808 sub file_type_long {
809         my $mode = shift;
810
811         if ($mode !~ m/^[0-7]+$/) {
812                 return $mode;
813         } else {
814                 $mode = oct $mode;
815         }
816
817         if (S_ISDIR($mode & S_IFMT)) {
818                 return "directory";
819         } elsif (S_ISLNK($mode)) {
820                 return "symlink";
821         } elsif (S_ISREG($mode)) {
822                 if ($mode & S_IXUSR) {
823                         return "executable";
824                 } else {
825                         return "file";
826                 };
827         } else {
828                 return "unknown";
829         }
830 }
831
832
833 ## ----------------------------------------------------------------------
834 ## functions returning short HTML fragments, or transforming HTML fragments
835 ## which don't belong to other sections
836
837 # format line of commit message.
838 sub format_log_line_html {
839         my $line = shift;
840
841         $line = esc_html($line, -nbsp=>1);
842         if ($line =~ m/([0-9a-fA-F]{8,40})/) {
843                 my $hash_text = $1;
844                 my $link =
845                         $cgi->a({-href => href(action=>"object", hash=>$hash_text),
846                                 -class => "text"}, $hash_text);
847                 $line =~ s/$hash_text/$link/;
848         }
849         return $line;
850 }
851
852 # format marker of refs pointing to given object
853 sub format_ref_marker {
854         my ($refs, $id) = @_;
855         my $markers = '';
856
857         if (defined $refs->{$id}) {
858                 foreach my $ref (@{$refs->{$id}}) {
859                         my ($type, $name) = qw();
860                         # e.g. tags/v2.6.11 or heads/next
861                         if ($ref =~ m!^(.*?)s?/(.*)$!) {
862                                 $type = $1;
863                                 $name = $2;
864                         } else {
865                                 $type = "ref";
866                                 $name = $ref;
867                         }
868
869                         $markers .= " <span class=\"$type\" title=\"$ref\">" .
870                                     esc_html($name) . "</span>";
871                 }
872         }
873
874         if ($markers) {
875                 return ' <span class="refs">'. $markers . '</span>';
876         } else {
877                 return "";
878         }
879 }
880
881 # format, perhaps shortened and with markers, title line
882 sub format_subject_html {
883         my ($long, $short, $href, $extra) = @_;
884         $extra = '' unless defined($extra);
885
886         if (length($short) < length($long)) {
887                 return $cgi->a({-href => $href, -class => "list subject",
888                                 -title => decode_utf8($long)},
889                        esc_html($short) . $extra);
890         } else {
891                 return $cgi->a({-href => $href, -class => "list subject"},
892                        esc_html($long)  . $extra);
893         }
894 }
895
896 # format patch (diff) line (rather not to be used for diff headers)
897 sub format_diff_line {
898         my $line = shift;
899         my ($from, $to) = @_;
900         my $char = substr($line, 0, 1);
901         my $diff_class = "";
902
903         chomp $line;
904
905         if ($char eq '+') {
906                 $diff_class = " add";
907         } elsif ($char eq "-") {
908                 $diff_class = " rem";
909         } elsif ($char eq "@") {
910                 $diff_class = " chunk_header";
911         } elsif ($char eq "\\") {
912                 $diff_class = " incomplete";
913         }
914         $line = untabify($line);
915         if ($from && $to && $line =~ m/^\@{2} /) {
916                 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
917                         $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
918
919                 $from_lines = 0 unless defined $from_lines;
920                 $to_lines   = 0 unless defined $to_lines;
921
922                 if ($from->{'href'}) {
923                         $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
924                                              -class=>"list"}, $from_text);
925                 }
926                 if ($to->{'href'}) {
927                         $to_text   = $cgi->a({-href=>"$to->{'href'}#l$to_start",
928                                              -class=>"list"}, $to_text);
929                 }
930                 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
931                         "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
932                 return "<div class=\"diff$diff_class\">$line</div>\n";
933         }
934         return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
935 }
936
937 ## ----------------------------------------------------------------------
938 ## git utility subroutines, invoking git commands
939
940 # returns path to the core git executable and the --git-dir parameter as list
941 sub git_cmd {
942         return $GIT, '--git-dir='.$git_dir;
943 }
944
945 # returns path to the core git executable and the --git-dir parameter as string
946 sub git_cmd_str {
947         return join(' ', git_cmd());
948 }
949
950 # get HEAD ref of given project as hash
951 sub git_get_head_hash {
952         my $project = shift;
953         my $o_git_dir = $git_dir;
954         my $retval = undef;
955         $git_dir = "$projectroot/$project";
956         if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
957                 my $head = <$fd>;
958                 close $fd;
959                 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
960                         $retval = $1;
961                 }
962         }
963         if (defined $o_git_dir) {
964                 $git_dir = $o_git_dir;
965         }
966         return $retval;
967 }
968
969 # get type of given object
970 sub git_get_type {
971         my $hash = shift;
972
973         open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
974         my $type = <$fd>;
975         close $fd or return;
976         chomp $type;
977         return $type;
978 }
979
980 sub git_get_project_config {
981         my ($key, $type) = @_;
982
983         return unless ($key);
984         $key =~ s/^gitweb\.//;
985         return if ($key =~ m/\W/);
986
987         my @x = (git_cmd(), 'config');
988         if (defined $type) { push @x, $type; }
989         push @x, "--get";
990         push @x, "gitweb.$key";
991         my $val = qx(@x);
992         chomp $val;
993         return ($val);
994 }
995
996 # get hash of given path at given ref
997 sub git_get_hash_by_path {
998         my $base = shift;
999         my $path = shift || return undef;
1000         my $type = shift;
1001
1002         $path =~ s,/+$,,;
1003
1004         open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
1005                 or die_error(undef, "Open git-ls-tree failed");
1006         my $line = <$fd>;
1007         close $fd or return undef;
1008
1009         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1010         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
1011         if (defined $type && $type ne $2) {
1012                 # type doesn't match
1013                 return undef;
1014         }
1015         return $3;
1016 }
1017
1018 ## ......................................................................
1019 ## git utility functions, directly accessing git repository
1020
1021 sub git_get_project_description {
1022         my $path = shift;
1023
1024         open my $fd, "$projectroot/$path/description" or return undef;
1025         my $descr = <$fd>;
1026         close $fd;
1027         chomp $descr;
1028         return $descr;
1029 }
1030
1031 sub git_get_project_url_list {
1032         my $path = shift;
1033
1034         open my $fd, "$projectroot/$path/cloneurl" or return;
1035         my @git_project_url_list = map { chomp; $_ } <$fd>;
1036         close $fd;
1037
1038         return wantarray ? @git_project_url_list : \@git_project_url_list;
1039 }
1040
1041 sub git_get_projects_list {
1042         my ($filter) = @_;
1043         my @list;
1044
1045         $filter ||= '';
1046         $filter =~ s/\.git$//;
1047
1048         if (-d $projects_list) {
1049                 # search in directory
1050                 my $dir = $projects_list . ($filter ? "/$filter" : '');
1051                 # remove the trailing "/"
1052                 $dir =~ s!/+$!!;
1053                 my $pfxlen = length("$dir");
1054
1055                 my ($check_forks) = gitweb_check_feature('forks');
1056
1057                 File::Find::find({
1058                         follow_fast => 1, # follow symbolic links
1059                         dangling_symlinks => 0, # ignore dangling symlinks, silently
1060                         wanted => sub {
1061                                 # skip project-list toplevel, if we get it.
1062                                 return if (m!^[/.]$!);
1063                                 # only directories can be git repositories
1064                                 return unless (-d $_);
1065
1066                                 my $subdir = substr($File::Find::name, $pfxlen + 1);
1067                                 # we check related file in $projectroot
1068                                 if ($check_forks and $subdir =~ m#/.#) {
1069                                         $File::Find::prune = 1;
1070                                 } elsif (check_export_ok("$projectroot/$filter/$subdir")) {
1071                                         push @list, { path => ($filter ? "$filter/" : '') . $subdir };
1072                                         $File::Find::prune = 1;
1073                                 }
1074                         },
1075                 }, "$dir");
1076
1077         } elsif (-f $projects_list) {
1078                 # read from file(url-encoded):
1079                 # 'git%2Fgit.git Linus+Torvalds'
1080                 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1081                 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1082                 open my ($fd), $projects_list or return;
1083                 while (my $line = <$fd>) {
1084                         chomp $line;
1085                         my ($path, $owner) = split ' ', $line;
1086                         $path = unescape($path);
1087                         $owner = unescape($owner);
1088                         if (!defined $path) {
1089                                 next;
1090                         }
1091                         if ($filter ne '') {
1092                                 # looking for forks;
1093                                 my $pfx = substr($path, 0, length($filter));
1094                                 if ($pfx ne $filter) {
1095                                         next;
1096                                 }
1097                                 my $sfx = substr($path, length($filter));
1098                                 if ($sfx !~ /^\/.*\.git$/) {
1099                                         next;
1100                                 }
1101                         }
1102                         if (check_export_ok("$projectroot/$path")) {
1103                                 my $pr = {
1104                                         path => $path,
1105                                         owner => decode_utf8($owner),
1106                                 };
1107                                 push @list, $pr
1108                         }
1109                 }
1110                 close $fd;
1111         }
1112         @list = sort {$a->{'path'} cmp $b->{'path'}} @list;
1113         return @list;
1114 }
1115
1116 sub git_get_project_owner {
1117         my $project = shift;
1118         my $owner;
1119
1120         return undef unless $project;
1121
1122         # read from file (url-encoded):
1123         # 'git%2Fgit.git Linus+Torvalds'
1124         # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1125         # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1126         if (-f $projects_list) {
1127                 open (my $fd , $projects_list);
1128                 while (my $line = <$fd>) {
1129                         chomp $line;
1130                         my ($pr, $ow) = split ' ', $line;
1131                         $pr = unescape($pr);
1132                         $ow = unescape($ow);
1133                         if ($pr eq $project) {
1134                                 $owner = decode_utf8($ow);
1135                                 last;
1136                         }
1137                 }
1138                 close $fd;
1139         }
1140         if (!defined $owner) {
1141                 $owner = get_file_owner("$projectroot/$project");
1142         }
1143
1144         return $owner;
1145 }
1146
1147 sub git_get_last_activity {
1148         my ($path) = @_;
1149         my $fd;
1150
1151         $git_dir = "$projectroot/$path";
1152         open($fd, "-|", git_cmd(), 'for-each-ref',
1153              '--format=%(committer)',
1154              '--sort=-committerdate',
1155              '--count=1',
1156              'refs/heads') or return;
1157         my $most_recent = <$fd>;
1158         close $fd or return;
1159         if ($most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
1160                 my $timestamp = $1;
1161                 my $age = time - $timestamp;
1162                 return ($age, age_string($age));
1163         }
1164 }
1165
1166 sub git_get_references {
1167         my $type = shift || "";
1168         my %refs;
1169         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
1170         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
1171         open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
1172                 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
1173                 or return;
1174
1175         while (my $line = <$fd>) {
1176                 chomp $line;
1177                 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type/?[^^]+)!) {
1178                         if (defined $refs{$1}) {
1179                                 push @{$refs{$1}}, $2;
1180                         } else {
1181                                 $refs{$1} = [ $2 ];
1182                         }
1183                 }
1184         }
1185         close $fd or return;
1186         return \%refs;
1187 }
1188
1189 sub git_get_rev_name_tags {
1190         my $hash = shift || return undef;
1191
1192         open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
1193                 or return;
1194         my $name_rev = <$fd>;
1195         close $fd;
1196
1197         if ($name_rev =~ m|^$hash tags/(.*)$|) {
1198                 return $1;
1199         } else {
1200                 # catches also '$hash undefined' output
1201                 return undef;
1202         }
1203 }
1204
1205 ## ----------------------------------------------------------------------
1206 ## parse to hash functions
1207
1208 sub parse_date {
1209         my $epoch = shift;
1210         my $tz = shift || "-0000";
1211
1212         my %date;
1213         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
1214         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
1215         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
1216         $date{'hour'} = $hour;
1217         $date{'minute'} = $min;
1218         $date{'mday'} = $mday;
1219         $date{'day'} = $days[$wday];
1220         $date{'month'} = $months[$mon];
1221         $date{'rfc2822'}   = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
1222                              $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
1223         $date{'mday-time'} = sprintf "%d %s %02d:%02d",
1224                              $mday, $months[$mon], $hour ,$min;
1225         $date{'iso-8601'}  = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
1226                              1900+$year, $mon, $mday, $hour ,$min, $sec;
1227
1228         $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
1229         my $local = $epoch + ((int $1 + ($2/60)) * 3600);
1230         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
1231         $date{'hour_local'} = $hour;
1232         $date{'minute_local'} = $min;
1233         $date{'tz_local'} = $tz;
1234         $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
1235                                   1900+$year, $mon+1, $mday,
1236                                   $hour, $min, $sec, $tz);
1237         return %date;
1238 }
1239
1240 sub parse_tag {
1241         my $tag_id = shift;
1242         my %tag;
1243         my @comment;
1244
1245         open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
1246         $tag{'id'} = $tag_id;
1247         while (my $line = <$fd>) {
1248                 chomp $line;
1249                 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
1250                         $tag{'object'} = $1;
1251                 } elsif ($line =~ m/^type (.+)$/) {
1252                         $tag{'type'} = $1;
1253                 } elsif ($line =~ m/^tag (.+)$/) {
1254                         $tag{'name'} = $1;
1255                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
1256                         $tag{'author'} = $1;
1257                         $tag{'epoch'} = $2;
1258                         $tag{'tz'} = $3;
1259                 } elsif ($line =~ m/--BEGIN/) {
1260                         push @comment, $line;
1261                         last;
1262                 } elsif ($line eq "") {
1263                         last;
1264                 }
1265         }
1266         push @comment, <$fd>;
1267         $tag{'comment'} = \@comment;
1268         close $fd or return;
1269         if (!defined $tag{'name'}) {
1270                 return
1271         };
1272         return %tag
1273 }
1274
1275 sub parse_commit_text {
1276         my ($commit_text, $withparents) = @_;
1277         my @commit_lines = split '\n', $commit_text;
1278         my %co;
1279
1280         pop @commit_lines; # Remove '\0'
1281
1282         my $header = shift @commit_lines;
1283         if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
1284                 return;
1285         }
1286         ($co{'id'}, my @parents) = split ' ', $header;
1287         while (my $line = shift @commit_lines) {
1288                 last if $line eq "\n";
1289                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1290                         $co{'tree'} = $1;
1291                 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
1292                         push @parents, $1;
1293                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1294                         $co{'author'} = $1;
1295                         $co{'author_epoch'} = $2;
1296                         $co{'author_tz'} = $3;
1297                         if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
1298                                 $co{'author_name'}  = $1;
1299                                 $co{'author_email'} = $2;
1300                         } else {
1301                                 $co{'author_name'} = $co{'author'};
1302                         }
1303                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1304                         $co{'committer'} = $1;
1305                         $co{'committer_epoch'} = $2;
1306                         $co{'committer_tz'} = $3;
1307                         $co{'committer_name'} = $co{'committer'};
1308                         if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
1309                                 $co{'committer_name'}  = $1;
1310                                 $co{'committer_email'} = $2;
1311                         } else {
1312                                 $co{'committer_name'} = $co{'committer'};
1313                         }
1314                 }
1315         }
1316         if (!defined $co{'tree'}) {
1317                 return;
1318         };
1319         $co{'parents'} = \@parents;
1320         $co{'parent'} = $parents[0];
1321
1322         foreach my $title (@commit_lines) {
1323                 $title =~ s/^    //;
1324                 if ($title ne "") {
1325                         $co{'title'} = chop_str($title, 80, 5);
1326                         # remove leading stuff of merges to make the interesting part visible
1327                         if (length($title) > 50) {
1328                                 $title =~ s/^Automatic //;
1329                                 $title =~ s/^merge (of|with) /Merge ... /i;
1330                                 if (length($title) > 50) {
1331                                         $title =~ s/(http|rsync):\/\///;
1332                                 }
1333                                 if (length($title) > 50) {
1334                                         $title =~ s/(master|www|rsync)\.//;
1335                                 }
1336                                 if (length($title) > 50) {
1337                                         $title =~ s/kernel.org:?//;
1338                                 }
1339                                 if (length($title) > 50) {
1340                                         $title =~ s/\/pub\/scm//;
1341                                 }
1342                         }
1343                         $co{'title_short'} = chop_str($title, 50, 5);
1344                         last;
1345                 }
1346         }
1347         if ($co{'title'} eq "") {
1348                 $co{'title'} = $co{'title_short'} = '(no commit message)';
1349         }
1350         # remove added spaces
1351         foreach my $line (@commit_lines) {
1352                 $line =~ s/^    //;
1353         }
1354         $co{'comment'} = \@commit_lines;
1355
1356         my $age = time - $co{'committer_epoch'};
1357         $co{'age'} = $age;
1358         $co{'age_string'} = age_string($age);
1359         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1360         if ($age > 60*60*24*7*2) {
1361                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1362                 $co{'age_string_age'} = $co{'age_string'};
1363         } else {
1364                 $co{'age_string_date'} = $co{'age_string'};
1365                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1366         }
1367         return %co;
1368 }
1369
1370 sub parse_commit {
1371         my ($commit_id) = @_;
1372         my %co;
1373
1374         local $/ = "\0";
1375
1376         open my $fd, "-|", git_cmd(), "rev-list",
1377                 "--parents",
1378                 "--header",
1379                 "--max-count=1",
1380                 $commit_id,
1381                 "--",
1382                 or die_error(undef, "Open git-rev-list failed");
1383         %co = parse_commit_text(<$fd>, 1);
1384         close $fd;
1385
1386         return %co;
1387 }
1388
1389 sub parse_commits {
1390         my ($commit_id, $maxcount, $skip, $arg, $filename) = @_;
1391         my @cos;
1392
1393         $maxcount ||= 1;
1394         $skip ||= 0;
1395
1396         local $/ = "\0";
1397
1398         open my $fd, "-|", git_cmd(), "rev-list",
1399                 "--header",
1400                 ($arg ? ($arg) : ()),
1401                 ("--max-count=" . $maxcount),
1402                 ("--skip=" . $skip),
1403                 $commit_id,
1404                 "--",
1405                 ($filename ? ($filename) : ())
1406                 or die_error(undef, "Open git-rev-list failed");
1407         while (my $line = <$fd>) {
1408                 my %co = parse_commit_text($line);
1409                 push @cos, \%co;
1410         }
1411         close $fd;
1412
1413         return wantarray ? @cos : \@cos;
1414 }
1415
1416 # parse ref from ref_file, given by ref_id, with given type
1417 sub parse_ref {
1418         my $ref_file = shift;
1419         my $ref_id = shift;
1420         my $type = shift || git_get_type($ref_id);
1421         my %ref_item;
1422
1423         $ref_item{'type'} = $type;
1424         $ref_item{'id'} = $ref_id;
1425         $ref_item{'epoch'} = 0;
1426         $ref_item{'age'} = "unknown";
1427         if ($type eq "tag") {
1428                 my %tag = parse_tag($ref_id);
1429                 $ref_item{'comment'} = $tag{'comment'};
1430                 if ($tag{'type'} eq "commit") {
1431                         my %co = parse_commit($tag{'object'});
1432                         $ref_item{'epoch'} = $co{'committer_epoch'};
1433                         $ref_item{'age'} = $co{'age_string'};
1434                 } elsif (defined($tag{'epoch'})) {
1435                         my $age = time - $tag{'epoch'};
1436                         $ref_item{'epoch'} = $tag{'epoch'};
1437                         $ref_item{'age'} = age_string($age);
1438                 }
1439                 $ref_item{'reftype'} = $tag{'type'};
1440                 $ref_item{'name'} = $tag{'name'};
1441                 $ref_item{'refid'} = $tag{'object'};
1442         } elsif ($type eq "commit"){
1443                 my %co = parse_commit($ref_id);
1444                 $ref_item{'reftype'} = "commit";
1445                 $ref_item{'name'} = $ref_file;
1446                 $ref_item{'title'} = $co{'title'};
1447                 $ref_item{'refid'} = $ref_id;
1448                 $ref_item{'epoch'} = $co{'committer_epoch'};
1449                 $ref_item{'age'} = $co{'age_string'};
1450         } else {
1451                 $ref_item{'reftype'} = $type;
1452                 $ref_item{'name'} = $ref_file;
1453                 $ref_item{'refid'} = $ref_id;
1454         }
1455
1456         return %ref_item;
1457 }
1458
1459 # parse line of git-diff-tree "raw" output
1460 sub parse_difftree_raw_line {
1461         my $line = shift;
1462         my %res;
1463
1464         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1465         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1466         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1467                 $res{'from_mode'} = $1;
1468                 $res{'to_mode'} = $2;
1469                 $res{'from_id'} = $3;
1470                 $res{'to_id'} = $4;
1471                 $res{'status'} = $5;
1472                 $res{'similarity'} = $6;
1473                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1474                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1475                 } else {
1476                         $res{'file'} = unquote($7);
1477                 }
1478         }
1479         # 'c512b523472485aef4fff9e57b229d9d243c967f'
1480         elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1481                 $res{'commit'} = $1;
1482         }
1483
1484         return wantarray ? %res : \%res;
1485 }
1486
1487 # parse line of git-ls-tree output
1488 sub parse_ls_tree_line ($;%) {
1489         my $line = shift;
1490         my %opts = @_;
1491         my %res;
1492
1493         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1494         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
1495
1496         $res{'mode'} = $1;
1497         $res{'type'} = $2;
1498         $res{'hash'} = $3;
1499         if ($opts{'-z'}) {
1500                 $res{'name'} = $4;
1501         } else {
1502                 $res{'name'} = unquote($4);
1503         }
1504
1505         return wantarray ? %res : \%res;
1506 }
1507
1508 ## ......................................................................
1509 ## parse to array of hashes functions
1510
1511 sub git_get_heads_list {
1512         my $limit = shift;
1513         my @headslist;
1514
1515         open my $fd, '-|', git_cmd(), 'for-each-ref',
1516                 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
1517                 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
1518                 'refs/heads'
1519                 or return;
1520         while (my $line = <$fd>) {
1521                 my %ref_item;
1522
1523                 chomp $line;
1524                 my ($refinfo, $committerinfo) = split(/\0/, $line);
1525                 my ($hash, $name, $title) = split(' ', $refinfo, 3);
1526                 my ($committer, $epoch, $tz) =
1527                         ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
1528                 $name =~ s!^refs/heads/!!;
1529
1530                 $ref_item{'name'}  = $name;
1531                 $ref_item{'id'}    = $hash;
1532                 $ref_item{'title'} = $title || '(no commit message)';
1533                 $ref_item{'epoch'} = $epoch;
1534                 if ($epoch) {
1535                         $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
1536                 } else {
1537                         $ref_item{'age'} = "unknown";
1538                 }
1539
1540                 push @headslist, \%ref_item;
1541         }
1542         close $fd;
1543
1544         return wantarray ? @headslist : \@headslist;
1545 }
1546
1547 sub git_get_tags_list {
1548         my $limit = shift;
1549         my @tagslist;
1550
1551         open my $fd, '-|', git_cmd(), 'for-each-ref',
1552                 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
1553                 '--format=%(objectname) %(objecttype) %(refname) '.
1554                 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
1555                 'refs/tags'
1556                 or return;
1557         while (my $line = <$fd>) {
1558                 my %ref_item;
1559
1560                 chomp $line;
1561                 my ($refinfo, $creatorinfo) = split(/\0/, $line);
1562                 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
1563                 my ($creator, $epoch, $tz) =
1564                         ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
1565                 $name =~ s!^refs/tags/!!;
1566
1567                 $ref_item{'type'} = $type;
1568                 $ref_item{'id'} = $id;
1569                 $ref_item{'name'} = $name;
1570                 if ($type eq "tag") {
1571                         $ref_item{'subject'} = $title;
1572                         $ref_item{'reftype'} = $reftype;
1573                         $ref_item{'refid'}   = $refid;
1574                 } else {
1575                         $ref_item{'reftype'} = $type;
1576                         $ref_item{'refid'}   = $id;
1577                 }
1578
1579                 if ($type eq "tag" || $type eq "commit") {
1580                         $ref_item{'epoch'} = $epoch;
1581                         if ($epoch) {
1582                                 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
1583                         } else {
1584                                 $ref_item{'age'} = "unknown";
1585                         }
1586                 }
1587
1588                 push @tagslist, \%ref_item;
1589         }
1590         close $fd;
1591
1592         return wantarray ? @tagslist : \@tagslist;
1593 }
1594
1595 ## ----------------------------------------------------------------------
1596 ## filesystem-related functions
1597
1598 sub get_file_owner {
1599         my $path = shift;
1600
1601         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1602         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1603         if (!defined $gcos) {
1604                 return undef;
1605         }
1606         my $owner = $gcos;
1607         $owner =~ s/[,;].*$//;
1608         return decode_utf8($owner);
1609 }
1610
1611 ## ......................................................................
1612 ## mimetype related functions
1613
1614 sub mimetype_guess_file {
1615         my $filename = shift;
1616         my $mimemap = shift;
1617         -r $mimemap or return undef;
1618
1619         my %mimemap;
1620         open(MIME, $mimemap) or return undef;
1621         while (<MIME>) {
1622                 next if m/^#/; # skip comments
1623                 my ($mime, $exts) = split(/\t+/);
1624                 if (defined $exts) {
1625                         my @exts = split(/\s+/, $exts);
1626                         foreach my $ext (@exts) {
1627                                 $mimemap{$ext} = $mime;
1628                         }
1629                 }
1630         }
1631         close(MIME);
1632
1633         $filename =~ /\.([^.]*)$/;
1634         return $mimemap{$1};
1635 }
1636
1637 sub mimetype_guess {
1638         my $filename = shift;
1639         my $mime;
1640         $filename =~ /\./ or return undef;
1641
1642         if ($mimetypes_file) {
1643                 my $file = $mimetypes_file;
1644                 if ($file !~ m!^/!) { # if it is relative path
1645                         # it is relative to project
1646                         $file = "$projectroot/$project/$file";
1647                 }
1648                 $mime = mimetype_guess_file($filename, $file);
1649         }
1650         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1651         return $mime;
1652 }
1653
1654 sub blob_mimetype {
1655         my $fd = shift;
1656         my $filename = shift;
1657
1658         if ($filename) {
1659                 my $mime = mimetype_guess($filename);
1660                 $mime and return $mime;
1661         }
1662
1663         # just in case
1664         return $default_blob_plain_mimetype unless $fd;
1665
1666         if (-T $fd) {
1667                 return 'text/plain' .
1668                        ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1669         } elsif (! $filename) {
1670                 return 'application/octet-stream';
1671         } elsif ($filename =~ m/\.png$/i) {
1672                 return 'image/png';
1673         } elsif ($filename =~ m/\.gif$/i) {
1674                 return 'image/gif';
1675         } elsif ($filename =~ m/\.jpe?g$/i) {
1676                 return 'image/jpeg';
1677         } else {
1678                 return 'application/octet-stream';
1679         }
1680 }
1681
1682 ## ======================================================================
1683 ## functions printing HTML: header, footer, error page
1684
1685 sub git_header_html {
1686         my $status = shift || "200 OK";
1687         my $expires = shift;
1688
1689         my $title = "$site_name";
1690         if (defined $project) {
1691                 $title .= " - " . decode_utf8($project);
1692                 if (defined $action) {
1693                         $title .= "/$action";
1694                         if (defined $file_name) {
1695                                 $title .= " - " . esc_path($file_name);
1696                                 if ($action eq "tree" && $file_name !~ m|/$|) {
1697                                         $title .= "/";
1698                                 }
1699                         }
1700                 }
1701         }
1702         my $content_type;
1703         # require explicit support from the UA if we are to send the page as
1704         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1705         # we have to do this because MSIE sometimes globs '*/*', pretending to
1706         # support xhtml+xml but choking when it gets what it asked for.
1707         if (defined $cgi->http('HTTP_ACCEPT') &&
1708             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1709             $cgi->Accept('application/xhtml+xml') != 0) {
1710                 $content_type = 'application/xhtml+xml';
1711         } else {
1712                 $content_type = 'text/html';
1713         }
1714         print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1715                            -status=> $status, -expires => $expires);
1716         my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
1717         print <<EOF;
1718 <?xml version="1.0" encoding="utf-8"?>
1719 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1720 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1721 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1722 <!-- git core binaries version $git_version -->
1723 <head>
1724 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1725 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
1726 <meta name="robots" content="index, nofollow"/>
1727 <title>$title</title>
1728 EOF
1729 # print out each stylesheet that exist
1730         if (defined $stylesheet) {
1731 #provides backwards capability for those people who define style sheet in a config file
1732                 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
1733         } else {
1734                 foreach my $stylesheet (@stylesheets) {
1735                         next unless $stylesheet;
1736                         print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
1737                 }
1738         }
1739         if (defined $project) {
1740                 printf('<link rel="alternate" title="%s log RSS feed" '.
1741                        'href="%s" type="application/rss+xml" />'."\n",
1742                        esc_param($project), href(action=>"rss"));
1743                 printf('<link rel="alternate" title="%s log Atom feed" '.
1744                        'href="%s" type="application/atom+xml" />'."\n",
1745                        esc_param($project), href(action=>"atom"));
1746         } else {
1747                 printf('<link rel="alternate" title="%s projects list" '.
1748                        'href="%s" type="text/plain; charset=utf-8"/>'."\n",
1749                        $site_name, href(project=>undef, action=>"project_index"));
1750                 printf('<link rel="alternate" title="%s projects feeds" '.
1751                        'href="%s" type="text/x-opml"/>'."\n",
1752                        $site_name, href(project=>undef, action=>"opml"));
1753         }
1754         if (defined $favicon) {
1755                 print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
1756         }
1757
1758         print "</head>\n" .
1759               "<body>\n";
1760
1761         if (-f $site_header) {
1762                 open (my $fd, $site_header);
1763                 print <$fd>;
1764                 close $fd;
1765         }
1766
1767         print "<div class=\"page_header\">\n" .
1768               $cgi->a({-href => esc_url($logo_url),
1769                        -title => $logo_label},
1770                       qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
1771         print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
1772         if (defined $project) {
1773                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1774                 if (defined $action) {
1775                         print " / $action";
1776                 }
1777                 print "\n";
1778         }
1779         my ($have_search) = gitweb_check_feature('search');
1780         if ((defined $project) && ($have_search)) {
1781                 if (!defined $searchtext) {
1782                         $searchtext = "";
1783                 }
1784                 my $search_hash;
1785                 if (defined $hash_base) {
1786                         $search_hash = $hash_base;
1787                 } elsif (defined $hash) {
1788                         $search_hash = $hash;
1789                 } else {
1790                         $search_hash = "HEAD";
1791                 }
1792                 $cgi->param("a", "search");
1793                 $cgi->param("h", $search_hash);
1794                 $cgi->param("p", $project);
1795                 print $cgi->startform(-method => "get", -action => $my_uri) .
1796                       "<div class=\"search\">\n" .
1797                       $cgi->hidden(-name => "p") . "\n" .
1798                       $cgi->hidden(-name => "a") . "\n" .
1799                       $cgi->hidden(-name => "h") . "\n" .
1800                       $cgi->popup_menu(-name => 'st', -default => 'commit',
1801                                        -values => ['commit', 'author', 'committer', 'pickaxe']) .
1802                       $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
1803                       " search:\n",
1804                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1805                       "</div>" .
1806                       $cgi->end_form() . "\n";
1807         }
1808         print "</div>\n";
1809 }
1810
1811 sub git_footer_html {
1812         print "<div class=\"page_footer\">\n";
1813         if (defined $project) {
1814                 my $descr = git_get_project_description($project);
1815                 if (defined $descr) {
1816                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1817                 }
1818                 print $cgi->a({-href => href(action=>"rss"),
1819                               -class => "rss_logo"}, "RSS") . " ";
1820                 print $cgi->a({-href => href(action=>"atom"),
1821                               -class => "rss_logo"}, "Atom") . "\n";
1822         } else {
1823                 print $cgi->a({-href => href(project=>undef, action=>"opml"),
1824                               -class => "rss_logo"}, "OPML") . " ";
1825                 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
1826                               -class => "rss_logo"}, "TXT") . "\n";
1827         }
1828         print "</div>\n" ;
1829
1830         if (-f $site_footer) {
1831                 open (my $fd, $site_footer);
1832                 print <$fd>;
1833                 close $fd;
1834         }
1835
1836         print "</body>\n" .
1837               "</html>";
1838 }
1839
1840 sub die_error {
1841         my $status = shift || "403 Forbidden";
1842         my $error = shift || "Malformed query, file missing or permission denied";
1843
1844         git_header_html($status);
1845         print <<EOF;
1846 <div class="page_body">
1847 <br /><br />
1848 $status - $error
1849 <br />
1850 </div>
1851 EOF
1852         git_footer_html();
1853         exit;
1854 }
1855
1856 ## ----------------------------------------------------------------------
1857 ## functions printing or outputting HTML: navigation
1858
1859 sub git_print_page_nav {
1860         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1861         $extra = '' if !defined $extra; # pager or formats
1862
1863         my @navs = qw(summary shortlog log commit commitdiff tree);
1864         if ($suppress) {
1865                 @navs = grep { $_ ne $suppress } @navs;
1866         }
1867
1868         my %arg = map { $_ => {action=>$_} } @navs;
1869         if (defined $head) {
1870                 for (qw(commit commitdiff)) {
1871                         $arg{$_}{hash} = $head;
1872                 }
1873                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1874                         for (qw(shortlog log)) {
1875                                 $arg{$_}{hash} = $head;
1876                         }
1877                 }
1878         }
1879         $arg{tree}{hash} = $treehead if defined $treehead;
1880         $arg{tree}{hash_base} = $treebase if defined $treebase;
1881
1882         print "<div class=\"page_nav\">\n" .
1883                 (join " | ",
1884                  map { $_ eq $current ?
1885                        $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1886                  } @navs);
1887         print "<br/>\n$extra<br/>\n" .
1888               "</div>\n";
1889 }
1890
1891 sub format_paging_nav {
1892         my ($action, $hash, $head, $page, $nrevs) = @_;
1893         my $paging_nav;
1894
1895
1896         if ($hash ne $head || $page) {
1897                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1898         } else {
1899                 $paging_nav .= "HEAD";
1900         }
1901
1902         if ($page > 0) {
1903                 $paging_nav .= " &sdot; " .
1904                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1905                                  -accesskey => "p", -title => "Alt-p"}, "prev");
1906         } else {
1907                 $paging_nav .= " &sdot; prev";
1908         }
1909
1910         if ($nrevs >= (100 * ($page+1)-1)) {
1911                 $paging_nav .= " &sdot; " .
1912                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1913                                  -accesskey => "n", -title => "Alt-n"}, "next");
1914         } else {
1915                 $paging_nav .= " &sdot; next";
1916         }
1917
1918         return $paging_nav;
1919 }
1920
1921 ## ......................................................................
1922 ## functions printing or outputting HTML: div
1923
1924 sub git_print_header_div {
1925         my ($action, $title, $hash, $hash_base) = @_;
1926         my %args = ();
1927
1928         $args{action} = $action;
1929         $args{hash} = $hash if $hash;
1930         $args{hash_base} = $hash_base if $hash_base;
1931
1932         print "<div class=\"header\">\n" .
1933               $cgi->a({-href => href(%args), -class => "title"},
1934               $title ? $title : $action) .
1935               "\n</div>\n";
1936 }
1937
1938 #sub git_print_authorship (\%) {
1939 sub git_print_authorship {
1940         my $co = shift;
1941
1942         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
1943         print "<div class=\"author_date\">" .
1944               esc_html($co->{'author_name'}) .
1945               " [$ad{'rfc2822'}";
1946         if ($ad{'hour_local'} < 6) {
1947                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
1948                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1949         } else {
1950                 printf(" (%02d:%02d %s)",
1951                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1952         }
1953         print "]</div>\n";
1954 }
1955
1956 sub git_print_page_path {
1957         my $name = shift;
1958         my $type = shift;
1959         my $hb = shift;
1960
1961
1962         print "<div class=\"page_path\">";
1963         print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
1964                       -title => 'tree root'}, decode_utf8("[$project]"));
1965         print " / ";
1966         if (defined $name) {
1967                 my @dirname = split '/', $name;
1968                 my $basename = pop @dirname;
1969                 my $fullname = '';
1970
1971                 foreach my $dir (@dirname) {
1972                         $fullname .= ($fullname ? '/' : '') . $dir;
1973                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
1974                                                      hash_base=>$hb),
1975                                       -title => $fullname}, esc_path($dir));
1976                         print " / ";
1977                 }
1978                 if (defined $type && $type eq 'blob') {
1979                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
1980                                                      hash_base=>$hb),
1981                                       -title => $name}, esc_path($basename));
1982                 } elsif (defined $type && $type eq 'tree') {
1983                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
1984                                                      hash_base=>$hb),
1985                                       -title => $name}, esc_path($basename));
1986                         print " / ";
1987                 } else {
1988                         print esc_path($basename);
1989                 }
1990         }
1991         print "<br/></div>\n";
1992 }
1993
1994 # sub git_print_log (\@;%) {
1995 sub git_print_log ($;%) {
1996         my $log = shift;
1997         my %opts = @_;
1998
1999         if ($opts{'-remove_title'}) {
2000                 # remove title, i.e. first line of log
2001                 shift @$log;
2002         }
2003         # remove leading empty lines
2004         while (defined $log->[0] && $log->[0] eq "") {
2005                 shift @$log;
2006         }
2007
2008         # print log
2009         my $signoff = 0;
2010         my $empty = 0;
2011         foreach my $line (@$log) {
2012                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
2013                         $signoff = 1;
2014                         $empty = 0;
2015                         if (! $opts{'-remove_signoff'}) {
2016                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
2017                                 next;
2018                         } else {
2019                                 # remove signoff lines
2020                                 next;
2021                         }
2022                 } else {
2023                         $signoff = 0;
2024                 }
2025
2026                 # print only one empty line
2027                 # do not print empty line after signoff
2028                 if ($line eq "") {
2029                         next if ($empty || $signoff);
2030                         $empty = 1;
2031                 } else {
2032                         $empty = 0;
2033                 }
2034
2035                 print format_log_line_html($line) . "<br/>\n";
2036         }
2037
2038         if ($opts{'-final_empty_line'}) {
2039                 # end with single empty line
2040                 print "<br/>\n" unless $empty;
2041         }
2042 }
2043
2044 # return link target (what link points to)
2045 sub git_get_link_target {
2046         my $hash = shift;
2047         my $link_target;
2048
2049         # read link
2050         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2051                 or return;
2052         {
2053                 local $/;
2054                 $link_target = <$fd>;
2055         }
2056         close $fd
2057                 or return;
2058
2059         return $link_target;
2060 }
2061
2062 # given link target, and the directory (basedir) the link is in,
2063 # return target of link relative to top directory (top tree);
2064 # return undef if it is not possible (including absolute links).
2065 sub normalize_link_target {
2066         my ($link_target, $basedir, $hash_base) = @_;
2067
2068         # we can normalize symlink target only if $hash_base is provided
2069         return unless $hash_base;
2070
2071         # absolute symlinks (beginning with '/') cannot be normalized
2072         return if (substr($link_target, 0, 1) eq '/');
2073
2074         # normalize link target to path from top (root) tree (dir)
2075         my $path;
2076         if ($basedir) {
2077                 $path = $basedir . '/' . $link_target;
2078         } else {
2079                 # we are in top (root) tree (dir)
2080                 $path = $link_target;
2081         }
2082
2083         # remove //, /./, and /../
2084         my @path_parts;
2085         foreach my $part (split('/', $path)) {
2086                 # discard '.' and ''
2087                 next if (!$part || $part eq '.');
2088                 # handle '..'
2089                 if ($part eq '..') {
2090                         if (@path_parts) {
2091                                 pop @path_parts;
2092                         } else {
2093                                 # link leads outside repository (outside top dir)
2094                                 return;
2095                         }
2096                 } else {
2097                         push @path_parts, $part;
2098                 }
2099         }
2100         $path = join('/', @path_parts);
2101
2102         return $path;
2103 }
2104
2105 # print tree entry (row of git_tree), but without encompassing <tr> element
2106 sub git_print_tree_entry {
2107         my ($t, $basedir, $hash_base, $have_blame) = @_;
2108
2109         my %base_key = ();
2110         $base_key{'hash_base'} = $hash_base if defined $hash_base;
2111
2112         # The format of a table row is: mode list link.  Where mode is
2113         # the mode of the entry, list is the name of the entry, an href,
2114         # and link is the action links of the entry.
2115
2116         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
2117         if ($t->{'type'} eq "blob") {
2118                 print "<td class=\"list\">" .
2119                         $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2120                                                file_name=>"$basedir$t->{'name'}", %base_key),
2121                                 -class => "list"}, esc_path($t->{'name'}));
2122                 if (S_ISLNK(oct $t->{'mode'})) {
2123                         my $link_target = git_get_link_target($t->{'hash'});
2124                         if ($link_target) {
2125                                 my $norm_target = normalize_link_target($link_target, $basedir, $hash_base);
2126                                 if (defined $norm_target) {
2127                                         print " -> " .
2128                                               $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
2129                                                                      file_name=>$norm_target),
2130                                                        -title => $norm_target}, esc_path($link_target));
2131                                 } else {
2132                                         print " -> " . esc_path($link_target);
2133                                 }
2134                         }
2135                 }
2136                 print "</td>\n";
2137                 print "<td class=\"link\">";
2138                 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2139                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2140                               "blob");
2141                 if ($have_blame) {
2142                         print " | " .
2143                               $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
2144                                                      file_name=>"$basedir$t->{'name'}", %base_key)},
2145                                       "blame");
2146                 }
2147                 if (defined $hash_base) {
2148                         print " | " .
2149                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2150                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
2151                                       "history");
2152                 }
2153                 print " | " .
2154                         $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
2155                                                file_name=>"$basedir$t->{'name'}")},
2156                                 "raw");
2157                 print "</td>\n";
2158
2159         } elsif ($t->{'type'} eq "tree") {
2160                 print "<td class=\"list\">";
2161                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2162                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2163                               esc_path($t->{'name'}));
2164                 print "</td>\n";
2165                 print "<td class=\"link\">";
2166                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2167                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2168                               "tree");
2169                 if (defined $hash_base) {
2170                         print " | " .
2171                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2172                                                      file_name=>"$basedir$t->{'name'}")},
2173                                       "history");
2174                 }
2175                 print "</td>\n";
2176         }
2177 }
2178
2179 ## ......................................................................
2180 ## functions printing large fragments of HTML
2181
2182 sub git_difftree_body {
2183         my ($difftree, $hash, $parent) = @_;
2184         my ($have_blame) = gitweb_check_feature('blame');
2185         print "<div class=\"list_head\">\n";
2186         if ($#{$difftree} > 10) {
2187                 print(($#{$difftree} + 1) . " files changed:\n");
2188         }
2189         print "</div>\n";
2190
2191         print "<table class=\"diff_tree\">\n";
2192         my $alternate = 1;
2193         my $patchno = 0;
2194         foreach my $line (@{$difftree}) {
2195                 my %diff = parse_difftree_raw_line($line);
2196
2197                 if ($alternate) {
2198                         print "<tr class=\"dark\">\n";
2199                 } else {
2200                         print "<tr class=\"light\">\n";
2201                 }
2202                 $alternate ^= 1;
2203
2204                 my ($to_mode_oct, $to_mode_str, $to_file_type);
2205                 my ($from_mode_oct, $from_mode_str, $from_file_type);
2206                 if ($diff{'to_mode'} ne ('0' x 6)) {
2207                         $to_mode_oct = oct $diff{'to_mode'};
2208                         if (S_ISREG($to_mode_oct)) { # only for regular file
2209                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
2210                         }
2211                         $to_file_type = file_type($diff{'to_mode'});
2212                 }
2213                 if ($diff{'from_mode'} ne ('0' x 6)) {
2214                         $from_mode_oct = oct $diff{'from_mode'};
2215                         if (S_ISREG($to_mode_oct)) { # only for regular file
2216                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
2217                         }
2218                         $from_file_type = file_type($diff{'from_mode'});
2219                 }
2220
2221                 if ($diff{'status'} eq "A") { # created
2222                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
2223                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
2224                         $mode_chng   .= "]</span>";
2225                         print "<td>";
2226                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2227                                                      hash_base=>$hash, file_name=>$diff{'file'}),
2228                                       -class => "list"}, esc_path($diff{'file'}));
2229                         print "</td>\n";
2230                         print "<td>$mode_chng</td>\n";
2231                         print "<td class=\"link\">";
2232                         if ($action eq 'commitdiff') {
2233                                 # link to patch
2234                                 $patchno++;
2235                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
2236                                 print " | ";
2237                         }
2238                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2239                                                      hash_base=>$hash, file_name=>$diff{'file'})},
2240                                       "blob");
2241                         print "</td>\n";
2242
2243                 } elsif ($diff{'status'} eq "D") { # deleted
2244                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
2245                         print "<td>";
2246                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
2247                                                      hash_base=>$parent, file_name=>$diff{'file'}),
2248                                        -class => "list"}, esc_path($diff{'file'}));
2249                         print "</td>\n";
2250                         print "<td>$mode_chng</td>\n";
2251                         print "<td class=\"link\">";
2252                         if ($action eq 'commitdiff') {
2253                                 # link to patch
2254                                 $patchno++;
2255                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
2256                                 print " | ";
2257                         }
2258                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
2259                                                      hash_base=>$parent, file_name=>$diff{'file'})},
2260                                       "blob") . " | ";
2261                         if ($have_blame) {
2262                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
2263                                                              file_name=>$diff{'file'})},
2264                                               "blame") . " | ";
2265                         }
2266                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
2267                                                      file_name=>$diff{'file'})},
2268                                       "history");
2269                         print "</td>\n";
2270
2271                 } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
2272                         my $mode_chnge = "";
2273                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
2274                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
2275                                 if ($from_file_type ne $to_file_type) {
2276                                         $mode_chnge .= " from $from_file_type to $to_file_type";
2277                                 }
2278                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
2279                                         if ($from_mode_str && $to_mode_str) {
2280                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
2281                                         } elsif ($to_mode_str) {
2282                                                 $mode_chnge .= " mode: $to_mode_str";
2283                                         }
2284                                 }
2285                                 $mode_chnge .= "]</span>\n";
2286                         }
2287                         print "<td>";
2288                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2289                                                      hash_base=>$hash, file_name=>$diff{'file'}),
2290                                       -class => "list"}, esc_path($diff{'file'}));
2291                         print "</td>\n";
2292                         print "<td>$mode_chnge</td>\n";
2293                         print "<td class=\"link\">";
2294                         if ($action eq 'commitdiff') {
2295                                 # link to patch
2296                                 $patchno++;
2297                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
2298                                       " | ";
2299                         } elsif ($diff{'to_id'} ne $diff{'from_id'}) {
2300                                 # "commit" view and modified file (not onlu mode changed)
2301                                 print $cgi->a({-href => href(action=>"blobdiff",
2302                                                              hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
2303                                                              hash_base=>$hash, hash_parent_base=>$parent,
2304                                                              file_name=>$diff{'file'})},
2305                                               "diff") .
2306                                       " | ";
2307                         }
2308                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2309                                                      hash_base=>$hash, file_name=>$diff{'file'})},
2310                                        "blob") . " | ";
2311                         if ($have_blame) {
2312                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
2313                                                              file_name=>$diff{'file'})},
2314                                               "blame") . " | ";
2315                         }
2316                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
2317                                                      file_name=>$diff{'file'})},
2318                                       "history");
2319                         print "</td>\n";
2320
2321                 } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
2322                         my %status_name = ('R' => 'moved', 'C' => 'copied');
2323                         my $nstatus = $status_name{$diff{'status'}};
2324                         my $mode_chng = "";
2325                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
2326                                 # mode also for directories, so we cannot use $to_mode_str
2327                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
2328                         }
2329                         print "<td>" .
2330                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2331                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
2332                                       -class => "list"}, esc_path($diff{'to_file'})) . "</td>\n" .
2333                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
2334                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
2335                                                      hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
2336                                       -class => "list"}, esc_path($diff{'from_file'})) .
2337                               " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
2338                               "<td class=\"link\">";
2339                         if ($action eq 'commitdiff') {
2340                                 # link to patch
2341                                 $patchno++;
2342                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
2343                                       " | ";
2344                         } elsif ($diff{'to_id'} ne $diff{'from_id'}) {
2345                                 # "commit" view and modified file (not only pure rename or copy)
2346                                 print $cgi->a({-href => href(action=>"blobdiff",
2347                                                              hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
2348                                                              hash_base=>$hash, hash_parent_base=>$parent,
2349                                                              file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
2350                                               "diff") .
2351                                       " | ";
2352                         }
2353                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2354                                                      hash_base=>$parent, file_name=>$diff{'to_file'})},
2355                                       "blob") . " | ";
2356                         if ($have_blame) {
2357                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
2358                                                              file_name=>$diff{'to_file'})},
2359                                               "blame") . " | ";
2360                         }
2361                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
2362                                                     file_name=>$diff{'to_file'})},
2363                                       "history");
2364                         print "</td>\n";
2365
2366                 } # we should not encounter Unmerged (U) or Unknown (X) status
2367                 print "</tr>\n";
2368         }
2369         print "</table>\n";
2370 }
2371
2372 sub git_patchset_body {
2373         my ($fd, $difftree, $hash, $hash_parent) = @_;
2374
2375         my $patch_idx = 0;
2376         my $patch_line;
2377         my $diffinfo;
2378         my (%from, %to);
2379
2380         print "<div class=\"patchset\">\n";
2381
2382         # skip to first patch
2383         while ($patch_line = <$fd>) {
2384                 chomp $patch_line;
2385
2386                 last if ($patch_line =~ m/^diff /);
2387         }
2388
2389  PATCH:
2390         while ($patch_line) {
2391                 my @diff_header;
2392                 my ($from_id, $to_id);
2393
2394                 # git diff header
2395                 #assert($patch_line =~ m/^diff /) if DEBUG;
2396                 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
2397                 push @diff_header, $patch_line;
2398
2399                 # extended diff header
2400         EXTENDED_HEADER:
2401                 while ($patch_line = <$fd>) {
2402                         chomp $patch_line;
2403
2404                         last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
2405
2406                         if ($patch_line =~ m/^index ([0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
2407                                 $from_id = $1;
2408                                 $to_id   = $2;
2409                         }
2410
2411                         push @diff_header, $patch_line;
2412                 }
2413                 my $last_patch_line = $patch_line;
2414
2415                 # check if current patch belong to current raw line
2416                 # and parse raw git-diff line if needed
2417                 if (defined $diffinfo &&
2418                     $diffinfo->{'from_id'} eq $from_id &&
2419                     $diffinfo->{'to_id'}   eq $to_id) {
2420                         # this is split patch
2421                         print "<div class=\"patch cont\">\n";
2422                 } else {
2423                         # advance raw git-diff output if needed
2424                         $patch_idx++ if defined $diffinfo;
2425
2426                         # read and prepare patch information
2427                         if (ref($difftree->[$patch_idx]) eq "HASH") {
2428                                 # pre-parsed (or generated by hand)
2429                                 $diffinfo = $difftree->[$patch_idx];
2430                         } else {
2431                                 $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
2432                         }
2433                         $from{'file'} = $diffinfo->{'from_file'} || $diffinfo->{'file'};
2434                         $to{'file'}   = $diffinfo->{'to_file'}   || $diffinfo->{'file'};
2435                         if ($diffinfo->{'status'} ne "A") { # not new (added) file
2436                                 $from{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2437                                                      hash=>$diffinfo->{'from_id'},
2438                                                      file_name=>$from{'file'});
2439                         } else {
2440                                 delete $from{'href'};
2441                         }
2442                         if ($diffinfo->{'status'} ne "D") { # not deleted file
2443                                 $to{'href'} = href(action=>"blob", hash_base=>$hash,
2444                                                    hash=>$diffinfo->{'to_id'},
2445                                                    file_name=>$to{'file'});
2446                         } else {
2447                                 delete $to{'href'};
2448                         }
2449                         # this is first patch for raw difftree line with $patch_idx index
2450                         # we index @$difftree array from 0, but number patches from 1
2451                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
2452                 }
2453
2454                 # print "git diff" header
2455                 $patch_line = shift @diff_header;
2456                 $patch_line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2457                 if ($from{'href'}) {
2458                         $patch_line .= $cgi->a({-href => $from{'href'}, -class => "path"},
2459                                                'a/' . esc_path($from{'file'}));
2460                 } else { # file was added
2461                         $patch_line .= 'a/' . esc_path($from{'file'});
2462                 }
2463                 $patch_line .= ' ';
2464                 if ($to{'href'}) {
2465                         $patch_line .= $cgi->a({-href => $to{'href'}, -class => "path"},
2466                                                'b/' . esc_path($to{'file'}));
2467                 } else { # file was deleted
2468                         $patch_line .= 'b/' . esc_path($to{'file'});
2469                 }
2470                 print "<div class=\"diff header\">$patch_line</div>\n";
2471
2472                 # print extended diff header
2473                 print "<div class=\"diff extended_header\">\n" if (@diff_header > 0);
2474         EXTENDED_HEADER:
2475                 foreach $patch_line (@diff_header) {
2476                         # match <path>
2477                         if ($patch_line =~ s!^((copy|rename) from ).*$!$1! && $from{'href'}) {
2478                                 $patch_line .= $cgi->a({-href=>$from{'href'}, -class=>"path"},
2479                                                        esc_path($from{'file'}));
2480                         }
2481                         if ($patch_line =~ s!^((copy|rename) to ).*$!$1! && $to{'href'}) {
2482                                 $patch_line .= $cgi->a({-href=>$to{'href'}, -class=>"path"},
2483                                                        esc_path($to{'file'}));
2484                         }
2485                         # match <mode>
2486                         if ($patch_line =~ m/\s(\d{6})$/) {
2487                                 $patch_line .= '<span class="info"> (' .
2488                                                file_type_long($1) .
2489                                                ')</span>';
2490                         }
2491                         # match <hash>
2492                         if ($patch_line =~ m/^index/) {
2493                                 my ($from_link, $to_link);
2494                                 if ($from{'href'}) {
2495                                         $from_link = $cgi->a({-href=>$from{'href'}, -class=>"hash"},
2496                                                              substr($diffinfo->{'from_id'},0,7));
2497                                 } else {
2498                                         $from_link = '0' x 7;
2499                                 }
2500                                 if ($to{'href'}) {
2501                                         $to_link = $cgi->a({-href=>$to{'href'}, -class=>"hash"},
2502                                                            substr($diffinfo->{'to_id'},0,7));
2503                                 } else {
2504                                         $to_link = '0' x 7;
2505                                 }
2506                                 #affirm {
2507                                 #       my ($from_hash, $to_hash) =
2508                                 #               ($patch_line =~ m/^index ([0-9a-fA-F]{40})..([0-9a-fA-F]{40})/);
2509                                 #       my ($from_id, $to_id) =
2510                                 #               ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2511                                 #       ($from_hash eq $from_id) && ($to_hash eq $to_id);
2512                                 #} if DEBUG;
2513                                 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2514                                 $patch_line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2515                         }
2516                         print $patch_line . "<br/>\n";
2517                 }
2518                 print "</div>\n"  if (@diff_header > 0); # class="diff extended_header"
2519
2520                 # from-file/to-file diff header
2521                 $patch_line = $last_patch_line;
2522                 if (! $patch_line) {
2523                         print "</div>\n"; # class="patch"
2524                         last PATCH;
2525                 }
2526                 next PATCH if ($patch_line =~ m/^diff /);
2527                 #assert($patch_line =~ m/^---/) if DEBUG;
2528                 if ($from{'href'} && $patch_line =~ m!^--- "?a/!) {
2529                         $patch_line = '--- a/' .
2530                                       $cgi->a({-href=>$from{'href'}, -class=>"path"},
2531                                               esc_path($from{'file'}));
2532                 }
2533                 print "<div class=\"diff from_file\">$patch_line</div>\n";
2534
2535                 $patch_line = <$fd>;
2536                 chomp $patch_line;
2537
2538                 #assert($patch_line =~ m/^+++/) if DEBUG;
2539                 if ($to{'href'} && $patch_line =~ m!^\+\+\+ "?b/!) {
2540                         $patch_line = '+++ b/' .
2541                                       $cgi->a({-href=>$to{'href'}, -class=>"path"},
2542                                               esc_path($to{'file'}));
2543                 }
2544                 print "<div class=\"diff to_file\">$patch_line</div>\n";
2545
2546                 # the patch itself
2547         LINE:
2548                 while ($patch_line = <$fd>) {
2549                         chomp $patch_line;
2550
2551                         next PATCH if ($patch_line =~ m/^diff /);
2552
2553                         print format_diff_line($patch_line, \%from, \%to);
2554                 }
2555
2556         } continue {
2557                 print "</div>\n"; # class="patch"
2558         }
2559
2560         print "</div>\n"; # class="patchset"
2561 }
2562
2563 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2564
2565 sub git_project_list_body {
2566         my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
2567
2568         my ($check_forks) = gitweb_check_feature('forks');
2569
2570         my @projects;
2571         foreach my $pr (@$projlist) {
2572                 my (@aa) = git_get_last_activity($pr->{'path'});
2573                 unless (@aa) {
2574                         next;
2575                 }
2576                 ($pr->{'age'}, $pr->{'age_string'}) = @aa;
2577                 if (!defined $pr->{'descr'}) {
2578                         my $descr = git_get_project_description($pr->{'path'}) || "";
2579                         $pr->{'descr_long'} = decode_utf8($descr);
2580                         $pr->{'descr'} = chop_str($descr, 25, 5);
2581                 }
2582                 if (!defined $pr->{'owner'}) {
2583                         $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2584                 }
2585                 if ($check_forks) {
2586                         my $pname = $pr->{'path'};
2587                         if (($pname =~ s/\.git$//) &&
2588                             ($pname !~ /\/$/) &&
2589                             (-d "$projectroot/$pname")) {
2590                                 $pr->{'forks'} = "-d $projectroot/$pname";
2591                         }
2592                         else {
2593                                 $pr->{'forks'} = 0;
2594                         }
2595                 }
2596                 push @projects, $pr;
2597         }
2598
2599         $order ||= "project";
2600         $from = 0 unless defined $from;
2601         $to = $#projects if (!defined $to || $#projects < $to);
2602
2603         print "<table class=\"project_list\">\n";
2604         unless ($no_header) {
2605                 print "<tr>\n";
2606                 if ($check_forks) {
2607                         print "<th></th>\n";
2608                 }
2609                 if ($order eq "project") {
2610                         @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2611                         print "<th>Project</th>\n";
2612                 } else {
2613                         print "<th>" .
2614                               $cgi->a({-href => href(project=>undef, order=>'project'),
2615                                        -class => "header"}, "Project") .
2616                               "</th>\n";
2617                 }
2618                 if ($order eq "descr") {
2619                         @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2620                         print "<th>Description</th>\n";
2621                 } else {
2622                         print "<th>" .
2623                               $cgi->a({-href => href(project=>undef, order=>'descr'),
2624                                        -class => "header"}, "Description") .
2625                               "</th>\n";
2626                 }
2627                 if ($order eq "owner") {
2628                         @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2629                         print "<th>Owner</th>\n";
2630                 } else {
2631                         print "<th>" .
2632                               $cgi->a({-href => href(project=>undef, order=>'owner'),
2633                                        -class => "header"}, "Owner") .
2634                               "</th>\n";
2635                 }
2636                 if ($order eq "age") {
2637                         @projects = sort {$a->{'age'} <=> $b->{'age'}} @projects;
2638                         print "<th>Last Change</th>\n";
2639                 } else {
2640                         print "<th>" .
2641                               $cgi->a({-href => href(project=>undef, order=>'age'),
2642                                        -class => "header"}, "Last Change") .
2643                               "</th>\n";
2644                 }
2645                 print "<th></th>\n" .
2646                       "</tr>\n";
2647         }
2648         my $alternate = 1;
2649         for (my $i = $from; $i <= $to; $i++) {
2650                 my $pr = $projects[$i];
2651                 if ($alternate) {
2652                         print "<tr class=\"dark\">\n";
2653                 } else {
2654                         print "<tr class=\"light\">\n";
2655                 }
2656                 $alternate ^= 1;
2657                 if ($check_forks) {
2658                         print "<td>";
2659                         if ($pr->{'forks'}) {
2660                                 print "<!-- $pr->{'forks'} -->\n";
2661                                 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
2662                         }
2663                         print "</td>\n";
2664                 }
2665                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2666                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2667                       "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2668                                         -class => "list", -title => $pr->{'descr_long'}},
2669                                         esc_html($pr->{'descr'})) . "</td>\n" .
2670                       "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2671                 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
2672                       $pr->{'age_string'} . "</td>\n" .
2673                       "<td class=\"link\">" .
2674                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2675                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
2676                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
2677                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
2678                       ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
2679                       "</td>\n" .
2680                       "</tr>\n";
2681         }
2682         if (defined $extra) {
2683                 print "<tr>\n";
2684                 if ($check_forks) {
2685                         print "<td></td>\n";
2686                 }
2687                 print "<td colspan=\"5\">$extra</td>\n" .
2688                       "</tr>\n";
2689         }
2690         print "</table>\n";
2691 }
2692
2693 sub git_shortlog_body {
2694         # uses global variable $project
2695         my ($commitlist, $from, $to, $refs, $extra) = @_;
2696
2697         my $have_snapshot = gitweb_have_snapshot();
2698
2699         $from = 0 unless defined $from;
2700         $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
2701
2702         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
2703         my $alternate = 1;
2704         for (my $i = $from; $i <= $to; $i++) {
2705                 my %co = %{$commitlist->[$i]};
2706                 my $commit = $co{'id'};
2707                 my $ref = format_ref_marker($refs, $commit);
2708                 if ($alternate) {
2709                         print "<tr class=\"dark\">\n";
2710                 } else {
2711                         print "<tr class=\"light\">\n";
2712                 }
2713                 $alternate ^= 1;
2714                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
2715                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2716                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
2717                       "<td>";
2718                 print format_subject_html($co{'title'}, $co{'title_short'},
2719                                           href(action=>"commit", hash=>$commit), $ref);
2720                 print "</td>\n" .
2721                       "<td class=\"link\">" .
2722                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
2723                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
2724                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
2725                 if ($have_snapshot) {
2726                         print " | " . $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
2727                 }
2728                 print "</td>\n" .
2729                       "</tr>\n";
2730         }
2731         if (defined $extra) {
2732                 print "<tr>\n" .
2733                       "<td colspan=\"4\">$extra</td>\n" .
2734                       "</tr>\n";
2735         }
2736         print "</table>\n";
2737 }
2738
2739 sub git_history_body {
2740         # Warning: assumes constant type (blob or tree) during history
2741         my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
2742
2743         $from = 0 unless defined $from;
2744         $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
2745
2746         print "<table class=\"history\" cellspacing=\"0\">\n";
2747         my $alternate = 1;
2748         for (my $i = $from; $i <= $to; $i++) {
2749                 my %co = %{$commitlist->[$i]};
2750                 if (!%co) {
2751                         next;
2752                 }
2753                 my $commit = $co{'id'};
2754
2755                 my $ref = format_ref_marker($refs, $commit);
2756
2757                 if ($alternate) {
2758                         print "<tr class=\"dark\">\n";
2759                 } else {
2760                         print "<tr class=\"light\">\n";
2761                 }
2762                 $alternate ^= 1;
2763                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2764                       # shortlog uses      chop_str($co{'author_name'}, 10)
2765                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
2766                       "<td>";
2767                 # originally git_history used chop_str($co{'title'}, 50)
2768                 print format_subject_html($co{'title'}, $co{'title_short'},
2769                                           href(action=>"commit", hash=>$commit), $ref);
2770                 print "</td>\n" .
2771                       "<td class=\"link\">" .
2772                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
2773                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
2774
2775                 if ($ftype eq 'blob') {
2776                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
2777                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
2778                         if (defined $blob_current && defined $blob_parent &&
2779                                         $blob_current ne $blob_parent) {
2780                                 print " | " .
2781                                         $cgi->a({-href => href(action=>"blobdiff",
2782                                                                hash=>$blob_current, hash_parent=>$blob_parent,
2783                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
2784                                                                file_name=>$file_name)},
2785                                                 "diff to current");
2786                         }
2787                 }
2788                 print "</td>\n" .
2789                       "</tr>\n";
2790         }
2791         if (defined $extra) {
2792                 print "<tr>\n" .
2793                       "<td colspan=\"4\">$extra</td>\n" .
2794                       "</tr>\n";
2795         }
2796         print "</table>\n";
2797 }
2798
2799 sub git_tags_body {
2800         # uses global variable $project
2801         my ($taglist, $from, $to, $extra) = @_;
2802         $from = 0 unless defined $from;
2803         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2804
2805         print "<table class=\"tags\" cellspacing=\"0\">\n";
2806         my $alternate = 1;
2807         for (my $i = $from; $i <= $to; $i++) {
2808                 my $entry = $taglist->[$i];
2809                 my %tag = %$entry;
2810                 my $comment = $tag{'subject'};
2811                 my $comment_short;
2812                 if (defined $comment) {
2813                         $comment_short = chop_str($comment, 30, 5);
2814                 }
2815                 if ($alternate) {
2816                         print "<tr class=\"dark\">\n";
2817                 } else {
2818                         print "<tr class=\"light\">\n";
2819                 }
2820                 $alternate ^= 1;
2821                 if (defined $tag{'age'}) {
2822                         print "<td><i>$tag{'age'}</i></td>\n";
2823                 } else {
2824                         print "<td></td>\n";
2825                 }
2826                 print "<td>" .
2827                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
2828                                -class => "list name"}, esc_html($tag{'name'})) .
2829                       "</td>\n" .
2830                       "<td>";
2831                 if (defined $comment) {
2832                         print format_subject_html($comment, $comment_short,
2833                                                   href(action=>"tag", hash=>$tag{'id'}));
2834                 }
2835                 print "</td>\n" .
2836                       "<td class=\"selflink\">";
2837                 if ($tag{'type'} eq "tag") {
2838                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
2839                 } else {
2840                         print "&nbsp;";
2841                 }
2842                 print "</td>\n" .
2843                       "<td class=\"link\">" . " | " .
2844                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
2845                 if ($tag{'reftype'} eq "commit") {
2846                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
2847                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log");
2848                 } elsif ($tag{'reftype'} eq "blob") {
2849                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
2850                 }
2851                 print "</td>\n" .
2852                       "</tr>";
2853         }
2854         if (defined $extra) {
2855                 print "<tr>\n" .
2856                       "<td colspan=\"5\">$extra</td>\n" .
2857                       "</tr>\n";
2858         }
2859         print "</table>\n";
2860 }
2861
2862 sub git_heads_body {
2863         # uses global variable $project
2864         my ($headlist, $head, $from, $to, $extra) = @_;
2865         $from = 0 unless defined $from;
2866         $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
2867
2868         print "<table class=\"heads\" cellspacing=\"0\">\n";
2869         my $alternate = 1;
2870         for (my $i = $from; $i <= $to; $i++) {
2871                 my $entry = $headlist->[$i];
2872                 my %ref = %$entry;
2873                 my $curr = $ref{'id'} eq $head;
2874                 if ($alternate) {
2875                         print "<tr class=\"dark\">\n";
2876                 } else {
2877                         print "<tr class=\"light\">\n";
2878                 }
2879                 $alternate ^= 1;
2880                 print "<td><i>$ref{'age'}</i></td>\n" .
2881                       ($curr ? "<td class=\"current_head\">" : "<td>") .
2882                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'}),
2883                                -class => "list name"},esc_html($ref{'name'})) .
2884                       "</td>\n" .
2885                       "<td class=\"link\">" .
2886                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'})}, "shortlog") . " | " .
2887                       $cgi->a({-href => href(action=>"log", hash=>$ref{'name'})}, "log") . " | " .
2888                       $cgi->a({-href => href(action=>"tree", hash=>$ref{'name'}, hash_base=>$ref{'name'})}, "tree") .
2889                       "</td>\n" .
2890                       "</tr>";
2891         }
2892         if (defined $extra) {
2893                 print "<tr>\n" .
2894                       "<td colspan=\"3\">$extra</td>\n" .
2895                       "</tr>\n";
2896         }
2897         print "</table>\n";
2898 }
2899
2900 sub git_search_grep_body {
2901         my ($commitlist, $from, $to, $extra) = @_;
2902         $from = 0 unless defined $from;
2903         $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
2904
2905         print "<table class=\"grep\" cellspacing=\"0\">\n";
2906         my $alternate = 1;
2907         for (my $i = $from; $i <= $to; $i++) {
2908                 my %co = %{$commitlist->[$i]};
2909                 if (!%co) {
2910                         next;
2911                 }
2912                 my $commit = $co{'id'};
2913                 if ($alternate) {
2914                         print "<tr class=\"dark\">\n";
2915                 } else {
2916                         print "<tr class=\"light\">\n";
2917                 }
2918                 $alternate ^= 1;
2919                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2920                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
2921                       "<td>" .
2922                       $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
2923                                esc_html(chop_str($co{'title'}, 50)) . "<br/>");
2924                 my $comment = $co{'comment'};
2925                 foreach my $line (@$comment) {
2926                         if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
2927                                 my $lead = esc_html($1) || "";
2928                                 $lead = chop_str($lead, 30, 10);
2929                                 my $match = esc_html($2) || "";
2930                                 my $trail = esc_html($3) || "";
2931                                 $trail = chop_str($trail, 30, 10);
2932                                 my $text = "$lead<span class=\"match\">$match</span>$trail";
2933                                 print chop_str($text, 80, 5) . "<br/>\n";
2934                         }
2935                 }
2936                 print "</td>\n" .
2937                       "<td class=\"link\">" .
2938                       $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
2939                       " | " .
2940                       $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
2941                 print "</td>\n" .
2942                       "</tr>\n";
2943         }
2944         if (defined $extra) {
2945                 print "<tr>\n" .
2946                       "<td colspan=\"3\">$extra</td>\n" .
2947                       "</tr>\n";
2948         }
2949         print "</table>\n";
2950 }
2951
2952 ## ======================================================================
2953 ## ======================================================================
2954 ## actions
2955
2956 sub git_project_list {
2957         my $order = $cgi->param('o');
2958         if (defined $order && $order !~ m/project|descr|owner|age/) {
2959                 die_error(undef, "Unknown order parameter");
2960         }
2961
2962         my @list = git_get_projects_list();
2963         if (!@list) {
2964                 die_error(undef, "No projects found");
2965         }
2966
2967         git_header_html();
2968         if (-f $home_text) {
2969                 print "<div class=\"index_include\">\n";
2970                 open (my $fd, $home_text);
2971                 print <$fd>;
2972                 close $fd;
2973                 print "</div>\n";
2974         }
2975         git_project_list_body(\@list, $order);
2976         git_footer_html();
2977 }
2978
2979 sub git_forks {
2980         my $order = $cgi->param('o');
2981         if (defined $order && $order !~ m/project|descr|owner|age/) {
2982                 die_error(undef, "Unknown order parameter");
2983         }
2984
2985         my @list = git_get_projects_list($project);
2986         if (!@list) {
2987                 die_error(undef, "No forks found");
2988         }
2989
2990         git_header_html();
2991         git_print_page_nav('','');
2992         git_print_header_div('summary', "$project forks");
2993         git_project_list_body(\@list, $order);
2994         git_footer_html();
2995 }
2996
2997 sub git_project_index {
2998         my @projects = git_get_projects_list($project);
2999
3000         print $cgi->header(
3001                 -type => 'text/plain',
3002                 -charset => 'utf-8',
3003                 -content_disposition => 'inline; filename="index.aux"');
3004
3005         foreach my $pr (@projects) {
3006                 if (!exists $pr->{'owner'}) {
3007                         $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}");
3008                 }
3009
3010                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
3011                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
3012                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3013                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3014                 $path  =~ s/ /\+/g;
3015                 $owner =~ s/ /\+/g;
3016
3017                 print "$path $owner\n";
3018         }
3019 }
3020
3021 sub git_summary {
3022         my $descr = git_get_project_description($project) || "none";
3023         my %co = parse_commit("HEAD");
3024         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
3025         my $head = $co{'id'};
3026
3027         my $owner = git_get_project_owner($project);
3028
3029         my $refs = git_get_references();
3030         # These get_*_list functions return one more to allow us to see if
3031         # there are more ...
3032         my @taglist  = git_get_tags_list(16);
3033         my @headlist = git_get_heads_list(16);
3034         my @forklist;
3035         my ($check_forks) = gitweb_check_feature('forks');
3036
3037         if ($check_forks) {
3038                 @forklist = git_get_projects_list($project);
3039         }
3040
3041         git_header_html();
3042         git_print_page_nav('summary','', $head);
3043
3044         print "<div class=\"title\">&nbsp;</div>\n";
3045         print "<table cellspacing=\"0\">\n" .
3046               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
3047               "<tr><td>owner</td><td>$owner</td></tr>\n" .
3048               "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
3049         # use per project git URL list in $projectroot/$project/cloneurl
3050         # or make project git URL from git base URL and project name
3051         my $url_tag = "URL";
3052         my @url_list = git_get_project_url_list($project);
3053         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
3054         foreach my $git_url (@url_list) {
3055                 next unless $git_url;
3056                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
3057                 $url_tag = "";
3058         }
3059         print "</table>\n";
3060
3061         if (-s "$projectroot/$project/README.html") {
3062                 if (open my $fd, "$projectroot/$project/README.html") {
3063                         print "<div class=\"title\">readme</div>\n";
3064                         print $_ while (<$fd>);
3065                         close $fd;
3066                 }
3067         }
3068
3069         # we need to request one more than 16 (0..15) to check if
3070         # those 16 are all
3071         my @commitlist = parse_commits($head, 17);
3072         git_print_header_div('shortlog');
3073         git_shortlog_body(\@commitlist, 0, 15, $refs,
3074                           $#commitlist <=  15 ? undef :
3075                           $cgi->a({-href => href(action=>"shortlog")}, "..."));
3076
3077         if (@taglist) {
3078                 git_print_header_div('tags');
3079                 git_tags_body(\@taglist, 0, 15,
3080                               $#taglist <=  15 ? undef :
3081                               $cgi->a({-href => href(action=>"tags")}, "..."));
3082         }
3083
3084         if (@headlist) {
3085                 git_print_header_div('heads');
3086                 git_heads_body(\@headlist, $head, 0, 15,
3087                                $#headlist <= 15 ? undef :
3088                                $cgi->a({-href => href(action=>"heads")}, "..."));
3089         }
3090
3091         if (@forklist) {
3092                 git_print_header_div('forks');
3093                 git_project_list_body(\@forklist, undef, 0, 15,
3094                                       $#forklist <= 15 ? undef :
3095                                       $cgi->a({-href => href(action=>"forks")}, "..."),
3096                                       'noheader');
3097         }
3098
3099         git_footer_html();
3100 }
3101
3102 sub git_tag {
3103         my $head = git_get_head_hash($project);
3104         git_header_html();
3105         git_print_page_nav('','', $head,undef,$head);
3106         my %tag = parse_tag($hash);
3107         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
3108         print "<div class=\"title_text\">\n" .
3109               "<table cellspacing=\"0\">\n" .
3110               "<tr>\n" .
3111               "<td>object</td>\n" .
3112               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3113                                $tag{'object'}) . "</td>\n" .
3114               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3115                                               $tag{'type'}) . "</td>\n" .
3116               "</tr>\n";
3117         if (defined($tag{'author'})) {
3118                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
3119                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
3120                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
3121                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
3122                         "</td></tr>\n";
3123         }
3124         print "</table>\n\n" .
3125               "</div>\n";
3126         print "<div class=\"page_body\">";
3127         my $comment = $tag{'comment'};
3128         foreach my $line (@$comment) {
3129                 chomp $line;
3130                 print esc_html($line, -nbsp=>1) . "<br/>\n";
3131         }
3132         print "</div>\n";
3133         git_footer_html();
3134 }
3135
3136 sub git_blame2 {
3137         my $fd;
3138         my $ftype;
3139
3140         my ($have_blame) = gitweb_check_feature('blame');
3141         if (!$have_blame) {
3142                 die_error('403 Permission denied', "Permission denied");
3143         }
3144         die_error('404 Not Found', "File name not defined") if (!$file_name);
3145         $hash_base ||= git_get_head_hash($project);
3146         die_error(undef, "Couldn't find base commit") unless ($hash_base);
3147         my %co = parse_commit($hash_base)
3148                 or die_error(undef, "Reading commit failed");
3149         if (!defined $hash) {
3150                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3151                         or die_error(undef, "Error looking up file");
3152         }
3153         $ftype = git_get_type($hash);
3154         if ($ftype !~ "blob") {
3155                 die_error('400 Bad Request', "Object is not a blob");
3156         }
3157         open ($fd, "-|", git_cmd(), "blame", '-p', '--',
3158               $file_name, $hash_base)
3159                 or die_error(undef, "Open git-blame failed");
3160         git_header_html();
3161         my $formats_nav =
3162                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3163                         "blob") .
3164                 " | " .
3165                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3166                         "history") .
3167                 " | " .
3168                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3169                         "HEAD");
3170         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3171         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3172         git_print_page_path($file_name, $ftype, $hash_base);
3173         my @rev_color = (qw(light2 dark2));
3174         my $num_colors = scalar(@rev_color);
3175         my $current_color = 0;
3176         my $last_rev;
3177         print <<HTML;
3178 <div class="page_body">
3179 <table class="blame">
3180 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
3181 HTML
3182         my %metainfo = ();
3183         while (1) {
3184                 $_ = <$fd>;
3185                 last unless defined $_;
3186                 my ($full_rev, $orig_lineno, $lineno, $group_size) =
3187                     /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
3188                 if (!exists $metainfo{$full_rev}) {
3189                         $metainfo{$full_rev} = {};
3190                 }
3191                 my $meta = $metainfo{$full_rev};
3192                 while (<$fd>) {
3193                         last if (s/^\t//);
3194                         if (/^(\S+) (.*)$/) {
3195                                 $meta->{$1} = $2;
3196                         }
3197                 }
3198                 my $data = $_;
3199                 chomp $data;
3200                 my $rev = substr($full_rev, 0, 8);
3201                 my $author = $meta->{'author'};
3202                 my %date = parse_date($meta->{'author-time'},
3203                                       $meta->{'author-tz'});
3204                 my $date = $date{'iso-tz'};
3205                 if ($group_size) {
3206                         $current_color = ++$current_color % $num_colors;
3207                 }
3208                 print "<tr class=\"$rev_color[$current_color]\">\n";
3209                 if ($group_size) {
3210                         print "<td class=\"sha1\"";
3211                         print " title=\"". esc_html($author) . ", $date\"";
3212                         print " rowspan=\"$group_size\"" if ($group_size > 1);
3213                         print ">";
3214                         print $cgi->a({-href => href(action=>"commit",
3215                                                      hash=>$full_rev,
3216                                                      file_name=>$file_name)},
3217                                       esc_html($rev));
3218                         print "</td>\n";
3219                 }
3220                 open (my $dd, "-|", git_cmd(), "rev-parse", "$full_rev^")
3221                         or die_error(undef, "Open git-rev-parse failed");
3222                 my $parent_commit = <$dd>;
3223                 close $dd;
3224                 chomp($parent_commit);
3225                 my $blamed = href(action => 'blame',
3226                                   file_name => $meta->{'filename'},
3227                                   hash_base => $parent_commit);
3228                 print "<td class=\"linenr\">";
3229                 print $cgi->a({ -href => "$blamed#l$orig_lineno",
3230                                 -id => "l$lineno",
3231                                 -class => "linenr" },
3232                               esc_html($lineno));
3233                 print "</td>";
3234                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
3235                 print "</tr>\n";
3236         }
3237         print "</table>\n";
3238         print "</div>";
3239         close $fd
3240                 or print "Reading blob failed\n";
3241         git_footer_html();
3242 }
3243
3244 sub git_blame {
3245         my $fd;
3246
3247         my ($have_blame) = gitweb_check_feature('blame');
3248         if (!$have_blame) {
3249                 die_error('403 Permission denied', "Permission denied");
3250         }
3251         die_error('404 Not Found', "File name not defined") if (!$file_name);
3252         $hash_base ||= git_get_head_hash($project);
3253         die_error(undef, "Couldn't find base commit") unless ($hash_base);
3254         my %co = parse_commit($hash_base)
3255                 or die_error(undef, "Reading commit failed");
3256         if (!defined $hash) {
3257                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3258                         or die_error(undef, "Error lookup file");
3259         }
3260         open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
3261                 or die_error(undef, "Open git-annotate failed");
3262         git_header_html();
3263         my $formats_nav =
3264                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3265                         "blob") .
3266                 " | " .
3267                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3268                         "history") .
3269                 " | " .
3270                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3271                         "HEAD");
3272         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3273         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3274         git_print_page_path($file_name, 'blob', $hash_base);
3275         print "<div class=\"page_body\">\n";
3276         print <<HTML;
3277 <table class="blame">
3278   <tr>
3279     <th>Commit</th>
3280     <th>Age</th>
3281     <th>Author</th>
3282     <th>Line</th>
3283     <th>Data</th>
3284   </tr>
3285 HTML
3286         my @line_class = (qw(light dark));
3287         my $line_class_len = scalar (@line_class);
3288         my $line_class_num = $#line_class;
3289         while (my $line = <$fd>) {
3290                 my $long_rev;
3291                 my $short_rev;
3292                 my $author;
3293                 my $time;
3294                 my $lineno;
3295                 my $data;
3296                 my $age;
3297                 my $age_str;
3298                 my $age_class;
3299
3300                 chomp $line;
3301                 $line_class_num = ($line_class_num + 1) % $line_class_len;
3302
3303                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
3304                         $long_rev = $1;
3305                         $author   = $2;
3306                         $time     = $3;
3307                         $lineno   = $4;
3308                         $data     = $5;
3309                 } else {
3310                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
3311                         next;
3312                 }
3313                 $short_rev  = substr ($long_rev, 0, 8);
3314                 $age        = time () - $time;
3315                 $age_str    = age_string ($age);
3316                 $age_str    =~ s/ /&nbsp;/g;
3317                 $age_class  = age_class($age);
3318                 $author     = esc_html ($author);
3319                 $author     =~ s/ /&nbsp;/g;
3320
3321                 $data = untabify($data);
3322                 $data = esc_html ($data);
3323
3324                 print <<HTML;
3325   <tr class="$line_class[$line_class_num]">
3326     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
3327     <td class="$age_class">$age_str</td>
3328     <td>$author</td>
3329     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
3330     <td class="pre">$data</td>
3331   </tr>
3332 HTML
3333         } # while (my $line = <$fd>)
3334         print "</table>\n\n";
3335         close $fd
3336                 or print "Reading blob failed.\n";
3337         print "</div>";
3338         git_footer_html();
3339 }
3340
3341 sub git_tags {
3342         my $head = git_get_head_hash($project);
3343         git_header_html();
3344         git_print_page_nav('','', $head,undef,$head);
3345         git_print_header_div('summary', $project);
3346
3347         my @tagslist = git_get_tags_list();
3348         if (@tagslist) {
3349                 git_tags_body(\@tagslist);
3350         }
3351         git_footer_html();
3352 }
3353
3354 sub git_heads {
3355         my $head = git_get_head_hash($project);
3356         git_header_html();
3357         git_print_page_nav('','', $head,undef,$head);
3358         git_print_header_div('summary', $project);
3359
3360         my @headslist = git_get_heads_list();
3361         if (@headslist) {
3362                 git_heads_body(\@headslist, $head);
3363         }
3364         git_footer_html();
3365 }
3366
3367 sub git_blob_plain {
3368         my $expires;
3369
3370         if (!defined $hash) {
3371                 if (defined $file_name) {
3372                         my $base = $hash_base || git_get_head_hash($project);
3373                         $hash = git_get_hash_by_path($base, $file_name, "blob")
3374                                 or die_error(undef, "Error lookup file");
3375                 } else {
3376                         die_error(undef, "No file name defined");
3377                 }
3378         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3379                 # blobs defined by non-textual hash id's can be cached
3380                 $expires = "+1d";
3381         }
3382
3383         my $type = shift;
3384         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3385                 or die_error(undef, "Couldn't cat $file_name, $hash");
3386
3387         $type ||= blob_mimetype($fd, $file_name);
3388
3389         # save as filename, even when no $file_name is given
3390         my $save_as = "$hash";
3391         if (defined $file_name) {
3392                 $save_as = $file_name;
3393         } elsif ($type =~ m/^text\//) {
3394                 $save_as .= '.txt';
3395         }
3396
3397         print $cgi->header(
3398                 -type => "$type",
3399                 -expires=>$expires,
3400                 -content_disposition => 'inline; filename="' . "$save_as" . '"');
3401         undef $/;
3402         binmode STDOUT, ':raw';
3403         print <$fd>;
3404         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
3405         $/ = "\n";
3406         close $fd;
3407 }
3408
3409 sub git_blob {
3410         my $expires;
3411
3412         if (!defined $hash) {
3413                 if (defined $file_name) {
3414                         my $base = $hash_base || git_get_head_hash($project);
3415                         $hash = git_get_hash_by_path($base, $file_name, "blob")
3416                                 or die_error(undef, "Error lookup file");
3417                 } else {
3418                         die_error(undef, "No file name defined");
3419                 }
3420         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3421                 # blobs defined by non-textual hash id's can be cached
3422                 $expires = "+1d";
3423         }
3424
3425         my ($have_blame) = gitweb_check_feature('blame');
3426         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3427                 or die_error(undef, "Couldn't cat $file_name, $hash");
3428         my $mimetype = blob_mimetype($fd, $file_name);
3429         if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)!) {
3430                 close $fd;
3431                 return git_blob_plain($mimetype);
3432         }
3433         # we can have blame only for text/* mimetype
3434         $have_blame &&= ($mimetype =~ m!^text/!);
3435
3436         git_header_html(undef, $expires);
3437         my $formats_nav = '';
3438         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3439                 if (defined $file_name) {
3440                         if ($have_blame) {
3441                                 $formats_nav .=
3442                                         $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
3443                                                                hash=>$hash, file_name=>$file_name)},
3444                                                 "blame") .
3445                                         " | ";
3446                         }
3447                         $formats_nav .=
3448                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3449                                                        hash=>$hash, file_name=>$file_name)},
3450                                         "history") .
3451                                 " | " .
3452                                 $cgi->a({-href => href(action=>"blob_plain",
3453                                                        hash=>$hash, file_name=>$file_name)},
3454                                         "raw") .
3455                                 " | " .
3456                                 $cgi->a({-href => href(action=>"blob",
3457                                                        hash_base=>"HEAD", file_name=>$file_name)},
3458                                         "HEAD");
3459                 } else {
3460                         $formats_nav .=
3461                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
3462                 }
3463                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3464                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3465         } else {
3466                 print "<div class=\"page_nav\">\n" .
3467                       "<br/><br/></div>\n" .
3468                       "<div class=\"title\">$hash</div>\n";
3469         }
3470         git_print_page_path($file_name, "blob", $hash_base);
3471         print "<div class=\"page_body\">\n";
3472         if ($mimetype =~ m!^text/!) {
3473                 my $nr;
3474                 while (my $line = <$fd>) {
3475                         chomp $line;
3476                         $nr++;
3477                         $line = untabify($line);
3478                         printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
3479                                $nr, $nr, $nr, esc_html($line, -nbsp=>1);
3480                 }
3481         } elsif ($mimetype =~ m!^image/!) {
3482                 print qq!<img type="$mimetype"!;
3483                 if ($file_name) {
3484                         print qq! alt="$file_name" title="$file_name"!;
3485                 }
3486                 print qq! src="! .
3487                       href(action=>"blob_plain", hash=>$hash,
3488                            hash_base=>$hash_base, file_name=>$file_name) .
3489                       qq!" />\n!;
3490         }
3491         close $fd
3492                 or print "Reading blob failed.\n";
3493         print "</div>";
3494         git_footer_html();
3495 }
3496
3497 sub git_tree {
3498         my $have_snapshot = gitweb_have_snapshot();
3499
3500         if (!defined $hash_base) {
3501                 $hash_base = "HEAD";
3502         }
3503         if (!defined $hash) {
3504                 if (defined $file_name) {
3505                         $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
3506                 } else {
3507                         $hash = $hash_base;
3508                 }
3509         }
3510         $/ = "\0";
3511         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
3512                 or die_error(undef, "Open git-ls-tree failed");
3513         my @entries = map { chomp; $_ } <$fd>;
3514         close $fd or die_error(undef, "Reading tree failed");
3515         $/ = "\n";
3516
3517         my $refs = git_get_references();
3518         my $ref = format_ref_marker($refs, $hash_base);
3519         git_header_html();
3520         my $basedir = '';
3521         my ($have_blame) = gitweb_check_feature('blame');
3522         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3523                 my @views_nav = ();
3524                 if (defined $file_name) {
3525                         push @views_nav,
3526                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3527                                                        hash=>$hash, file_name=>$file_name)},
3528                                         "history"),
3529                                 $cgi->a({-href => href(action=>"tree",
3530                                                        hash_base=>"HEAD", file_name=>$file_name)},
3531                                         "HEAD"),
3532                 }
3533                 if ($have_snapshot) {
3534                         # FIXME: Should be available when we have no hash base as well.
3535                         push @views_nav,
3536                                 $cgi->a({-href => href(action=>"snapshot", hash=>$hash)},
3537                                         "snapshot");
3538                 }
3539                 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
3540                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
3541         } else {
3542                 undef $hash_base;
3543                 print "<div class=\"page_nav\">\n";
3544                 print "<br/><br/></div>\n";
3545                 print "<div class=\"title\">$hash</div>\n";
3546         }
3547         if (defined $file_name) {
3548                 $basedir = $file_name;
3549                 if ($basedir ne '' && substr($basedir, -1) ne '/') {
3550                         $basedir .= '/';
3551                 }
3552         }
3553         git_print_page_path($file_name, 'tree', $hash_base);
3554         print "<div class=\"page_body\">\n";
3555         print "<table cellspacing=\"0\">\n";
3556         my $alternate = 1;
3557         # '..' (top directory) link if possible
3558         if (defined $hash_base &&
3559             defined $file_name && $file_name =~ m![^/]+$!) {
3560                 if ($alternate) {
3561                         print "<tr class=\"dark\">\n";
3562                 } else {
3563                         print "<tr class=\"light\">\n";
3564                 }
3565                 $alternate ^= 1;
3566
3567                 my $up = $file_name;
3568                 $up =~ s!/?[^/]+$!!;
3569                 undef $up unless $up;
3570                 # based on git_print_tree_entry
3571                 print '<td class="mode">' . mode_str('040000') . "</td>\n";
3572                 print '<td class="list">';
3573                 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
3574                                              file_name=>$up)},
3575                               "..");
3576                 print "</td>\n";
3577                 print "<td class=\"link\"></td>\n";
3578
3579                 print "</tr>\n";
3580         }
3581         foreach my $line (@entries) {
3582                 my %t = parse_ls_tree_line($line, -z => 1);
3583
3584                 if ($alternate) {
3585                         print "<tr class=\"dark\">\n";
3586                 } else {
3587                         print "<tr class=\"light\">\n";
3588                 }
3589                 $alternate ^= 1;
3590
3591                 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
3592
3593                 print "</tr>\n";
3594         }
3595         print "</table>\n" .
3596               "</div>";
3597         git_footer_html();
3598 }
3599
3600 sub git_snapshot {
3601         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
3602         my $have_snapshot = (defined $ctype && defined $suffix);
3603         if (!$have_snapshot) {
3604                 die_error('403 Permission denied', "Permission denied");
3605         }
3606
3607         if (!defined $hash) {
3608                 $hash = git_get_head_hash($project);
3609         }
3610
3611         my $filename = decode_utf8(basename($project)) . "-$hash.tar.$suffix";
3612
3613         print $cgi->header(
3614                 -type => "application/$ctype",
3615                 -content_disposition => 'inline; filename="' . "$filename" . '"',
3616                 -status => '200 OK');
3617
3618         my $git = git_cmd_str();
3619         my $name = $project;
3620         $name =~ s/\047/\047\\\047\047/g;
3621         open my $fd, "-|",
3622         "$git archive --format=tar --prefix=\'$name\'/ $hash | $command"
3623                 or die_error(undef, "Execute git-tar-tree failed");
3624         binmode STDOUT, ':raw';
3625         print <$fd>;
3626         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
3627         close $fd;
3628
3629 }
3630
3631 sub git_log {
3632         my $head = git_get_head_hash($project);
3633         if (!defined $hash) {
3634                 $hash = $head;
3635         }
3636         if (!defined $page) {
3637                 $page = 0;
3638         }
3639         my $refs = git_get_references();
3640
3641         my @commitlist = parse_commits($hash, 101, (100 * $page));
3642
3643         my $paging_nav = format_paging_nav('log', $hash, $head, $page, (100 * ($page+1)));
3644
3645         git_header_html();
3646         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
3647
3648         if (!@commitlist) {
3649                 my %co = parse_commit($hash);
3650
3651                 git_print_header_div('summary', $project);
3652                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
3653         }
3654         my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
3655         for (my $i = 0; $i <= $to; $i++) {
3656                 my %co = %{$commitlist[$i]};
3657                 next if !%co;
3658                 my $commit = $co{'id'};
3659                 my $ref = format_ref_marker($refs, $commit);
3660                 my %ad = parse_date($co{'author_epoch'});
3661                 git_print_header_div('commit',
3662                                "<span class=\"age\">$co{'age_string'}</span>" .
3663                                esc_html($co{'title'}) . $ref,
3664                                $commit);
3665                 print "<div class=\"title_text\">\n" .
3666                       "<div class=\"log_link\">\n" .
3667                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
3668                       " | " .
3669                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
3670                       " | " .
3671                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
3672                       "<br/>\n" .
3673                       "</div>\n" .
3674                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
3675                       "</div>\n";
3676
3677                 print "<div class=\"log_body\">\n";
3678                 git_print_log($co{'comment'}, -final_empty_line=> 1);
3679                 print "</div>\n";
3680         }
3681         if ($#commitlist >= 100) {
3682                 print "<div class=\"page_nav\">\n";
3683                 print $cgi->a({-href => href(action=>"log", hash=>$hash, page=>$page+1),
3684                                -accesskey => "n", -title => "Alt-n"}, "next");
3685                 print "</div>\n";
3686         }
3687         git_footer_html();
3688 }
3689
3690 sub git_commit {
3691         $hash ||= $hash_base || "HEAD";
3692         my %co = parse_commit($hash);
3693         if (!%co) {
3694                 die_error(undef, "Unknown commit object");
3695         }
3696         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3697         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
3698
3699         my $parent  = $co{'parent'};
3700         my $parents = $co{'parents'}; # listref
3701
3702         # we need to prepare $formats_nav before any parameter munging
3703         my $formats_nav;
3704         if (!defined $parent) {
3705                 # --root commitdiff
3706                 $formats_nav .= '(initial)';
3707         } elsif (@$parents == 1) {
3708                 # single parent commit
3709                 $formats_nav .=
3710                         '(parent: ' .
3711                         $cgi->a({-href => href(action=>"commit",
3712                                                hash=>$parent)},
3713                                 esc_html(substr($parent, 0, 7))) .
3714                         ')';
3715         } else {
3716                 # merge commit
3717                 $formats_nav .=
3718                         '(merge: ' .
3719                         join(' ', map {
3720                                 $cgi->a({-href => href(action=>"commit",
3721                                                        hash=>$_)},
3722                                         esc_html(substr($_, 0, 7)));
3723                         } @$parents ) .
3724                         ')';
3725         }
3726
3727         if (!defined $parent) {
3728                 $parent = "--root";
3729         }
3730         my @difftree;
3731         if (@$parents <= 1) {
3732                 # difftree output is not printed for merges
3733                 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
3734                         @diff_opts, $parent, $hash, "--"
3735                                 or die_error(undef, "Open git-diff-tree failed");
3736                 @difftree = map { chomp; $_ } <$fd>;
3737                 close $fd or die_error(undef, "Reading git-diff-tree failed");
3738         }
3739
3740         # non-textual hash id's can be cached
3741         my $expires;
3742         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3743                 $expires = "+1d";
3744         }
3745         my $refs = git_get_references();
3746         my $ref = format_ref_marker($refs, $co{'id'});
3747
3748         my $have_snapshot = gitweb_have_snapshot();
3749
3750         git_header_html(undef, $expires);
3751         git_print_page_nav('commit', '',
3752                            $hash, $co{'tree'}, $hash,
3753                            $formats_nav);
3754
3755         if (defined $co{'parent'}) {
3756                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
3757         } else {
3758                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
3759         }
3760         print "<div class=\"title_text\">\n" .
3761               "<table cellspacing=\"0\">\n";
3762         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
3763               "<tr>" .
3764               "<td></td><td> $ad{'rfc2822'}";
3765         if ($ad{'hour_local'} < 6) {
3766                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3767                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3768         } else {
3769                 printf(" (%02d:%02d %s)",
3770                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3771         }
3772         print "</td>" .
3773               "</tr>\n";
3774         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
3775         print "<tr><td></td><td> $cd{'rfc2822'}" .
3776               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
3777               "</td></tr>\n";
3778         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
3779         print "<tr>" .
3780               "<td>tree</td>" .
3781               "<td class=\"sha1\">" .
3782               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
3783                        class => "list"}, $co{'tree'}) .
3784               "</td>" .
3785               "<td class=\"link\">" .
3786               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
3787                       "tree");
3788         if ($have_snapshot) {
3789                 print " | " .
3790                       $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
3791         }
3792         print "</td>" .
3793               "</tr>\n";
3794
3795         foreach my $par (@$parents) {
3796                 print "<tr>" .
3797                       "<td>parent</td>" .
3798                       "<td class=\"sha1\">" .
3799                       $cgi->a({-href => href(action=>"commit", hash=>$par),
3800                                class => "list"}, $par) .
3801                       "</td>" .
3802                       "<td class=\"link\">" .
3803                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
3804                       " | " .
3805                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
3806                       "</td>" .
3807                       "</tr>\n";
3808         }
3809         print "</table>".
3810               "</div>\n";
3811
3812         print "<div class=\"page_body\">\n";
3813         git_print_log($co{'comment'});
3814         print "</div>\n";
3815
3816         if (@$parents <= 1) {
3817                 # do not output difftree/whatchanged for merges
3818                 git_difftree_body(\@difftree, $hash, $parent);
3819         }
3820
3821         git_footer_html();
3822 }
3823
3824 sub git_object {
3825         # object is defined by:
3826         # - hash or hash_base alone
3827         # - hash_base and file_name
3828         my $type;
3829
3830         # - hash or hash_base alone
3831         if ($hash || ($hash_base && !defined $file_name)) {
3832                 my $object_id = $hash || $hash_base;
3833
3834                 my $git_command = git_cmd_str();
3835                 open my $fd, "-|", "$git_command cat-file -t $object_id 2>/dev/null"
3836                         or die_error('404 Not Found', "Object does not exist");
3837                 $type = <$fd>;
3838                 chomp $type;
3839                 close $fd
3840                         or die_error('404 Not Found', "Object does not exist");
3841
3842         # - hash_base and file_name
3843         } elsif ($hash_base && defined $file_name) {
3844                 $file_name =~ s,/+$,,;
3845
3846                 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
3847                         or die_error('404 Not Found', "Base object does not exist");
3848
3849                 # here errors should not hapen
3850                 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
3851                         or die_error(undef, "Open git-ls-tree failed");
3852                 my $line = <$fd>;
3853                 close $fd;
3854
3855                 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
3856                 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
3857                         die_error('404 Not Found', "File or directory for given base does not exist");
3858                 }
3859                 $type = $2;
3860                 $hash = $3;
3861         } else {
3862                 die_error('404 Not Found', "Not enough information to find object");
3863         }
3864
3865         print $cgi->redirect(-uri => href(action=>$type, -full=>1,
3866                                           hash=>$hash, hash_base=>$hash_base,
3867                                           file_name=>$file_name),
3868                              -status => '302 Found');
3869 }
3870
3871 sub git_blobdiff {
3872         my $format = shift || 'html';
3873
3874         my $fd;
3875         my @difftree;
3876         my %diffinfo;
3877         my $expires;
3878
3879         # preparing $fd and %diffinfo for git_patchset_body
3880         # new style URI
3881         if (defined $hash_base && defined $hash_parent_base) {
3882                 if (defined $file_name) {
3883                         # read raw output
3884                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3885                                 $hash_parent_base, $hash_base,
3886                                 "--", (defined $file_parent ? $file_parent : ()), $file_name
3887                                 or die_error(undef, "Open git-diff-tree failed");
3888                         @difftree = map { chomp; $_ } <$fd>;
3889                         close $fd
3890                                 or die_error(undef, "Reading git-diff-tree failed");
3891                         @difftree
3892                                 or die_error('404 Not Found', "Blob diff not found");
3893
3894                 } elsif (defined $hash &&
3895                          $hash =~ /[0-9a-fA-F]{40}/) {
3896                         # try to find filename from $hash
3897
3898                         # read filtered raw output
3899                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3900                                 $hash_parent_base, $hash_base, "--"
3901                                 or die_error(undef, "Open git-diff-tree failed");
3902                         @difftree =
3903                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
3904                                 # $hash == to_id
3905                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
3906                                 map { chomp; $_ } <$fd>;
3907                         close $fd
3908                                 or die_error(undef, "Reading git-diff-tree failed");
3909                         @difftree
3910                                 or die_error('404 Not Found', "Blob diff not found");
3911
3912                 } else {
3913                         die_error('404 Not Found', "Missing one of the blob diff parameters");
3914                 }
3915
3916                 if (@difftree > 1) {
3917                         die_error('404 Not Found', "Ambiguous blob diff specification");
3918                 }
3919
3920                 %diffinfo = parse_difftree_raw_line($difftree[0]);
3921                 $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
3922                 $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
3923
3924                 $hash_parent ||= $diffinfo{'from_id'};
3925                 $hash        ||= $diffinfo{'to_id'};
3926
3927                 # non-textual hash id's can be cached
3928                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
3929                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
3930                         $expires = '+1d';
3931                 }
3932
3933                 # open patch output
3934                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3935                         '-p', ($format eq 'html' ? "--full-index" : ()),
3936                         $hash_parent_base, $hash_base,
3937                         "--", (defined $file_parent ? $file_parent : ()), $file_name
3938                         or die_error(undef, "Open git-diff-tree failed");
3939         }
3940
3941         # old/legacy style URI
3942         if (!%diffinfo && # if new style URI failed
3943             defined $hash && defined $hash_parent) {
3944                 # fake git-diff-tree raw output
3945                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
3946                 $diffinfo{'from_id'} = $hash_parent;
3947                 $diffinfo{'to_id'}   = $hash;
3948                 if (defined $file_name) {
3949                         if (defined $file_parent) {
3950                                 $diffinfo{'status'} = '2';
3951                                 $diffinfo{'from_file'} = $file_parent;
3952                                 $diffinfo{'to_file'}   = $file_name;
3953                         } else { # assume not renamed
3954                                 $diffinfo{'status'} = '1';
3955                                 $diffinfo{'from_file'} = $file_name;
3956                                 $diffinfo{'to_file'}   = $file_name;
3957                         }
3958                 } else { # no filename given
3959                         $diffinfo{'status'} = '2';
3960                         $diffinfo{'from_file'} = $hash_parent;
3961                         $diffinfo{'to_file'}   = $hash;
3962                 }
3963
3964                 # non-textual hash id's can be cached
3965                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
3966                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3967                         $expires = '+1d';
3968                 }
3969
3970                 # open patch output
3971                 open $fd, "-|", git_cmd(), "diff", @diff_opts,
3972                         '-p', ($format eq 'html' ? "--full-index" : ()),
3973                         $hash_parent, $hash, "--"
3974                         or die_error(undef, "Open git-diff failed");
3975         } else  {
3976                 die_error('404 Not Found', "Missing one of the blob diff parameters")
3977                         unless %diffinfo;
3978         }
3979
3980         # header
3981         if ($format eq 'html') {
3982                 my $formats_nav =
3983                         $cgi->a({-href => href(action=>"blobdiff_plain",
3984                                                hash=>$hash, hash_parent=>$hash_parent,
3985                                                hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
3986                                                file_name=>$file_name, file_parent=>$file_parent)},
3987                                 "raw");
3988                 git_header_html(undef, $expires);
3989                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3990                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3991                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3992                 } else {
3993                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
3994                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
3995                 }
3996                 if (defined $file_name) {
3997                         git_print_page_path($file_name, "blob", $hash_base);
3998                 } else {
3999                         print "<div class=\"page_path\"></div>\n";
4000                 }
4001
4002         } elsif ($format eq 'plain') {
4003                 print $cgi->header(
4004                         -type => 'text/plain',
4005                         -charset => 'utf-8',
4006                         -expires => $expires,
4007                         -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
4008
4009                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4010
4011         } else {
4012                 die_error(undef, "Unknown blobdiff format");
4013         }
4014
4015         # patch
4016         if ($format eq 'html') {
4017                 print "<div class=\"page_body\">\n";
4018
4019                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
4020                 close $fd;
4021
4022                 print "</div>\n"; # class="page_body"
4023                 git_footer_html();
4024
4025         } else {
4026                 while (my $line = <$fd>) {
4027                         $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
4028                         $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
4029
4030                         print $line;
4031
4032                         last if $line =~ m!^\+\+\+!;
4033                 }
4034                 local $/ = undef;
4035                 print <$fd>;
4036                 close $fd;
4037         }
4038 }
4039
4040 sub git_blobdiff_plain {
4041         git_blobdiff('plain');
4042 }
4043
4044 sub git_commitdiff {
4045         my $format = shift || 'html';
4046         $hash ||= $hash_base || "HEAD";
4047         my %co = parse_commit($hash);
4048         if (!%co) {
4049                 die_error(undef, "Unknown commit object");
4050         }
4051
4052         # we need to prepare $formats_nav before any parameter munging
4053         my $formats_nav;
4054         if ($format eq 'html') {
4055                 $formats_nav =
4056                         $cgi->a({-href => href(action=>"commitdiff_plain",
4057                                                hash=>$hash, hash_parent=>$hash_parent)},
4058                                 "raw");
4059
4060                 if (defined $hash_parent) {
4061                         # commitdiff with two commits given
4062                         my $hash_parent_short = $hash_parent;
4063                         if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4064                                 $hash_parent_short = substr($hash_parent, 0, 7);
4065                         }
4066                         $formats_nav .=
4067                                 ' (from: ' .
4068                                 $cgi->a({-href => href(action=>"commitdiff",
4069                                                        hash=>$hash_parent)},
4070                                         esc_html($hash_parent_short)) .
4071                                 ')';
4072                 } elsif (!$co{'parent'}) {
4073                         # --root commitdiff
4074                         $formats_nav .= ' (initial)';
4075                 } elsif (scalar @{$co{'parents'}} == 1) {
4076                         # single parent commit
4077                         $formats_nav .=
4078                                 ' (parent: ' .
4079                                 $cgi->a({-href => href(action=>"commitdiff",
4080                                                        hash=>$co{'parent'})},
4081                                         esc_html(substr($co{'parent'}, 0, 7))) .
4082                                 ')';
4083                 } else {
4084                         # merge commit
4085                         $formats_nav .=
4086                                 ' (merge: ' .
4087                                 join(' ', map {
4088                                         $cgi->a({-href => href(action=>"commitdiff",
4089                                                                hash=>$_)},
4090                                                 esc_html(substr($_, 0, 7)));
4091                                 } @{$co{'parents'}} ) .
4092                                 ')';
4093                 }
4094         }
4095
4096         if (!defined $hash_parent) {
4097                 $hash_parent = $co{'parent'} || '--root';
4098         }
4099
4100         # read commitdiff
4101         my $fd;
4102         my @difftree;
4103         if ($format eq 'html') {
4104                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4105                         "--no-commit-id", "--patch-with-raw", "--full-index",
4106                         $hash_parent, $hash, "--"
4107                         or die_error(undef, "Open git-diff-tree failed");
4108
4109                 while (my $line = <$fd>) {
4110                         chomp $line;
4111                         # empty line ends raw part of diff-tree output
4112                         last unless $line;
4113                         push @difftree, $line;
4114                 }
4115
4116         } elsif ($format eq 'plain') {
4117                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4118                         '-p', $hash_parent, $hash, "--"
4119                         or die_error(undef, "Open git-diff-tree failed");
4120
4121         } else {
4122                 die_error(undef, "Unknown commitdiff format");
4123         }
4124
4125         # non-textual hash id's can be cached
4126         my $expires;
4127         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4128                 $expires = "+1d";
4129         }
4130
4131         # write commit message
4132         if ($format eq 'html') {
4133                 my $refs = git_get_references();
4134                 my $ref = format_ref_marker($refs, $co{'id'});
4135
4136                 git_header_html(undef, $expires);
4137                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
4138                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
4139                 git_print_authorship(\%co);
4140                 print "<div class=\"page_body\">\n";
4141                 if (@{$co{'comment'}} > 1) {
4142                         print "<div class=\"log\">\n";
4143                         git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
4144                         print "</div>\n"; # class="log"
4145                 }
4146
4147         } elsif ($format eq 'plain') {
4148                 my $refs = git_get_references("tags");
4149                 my $tagname = git_get_rev_name_tags($hash);
4150                 my $filename = basename($project) . "-$hash.patch";
4151
4152                 print $cgi->header(
4153                         -type => 'text/plain',
4154                         -charset => 'utf-8',
4155                         -expires => $expires,
4156                         -content_disposition => 'inline; filename="' . "$filename" . '"');
4157                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4158                 print <<TEXT;
4159 From: $co{'author'}
4160 Date: $ad{'rfc2822'} ($ad{'tz_local'})
4161 Subject: $co{'title'}
4162 TEXT
4163                 print "X-Git-Tag: $tagname\n" if $tagname;
4164                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4165
4166                 foreach my $line (@{$co{'comment'}}) {
4167                         print "$line\n";
4168                 }
4169                 print "---\n\n";
4170         }
4171
4172         # write patch
4173         if ($format eq 'html') {
4174                 git_difftree_body(\@difftree, $hash, $hash_parent);
4175                 print "<br/>\n";
4176
4177                 git_patchset_body($fd, \@difftree, $hash, $hash_parent);
4178                 close $fd;
4179                 print "</div>\n"; # class="page_body"
4180                 git_footer_html();
4181
4182         } elsif ($format eq 'plain') {
4183                 local $/ = undef;
4184                 print <$fd>;
4185                 close $fd
4186                         or print "Reading git-diff-tree failed\n";
4187         }
4188 }
4189
4190 sub git_commitdiff_plain {
4191         git_commitdiff('plain');
4192 }
4193
4194 sub git_history {
4195         if (!defined $hash_base) {
4196                 $hash_base = git_get_head_hash($project);
4197         }
4198         if (!defined $page) {
4199                 $page = 0;
4200         }
4201         my $ftype;
4202         my %co = parse_commit($hash_base);
4203         if (!%co) {
4204                 die_error(undef, "Unknown commit object");
4205         }
4206
4207         my $refs = git_get_references();
4208         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
4209
4210         if (!defined $hash && defined $file_name) {
4211                 $hash = git_get_hash_by_path($hash_base, $file_name);
4212         }
4213         if (defined $hash) {
4214                 $ftype = git_get_type($hash);
4215         }
4216
4217         my @commitlist = parse_commits($hash_base, 101, (100 * $page), "--full-history", $file_name);
4218
4219         my $paging_nav = '';
4220         if ($page > 0) {
4221                 $paging_nav .=
4222                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4223                                                file_name=>$file_name)},
4224                                 "first");
4225                 $paging_nav .= " &sdot; " .
4226                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4227                                                file_name=>$file_name, page=>$page-1),
4228                                  -accesskey => "p", -title => "Alt-p"}, "prev");
4229         } else {
4230                 $paging_nav .= "first";
4231                 $paging_nav .= " &sdot; prev";
4232         }
4233         if ($#commitlist >= 100) {
4234                 $paging_nav .= " &sdot; " .
4235                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4236                                                file_name=>$file_name, page=>$page+1),
4237                                  -accesskey => "n", -title => "Alt-n"}, "next");
4238         } else {
4239                 $paging_nav .= " &sdot; next";
4240         }
4241         my $next_link = '';
4242         if ($#commitlist >= 100) {
4243                 $next_link =
4244                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4245                                                file_name=>$file_name, page=>$page+1),
4246                                  -accesskey => "n", -title => "Alt-n"}, "next");
4247         }
4248
4249         git_header_html();
4250         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
4251         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4252         git_print_page_path($file_name, $ftype, $hash_base);
4253
4254         git_history_body(\@commitlist, 0, 99,
4255                          $refs, $hash_base, $ftype, $next_link);
4256
4257         git_footer_html();
4258 }
4259
4260 sub git_search {
4261         my ($have_search) = gitweb_check_feature('search');
4262         if (!$have_search) {
4263                 die_error('403 Permission denied', "Permission denied");
4264         }
4265         if (!defined $searchtext) {
4266                 die_error(undef, "Text field empty");
4267         }
4268         if (!defined $hash) {
4269                 $hash = git_get_head_hash($project);
4270         }
4271         my %co = parse_commit($hash);
4272         if (!%co) {
4273                 die_error(undef, "Unknown commit object");
4274         }
4275         if (!defined $page) {
4276                 $page = 0;
4277         }
4278
4279         $searchtype ||= 'commit';
4280         if ($searchtype eq 'pickaxe') {
4281                 # pickaxe may take all resources of your box and run for several minutes
4282                 # with every query - so decide by yourself how public you make this feature
4283                 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
4284                 if (!$have_pickaxe) {
4285                         die_error('403 Permission denied', "Permission denied");
4286                 }
4287         }
4288
4289         git_header_html();
4290
4291         if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
4292                 my $greptype;
4293                 if ($searchtype eq 'commit') {
4294                         $greptype = "--grep=";
4295                 } elsif ($searchtype eq 'author') {
4296                         $greptype = "--author=";
4297                 } elsif ($searchtype eq 'committer') {
4298                         $greptype = "--committer=";
4299                 }
4300                 $greptype .= $searchtext;
4301                 my @commitlist = parse_commits($hash, 101, (100 * $page), $greptype);
4302
4303                 my $paging_nav = '';
4304                 if ($page > 0) {
4305                         $paging_nav .=
4306                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
4307                                                        searchtext=>$searchtext, searchtype=>$searchtype)},
4308                                         "first");
4309                         $paging_nav .= " &sdot; " .
4310                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
4311                                                        searchtext=>$searchtext, searchtype=>$searchtype,
4312                                                        page=>$page-1),
4313                                          -accesskey => "p", -title => "Alt-p"}, "prev");
4314                 } else {
4315                         $paging_nav .= "first";
4316                         $paging_nav .= " &sdot; prev";
4317                 }
4318                 if ($#commitlist >= 100) {
4319                         $paging_nav .= " &sdot; " .
4320                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
4321                                                        searchtext=>$searchtext, searchtype=>$searchtype,
4322                                                        page=>$page+1),
4323                                          -accesskey => "n", -title => "Alt-n"}, "next");
4324                 } else {
4325                         $paging_nav .= " &sdot; next";
4326                 }
4327                 my $next_link = '';
4328                 if ($#commitlist >= 100) {
4329                         $next_link =
4330                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
4331                                                        searchtext=>$searchtext, searchtype=>$searchtype,
4332                                                        page=>$page+1),
4333                                          -accesskey => "n", -title => "Alt-n"}, "next");
4334                 }
4335
4336                 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
4337                 git_print_header_div('commit', esc_html($co{'title'}), $hash);
4338                 git_search_grep_body(\@commitlist, 0, 99, $next_link);
4339         }
4340
4341         if ($searchtype eq 'pickaxe') {
4342                 git_print_page_nav('','', $hash,$co{'tree'},$hash);
4343                 git_print_header_div('commit', esc_html($co{'title'}), $hash);
4344
4345                 print "<table cellspacing=\"0\">\n";
4346                 my $alternate = 1;
4347                 $/ = "\n";
4348                 my $git_command = git_cmd_str();
4349                 open my $fd, "-|", "$git_command rev-list $hash | " .
4350                         "$git_command diff-tree -r --stdin -S\'$searchtext\'";
4351                 undef %co;
4352                 my @files;
4353                 while (my $line = <$fd>) {
4354                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
4355                                 my %set;
4356                                 $set{'file'} = $6;
4357                                 $set{'from_id'} = $3;
4358                                 $set{'to_id'} = $4;
4359                                 $set{'id'} = $set{'to_id'};
4360                                 if ($set{'id'} =~ m/0{40}/) {
4361                                         $set{'id'} = $set{'from_id'};
4362                                 }
4363                                 if ($set{'id'} =~ m/0{40}/) {
4364                                         next;
4365                                 }
4366                                 push @files, \%set;
4367                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
4368                                 if (%co) {
4369                                         if ($alternate) {
4370                                                 print "<tr class=\"dark\">\n";
4371                                         } else {
4372                                                 print "<tr class=\"light\">\n";
4373                                         }
4374                                         $alternate ^= 1;
4375                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4376                                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
4377                                               "<td>" .
4378                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4379                                                       -class => "list subject"},
4380                                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
4381                                         while (my $setref = shift @files) {
4382                                                 my %set = %$setref;
4383                                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
4384                                                                              hash=>$set{'id'}, file_name=>$set{'file'}),
4385                                                               -class => "list"},
4386                                                               "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
4387                                                       "<br/>\n";
4388                                         }
4389                                         print "</td>\n" .
4390                                               "<td class=\"link\">" .
4391                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4392                                               " | " .
4393                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4394                                         print "</td>\n" .
4395                                               "</tr>\n";
4396                                 }
4397                                 %co = parse_commit($1);
4398                         }
4399                 }
4400                 close $fd;
4401
4402                 print "</table>\n";
4403         }
4404         git_footer_html();
4405 }
4406
4407 sub git_search_help {
4408         git_header_html();
4409         git_print_page_nav('','', $hash,$hash,$hash);
4410         print <<EOT;
4411 <dl>
4412 <dt><b>commit</b></dt>
4413 <dd>The commit messages and authorship information will be scanned for the given string.</dd>
4414 <dt><b>author</b></dt>
4415 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given string.</dd>
4416 <dt><b>committer</b></dt>
4417 <dd>Name and e-mail of the committer and date of commit will be scanned for the given string.</dd>
4418 EOT
4419         my ($have_pickaxe) = gitweb_check_feature('pickaxe');
4420         if ($have_pickaxe) {
4421                 print <<EOT;
4422 <dt><b>pickaxe</b></dt>
4423 <dd>All commits that caused the string to appear or disappear from any file (changes that
4424 added, removed or "modified" the string) will be listed. This search can take a while and
4425 takes a lot of strain on the server, so please use it wisely.</dd>
4426 EOT
4427         }
4428         print "</dl>\n";
4429         git_footer_html();
4430 }
4431
4432 sub git_shortlog {
4433         my $head = git_get_head_hash($project);
4434         if (!defined $hash) {
4435                 $hash = $head;
4436         }
4437         if (!defined $page) {
4438                 $page = 0;
4439         }
4440         my $refs = git_get_references();
4441
4442         my @commitlist = parse_commits($hash, 101, (100 * $page));
4443
4444         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, (100 * ($page+1)));
4445         my $next_link = '';
4446         if ($#commitlist >= 100) {
4447                 $next_link =
4448                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
4449                                  -accesskey => "n", -title => "Alt-n"}, "next");
4450         }
4451
4452         git_header_html();
4453         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
4454         git_print_header_div('summary', $project);
4455
4456         git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
4457
4458         git_footer_html();
4459 }
4460
4461 ## ......................................................................
4462 ## feeds (RSS, Atom; OPML)
4463
4464 sub git_feed {
4465         my $format = shift || 'atom';
4466         my ($have_blame) = gitweb_check_feature('blame');
4467
4468         # Atom: http://www.atomenabled.org/developers/syndication/
4469         # RSS:  http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
4470         if ($format ne 'rss' && $format ne 'atom') {
4471                 die_error(undef, "Unknown web feed format");
4472         }
4473
4474         # log/feed of current (HEAD) branch, log of given branch, history of file/directory
4475         my $head = $hash || 'HEAD';
4476         my @commitlist = parse_commits($head, 150);
4477
4478         my %latest_commit;
4479         my %latest_date;
4480         my $content_type = "application/$format+xml";
4481         if (defined $cgi->http('HTTP_ACCEPT') &&
4482                  $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
4483                 # browser (feed reader) prefers text/xml
4484                 $content_type = 'text/xml';
4485         }
4486         if (defined($commitlist[0])) {
4487                 %latest_commit = %{$commitlist[0]};
4488                 %latest_date   = parse_date($latest_commit{'author_epoch'});
4489                 print $cgi->header(
4490                         -type => $content_type,
4491                         -charset => 'utf-8',
4492                         -last_modified => $latest_date{'rfc2822'});
4493         } else {
4494                 print $cgi->header(
4495                         -type => $content_type,
4496                         -charset => 'utf-8');
4497         }
4498
4499         # Optimization: skip generating the body if client asks only
4500         # for Last-Modified date.
4501         return if ($cgi->request_method() eq 'HEAD');
4502
4503         # header variables
4504         my $title = "$site_name - $project/$action";
4505         my $feed_type = 'log';
4506         if (defined $hash) {
4507                 $title .= " - '$hash'";
4508                 $feed_type = 'branch log';
4509                 if (defined $file_name) {
4510                         $title .= " :: $file_name";
4511                         $feed_type = 'history';
4512                 }
4513         } elsif (defined $file_name) {
4514                 $title .= " - $file_name";
4515                 $feed_type = 'history';
4516         }
4517         $title .= " $feed_type";
4518         my $descr = git_get_project_description($project);
4519         if (defined $descr) {
4520                 $descr = esc_html($descr);
4521         } else {
4522                 $descr = "$project " .
4523                          ($format eq 'rss' ? 'RSS' : 'Atom') .
4524                          " feed";
4525         }
4526         my $owner = git_get_project_owner($project);
4527         $owner = esc_html($owner);
4528
4529         #header
4530         my $alt_url;
4531         if (defined $file_name) {
4532                 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
4533         } elsif (defined $hash) {
4534                 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
4535         } else {
4536                 $alt_url = href(-full=>1, action=>"summary");
4537         }
4538         print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
4539         if ($format eq 'rss') {
4540                 print <<XML;
4541 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
4542 <channel>
4543 XML
4544                 print "<title>$title</title>\n" .
4545                       "<link>$alt_url</link>\n" .
4546                       "<description>$descr</description>\n" .
4547                       "<language>en</language>\n";
4548         } elsif ($format eq 'atom') {
4549                 print <<XML;
4550 <feed xmlns="http://www.w3.org/2005/Atom">
4551 XML
4552                 print "<title>$title</title>\n" .
4553                       "<subtitle>$descr</subtitle>\n" .
4554                       '<link rel="alternate" type="text/html" href="' .
4555                       $alt_url . '" />' . "\n" .
4556                       '<link rel="self" type="' . $content_type . '" href="' .
4557                       $cgi->self_url() . '" />' . "\n" .
4558                       "<id>" . href(-full=>1) . "</id>\n" .
4559                       # use project owner for feed author
4560                       "<author><name>$owner</name></author>\n";
4561                 if (defined $favicon) {
4562                         print "<icon>" . esc_url($favicon) . "</icon>\n";
4563                 }
4564                 if (defined $logo_url) {
4565                         # not twice as wide as tall: 72 x 27 pixels
4566                         print "<logo>" . esc_url($logo) . "</logo>\n";
4567                 }
4568                 if (! %latest_date) {
4569                         # dummy date to keep the feed valid until commits trickle in:
4570                         print "<updated>1970-01-01T00:00:00Z</updated>\n";
4571                 } else {
4572                         print "<updated>$latest_date{'iso-8601'}</updated>\n";
4573                 }
4574         }
4575
4576         # contents
4577         for (my $i = 0; $i <= $#commitlist; $i++) {
4578                 my %co = %{$commitlist[$i]};
4579                 my $commit = $co{'id'};
4580                 # we read 150, we always show 30 and the ones more recent than 48 hours
4581                 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
4582                         last;
4583                 }
4584                 my %cd = parse_date($co{'author_epoch'});
4585
4586                 # get list of changed files
4587                 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4588                         $co{'parent'}, $co{'id'}, "--", (defined $file_name ? $file_name : ())
4589                         or next;
4590                 my @difftree = map { chomp; $_ } <$fd>;
4591                 close $fd
4592                         or next;
4593
4594                 # print element (entry, item)
4595                 my $co_url = href(-full=>1, action=>"commit", hash=>$commit);
4596                 if ($format eq 'rss') {
4597                         print "<item>\n" .
4598                               "<title>" . esc_html($co{'title'}) . "</title>\n" .
4599                               "<author>" . esc_html($co{'author'}) . "</author>\n" .
4600                               "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
4601                               "<guid isPermaLink=\"true\">$co_url</guid>\n" .
4602                               "<link>$co_url</link>\n" .
4603                               "<description>" . esc_html($co{'title'}) . "</description>\n" .
4604                               "<content:encoded>" .
4605                               "<![CDATA[\n";
4606                 } elsif ($format eq 'atom') {
4607                         print "<entry>\n" .
4608                               "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
4609                               "<updated>$cd{'iso-8601'}</updated>\n" .
4610                               "<author>\n" .
4611                               "  <name>" . esc_html($co{'author_name'}) . "</name>\n";
4612                         if ($co{'author_email'}) {
4613                                 print "  <email>" . esc_html($co{'author_email'}) . "</email>\n";
4614                         }
4615                         print "</author>\n" .
4616                               # use committer for contributor
4617                               "<contributor>\n" .
4618                               "  <name>" . esc_html($co{'committer_name'}) . "</name>\n";
4619                         if ($co{'committer_email'}) {
4620                                 print "  <email>" . esc_html($co{'committer_email'}) . "</email>\n";
4621                         }
4622                         print "</contributor>\n" .
4623                               "<published>$cd{'iso-8601'}</published>\n" .
4624                               "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
4625                               "<id>$co_url</id>\n" .
4626                               "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
4627                               "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
4628                 }
4629                 my $comment = $co{'comment'};
4630                 print "<pre>\n";
4631                 foreach my $line (@$comment) {
4632                         $line = esc_html($line);
4633                         print "$line\n";
4634                 }
4635                 print "</pre><ul>\n";
4636                 foreach my $difftree_line (@difftree) {
4637                         my %difftree = parse_difftree_raw_line($difftree_line);
4638                         next if !$difftree{'from_id'};
4639
4640                         my $file = $difftree{'file'} || $difftree{'to_file'};
4641
4642                         print "<li>" .
4643                               "[" .
4644                               $cgi->a({-href => href(-full=>1, action=>"blobdiff",
4645                                                      hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
4646                                                      hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
4647                                                      file_name=>$file, file_parent=>$difftree{'from_file'}),
4648                                       -title => "diff"}, 'D');
4649                         if ($have_blame) {
4650                                 print $cgi->a({-href => href(-full=>1, action=>"blame",
4651                                                              file_name=>$file, hash_base=>$commit),
4652                                               -title => "blame"}, 'B');
4653                         }
4654                         # if this is not a feed of a file history
4655                         if (!defined $file_name || $file_name ne $file) {
4656                                 print $cgi->a({-href => href(-full=>1, action=>"history",
4657                                                              file_name=>$file, hash=>$commit),
4658                                               -title => "history"}, 'H');
4659                         }
4660                         $file = esc_path($file);
4661                         print "] ".
4662                               "$file</li>\n";
4663                 }
4664                 if ($format eq 'rss') {
4665                         print "</ul>]]>\n" .
4666                               "</content:encoded>\n" .
4667                               "</item>\n";
4668                 } elsif ($format eq 'atom') {
4669                         print "</ul>\n</div>\n" .
4670                               "</content>\n" .
4671                               "</entry>\n";
4672                 }
4673         }
4674
4675         # end of feed
4676         if ($format eq 'rss') {
4677                 print "</channel>\n</rss>\n";
4678         }       elsif ($format eq 'atom') {
4679                 print "</feed>\n";
4680         }
4681 }
4682
4683 sub git_rss {
4684         git_feed('rss');
4685 }
4686
4687 sub git_atom {
4688         git_feed('atom');
4689 }
4690
4691 sub git_opml {
4692         my @list = git_get_projects_list();
4693
4694         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
4695         print <<XML;
4696 <?xml version="1.0" encoding="utf-8"?>
4697 <opml version="1.0">
4698 <head>
4699   <title>$site_name OPML Export</title>
4700 </head>
4701 <body>
4702 <outline text="git RSS feeds">
4703 XML
4704
4705         foreach my $pr (@list) {
4706                 my %proj = %$pr;
4707                 my $head = git_get_head_hash($proj{'path'});
4708                 if (!defined $head) {
4709                         next;
4710                 }
4711                 $git_dir = "$projectroot/$proj{'path'}";
4712                 my %co = parse_commit($head);
4713                 if (!%co) {
4714                         next;
4715                 }
4716
4717                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
4718                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
4719                 my $html = "$my_url?p=$proj{'path'};a=summary";
4720                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
4721         }
4722         print <<XML;
4723 </outline>
4724 </body>
4725 </opml>
4726 XML
4727 }