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