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