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