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