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