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