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