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