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