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