Code

gitweb: Use character or octal escape codes (and add span.cntrl) in esc_path
[git.git] / gitweb / gitweb.perl
1 #!/usr/bin/perl
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
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';
21 our $cgi = new CGI;
22 our $version = "++GIT_VERSION++";
23 our $my_url = $cgi->url();
24 our $my_uri = $cgi->url(-absolute => 1);
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";
30 # absolute fs-path which will be prepended to the project path
31 #our $projectroot = "/pub/scm";
32 our $projectroot = "++GITWEB_PROJECTROOT++";
34 # target of the home link on top of all pages
35 our $home_link = $my_uri || "/";
37 # string of the home link on top of all pages
38 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
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";
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++";
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++";
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";
67 # source of projects list
68 our $projects_list = "++GITWEB_LIST++";
70 # show repository only if this file exists
71 # (only effective if this variable evaluates to true)
72 our $export_ok = "++GITWEB_EXPORT_OK++";
74 # only allow viewing of repositories also shown on the overview page
75 our $strict_export = "++GITWEB_STRICT_EXPORT++";
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++");
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;
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;
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
103         # Enable the 'blame' blob view, showing the last commit that modified
104         # each line in the file. This can be very CPU-intensive.
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]},
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.
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{'blame'}{'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']},
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.
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]},
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.
152         # To enable system wide have in $GITWEB_CONFIG
153         # $feature{'pathinfo'}{'default'} = [1];
154         # Project specific override is not supported.
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]},
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.
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 );
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);
195 sub feature_blame {
196         my ($val) = git_get_project_config('blame', '--bool');
198         if ($val eq 'true') {
199                 return 1;
200         } elsif ($val eq 'false') {
201                 return 0;
202         }
204         return $_[0];
207 sub feature_snapshot {
208         my ($ctype, $suffix, $command) = @_;
210         my ($val) = git_get_project_config('snapshot');
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         }
220         return ($ctype, $suffix, $command);
223 sub gitweb_have_snapshot {
224         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
225         my $have_snapshot = (defined $ctype && defined $suffix);
227         return $have_snapshot;
230 sub feature_pickaxe {
231         my ($val) = git_get_project_config('pickaxe', '--bool');
233         if ($val eq 'true') {
234                 return (1);
235         } elsif ($val eq 'false') {
236                 return (0);
237         }
239         return ($_[0]);
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\//));
252 sub check_export_ok {
253         my ($dir) = @_;
254         return (check_head_link($dir) &&
255                 (!$export_ok || -e "$dir/$export_ok"));
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
268 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
269 do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
271 # version of the core git binary
272 our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
274 $projects_list ||= $projectroot;
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         }
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         }
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         }
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         }
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         }
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         }
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         }
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         }
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         }
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;
357 our $searchtype = $cgi->param('st');
358 if (defined $searchtype) {
359         if ($searchtype =~ m/[^a-z]/) {
360                 die_error(undef, "Invalid searchtype parameter");
361         }
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         }
407 evaluate_path_info();
409 # path to the current git repository
410 our $git_dir;
411 $git_dir = "$projectroot/$project" if $project;
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         "search" => \&git_search,
429         "search_help" => \&git_search_help,
430         "shortlog" => \&git_shortlog,
431         "summary" => \&git_summary,
432         "tag" => \&git_tag,
433         "tags" => \&git_tags,
434         "tree" => \&git_tree,
435         "snapshot" => \&git_snapshot,
436         # those below don't need $project
437         "opml" => \&git_opml,
438         "project_list" => \&git_project_list,
439         "project_index" => \&git_project_index,
440 );
442 if (defined $project) {
443         $action ||= 'summary';
444 } else {
445         $action ||= 'project_list';
447 if (!defined($actions{$action})) {
448         die_error(undef, "Unknown action");
450 if ($action !~ m/^(opml|project_list|project_index)$/ &&
451     !$project) {
452         die_error(undef, "Project needed");
454 $actions{$action}->();
455 exit;
457 ## ======================================================================
458 ## action links
460 sub href(%) {
461         my %params = @_;
462         my $href = $my_uri;
464         # XXX: Warning: If you touch this, check the search form for updating,
465         # too.
467         my @mapping = (
468                 project => "p",
469                 action => "a",
470                 file_name => "f",
471                 file_parent => "fp",
472                 hash => "h",
473                 hash_parent => "hp",
474                 hash_base => "hb",
475                 hash_parent_base => "hpb",
476                 page => "pg",
477                 order => "o",
478                 searchtext => "s",
479                 searchtype => "st",
480         );
481         my %mapping = @mapping;
483         $params{'project'} = $project unless exists $params{'project'};
485         my ($use_pathinfo) = gitweb_check_feature('pathinfo');
486         if ($use_pathinfo) {
487                 # use PATH_INFO for project name
488                 $href .= "/$params{'project'}" if defined $params{'project'};
489                 delete $params{'project'};
491                 # Summary just uses the project path URL
492                 if (defined $params{'action'} && $params{'action'} eq 'summary') {
493                         delete $params{'action'};
494                 }
495         }
497         # now encode the parameters explicitly
498         my @result = ();
499         for (my $i = 0; $i < @mapping; $i += 2) {
500                 my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
501                 if (defined $params{$name}) {
502                         push @result, $symbol . "=" . esc_param($params{$name});
503                 }
504         }
505         $href .= "?" . join(';', @result) if scalar @result;
507         return $href;
511 ## ======================================================================
512 ## validation, quoting/unquoting and escaping
514 sub validate_pathname {
515         my $input = shift || return undef;
517         # no '.' or '..' as elements of path, i.e. no '.' nor '..'
518         # at the beginning, at the end, and between slashes.
519         # also this catches doubled slashes
520         if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
521                 return undef;
522         }
523         # no null characters
524         if ($input =~ m!\0!) {
525                 return undef;
526         }
527         return $input;
530 sub validate_refname {
531         my $input = shift || return undef;
533         # textual hashes are O.K.
534         if ($input =~ m/^[0-9a-fA-F]{40}$/) {
535                 return $input;
536         }
537         # it must be correct pathname
538         $input = validate_pathname($input)
539                 or return undef;
540         # restrictions on ref name according to git-check-ref-format
541         if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
542                 return undef;
543         }
544         return $input;
547 # very thin wrapper for decode("utf8", $str, Encode::FB_DEFAULT);
548 sub to_utf8 {
549         my $str = shift;
550         return decode("utf8", $str, Encode::FB_DEFAULT);
553 # quote unsafe chars, but keep the slash, even when it's not
554 # correct, but quoted slashes look too horrible in bookmarks
555 sub esc_param {
556         my $str = shift;
557         $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
558         $str =~ s/\+/%2B/g;
559         $str =~ s/ /\+/g;
560         return $str;
563 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
564 sub esc_url {
565         my $str = shift;
566         $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
567         $str =~ s/\+/%2B/g;
568         $str =~ s/ /\+/g;
569         return $str;
572 # replace invalid utf8 character with SUBSTITUTION sequence
573 sub esc_html ($;%) {
574         my $str = shift;
575         my %opts = @_;
577         $str = to_utf8($str);
578         $str = escapeHTML($str);
579         $str =~ s/\014/^L/g; # escape FORM FEED (FF) character (e.g. in COPYING file)
580         $str =~ s/\033/^[/g; # "escape" ESCAPE (\e) character (e.g. commit 20a3847d8a5032ce41f90dcc68abfb36e6fee9b1)
581         if ($opts{'-nbsp'}) {
582                 $str =~ s/ /&nbsp;/g;
583         }
584         return $str;
587 # Make control characterss "printable".
588 sub quot_cec {
589         my $cntrl = shift;
590         my %es = ( # character escape codes, aka escape sequences
591                    "\t" => '\t',   # tab            (HT)
592                    "\n" => '\n',   # line feed      (LF)
593                    "\r" => '\r',   # carrige return (CR)
594                    "\f" => '\f',   # form feed      (FF)
595                    "\b" => '\b',   # backspace      (BS)
596                    "\a" => '\a',   # alarm (bell)   (BEL)
597                    "\e" => '\e',   # escape         (ESC)
598                    "\013" => '\v', # vertical tab   (VT)
599                    "\000" => '\0', # nul character  (NUL)
600                    );
601         my $chr = ( (exists $es{$cntrl})
602                     ? $es{$cntrl}
603                     : sprintf('\%03o', ord($cntrl)) );
604         return "<span class=\"cntrl\">$chr</span>";
607 # Alternatively use unicode control pictures codepoints.
608 sub quot_upr {
609         my $cntrl = shift;
610         my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
611         return "<span class=\"cntrl\">$chr</span>";
614 # quote control characters and escape filename to HTML
615 sub esc_path {
616         my $str = shift;
618         $str = esc_html($str);
619         $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
620         return $str;
623 # git may return quoted and escaped filenames
624 sub unquote {
625         my $str = shift;
627         sub unq {
628                 my $seq = shift;
629                 my %es = ( # character escape codes, aka escape sequences
630                         't' => "\t",   # tab            (HT, TAB)
631                         'n' => "\n",   # newline        (NL)
632                         'r' => "\r",   # return         (CR)
633                         'f' => "\f",   # form feed      (FF)
634                         'b' => "\b",   # backspace      (BS)
635                         'a' => "\a",   # alarm (bell)   (BEL)
636                         'e' => "\e",   # escape         (ESC)
637                         'v' => "\013", # vertical tab   (VT)
638                 );
640                 if ($seq =~ m/^[0-7]{1,3}$/) {
641                         # octal char sequence
642                         return chr(oct($seq));
643                 } elsif (exists $es{$seq}) {
644                         # C escape sequence, aka character escape code
645                         return $es{$seq}
646                 }
647                 # quoted ordinary character
648                 return $seq;
649         }
651         if ($str =~ m/^"(.*)"$/) {
652                 # needs unquoting
653                 $str = $1;
654                 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
655         }
656         return $str;
659 # escape tabs (convert tabs to spaces)
660 sub untabify {
661         my $line = shift;
663         while ((my $pos = index($line, "\t")) != -1) {
664                 if (my $count = (8 - ($pos % 8))) {
665                         my $spaces = ' ' x $count;
666                         $line =~ s/\t/$spaces/;
667                 }
668         }
670         return $line;
673 sub project_in_list {
674         my $project = shift;
675         my @list = git_get_projects_list();
676         return @list && scalar(grep { $_->{'path'} eq $project } @list);
679 ## ----------------------------------------------------------------------
680 ## HTML aware string manipulation
682 sub chop_str {
683         my $str = shift;
684         my $len = shift;
685         my $add_len = shift || 10;
687         # allow only $len chars, but don't cut a word if it would fit in $add_len
688         # if it doesn't fit, cut it if it's still longer than the dots we would add
689         $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
690         my $body = $1;
691         my $tail = $2;
692         if (length($tail) > 4) {
693                 $tail = " ...";
694                 $body =~ s/&[^;]*$//; # remove chopped character entities
695         }
696         return "$body$tail";
699 ## ----------------------------------------------------------------------
700 ## functions returning short strings
702 # CSS class for given age value (in seconds)
703 sub age_class {
704         my $age = shift;
706         if ($age < 60*60*2) {
707                 return "age0";
708         } elsif ($age < 60*60*24*2) {
709                 return "age1";
710         } else {
711                 return "age2";
712         }
715 # convert age in seconds to "nn units ago" string
716 sub age_string {
717         my $age = shift;
718         my $age_str;
720         if ($age > 60*60*24*365*2) {
721                 $age_str = (int $age/60/60/24/365);
722                 $age_str .= " years ago";
723         } elsif ($age > 60*60*24*(365/12)*2) {
724                 $age_str = int $age/60/60/24/(365/12);
725                 $age_str .= " months ago";
726         } elsif ($age > 60*60*24*7*2) {
727                 $age_str = int $age/60/60/24/7;
728                 $age_str .= " weeks ago";
729         } elsif ($age > 60*60*24*2) {
730                 $age_str = int $age/60/60/24;
731                 $age_str .= " days ago";
732         } elsif ($age > 60*60*2) {
733                 $age_str = int $age/60/60;
734                 $age_str .= " hours ago";
735         } elsif ($age > 60*2) {
736                 $age_str = int $age/60;
737                 $age_str .= " min ago";
738         } elsif ($age > 2) {
739                 $age_str = int $age;
740                 $age_str .= " sec ago";
741         } else {
742                 $age_str .= " right now";
743         }
744         return $age_str;
747 # convert file mode in octal to symbolic file mode string
748 sub mode_str {
749         my $mode = oct shift;
751         if (S_ISDIR($mode & S_IFMT)) {
752                 return 'drwxr-xr-x';
753         } elsif (S_ISLNK($mode)) {
754                 return 'lrwxrwxrwx';
755         } elsif (S_ISREG($mode)) {
756                 # git cares only about the executable bit
757                 if ($mode & S_IXUSR) {
758                         return '-rwxr-xr-x';
759                 } else {
760                         return '-rw-r--r--';
761                 };
762         } else {
763                 return '----------';
764         }
767 # convert file mode in octal to file type string
768 sub file_type {
769         my $mode = shift;
771         if ($mode !~ m/^[0-7]+$/) {
772                 return $mode;
773         } else {
774                 $mode = oct $mode;
775         }
777         if (S_ISDIR($mode & S_IFMT)) {
778                 return "directory";
779         } elsif (S_ISLNK($mode)) {
780                 return "symlink";
781         } elsif (S_ISREG($mode)) {
782                 return "file";
783         } else {
784                 return "unknown";
785         }
788 ## ----------------------------------------------------------------------
789 ## functions returning short HTML fragments, or transforming HTML fragments
790 ## which don't beling to other sections
792 # format line of commit message or tag comment
793 sub format_log_line_html {
794         my $line = shift;
796         $line = esc_html($line);
797         $line =~ s/ /&nbsp;/g;
798         if ($line =~ m/([0-9a-fA-F]{40})/) {
799                 my $hash_text = $1;
800                 if (git_get_type($hash_text) eq "commit") {
801                         my $link =
802                                 $cgi->a({-href => href(action=>"commit", hash=>$hash_text),
803                                         -class => "text"}, $hash_text);
804                         $line =~ s/$hash_text/$link/;
805                 }
806         }
807         return $line;
810 # format marker of refs pointing to given object
811 sub format_ref_marker {
812         my ($refs, $id) = @_;
813         my $markers = '';
815         if (defined $refs->{$id}) {
816                 foreach my $ref (@{$refs->{$id}}) {
817                         my ($type, $name) = qw();
818                         # e.g. tags/v2.6.11 or heads/next
819                         if ($ref =~ m!^(.*?)s?/(.*)$!) {
820                                 $type = $1;
821                                 $name = $2;
822                         } else {
823                                 $type = "ref";
824                                 $name = $ref;
825                         }
827                         $markers .= " <span class=\"$type\">" . esc_html($name) . "</span>";
828                 }
829         }
831         if ($markers) {
832                 return ' <span class="refs">'. $markers . '</span>';
833         } else {
834                 return "";
835         }
838 # format, perhaps shortened and with markers, title line
839 sub format_subject_html {
840         my ($long, $short, $href, $extra) = @_;
841         $extra = '' unless defined($extra);
843         if (length($short) < length($long)) {
844                 return $cgi->a({-href => $href, -class => "list subject",
845                                 -title => to_utf8($long)},
846                        esc_html($short) . $extra);
847         } else {
848                 return $cgi->a({-href => $href, -class => "list subject"},
849                        esc_html($long)  . $extra);
850         }
853 sub format_diff_line {
854         my $line = shift;
855         my $char = substr($line, 0, 1);
856         my $diff_class = "";
858         chomp $line;
860         if ($char eq '+') {
861                 $diff_class = " add";
862         } elsif ($char eq "-") {
863                 $diff_class = " rem";
864         } elsif ($char eq "@") {
865                 $diff_class = " chunk_header";
866         } elsif ($char eq "\\") {
867                 $diff_class = " incomplete";
868         }
869         $line = untabify($line);
870         return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
873 ## ----------------------------------------------------------------------
874 ## git utility subroutines, invoking git commands
876 # returns path to the core git executable and the --git-dir parameter as list
877 sub git_cmd {
878         return $GIT, '--git-dir='.$git_dir;
881 # returns path to the core git executable and the --git-dir parameter as string
882 sub git_cmd_str {
883         return join(' ', git_cmd());
886 # get HEAD ref of given project as hash
887 sub git_get_head_hash {
888         my $project = shift;
889         my $o_git_dir = $git_dir;
890         my $retval = undef;
891         $git_dir = "$projectroot/$project";
892         if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
893                 my $head = <$fd>;
894                 close $fd;
895                 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
896                         $retval = $1;
897                 }
898         }
899         if (defined $o_git_dir) {
900                 $git_dir = $o_git_dir;
901         }
902         return $retval;
905 # get type of given object
906 sub git_get_type {
907         my $hash = shift;
909         open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
910         my $type = <$fd>;
911         close $fd or return;
912         chomp $type;
913         return $type;
916 sub git_get_project_config {
917         my ($key, $type) = @_;
919         return unless ($key);
920         $key =~ s/^gitweb\.//;
921         return if ($key =~ m/\W/);
923         my @x = (git_cmd(), 'repo-config');
924         if (defined $type) { push @x, $type; }
925         push @x, "--get";
926         push @x, "gitweb.$key";
927         my $val = qx(@x);
928         chomp $val;
929         return ($val);
932 # get hash of given path at given ref
933 sub git_get_hash_by_path {
934         my $base = shift;
935         my $path = shift || return undef;
936         my $type = shift;
938         $path =~ s,/+$,,;
940         open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
941                 or die_error(undef, "Open git-ls-tree failed");
942         my $line = <$fd>;
943         close $fd or return undef;
945         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
946         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
947         if (defined $type && $type ne $2) {
948                 # type doesn't match
949                 return undef;
950         }
951         return $3;
954 ## ......................................................................
955 ## git utility functions, directly accessing git repository
957 sub git_get_project_description {
958         my $path = shift;
960         open my $fd, "$projectroot/$path/description" or return undef;
961         my $descr = <$fd>;
962         close $fd;
963         chomp $descr;
964         return $descr;
967 sub git_get_project_url_list {
968         my $path = shift;
970         open my $fd, "$projectroot/$path/cloneurl" or return;
971         my @git_project_url_list = map { chomp; $_ } <$fd>;
972         close $fd;
974         return wantarray ? @git_project_url_list : \@git_project_url_list;
977 sub git_get_projects_list {
978         my ($filter) = @_;
979         my @list;
981         $filter ||= '';
982         $filter =~ s/\.git$//;
984         if (-d $projects_list) {
985                 # search in directory
986                 my $dir = $projects_list . ($filter ? "/$filter" : '');
987                 # remove the trailing "/"
988                 $dir =~ s!/+$!!;
989                 my $pfxlen = length("$dir");
991                 my ($check_forks) = gitweb_check_feature('forks');
993                 File::Find::find({
994                         follow_fast => 1, # follow symbolic links
995                         dangling_symlinks => 0, # ignore dangling symlinks, silently
996                         wanted => sub {
997                                 # skip project-list toplevel, if we get it.
998                                 return if (m!^[/.]$!);
999                                 # only directories can be git repositories
1000                                 return unless (-d $_);
1002                                 my $subdir = substr($File::Find::name, $pfxlen + 1);
1003                                 # we check related file in $projectroot
1004                                 if ($check_forks and $subdir =~ m#/.#) {
1005                                         $File::Find::prune = 1;
1006                                 } elsif (check_export_ok("$projectroot/$filter/$subdir")) {
1007                                         push @list, { path => ($filter ? "$filter/" : '') . $subdir };
1008                                         $File::Find::prune = 1;
1009                                 }
1010                         },
1011                 }, "$dir");
1013         } elsif (-f $projects_list) {
1014                 # read from file(url-encoded):
1015                 # 'git%2Fgit.git Linus+Torvalds'
1016                 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1017                 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1018                 open my ($fd), $projects_list or return;
1019                 while (my $line = <$fd>) {
1020                         chomp $line;
1021                         my ($path, $owner) = split ' ', $line;
1022                         $path = unescape($path);
1023                         $owner = unescape($owner);
1024                         if (!defined $path) {
1025                                 next;
1026                         }
1027                         if ($filter ne '') {
1028                                 # looking for forks;
1029                                 my $pfx = substr($path, 0, length($filter));
1030                                 if ($pfx ne $filter) {
1031                                         next;
1032                                 }
1033                                 my $sfx = substr($path, length($filter));
1034                                 if ($sfx !~ /^\/.*\.git$/) {
1035                                         next;
1036                                 }
1037                         }
1038                         if (check_export_ok("$projectroot/$path")) {
1039                                 my $pr = {
1040                                         path => $path,
1041                                         owner => to_utf8($owner),
1042                                 };
1043                                 push @list, $pr
1044                         }
1045                 }
1046                 close $fd;
1047         }
1048         @list = sort {$a->{'path'} cmp $b->{'path'}} @list;
1049         return @list;
1052 sub git_get_project_owner {
1053         my $project = shift;
1054         my $owner;
1056         return undef unless $project;
1058         # read from file (url-encoded):
1059         # 'git%2Fgit.git Linus+Torvalds'
1060         # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1061         # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1062         if (-f $projects_list) {
1063                 open (my $fd , $projects_list);
1064                 while (my $line = <$fd>) {
1065                         chomp $line;
1066                         my ($pr, $ow) = split ' ', $line;
1067                         $pr = unescape($pr);
1068                         $ow = unescape($ow);
1069                         if ($pr eq $project) {
1070                                 $owner = to_utf8($ow);
1071                                 last;
1072                         }
1073                 }
1074                 close $fd;
1075         }
1076         if (!defined $owner) {
1077                 $owner = get_file_owner("$projectroot/$project");
1078         }
1080         return $owner;
1083 sub git_get_last_activity {
1084         my ($path) = @_;
1085         my $fd;
1087         $git_dir = "$projectroot/$path";
1088         open($fd, "-|", git_cmd(), 'for-each-ref',
1089              '--format=%(refname) %(committer)',
1090              '--sort=-committerdate',
1091              'refs/heads') or return;
1092         my $most_recent = <$fd>;
1093         close $fd or return;
1094         if ($most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
1095                 my $timestamp = $1;
1096                 my $age = time - $timestamp;
1097                 return ($age, age_string($age));
1098         }
1101 sub git_get_references {
1102         my $type = shift || "";
1103         my %refs;
1104         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c      refs/tags/v2.6.11
1105         # c39ae07f393806ccf406ef966e9a15afc43cc36a      refs/tags/v2.6.11^{}
1106         open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
1107                 or return;
1109         while (my $line = <$fd>) {
1110                 chomp $line;
1111                 if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?[^\^]+)/) {
1112                         if (defined $refs{$1}) {
1113                                 push @{$refs{$1}}, $2;
1114                         } else {
1115                                 $refs{$1} = [ $2 ];
1116                         }
1117                 }
1118         }
1119         close $fd or return;
1120         return \%refs;
1123 sub git_get_rev_name_tags {
1124         my $hash = shift || return undef;
1126         open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
1127                 or return;
1128         my $name_rev = <$fd>;
1129         close $fd;
1131         if ($name_rev =~ m|^$hash tags/(.*)$|) {
1132                 return $1;
1133         } else {
1134                 # catches also '$hash undefined' output
1135                 return undef;
1136         }
1139 ## ----------------------------------------------------------------------
1140 ## parse to hash functions
1142 sub parse_date {
1143         my $epoch = shift;
1144         my $tz = shift || "-0000";
1146         my %date;
1147         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
1148         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
1149         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
1150         $date{'hour'} = $hour;
1151         $date{'minute'} = $min;
1152         $date{'mday'} = $mday;
1153         $date{'day'} = $days[$wday];
1154         $date{'month'} = $months[$mon];
1155         $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
1156                            $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
1157         $date{'mday-time'} = sprintf "%d %s %02d:%02d",
1158                              $mday, $months[$mon], $hour ,$min;
1160         $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
1161         my $local = $epoch + ((int $1 + ($2/60)) * 3600);
1162         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
1163         $date{'hour_local'} = $hour;
1164         $date{'minute_local'} = $min;
1165         $date{'tz_local'} = $tz;
1166         $date{'iso-tz'} = sprintf ("%04d-%02d-%02d %02d:%02d:%02d %s",
1167                                    1900+$year, $mon+1, $mday,
1168                                    $hour, $min, $sec, $tz);
1169         return %date;
1172 sub parse_tag {
1173         my $tag_id = shift;
1174         my %tag;
1175         my @comment;
1177         open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
1178         $tag{'id'} = $tag_id;
1179         while (my $line = <$fd>) {
1180                 chomp $line;
1181                 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
1182                         $tag{'object'} = $1;
1183                 } elsif ($line =~ m/^type (.+)$/) {
1184                         $tag{'type'} = $1;
1185                 } elsif ($line =~ m/^tag (.+)$/) {
1186                         $tag{'name'} = $1;
1187                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
1188                         $tag{'author'} = $1;
1189                         $tag{'epoch'} = $2;
1190                         $tag{'tz'} = $3;
1191                 } elsif ($line =~ m/--BEGIN/) {
1192                         push @comment, $line;
1193                         last;
1194                 } elsif ($line eq "") {
1195                         last;
1196                 }
1197         }
1198         push @comment, <$fd>;
1199         $tag{'comment'} = \@comment;
1200         close $fd or return;
1201         if (!defined $tag{'name'}) {
1202                 return
1203         };
1204         return %tag
1207 sub parse_commit {
1208         my $commit_id = shift;
1209         my $commit_text = shift;
1211         my @commit_lines;
1212         my %co;
1214         if (defined $commit_text) {
1215                 @commit_lines = @$commit_text;
1216         } else {
1217                 local $/ = "\0";
1218                 open my $fd, "-|", git_cmd(), "rev-list",
1219                         "--header", "--parents", "--max-count=1",
1220                         $commit_id, "--"
1221                         or return;
1222                 @commit_lines = split '\n', <$fd>;
1223                 close $fd or return;
1224                 pop @commit_lines;
1225         }
1226         my $header = shift @commit_lines;
1227         if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
1228                 return;
1229         }
1230         ($co{'id'}, my @parents) = split ' ', $header;
1231         $co{'parents'} = \@parents;
1232         $co{'parent'} = $parents[0];
1233         while (my $line = shift @commit_lines) {
1234                 last if $line eq "\n";
1235                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1236                         $co{'tree'} = $1;
1237                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1238                         $co{'author'} = $1;
1239                         $co{'author_epoch'} = $2;
1240                         $co{'author_tz'} = $3;
1241                         if ($co{'author'} =~ m/^([^<]+) </) {
1242                                 $co{'author_name'} = $1;
1243                         } else {
1244                                 $co{'author_name'} = $co{'author'};
1245                         }
1246                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1247                         $co{'committer'} = $1;
1248                         $co{'committer_epoch'} = $2;
1249                         $co{'committer_tz'} = $3;
1250                         $co{'committer_name'} = $co{'committer'};
1251                         $co{'committer_name'} =~ s/ <.*//;
1252                 }
1253         }
1254         if (!defined $co{'tree'}) {
1255                 return;
1256         };
1258         foreach my $title (@commit_lines) {
1259                 $title =~ s/^    //;
1260                 if ($title ne "") {
1261                         $co{'title'} = chop_str($title, 80, 5);
1262                         # remove leading stuff of merges to make the interesting part visible
1263                         if (length($title) > 50) {
1264                                 $title =~ s/^Automatic //;
1265                                 $title =~ s/^merge (of|with) /Merge ... /i;
1266                                 if (length($title) > 50) {
1267                                         $title =~ s/(http|rsync):\/\///;
1268                                 }
1269                                 if (length($title) > 50) {
1270                                         $title =~ s/(master|www|rsync)\.//;
1271                                 }
1272                                 if (length($title) > 50) {
1273                                         $title =~ s/kernel.org:?//;
1274                                 }
1275                                 if (length($title) > 50) {
1276                                         $title =~ s/\/pub\/scm//;
1277                                 }
1278                         }
1279                         $co{'title_short'} = chop_str($title, 50, 5);
1280                         last;
1281                 }
1282         }
1283         if ($co{'title'} eq "") {
1284                 $co{'title'} = $co{'title_short'} = '(no commit message)';
1285         }
1286         # remove added spaces
1287         foreach my $line (@commit_lines) {
1288                 $line =~ s/^    //;
1289         }
1290         $co{'comment'} = \@commit_lines;
1292         my $age = time - $co{'committer_epoch'};
1293         $co{'age'} = $age;
1294         $co{'age_string'} = age_string($age);
1295         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1296         if ($age > 60*60*24*7*2) {
1297                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1298                 $co{'age_string_age'} = $co{'age_string'};
1299         } else {
1300                 $co{'age_string_date'} = $co{'age_string'};
1301                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1302         }
1303         return %co;
1306 # parse ref from ref_file, given by ref_id, with given type
1307 sub parse_ref {
1308         my $ref_file = shift;
1309         my $ref_id = shift;
1310         my $type = shift || git_get_type($ref_id);
1311         my %ref_item;
1313         $ref_item{'type'} = $type;
1314         $ref_item{'id'} = $ref_id;
1315         $ref_item{'epoch'} = 0;
1316         $ref_item{'age'} = "unknown";
1317         if ($type eq "tag") {
1318                 my %tag = parse_tag($ref_id);
1319                 $ref_item{'comment'} = $tag{'comment'};
1320                 if ($tag{'type'} eq "commit") {
1321                         my %co = parse_commit($tag{'object'});
1322                         $ref_item{'epoch'} = $co{'committer_epoch'};
1323                         $ref_item{'age'} = $co{'age_string'};
1324                 } elsif (defined($tag{'epoch'})) {
1325                         my $age = time - $tag{'epoch'};
1326                         $ref_item{'epoch'} = $tag{'epoch'};
1327                         $ref_item{'age'} = age_string($age);
1328                 }
1329                 $ref_item{'reftype'} = $tag{'type'};
1330                 $ref_item{'name'} = $tag{'name'};
1331                 $ref_item{'refid'} = $tag{'object'};
1332         } elsif ($type eq "commit"){
1333                 my %co = parse_commit($ref_id);
1334                 $ref_item{'reftype'} = "commit";
1335                 $ref_item{'name'} = $ref_file;
1336                 $ref_item{'title'} = $co{'title'};
1337                 $ref_item{'refid'} = $ref_id;
1338                 $ref_item{'epoch'} = $co{'committer_epoch'};
1339                 $ref_item{'age'} = $co{'age_string'};
1340         } else {
1341                 $ref_item{'reftype'} = $type;
1342                 $ref_item{'name'} = $ref_file;
1343                 $ref_item{'refid'} = $ref_id;
1344         }
1346         return %ref_item;
1349 # parse line of git-diff-tree "raw" output
1350 sub parse_difftree_raw_line {
1351         my $line = shift;
1352         my %res;
1354         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1355         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1356         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1357                 $res{'from_mode'} = $1;
1358                 $res{'to_mode'} = $2;
1359                 $res{'from_id'} = $3;
1360                 $res{'to_id'} = $4;
1361                 $res{'status'} = $5;
1362                 $res{'similarity'} = $6;
1363                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1364                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1365                 } else {
1366                         $res{'file'} = unquote($7);
1367                 }
1368         }
1369         # 'c512b523472485aef4fff9e57b229d9d243c967f'
1370         elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1371                 $res{'commit'} = $1;
1372         }
1374         return wantarray ? %res : \%res;
1377 # parse line of git-ls-tree output
1378 sub parse_ls_tree_line ($;%) {
1379         my $line = shift;
1380         my %opts = @_;
1381         my %res;
1383         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1384         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
1386         $res{'mode'} = $1;
1387         $res{'type'} = $2;
1388         $res{'hash'} = $3;
1389         if ($opts{'-z'}) {
1390                 $res{'name'} = $4;
1391         } else {
1392                 $res{'name'} = unquote($4);
1393         }
1395         return wantarray ? %res : \%res;
1398 ## ......................................................................
1399 ## parse to array of hashes functions
1401 sub git_get_heads_list {
1402         my $limit = shift;
1403         my @headslist;
1405         open my $fd, '-|', git_cmd(), 'for-each-ref',
1406                 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
1407                 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
1408                 'refs/heads'
1409                 or return;
1410         while (my $line = <$fd>) {
1411                 my %ref_item;
1413                 chomp $line;
1414                 my ($refinfo, $committerinfo) = split(/\0/, $line);
1415                 my ($hash, $name, $title) = split(' ', $refinfo, 3);
1416                 my ($committer, $epoch, $tz) =
1417                         ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
1418                 $name =~ s!^refs/heads/!!;
1420                 $ref_item{'name'}  = $name;
1421                 $ref_item{'id'}    = $hash;
1422                 $ref_item{'title'} = $title || '(no commit message)';
1423                 $ref_item{'epoch'} = $epoch;
1424                 if ($epoch) {
1425                         $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
1426                 } else {
1427                         $ref_item{'age'} = "unknown";
1428                 }
1430                 push @headslist, \%ref_item;
1431         }
1432         close $fd;
1434         return wantarray ? @headslist : \@headslist;
1437 sub git_get_tags_list {
1438         my $limit = shift;
1439         my @tagslist;
1441         open my $fd, '-|', git_cmd(), 'for-each-ref',
1442                 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
1443                 '--format=%(objectname) %(objecttype) %(refname) '.
1444                 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
1445                 'refs/tags'
1446                 or return;
1447         while (my $line = <$fd>) {
1448                 my %ref_item;
1450                 chomp $line;
1451                 my ($refinfo, $creatorinfo) = split(/\0/, $line);
1452                 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
1453                 my ($creator, $epoch, $tz) =
1454                         ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
1455                 $name =~ s!^refs/tags/!!;
1457                 $ref_item{'type'} = $type;
1458                 $ref_item{'id'} = $id;
1459                 $ref_item{'name'} = $name;
1460                 if ($type eq "tag") {
1461                         $ref_item{'subject'} = $title;
1462                         $ref_item{'reftype'} = $reftype;
1463                         $ref_item{'refid'}   = $refid;
1464                 } else {
1465                         $ref_item{'reftype'} = $type;
1466                         $ref_item{'refid'}   = $id;
1467                 }
1469                 if ($type eq "tag" || $type eq "commit") {
1470                         $ref_item{'epoch'} = $epoch;
1471                         if ($epoch) {
1472                                 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
1473                         } else {
1474                                 $ref_item{'age'} = "unknown";
1475                         }
1476                 }
1478                 push @tagslist, \%ref_item;
1479         }
1480         close $fd;
1482         return wantarray ? @tagslist : \@tagslist;
1485 ## ----------------------------------------------------------------------
1486 ## filesystem-related functions
1488 sub get_file_owner {
1489         my $path = shift;
1491         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1492         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1493         if (!defined $gcos) {
1494                 return undef;
1495         }
1496         my $owner = $gcos;
1497         $owner =~ s/[,;].*$//;
1498         return to_utf8($owner);
1501 ## ......................................................................
1502 ## mimetype related functions
1504 sub mimetype_guess_file {
1505         my $filename = shift;
1506         my $mimemap = shift;
1507         -r $mimemap or return undef;
1509         my %mimemap;
1510         open(MIME, $mimemap) or return undef;
1511         while (<MIME>) {
1512                 next if m/^#/; # skip comments
1513                 my ($mime, $exts) = split(/\t+/);
1514                 if (defined $exts) {
1515                         my @exts = split(/\s+/, $exts);
1516                         foreach my $ext (@exts) {
1517                                 $mimemap{$ext} = $mime;
1518                         }
1519                 }
1520         }
1521         close(MIME);
1523         $filename =~ /\.([^.]*)$/;
1524         return $mimemap{$1};
1527 sub mimetype_guess {
1528         my $filename = shift;
1529         my $mime;
1530         $filename =~ /\./ or return undef;
1532         if ($mimetypes_file) {
1533                 my $file = $mimetypes_file;
1534                 if ($file !~ m!^/!) { # if it is relative path
1535                         # it is relative to project
1536                         $file = "$projectroot/$project/$file";
1537                 }
1538                 $mime = mimetype_guess_file($filename, $file);
1539         }
1540         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1541         return $mime;
1544 sub blob_mimetype {
1545         my $fd = shift;
1546         my $filename = shift;
1548         if ($filename) {
1549                 my $mime = mimetype_guess($filename);
1550                 $mime and return $mime;
1551         }
1553         # just in case
1554         return $default_blob_plain_mimetype unless $fd;
1556         if (-T $fd) {
1557                 return 'text/plain' .
1558                        ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1559         } elsif (! $filename) {
1560                 return 'application/octet-stream';
1561         } elsif ($filename =~ m/\.png$/i) {
1562                 return 'image/png';
1563         } elsif ($filename =~ m/\.gif$/i) {
1564                 return 'image/gif';
1565         } elsif ($filename =~ m/\.jpe?g$/i) {
1566                 return 'image/jpeg';
1567         } else {
1568                 return 'application/octet-stream';
1569         }
1572 ## ======================================================================
1573 ## functions printing HTML: header, footer, error page
1575 sub git_header_html {
1576         my $status = shift || "200 OK";
1577         my $expires = shift;
1579         my $title = "$site_name";
1580         if (defined $project) {
1581                 $title .= " - $project";
1582                 if (defined $action) {
1583                         $title .= "/$action";
1584                         if (defined $file_name) {
1585                                 $title .= " - " . esc_path($file_name);
1586                                 if ($action eq "tree" && $file_name !~ m|/$|) {
1587                                         $title .= "/";
1588                                 }
1589                         }
1590                 }
1591         }
1592         my $content_type;
1593         # require explicit support from the UA if we are to send the page as
1594         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1595         # we have to do this because MSIE sometimes globs '*/*', pretending to
1596         # support xhtml+xml but choking when it gets what it asked for.
1597         if (defined $cgi->http('HTTP_ACCEPT') &&
1598             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1599             $cgi->Accept('application/xhtml+xml') != 0) {
1600                 $content_type = 'application/xhtml+xml';
1601         } else {
1602                 $content_type = 'text/html';
1603         }
1604         print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1605                            -status=> $status, -expires => $expires);
1606         print <<EOF;
1607 <?xml version="1.0" encoding="utf-8"?>
1608 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1609 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1610 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1611 <!-- git core binaries version $git_version -->
1612 <head>
1613 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1614 <meta name="generator" content="gitweb/$version git/$git_version"/>
1615 <meta name="robots" content="index, nofollow"/>
1616 <title>$title</title>
1617 EOF
1618 # print out each stylesheet that exist
1619         if (defined $stylesheet) {
1620 #provides backwards capability for those people who define style sheet in a config file
1621                 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
1622         } else {
1623                 foreach my $stylesheet (@stylesheets) {
1624                         next unless $stylesheet;
1625                         print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
1626                 }
1627         }
1628         if (defined $project) {
1629                 printf('<link rel="alternate" title="%s log" '.
1630                        'href="%s" type="application/rss+xml"/>'."\n",
1631                        esc_param($project), href(action=>"rss"));
1632         } else {
1633                 printf('<link rel="alternate" title="%s projects list" '.
1634                        'href="%s" type="text/plain; charset=utf-8"/>'."\n",
1635                        $site_name, href(project=>undef, action=>"project_index"));
1636                 printf('<link rel="alternate" title="%s projects logs" '.
1637                        'href="%s" type="text/x-opml"/>'."\n",
1638                        $site_name, href(project=>undef, action=>"opml"));
1639         }
1640         if (defined $favicon) {
1641                 print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
1642         }
1644         print "</head>\n" .
1645               "<body>\n";
1647         if (-f $site_header) {
1648                 open (my $fd, $site_header);
1649                 print <$fd>;
1650                 close $fd;
1651         }
1653         print "<div class=\"page_header\">\n" .
1654               $cgi->a({-href => esc_url($logo_url),
1655                        -title => $logo_label},
1656                       qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
1657         print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
1658         if (defined $project) {
1659                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1660                 if (defined $action) {
1661                         print " / $action";
1662                 }
1663                 print "\n";
1664                 if (!defined $searchtext) {
1665                         $searchtext = "";
1666                 }
1667                 my $search_hash;
1668                 if (defined $hash_base) {
1669                         $search_hash = $hash_base;
1670                 } elsif (defined $hash) {
1671                         $search_hash = $hash;
1672                 } else {
1673                         $search_hash = "HEAD";
1674                 }
1675                 $cgi->param("a", "search");
1676                 $cgi->param("h", $search_hash);
1677                 $cgi->param("p", $project);
1678                 print $cgi->startform(-method => "get", -action => $my_uri) .
1679                       "<div class=\"search\">\n" .
1680                       $cgi->hidden(-name => "p") . "\n" .
1681                       $cgi->hidden(-name => "a") . "\n" .
1682                       $cgi->hidden(-name => "h") . "\n" .
1683                       $cgi->popup_menu(-name => 'st', -default => 'commit',
1684                                        -values => ['commit', 'author', 'committer', 'pickaxe']) .
1685                       $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
1686                       " search:\n",
1687                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1688                       "</div>" .
1689                       $cgi->end_form() . "\n";
1690         }
1691         print "</div>\n";
1694 sub git_footer_html {
1695         print "<div class=\"page_footer\">\n";
1696         if (defined $project) {
1697                 my $descr = git_get_project_description($project);
1698                 if (defined $descr) {
1699                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1700                 }
1701                 print $cgi->a({-href => href(action=>"rss"),
1702                               -class => "rss_logo"}, "RSS") . "\n";
1703         } else {
1704                 print $cgi->a({-href => href(project=>undef, action=>"opml"),
1705                               -class => "rss_logo"}, "OPML") . " ";
1706                 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
1707                               -class => "rss_logo"}, "TXT") . "\n";
1708         }
1709         print "</div>\n" ;
1711         if (-f $site_footer) {
1712                 open (my $fd, $site_footer);
1713                 print <$fd>;
1714                 close $fd;
1715         }
1717         print "</body>\n" .
1718               "</html>";
1721 sub die_error {
1722         my $status = shift || "403 Forbidden";
1723         my $error = shift || "Malformed query, file missing or permission denied";
1725         git_header_html($status);
1726         print <<EOF;
1727 <div class="page_body">
1728 <br /><br />
1729 $status - $error
1730 <br />
1731 </div>
1732 EOF
1733         git_footer_html();
1734         exit;
1737 ## ----------------------------------------------------------------------
1738 ## functions printing or outputting HTML: navigation
1740 sub git_print_page_nav {
1741         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1742         $extra = '' if !defined $extra; # pager or formats
1744         my @navs = qw(summary shortlog log commit commitdiff tree);
1745         if ($suppress) {
1746                 @navs = grep { $_ ne $suppress } @navs;
1747         }
1749         my %arg = map { $_ => {action=>$_} } @navs;
1750         if (defined $head) {
1751                 for (qw(commit commitdiff)) {
1752                         $arg{$_}{hash} = $head;
1753                 }
1754                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1755                         for (qw(shortlog log)) {
1756                                 $arg{$_}{hash} = $head;
1757                         }
1758                 }
1759         }
1760         $arg{tree}{hash} = $treehead if defined $treehead;
1761         $arg{tree}{hash_base} = $treebase if defined $treebase;
1763         print "<div class=\"page_nav\">\n" .
1764                 (join " | ",
1765                  map { $_ eq $current ?
1766                        $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1767                  } @navs);
1768         print "<br/>\n$extra<br/>\n" .
1769               "</div>\n";
1772 sub format_paging_nav {
1773         my ($action, $hash, $head, $page, $nrevs) = @_;
1774         my $paging_nav;
1777         if ($hash ne $head || $page) {
1778                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1779         } else {
1780                 $paging_nav .= "HEAD";
1781         }
1783         if ($page > 0) {
1784                 $paging_nav .= " &sdot; " .
1785                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1786                                  -accesskey => "p", -title => "Alt-p"}, "prev");
1787         } else {
1788                 $paging_nav .= " &sdot; prev";
1789         }
1791         if ($nrevs >= (100 * ($page+1)-1)) {
1792                 $paging_nav .= " &sdot; " .
1793                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1794                                  -accesskey => "n", -title => "Alt-n"}, "next");
1795         } else {
1796                 $paging_nav .= " &sdot; next";
1797         }
1799         return $paging_nav;
1802 ## ......................................................................
1803 ## functions printing or outputting HTML: div
1805 sub git_print_header_div {
1806         my ($action, $title, $hash, $hash_base) = @_;
1807         my %args = ();
1809         $args{action} = $action;
1810         $args{hash} = $hash if $hash;
1811         $args{hash_base} = $hash_base if $hash_base;
1813         print "<div class=\"header\">\n" .
1814               $cgi->a({-href => href(%args), -class => "title"},
1815               $title ? $title : $action) .
1816               "\n</div>\n";
1819 #sub git_print_authorship (\%) {
1820 sub git_print_authorship {
1821         my $co = shift;
1823         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
1824         print "<div class=\"author_date\">" .
1825               esc_html($co->{'author_name'}) .
1826               " [$ad{'rfc2822'}";
1827         if ($ad{'hour_local'} < 6) {
1828                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
1829                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1830         } else {
1831                 printf(" (%02d:%02d %s)",
1832                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1833         }
1834         print "]</div>\n";
1837 sub git_print_page_path {
1838         my $name = shift;
1839         my $type = shift;
1840         my $hb = shift;
1843         print "<div class=\"page_path\">";
1844         print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
1845                       -title => 'tree root'}, "[$project]");
1846         print " / ";
1847         if (defined $name) {
1848                 my @dirname = split '/', $name;
1849                 my $basename = pop @dirname;
1850                 my $fullname = '';
1852                 foreach my $dir (@dirname) {
1853                         $fullname .= ($fullname ? '/' : '') . $dir;
1854                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
1855                                                      hash_base=>$hb),
1856                                       -title => $fullname}, esc_path($dir));
1857                         print " / ";
1858                 }
1859                 if (defined $type && $type eq 'blob') {
1860                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
1861                                                      hash_base=>$hb),
1862                                       -title => $name}, esc_path($basename));
1863                 } elsif (defined $type && $type eq 'tree') {
1864                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
1865                                                      hash_base=>$hb),
1866                                       -title => $name}, esc_path($basename));
1867                         print " / ";
1868                 } else {
1869                         print esc_path($basename);
1870                 }
1871         }
1872         print "<br/></div>\n";
1875 # sub git_print_log (\@;%) {
1876 sub git_print_log ($;%) {
1877         my $log = shift;
1878         my %opts = @_;
1880         if ($opts{'-remove_title'}) {
1881                 # remove title, i.e. first line of log
1882                 shift @$log;
1883         }
1884         # remove leading empty lines
1885         while (defined $log->[0] && $log->[0] eq "") {
1886                 shift @$log;
1887         }
1889         # print log
1890         my $signoff = 0;
1891         my $empty = 0;
1892         foreach my $line (@$log) {
1893                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1894                         $signoff = 1;
1895                         $empty = 0;
1896                         if (! $opts{'-remove_signoff'}) {
1897                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1898                                 next;
1899                         } else {
1900                                 # remove signoff lines
1901                                 next;
1902                         }
1903                 } else {
1904                         $signoff = 0;
1905                 }
1907                 # print only one empty line
1908                 # do not print empty line after signoff
1909                 if ($line eq "") {
1910                         next if ($empty || $signoff);
1911                         $empty = 1;
1912                 } else {
1913                         $empty = 0;
1914                 }
1916                 print format_log_line_html($line) . "<br/>\n";
1917         }
1919         if ($opts{'-final_empty_line'}) {
1920                 # end with single empty line
1921                 print "<br/>\n" unless $empty;
1922         }
1925 # print tree entry (row of git_tree), but without encompassing <tr> element
1926 sub git_print_tree_entry {
1927         my ($t, $basedir, $hash_base, $have_blame) = @_;
1929         my %base_key = ();
1930         $base_key{hash_base} = $hash_base if defined $hash_base;
1932         # The format of a table row is: mode list link.  Where mode is
1933         # the mode of the entry, list is the name of the entry, an href,
1934         # and link is the action links of the entry.
1936         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
1937         if ($t->{'type'} eq "blob") {
1938                 print "<td class=\"list\">" .
1939                         $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1940                                                file_name=>"$basedir$t->{'name'}", %base_key),
1941                                 -class => "list"}, esc_path($t->{'name'})) . "</td>\n";
1942                 print "<td class=\"link\">";
1943                 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1944                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1945                               "blob");
1946                 if ($have_blame) {
1947                         print " | " .
1948                               $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
1949                                                            file_name=>"$basedir$t->{'name'}", %base_key)},
1950                                             "blame");
1951                 }
1952                 if (defined $hash_base) {
1953                         print " | " .
1954                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1955                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
1956                                       "history");
1957                 }
1958                 print " | " .
1959                         $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
1960                                                file_name=>"$basedir$t->{'name'}")},
1961                                 "raw");
1962                 print "</td>\n";
1964         } elsif ($t->{'type'} eq "tree") {
1965                 print "<td class=\"list\">";
1966                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1967                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1968                               esc_path($t->{'name'}));
1969                 print "</td>\n";
1970                 print "<td class=\"link\">";
1971                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1972                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1973                               "tree");
1974                 if (defined $hash_base) {
1975                         print " | " .
1976                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1977                                                      file_name=>"$basedir$t->{'name'}")},
1978                                       "history");
1979                 }
1980                 print "</td>\n";
1981         }
1984 ## ......................................................................
1985 ## functions printing large fragments of HTML
1987 sub git_difftree_body {
1988         my ($difftree, $hash, $parent) = @_;
1990         print "<div class=\"list_head\">\n";
1991         if ($#{$difftree} > 10) {
1992                 print(($#{$difftree} + 1) . " files changed:\n");
1993         }
1994         print "</div>\n";
1996         print "<table class=\"diff_tree\">\n";
1997         my $alternate = 1;
1998         my $patchno = 0;
1999         foreach my $line (@{$difftree}) {
2000                 my %diff = parse_difftree_raw_line($line);
2002                 if ($alternate) {
2003                         print "<tr class=\"dark\">\n";
2004                 } else {
2005                         print "<tr class=\"light\">\n";
2006                 }
2007                 $alternate ^= 1;
2009                 my ($to_mode_oct, $to_mode_str, $to_file_type);
2010                 my ($from_mode_oct, $from_mode_str, $from_file_type);
2011                 if ($diff{'to_mode'} ne ('0' x 6)) {
2012                         $to_mode_oct = oct $diff{'to_mode'};
2013                         if (S_ISREG($to_mode_oct)) { # only for regular file
2014                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
2015                         }
2016                         $to_file_type = file_type($diff{'to_mode'});
2017                 }
2018                 if ($diff{'from_mode'} ne ('0' x 6)) {
2019                         $from_mode_oct = oct $diff{'from_mode'};
2020                         if (S_ISREG($to_mode_oct)) { # only for regular file
2021                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
2022                         }
2023                         $from_file_type = file_type($diff{'from_mode'});
2024                 }
2026                 if ($diff{'status'} eq "A") { # created
2027                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
2028                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
2029                         $mode_chng   .= "]</span>";
2030                         print "<td>";
2031                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2032                                                      hash_base=>$hash, file_name=>$diff{'file'}),
2033                                       -class => "list"}, esc_path($diff{'file'}));
2034                         print "</td>\n";
2035                         print "<td>$mode_chng</td>\n";
2036                         print "<td class=\"link\">";
2037                         if ($action eq 'commitdiff') {
2038                                 # link to patch
2039                                 $patchno++;
2040                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
2041                         }
2042                         print "</td>\n";
2044                 } elsif ($diff{'status'} eq "D") { # deleted
2045                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
2046                         print "<td>";
2047                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
2048                                                      hash_base=>$parent, file_name=>$diff{'file'}),
2049                                        -class => "list"}, esc_path($diff{'file'}));
2050                         print "</td>\n";
2051                         print "<td>$mode_chng</td>\n";
2052                         print "<td class=\"link\">";
2053                         if ($action eq 'commitdiff') {
2054                                 # link to patch
2055                                 $patchno++;
2056                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
2057                                 print " | ";
2058                         }
2059                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
2060                                                      hash_base=>$parent, file_name=>$diff{'file'})},
2061                                       "blob") . " | ";
2062                         print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
2063                                                      file_name=>$diff{'file'})},
2064                                       "blame") . " | ";
2065                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
2066                                                      file_name=>$diff{'file'})},
2067                                       "history");
2068                         print "</td>\n";
2070                 } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
2071                         my $mode_chnge = "";
2072                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
2073                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
2074                                 if ($from_file_type != $to_file_type) {
2075                                         $mode_chnge .= " from $from_file_type to $to_file_type";
2076                                 }
2077                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
2078                                         if ($from_mode_str && $to_mode_str) {
2079                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
2080                                         } elsif ($to_mode_str) {
2081                                                 $mode_chnge .= " mode: $to_mode_str";
2082                                         }
2083                                 }
2084                                 $mode_chnge .= "]</span>\n";
2085                         }
2086                         print "<td>";
2087                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2088                                                      hash_base=>$hash, file_name=>$diff{'file'}),
2089                                       -class => "list"}, esc_path($diff{'file'}));
2090                         print "</td>\n";
2091                         print "<td>$mode_chnge</td>\n";
2092                         print "<td class=\"link\">";
2093                         if ($action eq 'commitdiff') {
2094                                 # link to patch
2095                                 $patchno++;
2096                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
2097                                       " | ";
2098                         } elsif ($diff{'to_id'} ne $diff{'from_id'}) {
2099                                 # "commit" view and modified file (not onlu mode changed)
2100                                 print $cgi->a({-href => href(action=>"blobdiff",
2101                                                              hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
2102                                                              hash_base=>$hash, hash_parent_base=>$parent,
2103                                                              file_name=>$diff{'file'})},
2104                                               "diff") .
2105                                       " | ";
2106                         }
2107                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2108                                                      hash_base=>$hash, file_name=>$diff{'file'})},
2109                                       "blob") . " | ";
2110                         print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
2111                                                      file_name=>$diff{'file'})},
2112                                       "blame") . " | ";
2113                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
2114                                                      file_name=>$diff{'file'})},
2115                                       "history");
2116                         print "</td>\n";
2118                 } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
2119                         my %status_name = ('R' => 'moved', 'C' => 'copied');
2120                         my $nstatus = $status_name{$diff{'status'}};
2121                         my $mode_chng = "";
2122                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
2123                                 # mode also for directories, so we cannot use $to_mode_str
2124                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
2125                         }
2126                         print "<td>" .
2127                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2128                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
2129                                       -class => "list"}, esc_path($diff{'to_file'})) . "</td>\n" .
2130                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
2131                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
2132                                                      hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
2133                                       -class => "list"}, esc_path($diff{'from_file'})) .
2134                               " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
2135                               "<td class=\"link\">";
2136                         if ($action eq 'commitdiff') {
2137                                 # link to patch
2138                                 $patchno++;
2139                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
2140                                       " | ";
2141                         } elsif ($diff{'to_id'} ne $diff{'from_id'}) {
2142                                 # "commit" view and modified file (not only pure rename or copy)
2143                                 print $cgi->a({-href => href(action=>"blobdiff",
2144                                                              hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
2145                                                              hash_base=>$hash, hash_parent_base=>$parent,
2146                                                              file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
2147                                               "diff") .
2148                                       " | ";
2149                         }
2150                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
2151                                                      hash_base=>$parent, file_name=>$diff{'from_file'})},
2152                                       "blob") . " | ";
2153                         print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
2154                                                      file_name=>$diff{'from_file'})},
2155                                       "blame") . " | ";
2156                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
2157                                                     file_name=>$diff{'from_file'})},
2158                                       "history");
2159                         print "</td>\n";
2161                 } # we should not encounter Unmerged (U) or Unknown (X) status
2162                 print "</tr>\n";
2163         }
2164         print "</table>\n";
2167 sub git_patchset_body {
2168         my ($fd, $difftree, $hash, $hash_parent) = @_;
2170         my $patch_idx = 0;
2171         my $in_header = 0;
2172         my $patch_found = 0;
2173         my $diffinfo;
2175         print "<div class=\"patchset\">\n";
2177         LINE:
2178         while (my $patch_line = <$fd>) {
2179                 chomp $patch_line;
2181                 if ($patch_line =~ m/^diff /) { # "git diff" header
2182                         # beginning of patch (in patchset)
2183                         if ($patch_found) {
2184                                 # close previous patch
2185                                 print "</div>\n"; # class="patch"
2186                         } else {
2187                                 # first patch in patchset
2188                                 $patch_found = 1;
2189                         }
2190                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
2192                         if (ref($difftree->[$patch_idx]) eq "HASH") {
2193                                 $diffinfo = $difftree->[$patch_idx];
2194                         } else {
2195                                 $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
2196                         }
2197                         $patch_idx++;
2199                         if ($diffinfo->{'status'} eq "A") { # added
2200                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'to_mode'}) . ":" .
2201                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2202                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
2203                                               $diffinfo->{'to_id'}) . " (new)" .
2204                                       "</div>\n"; # class="diff_info"
2206                         } elsif ($diffinfo->{'status'} eq "D") { # deleted
2207                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'from_mode'}) . ":" .
2208                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
2209                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
2210                                               $diffinfo->{'from_id'}) . " (deleted)" .
2211                                       "</div>\n"; # class="diff_info"
2213                         } elsif ($diffinfo->{'status'} eq "R" || # renamed
2214                                  $diffinfo->{'status'} eq "C" || # copied
2215                                  $diffinfo->{'status'} eq "2") { # with two filenames (from git_blobdiff)
2216                                 print "<div class=\"diff_info\">" .
2217                                       file_type($diffinfo->{'from_mode'}) . ":" .
2218                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
2219                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'from_file'})},
2220                                               $diffinfo->{'from_id'}) .
2221                                       " -> " .
2222                                       file_type($diffinfo->{'to_mode'}) . ":" .
2223                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2224                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'to_file'})},
2225                                               $diffinfo->{'to_id'});
2226                                 print "</div>\n"; # class="diff_info"
2228                         } else { # modified, mode changed, ...
2229                                 print "<div class=\"diff_info\">" .
2230                                       file_type($diffinfo->{'from_mode'}) . ":" .
2231                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
2232                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
2233                                               $diffinfo->{'from_id'}) .
2234                                       " -> " .
2235                                       file_type($diffinfo->{'to_mode'}) . ":" .
2236                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2237                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
2238                                               $diffinfo->{'to_id'});
2239                                 print "</div>\n"; # class="diff_info"
2240                         }
2242                         #print "<div class=\"diff extended_header\">\n";
2243                         $in_header = 1;
2244                         next LINE;
2245                 } # start of patch in patchset
2248                 if ($in_header && $patch_line =~ m/^---/) {
2249                         #print "</div>\n"; # class="diff extended_header"
2250                         $in_header = 0;
2252                         my $file = $diffinfo->{'from_file'};
2253                         $file  ||= $diffinfo->{'file'};
2254                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
2255                                                        hash=>$diffinfo->{'from_id'}, file_name=>$file),
2256                                         -class => "list"}, esc_path($file));
2257                         $patch_line =~ s|a/.*$|a/$file|g;
2258                         print "<div class=\"diff from_file\">$patch_line</div>\n";
2260                         $patch_line = <$fd>;
2261                         chomp $patch_line;
2263                         #$patch_line =~ m/^+++/;
2264                         $file    = $diffinfo->{'to_file'};
2265                         $file  ||= $diffinfo->{'file'};
2266                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2267                                                        hash=>$diffinfo->{'to_id'}, file_name=>$file),
2268                                         -class => "list"}, esc_path($file));
2269                         $patch_line =~ s|b/.*|b/$file|g;
2270                         print "<div class=\"diff to_file\">$patch_line</div>\n";
2272                         next LINE;
2273                 }
2274                 next LINE if $in_header;
2276                 print format_diff_line($patch_line);
2277         }
2278         print "</div>\n" if $patch_found; # class="patch"
2280         print "</div>\n"; # class="patchset"
2283 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2285 sub git_project_list_body {
2286         my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
2288         my ($check_forks) = gitweb_check_feature('forks');
2290         my @projects;
2291         foreach my $pr (@$projlist) {
2292                 my (@aa) = git_get_last_activity($pr->{'path'});
2293                 unless (@aa) {
2294                         next;
2295                 }
2296                 ($pr->{'age'}, $pr->{'age_string'}) = @aa;
2297                 if (!defined $pr->{'descr'}) {
2298                         my $descr = git_get_project_description($pr->{'path'}) || "";
2299                         $pr->{'descr'} = chop_str($descr, 25, 5);
2300                 }
2301                 if (!defined $pr->{'owner'}) {
2302                         $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2303                 }
2304                 if ($check_forks) {
2305                         my $pname = $pr->{'path'};
2306                         if (($pname =~ s/\.git$//) &&
2307                             ($pname !~ /\/$/) &&
2308                             (-d "$projectroot/$pname")) {
2309                                 $pr->{'forks'} = "-d $projectroot/$pname";
2310                         }
2311                         else {
2312                                 $pr->{'forks'} = 0;
2313                         }
2314                 }
2315                 push @projects, $pr;
2316         }
2318         $order ||= "project";
2319         $from = 0 unless defined $from;
2320         $to = $#projects if (!defined $to || $#projects < $to);
2322         print "<table class=\"project_list\">\n";
2323         unless ($no_header) {
2324                 print "<tr>\n";
2325                 if ($check_forks) {
2326                         print "<th></th>\n";
2327                 }
2328                 if ($order eq "project") {
2329                         @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2330                         print "<th>Project</th>\n";
2331                 } else {
2332                         print "<th>" .
2333                               $cgi->a({-href => href(project=>undef, order=>'project'),
2334                                        -class => "header"}, "Project") .
2335                               "</th>\n";
2336                 }
2337                 if ($order eq "descr") {
2338                         @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2339                         print "<th>Description</th>\n";
2340                 } else {
2341                         print "<th>" .
2342                               $cgi->a({-href => href(project=>undef, order=>'descr'),
2343                                        -class => "header"}, "Description") .
2344                               "</th>\n";
2345                 }
2346                 if ($order eq "owner") {
2347                         @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2348                         print "<th>Owner</th>\n";
2349                 } else {
2350                         print "<th>" .
2351                               $cgi->a({-href => href(project=>undef, order=>'owner'),
2352                                        -class => "header"}, "Owner") .
2353                               "</th>\n";
2354                 }
2355                 if ($order eq "age") {
2356                         @projects = sort {$a->{'age'} <=> $b->{'age'}} @projects;
2357                         print "<th>Last Change</th>\n";
2358                 } else {
2359                         print "<th>" .
2360                               $cgi->a({-href => href(project=>undef, order=>'age'),
2361                                        -class => "header"}, "Last Change") .
2362                               "</th>\n";
2363                 }
2364                 print "<th></th>\n" .
2365                       "</tr>\n";
2366         }
2367         my $alternate = 1;
2368         for (my $i = $from; $i <= $to; $i++) {
2369                 my $pr = $projects[$i];
2370                 if ($alternate) {
2371                         print "<tr class=\"dark\">\n";
2372                 } else {
2373                         print "<tr class=\"light\">\n";
2374                 }
2375                 $alternate ^= 1;
2376                 if ($check_forks) {
2377                         print "<td>";
2378                         if ($pr->{'forks'}) {
2379                                 print "<!-- $pr->{'forks'} -->\n";
2380                                 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
2381                         }
2382                         print "</td>\n";
2383                 }
2384                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2385                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2386                       "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
2387                       "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2388                 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
2389                       $pr->{'age_string'} . "</td>\n" .
2390                       "<td class=\"link\">" .
2391                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2392                       $cgi->a({-href => '/git-browser/by-commit.html?r='.$pr->{'path'}}, "graphiclog") . " | " .
2393                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
2394                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
2395                       ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
2396                       "</td>\n" .
2397                       "</tr>\n";
2398         }
2399         if (defined $extra) {
2400                 print "<tr>\n";
2401                 if ($check_forks) {
2402                         print "<td></td>\n";
2403                 }
2404                 print "<td colspan=\"5\">$extra</td>\n" .
2405                       "</tr>\n";
2406         }
2407         print "</table>\n";
2410 sub git_shortlog_body {
2411         # uses global variable $project
2412         my ($revlist, $from, $to, $refs, $extra) = @_;
2414         $from = 0 unless defined $from;
2415         $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
2417         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
2418         my $alternate = 1;
2419         for (my $i = $from; $i <= $to; $i++) {
2420                 my $commit = $revlist->[$i];
2421                 #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
2422                 my $ref = format_ref_marker($refs, $commit);
2423                 my %co = parse_commit($commit);
2424                 if ($alternate) {
2425                         print "<tr class=\"dark\">\n";
2426                 } else {
2427                         print "<tr class=\"light\">\n";
2428                 }
2429                 $alternate ^= 1;
2430                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
2431                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2432                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
2433                       "<td>";
2434                 print format_subject_html($co{'title'}, $co{'title_short'},
2435                                           href(action=>"commit", hash=>$commit), $ref);
2436                 print "</td>\n" .
2437                       "<td class=\"link\">" .
2438                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
2439                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
2440                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
2441                 if (gitweb_have_snapshot()) {
2442                         print " | " . $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
2443                 }
2444                 print "</td>\n" .
2445                       "</tr>\n";
2446         }
2447         if (defined $extra) {
2448                 print "<tr>\n" .
2449                       "<td colspan=\"4\">$extra</td>\n" .
2450                       "</tr>\n";
2451         }
2452         print "</table>\n";
2455 sub git_history_body {
2456         # Warning: assumes constant type (blob or tree) during history
2457         my ($revlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
2459         $from = 0 unless defined $from;
2460         $to = $#{$revlist} unless (defined $to && $to <= $#{$revlist});
2462         print "<table class=\"history\" cellspacing=\"0\">\n";
2463         my $alternate = 1;
2464         for (my $i = $from; $i <= $to; $i++) {
2465                 if ($revlist->[$i] !~ m/^([0-9a-fA-F]{40})/) {
2466                         next;
2467                 }
2469                 my $commit = $1;
2470                 my %co = parse_commit($commit);
2471                 if (!%co) {
2472                         next;
2473                 }
2475                 my $ref = format_ref_marker($refs, $commit);
2477                 if ($alternate) {
2478                         print "<tr class=\"dark\">\n";
2479                 } else {
2480                         print "<tr class=\"light\">\n";
2481                 }
2482                 $alternate ^= 1;
2483                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2484                       # shortlog uses      chop_str($co{'author_name'}, 10)
2485                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
2486                       "<td>";
2487                 # originally git_history used chop_str($co{'title'}, 50)
2488                 print format_subject_html($co{'title'}, $co{'title_short'},
2489                                           href(action=>"commit", hash=>$commit), $ref);
2490                 print "</td>\n" .
2491                       "<td class=\"link\">" .
2492                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
2493                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
2495                 if ($ftype eq 'blob') {
2496                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
2497                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
2498                         if (defined $blob_current && defined $blob_parent &&
2499                                         $blob_current ne $blob_parent) {
2500                                 print " | " .
2501                                         $cgi->a({-href => href(action=>"blobdiff",
2502                                                                hash=>$blob_current, hash_parent=>$blob_parent,
2503                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
2504                                                                file_name=>$file_name)},
2505                                                 "diff to current");
2506                         }
2507                 }
2508                 print "</td>\n" .
2509                       "</tr>\n";
2510         }
2511         if (defined $extra) {
2512                 print "<tr>\n" .
2513                       "<td colspan=\"4\">$extra</td>\n" .
2514                       "</tr>\n";
2515         }
2516         print "</table>\n";
2519 sub git_tags_body {
2520         # uses global variable $project
2521         my ($taglist, $from, $to, $extra) = @_;
2522         $from = 0 unless defined $from;
2523         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2525         print "<table class=\"tags\" cellspacing=\"0\">\n";
2526         my $alternate = 1;
2527         for (my $i = $from; $i <= $to; $i++) {
2528                 my $entry = $taglist->[$i];
2529                 my %tag = %$entry;
2530                 my $comment = $tag{'subject'};
2531                 my $comment_short;
2532                 if (defined $comment) {
2533                         $comment_short = chop_str($comment, 30, 5);
2534                 }
2535                 if ($alternate) {
2536                         print "<tr class=\"dark\">\n";
2537                 } else {
2538                         print "<tr class=\"light\">\n";
2539                 }
2540                 $alternate ^= 1;
2541                 print "<td><i>$tag{'age'}</i></td>\n" .
2542                       "<td>" .
2543                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
2544                                -class => "list name"}, esc_html($tag{'name'})) .
2545                       "</td>\n" .
2546                       "<td>";
2547                 if (defined $comment) {
2548                         print format_subject_html($comment, $comment_short,
2549                                                   href(action=>"tag", hash=>$tag{'id'}));
2550                 }
2551                 print "</td>\n" .
2552                       "<td class=\"selflink\">";
2553                 if ($tag{'type'} eq "tag") {
2554                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
2555                 } else {
2556                         print "&nbsp;";
2557                 }
2558                 print "</td>\n" .
2559                       "<td class=\"link\">" . " | " .
2560                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
2561                 if ($tag{'reftype'} eq "commit") {
2562                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
2563                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log");
2564                 } elsif ($tag{'reftype'} eq "blob") {
2565                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
2566                 }
2567                 print "</td>\n" .
2568                       "</tr>";
2569         }
2570         if (defined $extra) {
2571                 print "<tr>\n" .
2572                       "<td colspan=\"5\">$extra</td>\n" .
2573                       "</tr>\n";
2574         }
2575         print "</table>\n";
2578 sub git_heads_body {
2579         # uses global variable $project
2580         my ($headlist, $head, $from, $to, $extra) = @_;
2581         $from = 0 unless defined $from;
2582         $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
2584         print "<table class=\"heads\" cellspacing=\"0\">\n";
2585         my $alternate = 1;
2586         for (my $i = $from; $i <= $to; $i++) {
2587                 my $entry = $headlist->[$i];
2588                 my %ref = %$entry;
2589                 my $curr = $ref{'id'} eq $head;
2590                 if ($alternate) {
2591                         print "<tr class=\"dark\">\n";
2592                 } else {
2593                         print "<tr class=\"light\">\n";
2594                 }
2595                 $alternate ^= 1;
2596                 print "<td><i>$ref{'age'}</i></td>\n" .
2597                       ($curr ? "<td class=\"current_head\">" : "<td>") .
2598                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'}),
2599                                -class => "list name"},esc_html($ref{'name'})) .
2600                       "</td>\n" .
2601                       "<td class=\"link\">" .
2602                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'})}, "shortlog") . " | " .
2603                       $cgi->a({-href => href(action=>"log", hash=>$ref{'name'})}, "log") . " | " .
2604                       $cgi->a({-href => href(action=>"tree", hash=>$ref{'name'}, hash_base=>$ref{'name'})}, "tree") .
2605                       "</td>\n" .
2606                       "</tr>";
2607         }
2608         if (defined $extra) {
2609                 print "<tr>\n" .
2610                       "<td colspan=\"3\">$extra</td>\n" .
2611                       "</tr>\n";
2612         }
2613         print "</table>\n";
2616 ## ======================================================================
2617 ## ======================================================================
2618 ## actions
2620 sub git_project_list {
2621         my $order = $cgi->param('o');
2622         if (defined $order && $order !~ m/project|descr|owner|age/) {
2623                 die_error(undef, "Unknown order parameter");
2624         }
2626         my @list = git_get_projects_list();
2627         if (!@list) {
2628                 die_error(undef, "No projects found");
2629         }
2631         git_header_html();
2632         if (-f $home_text) {
2633                 print "<div class=\"index_include\">\n";
2634                 open (my $fd, $home_text);
2635                 print <$fd>;
2636                 close $fd;
2637                 print "</div>\n";
2638         }
2639         git_project_list_body(\@list, $order);
2640         git_footer_html();
2643 sub git_forks {
2644         my $order = $cgi->param('o');
2645         if (defined $order && $order !~ m/project|descr|owner|age/) {
2646                 die_error(undef, "Unknown order parameter");
2647         }
2649         my @list = git_get_projects_list($project);
2650         if (!@list) {
2651                 die_error(undef, "No forks found");
2652         }
2654         git_header_html();
2655         git_print_page_nav('','');
2656         git_print_header_div('summary', "$project forks");
2657         git_project_list_body(\@list, $order);
2658         git_footer_html();
2661 sub git_project_index {
2662         my @projects = git_get_projects_list($project);
2664         print $cgi->header(
2665                 -type => 'text/plain',
2666                 -charset => 'utf-8',
2667                 -content_disposition => 'inline; filename="index.aux"');
2669         foreach my $pr (@projects) {
2670                 if (!exists $pr->{'owner'}) {
2671                         $pr->{'owner'} = get_file_owner("$projectroot/$project");
2672                 }
2674                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
2675                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
2676                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2677                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2678                 $path  =~ s/ /\+/g;
2679                 $owner =~ s/ /\+/g;
2681                 print "$path $owner\n";
2682         }
2685 sub git_summary {
2686         my $descr = git_get_project_description($project) || "none";
2687         my $head = git_get_head_hash($project);
2688         my %co = parse_commit($head);
2689         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2691         my $owner = git_get_project_owner($project);
2693         my $refs = git_get_references();
2694         my @taglist  = git_get_tags_list(15);
2695         my @headlist = git_get_heads_list(15);
2696         my @forklist;
2697         my ($check_forks) = gitweb_check_feature('forks');
2699         if ($check_forks) {
2700                 @forklist = git_get_projects_list($project);
2701         }
2703         git_header_html();
2704         git_print_page_nav('summary','', $head);
2706         print "<div class=\"title\">&nbsp;</div>\n";
2707         print "<table cellspacing=\"0\">\n" .
2708               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
2709               "<tr><td>owner</td><td>$owner</td></tr>\n" .
2710               "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
2711         # use per project git URL list in $projectroot/$project/cloneurl
2712         # or make project git URL from git base URL and project name
2713         my $url_tag = "URL";
2714         my @url_list = git_get_project_url_list($project);
2715         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
2716         foreach my $git_url (@url_list) {
2717                 next unless $git_url;
2718                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
2719                 $url_tag = "";
2720         }
2721         print "</table>\n";
2723         if (-s "$projectroot/$project/README.html") {
2724                 if (open my $fd, "$projectroot/$project/README.html") {
2725                         print "<div class=\"title\">readme</div>\n";
2726                         print $_ while (<$fd>);
2727                         close $fd;
2728                 }
2729         }
2731         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=17",
2732                 git_get_head_hash($project), "--"
2733                 or die_error(undef, "Open git-rev-list failed");
2734         my @revlist = map { chomp; $_ } <$fd>;
2735         close $fd;
2736         git_print_header_div('shortlog');
2737         git_shortlog_body(\@revlist, 0, 15, $refs,
2738                           $cgi->a({-href => href(action=>"shortlog")}, "..."));
2740         if (@taglist) {
2741                 git_print_header_div('tags');
2742                 git_tags_body(\@taglist, 0, 15,
2743                               $cgi->a({-href => href(action=>"tags")}, "..."));
2744         }
2746         if (@headlist) {
2747                 git_print_header_div('heads');
2748                 git_heads_body(\@headlist, $head, 0, 15,
2749                                $cgi->a({-href => href(action=>"heads")}, "..."));
2750         }
2752         if (@forklist) {
2753                 git_print_header_div('forks');
2754                 git_project_list_body(\@forklist, undef, 0, 15,
2755                                       $cgi->a({-href => href(action=>"forks")}, "..."),
2756                                       'noheader');
2757         }
2759         git_footer_html();
2762 sub git_tag {
2763         my $head = git_get_head_hash($project);
2764         git_header_html();
2765         git_print_page_nav('','', $head,undef,$head);
2766         my %tag = parse_tag($hash);
2767         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
2768         print "<div class=\"title_text\">\n" .
2769               "<table cellspacing=\"0\">\n" .
2770               "<tr>\n" .
2771               "<td>object</td>\n" .
2772               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2773                                $tag{'object'}) . "</td>\n" .
2774               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2775                                               $tag{'type'}) . "</td>\n" .
2776               "</tr>\n";
2777         if (defined($tag{'author'})) {
2778                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
2779                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
2780                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
2781                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
2782                         "</td></tr>\n";
2783         }
2784         print "</table>\n\n" .
2785               "</div>\n";
2786         print "<div class=\"page_body\">";
2787         my $comment = $tag{'comment'};
2788         foreach my $line (@$comment) {
2789                 print esc_html($line) . "<br/>\n";
2790         }
2791         print "</div>\n";
2792         git_footer_html();
2795 sub git_blame2 {
2796         my $fd;
2797         my $ftype;
2799         my ($have_blame) = gitweb_check_feature('blame');
2800         if (!$have_blame) {
2801                 die_error('403 Permission denied', "Permission denied");
2802         }
2803         die_error('404 Not Found', "File name not defined") if (!$file_name);
2804         $hash_base ||= git_get_head_hash($project);
2805         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2806         my %co = parse_commit($hash_base)
2807                 or die_error(undef, "Reading commit failed");
2808         if (!defined $hash) {
2809                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2810                         or die_error(undef, "Error looking up file");
2811         }
2812         $ftype = git_get_type($hash);
2813         if ($ftype !~ "blob") {
2814                 die_error("400 Bad Request", "Object is not a blob");
2815         }
2816         open ($fd, "-|", git_cmd(), "blame", '-p', '--',
2817               $file_name, $hash_base)
2818                 or die_error(undef, "Open git-blame failed");
2819         git_header_html();
2820         my $formats_nav =
2821                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2822                         "blob") .
2823                 " | " .
2824                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2825                         "history") .
2826                 " | " .
2827                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2828                         "HEAD");
2829         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2830         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2831         git_print_page_path($file_name, $ftype, $hash_base);
2832         my @rev_color = (qw(light2 dark2));
2833         my $num_colors = scalar(@rev_color);
2834         my $current_color = 0;
2835         my $last_rev;
2836         print <<HTML;
2837 <div class="page_body">
2838 <table class="blame">
2839 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
2840 HTML
2841         my %metainfo = ();
2842         while (1) {
2843                 $_ = <$fd>;
2844                 last unless defined $_;
2845                 my ($full_rev, $orig_lineno, $lineno, $group_size) =
2846                     /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
2847                 if (!exists $metainfo{$full_rev}) {
2848                         $metainfo{$full_rev} = {};
2849                 }
2850                 my $meta = $metainfo{$full_rev};
2851                 while (<$fd>) {
2852                         last if (s/^\t//);
2853                         if (/^(\S+) (.*)$/) {
2854                                 $meta->{$1} = $2;
2855                         }
2856                 }
2857                 my $data = $_;
2858                 my $rev = substr($full_rev, 0, 8);
2859                 my $author = $meta->{'author'};
2860                 my %date = parse_date($meta->{'author-time'},
2861                                       $meta->{'author-tz'});
2862                 my $date = $date{'iso-tz'};
2863                 if ($group_size) {
2864                         $current_color = ++$current_color % $num_colors;
2865                 }
2866                 print "<tr class=\"$rev_color[$current_color]\">\n";
2867                 if ($group_size) {
2868                         print "<td class=\"sha1\"";
2869                         print " title=\"". esc_html($author) . ", $date\"";
2870                         print " rowspan=\"$group_size\"" if ($group_size > 1);
2871                         print ">";
2872                         print $cgi->a({-href => href(action=>"commit",
2873                                                      hash=>$full_rev,
2874                                                      file_name=>$file_name)},
2875                                       esc_html($rev));
2876                         print "</td>\n";
2877                 }
2878                 my $blamed = href(action => 'blame',
2879                                   file_name => $meta->{'filename'},
2880                                   hash_base => $full_rev);
2881                 print "<td class=\"linenr\">";
2882                 print $cgi->a({ -href => "$blamed#l$orig_lineno",
2883                                 -id => "l$lineno",
2884                                 -class => "linenr" },
2885                               esc_html($lineno));
2886                 print "</td>";
2887                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
2888                 print "</tr>\n";
2889         }
2890         print "</table>\n";
2891         print "</div>";
2892         close $fd
2893                 or print "Reading blob failed\n";
2894         git_footer_html();
2897 sub git_blame {
2898         my $fd;
2900         my ($have_blame) = gitweb_check_feature('blame');
2901         if (!$have_blame) {
2902                 die_error('403 Permission denied', "Permission denied");
2903         }
2904         die_error('404 Not Found', "File name not defined") if (!$file_name);
2905         $hash_base ||= git_get_head_hash($project);
2906         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2907         my %co = parse_commit($hash_base)
2908                 or die_error(undef, "Reading commit failed");
2909         if (!defined $hash) {
2910                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2911                         or die_error(undef, "Error lookup file");
2912         }
2913         open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
2914                 or die_error(undef, "Open git-annotate failed");
2915         git_header_html();
2916         my $formats_nav =
2917                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2918                         "blob") .
2919                 " | " .
2920                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2921                         "history") .
2922                 " | " .
2923                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2924                         "HEAD");
2925         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2926         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2927         git_print_page_path($file_name, 'blob', $hash_base);
2928         print "<div class=\"page_body\">\n";
2929         print <<HTML;
2930 <table class="blame">
2931   <tr>
2932     <th>Commit</th>
2933     <th>Age</th>
2934     <th>Author</th>
2935     <th>Line</th>
2936     <th>Data</th>
2937   </tr>
2938 HTML
2939         my @line_class = (qw(light dark));
2940         my $line_class_len = scalar (@line_class);
2941         my $line_class_num = $#line_class;
2942         while (my $line = <$fd>) {
2943                 my $long_rev;
2944                 my $short_rev;
2945                 my $author;
2946                 my $time;
2947                 my $lineno;
2948                 my $data;
2949                 my $age;
2950                 my $age_str;
2951                 my $age_class;
2953                 chomp $line;
2954                 $line_class_num = ($line_class_num + 1) % $line_class_len;
2956                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
2957                         $long_rev = $1;
2958                         $author   = $2;
2959                         $time     = $3;
2960                         $lineno   = $4;
2961                         $data     = $5;
2962                 } else {
2963                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
2964                         next;
2965                 }
2966                 $short_rev  = substr ($long_rev, 0, 8);
2967                 $age        = time () - $time;
2968                 $age_str    = age_string ($age);
2969                 $age_str    =~ s/ /&nbsp;/g;
2970                 $age_class  = age_class($age);
2971                 $author     = esc_html ($author);
2972                 $author     =~ s/ /&nbsp;/g;
2974                 $data = untabify($data);
2975                 $data = esc_html ($data);
2977                 print <<HTML;
2978   <tr class="$line_class[$line_class_num]">
2979     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
2980     <td class="$age_class">$age_str</td>
2981     <td>$author</td>
2982     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
2983     <td class="pre">$data</td>
2984   </tr>
2985 HTML
2986         } # while (my $line = <$fd>)
2987         print "</table>\n\n";
2988         close $fd
2989                 or print "Reading blob failed.\n";
2990         print "</div>";
2991         git_footer_html();
2994 sub git_tags {
2995         my $head = git_get_head_hash($project);
2996         git_header_html();
2997         git_print_page_nav('','', $head,undef,$head);
2998         git_print_header_div('summary', $project);
3000         my @tagslist = git_get_tags_list();
3001         if (@tagslist) {
3002                 git_tags_body(\@tagslist);
3003         }
3004         git_footer_html();
3007 sub git_heads {
3008         my $head = git_get_head_hash($project);
3009         git_header_html();
3010         git_print_page_nav('','', $head,undef,$head);
3011         git_print_header_div('summary', $project);
3013         my @headslist = git_get_heads_list();
3014         if (@headslist) {
3015                 git_heads_body(\@headslist, $head);
3016         }
3017         git_footer_html();
3020 sub git_blob_plain {
3021         my $expires;
3023         if (!defined $hash) {
3024                 if (defined $file_name) {
3025                         my $base = $hash_base || git_get_head_hash($project);
3026                         $hash = git_get_hash_by_path($base, $file_name, "blob")
3027                                 or die_error(undef, "Error lookup file");
3028                 } else {
3029                         die_error(undef, "No file name defined");
3030                 }
3031         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3032                 # blobs defined by non-textual hash id's can be cached
3033                 $expires = "+1d";
3034         }
3036         my $type = shift;
3037         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3038                 or die_error(undef, "Couldn't cat $file_name, $hash");
3040         $type ||= blob_mimetype($fd, $file_name);
3042         # save as filename, even when no $file_name is given
3043         my $save_as = "$hash";
3044         if (defined $file_name) {
3045                 $save_as = $file_name;
3046         } elsif ($type =~ m/^text\//) {
3047                 $save_as .= '.txt';
3048         }
3050         print $cgi->header(
3051                 -type => "$type",
3052                 -expires=>$expires,
3053                 -content_disposition => 'inline; filename="' . "$save_as" . '"');
3054         undef $/;
3055         binmode STDOUT, ':raw';
3056         print <$fd>;
3057         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
3058         $/ = "\n";
3059         close $fd;
3062 sub git_blob {
3063         my $expires;
3065         if (!defined $hash) {
3066                 if (defined $file_name) {
3067                         my $base = $hash_base || git_get_head_hash($project);
3068                         $hash = git_get_hash_by_path($base, $file_name, "blob")
3069                                 or die_error(undef, "Error lookup file");
3070                 } else {
3071                         die_error(undef, "No file name defined");
3072                 }
3073         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3074                 # blobs defined by non-textual hash id's can be cached
3075                 $expires = "+1d";
3076         }
3078         my ($have_blame) = gitweb_check_feature('blame');
3079         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3080                 or die_error(undef, "Couldn't cat $file_name, $hash");
3081         my $mimetype = blob_mimetype($fd, $file_name);
3082         if ($mimetype !~ m/^text\//) {
3083                 close $fd;
3084                 return git_blob_plain($mimetype);
3085         }
3086         git_header_html(undef, $expires);
3087         my $formats_nav = '';
3088         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3089                 if (defined $file_name) {
3090                         if ($have_blame) {
3091                                 $formats_nav .=
3092                                         $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
3093                                                                hash=>$hash, file_name=>$file_name)},
3094                                                 "blame") .
3095                                         " | ";
3096                         }
3097                         $formats_nav .=
3098                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3099                                                        hash=>$hash, file_name=>$file_name)},
3100                                         "history") .
3101                                 " | " .
3102                                 $cgi->a({-href => href(action=>"blob_plain",
3103                                                        hash=>$hash, file_name=>$file_name)},
3104                                         "raw") .
3105                                 " | " .
3106                                 $cgi->a({-href => href(action=>"blob",
3107                                                        hash_base=>"HEAD", file_name=>$file_name)},
3108                                         "HEAD");
3109                 } else {
3110                         $formats_nav .=
3111                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
3112                 }
3113                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3114                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3115         } else {
3116                 print "<div class=\"page_nav\">\n" .
3117                       "<br/><br/></div>\n" .
3118                       "<div class=\"title\">$hash</div>\n";
3119         }
3120         git_print_page_path($file_name, "blob", $hash_base);
3121         print "<div class=\"page_body\">\n";
3122         my $nr;
3123         while (my $line = <$fd>) {
3124                 chomp $line;
3125                 $nr++;
3126                 $line = untabify($line);
3127                 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
3128                        $nr, $nr, $nr, esc_html($line, -nbsp=>1);
3129         }
3130         close $fd
3131                 or print "Reading blob failed.\n";
3132         print "</div>";
3133         git_footer_html();
3136 sub git_tree {
3137         my $have_snapshot = gitweb_have_snapshot();
3139         if (!defined $hash_base) {
3140                 $hash_base = "HEAD";
3141         }
3142         if (!defined $hash) {
3143                 if (defined $file_name) {
3144                         $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
3145                 } else {
3146                         $hash = $hash_base;
3147                 }
3148         }
3149         $/ = "\0";
3150         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
3151                 or die_error(undef, "Open git-ls-tree failed");
3152         my @entries = map { chomp; $_ } <$fd>;
3153         close $fd or die_error(undef, "Reading tree failed");
3154         $/ = "\n";
3156         my $refs = git_get_references();
3157         my $ref = format_ref_marker($refs, $hash_base);
3158         git_header_html();
3159         my $basedir = '';
3160         my ($have_blame) = gitweb_check_feature('blame');
3161         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3162                 my @views_nav = ();
3163                 if (defined $file_name) {
3164                         push @views_nav,
3165                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3166                                                        hash=>$hash, file_name=>$file_name)},
3167                                         "history"),
3168                                 $cgi->a({-href => href(action=>"tree",
3169                                                        hash_base=>"HEAD", file_name=>$file_name)},
3170                                         "HEAD"),
3171                 }
3172                 if ($have_snapshot) {
3173                         # FIXME: Should be available when we have no hash base as well.
3174                         push @views_nav,
3175                                 $cgi->a({-href => href(action=>"snapshot", hash=>$hash)},
3176                                         "snapshot");
3177                 }
3178                 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
3179                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
3180         } else {
3181                 undef $hash_base;
3182                 print "<div class=\"page_nav\">\n";
3183                 print "<br/><br/></div>\n";
3184                 print "<div class=\"title\">$hash</div>\n";
3185         }
3186         if (defined $file_name) {
3187                 $basedir = $file_name;
3188                 if ($basedir ne '' && substr($basedir, -1) ne '/') {
3189                         $basedir .= '/';
3190                 }
3191         }
3192         git_print_page_path($file_name, 'tree', $hash_base);
3193         print "<div class=\"page_body\">\n";
3194         print "<table cellspacing=\"0\">\n";
3195         my $alternate = 1;
3196         # '..' (top directory) link if possible
3197         if (defined $hash_base &&
3198             defined $file_name && $file_name =~ m![^/]+$!) {
3199                 if ($alternate) {
3200                         print "<tr class=\"dark\">\n";
3201                 } else {
3202                         print "<tr class=\"light\">\n";
3203                 }
3204                 $alternate ^= 1;
3206                 my $up = $file_name;
3207                 $up =~ s!/?[^/]+$!!;
3208                 undef $up unless $up;
3209                 # based on git_print_tree_entry
3210                 print '<td class="mode">' . mode_str('040000') . "</td>\n";
3211                 print '<td class="list">';
3212                 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
3213                                              file_name=>$up)},
3214                               "..");
3215                 print "</td>\n";
3216                 print "<td class=\"link\"></td>\n";
3218                 print "</tr>\n";
3219         }
3220         foreach my $line (@entries) {
3221                 my %t = parse_ls_tree_line($line, -z => 1);
3223                 if ($alternate) {
3224                         print "<tr class=\"dark\">\n";
3225                 } else {
3226                         print "<tr class=\"light\">\n";
3227                 }
3228                 $alternate ^= 1;
3230                 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
3232                 print "</tr>\n";
3233         }
3234         print "</table>\n" .
3235               "</div>";
3236         git_footer_html();
3239 sub git_snapshot {
3240         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
3241         my $have_snapshot = (defined $ctype && defined $suffix);
3242         if (!$have_snapshot) {
3243                 die_error('403 Permission denied', "Permission denied");
3244         }
3246         if (!defined $hash) {
3247                 $hash = git_get_head_hash($project);
3248         }
3250         my $filename = basename($project) . "-$hash.tar.$suffix";
3252         print $cgi->header(
3253                 -type => 'application/x-tar',
3254                 -content_encoding => $ctype,
3255                 -content_disposition => 'inline; filename="' . "$filename" . '"',
3256                 -status => '200 OK');
3258         my $git = git_cmd_str();
3259         my $name = $project;
3260         $name =~ s/\047/\047\\\047\047/g;
3261         open my $fd, "-|",
3262         "$git archive --format=tar --prefix=\'$name\'/ $hash | $command"
3263                 or die_error(undef, "Execute git-tar-tree failed.");
3264         binmode STDOUT, ':raw';
3265         print <$fd>;
3266         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
3267         close $fd;
3271 sub git_log {
3272         my $head = git_get_head_hash($project);
3273         if (!defined $hash) {
3274                 $hash = $head;
3275         }
3276         if (!defined $page) {
3277                 $page = 0;
3278         }
3279         my $refs = git_get_references();
3281         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3282         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash, "--"
3283                 or die_error(undef, "Open git-rev-list failed");
3284         my @revlist = map { chomp; $_ } <$fd>;
3285         close $fd;
3287         my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
3289         git_header_html();
3290         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
3292         if (!@revlist) {
3293                 my %co = parse_commit($hash);
3295                 git_print_header_div('summary', $project);
3296                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
3297         }
3298         for (my $i = ($page * 100); $i <= $#revlist; $i++) {
3299                 my $commit = $revlist[$i];
3300                 my $ref = format_ref_marker($refs, $commit);
3301                 my %co = parse_commit($commit);
3302                 next if !%co;
3303                 my %ad = parse_date($co{'author_epoch'});
3304                 git_print_header_div('commit',
3305                                "<span class=\"age\">$co{'age_string'}</span>" .
3306                                esc_html($co{'title'}) . $ref,
3307                                $commit);
3308                 print "<div class=\"title_text\">\n" .
3309                       "<div class=\"log_link\">\n" .
3310                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
3311                       " | " .
3312                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
3313                       " | " .
3314                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
3315                       "<br/>\n" .
3316                       "</div>\n" .
3317                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
3318                       "</div>\n";
3320                 print "<div class=\"log_body\">\n";
3321                 git_print_log($co{'comment'}, -final_empty_line=> 1);
3322                 print "</div>\n";
3323         }
3324         git_footer_html();
3327 sub git_commit {
3328         my %co = parse_commit($hash);
3329         if (!%co) {
3330                 die_error(undef, "Unknown commit object");
3331         }
3332         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3333         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
3335         my $parent = $co{'parent'};
3336         if (!defined $parent) {
3337                 $parent = "--root";
3338         }
3339         open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
3340                 @diff_opts, $parent, $hash, "--"
3341                 or die_error(undef, "Open git-diff-tree failed");
3342         my @difftree = map { chomp; $_ } <$fd>;
3343         close $fd or die_error(undef, "Reading git-diff-tree failed");
3345         # non-textual hash id's can be cached
3346         my $expires;
3347         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3348                 $expires = "+1d";
3349         }
3350         my $refs = git_get_references();
3351         my $ref = format_ref_marker($refs, $co{'id'});
3353         my $have_snapshot = gitweb_have_snapshot();
3355         my @views_nav = ();
3356         if (defined $file_name && defined $co{'parent'}) {
3357                 push @views_nav,
3358                         $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)},
3359                                 "blame");
3360         }
3361         git_header_html(undef, $expires);
3362         git_print_page_nav('commit', '',
3363                            $hash, $co{'tree'}, $hash,
3364                            join (' | ', @views_nav));
3366         if (defined $co{'parent'}) {
3367                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
3368         } else {
3369                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
3370         }
3371         print "<div class=\"title_text\">\n" .
3372               "<table cellspacing=\"0\">\n";
3373         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
3374               "<tr>" .
3375               "<td></td><td> $ad{'rfc2822'}";
3376         if ($ad{'hour_local'} < 6) {
3377                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3378                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3379         } else {
3380                 printf(" (%02d:%02d %s)",
3381                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3382         }
3383         print "</td>" .
3384               "</tr>\n";
3385         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
3386         print "<tr><td></td><td> $cd{'rfc2822'}" .
3387               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
3388               "</td></tr>\n";
3389         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
3390         print "<tr>" .
3391               "<td>tree</td>" .
3392               "<td class=\"sha1\">" .
3393               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
3394                        class => "list"}, $co{'tree'}) .
3395               "</td>" .
3396               "<td class=\"link\">" .
3397               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
3398                       "tree");
3399         if ($have_snapshot) {
3400                 print " | " .
3401                       $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
3402         }
3403         print "</td>" .
3404               "</tr>\n";
3405         my $parents = $co{'parents'};
3406         foreach my $par (@$parents) {
3407                 print "<tr>" .
3408                       "<td>parent</td>" .
3409                       "<td class=\"sha1\">" .
3410                       $cgi->a({-href => href(action=>"commit", hash=>$par),
3411                                class => "list"}, $par) .
3412                       "</td>" .
3413                       "<td class=\"link\">" .
3414                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
3415                       " | " .
3416                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
3417                       "</td>" .
3418                       "</tr>\n";
3419         }
3420         print "</table>".
3421               "</div>\n";
3423         print "<div class=\"page_body\">\n";
3424         git_print_log($co{'comment'});
3425         print "</div>\n";
3427         git_difftree_body(\@difftree, $hash, $parent);
3429         git_footer_html();
3432 sub git_blobdiff {
3433         my $format = shift || 'html';
3435         my $fd;
3436         my @difftree;
3437         my %diffinfo;
3438         my $expires;
3440         # preparing $fd and %diffinfo for git_patchset_body
3441         # new style URI
3442         if (defined $hash_base && defined $hash_parent_base) {
3443                 if (defined $file_name) {
3444                         # read raw output
3445                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3446                                 $hash_parent_base, $hash_base,
3447                                 "--", $file_name
3448                                 or die_error(undef, "Open git-diff-tree failed");
3449                         @difftree = map { chomp; $_ } <$fd>;
3450                         close $fd
3451                                 or die_error(undef, "Reading git-diff-tree failed");
3452                         @difftree
3453                                 or die_error('404 Not Found', "Blob diff not found");
3455                 } elsif (defined $hash &&
3456                          $hash =~ /[0-9a-fA-F]{40}/) {
3457                         # try to find filename from $hash
3459                         # read filtered raw output
3460                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3461                                 $hash_parent_base, $hash_base, "--"
3462                                 or die_error(undef, "Open git-diff-tree failed");
3463                         @difftree =
3464                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
3465                                 # $hash == to_id
3466                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
3467                                 map { chomp; $_ } <$fd>;
3468                         close $fd
3469                                 or die_error(undef, "Reading git-diff-tree failed");
3470                         @difftree
3471                                 or die_error('404 Not Found', "Blob diff not found");
3473                 } else {
3474                         die_error('404 Not Found', "Missing one of the blob diff parameters");
3475                 }
3477                 if (@difftree > 1) {
3478                         die_error('404 Not Found', "Ambiguous blob diff specification");
3479                 }
3481                 %diffinfo = parse_difftree_raw_line($difftree[0]);
3482                 $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
3483                 $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
3485                 $hash_parent ||= $diffinfo{'from_id'};
3486                 $hash        ||= $diffinfo{'to_id'};
3488                 # non-textual hash id's can be cached
3489                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
3490                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
3491                         $expires = '+1d';
3492                 }
3494                 # open patch output
3495                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3496                         '-p', $hash_parent_base, $hash_base,
3497                         "--", $file_name
3498                         or die_error(undef, "Open git-diff-tree failed");
3499         }
3501         # old/legacy style URI
3502         if (!%diffinfo && # if new style URI failed
3503             defined $hash && defined $hash_parent) {
3504                 # fake git-diff-tree raw output
3505                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
3506                 $diffinfo{'from_id'} = $hash_parent;
3507                 $diffinfo{'to_id'}   = $hash;
3508                 if (defined $file_name) {
3509                         if (defined $file_parent) {
3510                                 $diffinfo{'status'} = '2';
3511                                 $diffinfo{'from_file'} = $file_parent;
3512                                 $diffinfo{'to_file'}   = $file_name;
3513                         } else { # assume not renamed
3514                                 $diffinfo{'status'} = '1';
3515                                 $diffinfo{'from_file'} = $file_name;
3516                                 $diffinfo{'to_file'}   = $file_name;
3517                         }
3518                 } else { # no filename given
3519                         $diffinfo{'status'} = '2';
3520                         $diffinfo{'from_file'} = $hash_parent;
3521                         $diffinfo{'to_file'}   = $hash;
3522                 }
3524                 # non-textual hash id's can be cached
3525                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
3526                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3527                         $expires = '+1d';
3528                 }
3530                 # open patch output
3531                 open $fd, "-|", git_cmd(), "diff", '-p', @diff_opts,
3532                         $hash_parent, $hash, "--"
3533                         or die_error(undef, "Open git-diff failed");
3534         } else  {
3535                 die_error('404 Not Found', "Missing one of the blob diff parameters")
3536                         unless %diffinfo;
3537         }
3539         # header
3540         if ($format eq 'html') {
3541                 my $formats_nav =
3542                         $cgi->a({-href => href(action=>"blobdiff_plain",
3543                                                hash=>$hash, hash_parent=>$hash_parent,
3544                                                hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
3545                                                file_name=>$file_name, file_parent=>$file_parent)},
3546                                 "raw");
3547                 git_header_html(undef, $expires);
3548                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3549                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3550                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3551                 } else {
3552                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
3553                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
3554                 }
3555                 if (defined $file_name) {
3556                         git_print_page_path($file_name, "blob", $hash_base);
3557                 } else {
3558                         print "<div class=\"page_path\"></div>\n";
3559                 }
3561         } elsif ($format eq 'plain') {
3562                 print $cgi->header(
3563                         -type => 'text/plain',
3564                         -charset => 'utf-8',
3565                         -expires => $expires,
3566                         -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
3568                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3570         } else {
3571                 die_error(undef, "Unknown blobdiff format");
3572         }
3574         # patch
3575         if ($format eq 'html') {
3576                 print "<div class=\"page_body\">\n";
3578                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
3579                 close $fd;
3581                 print "</div>\n"; # class="page_body"
3582                 git_footer_html();
3584         } else {
3585                 while (my $line = <$fd>) {
3586                         $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
3587                         $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
3589                         print $line;
3591                         last if $line =~ m!^\+\+\+!;
3592                 }
3593                 local $/ = undef;
3594                 print <$fd>;
3595                 close $fd;
3596         }
3599 sub git_blobdiff_plain {
3600         git_blobdiff('plain');
3603 sub git_commitdiff {
3604         my $format = shift || 'html';
3605         my %co = parse_commit($hash);
3606         if (!%co) {
3607                 die_error(undef, "Unknown commit object");
3608         }
3610         # we need to prepare $formats_nav before any parameter munging
3611         my $formats_nav;
3612         if ($format eq 'html') {
3613                 $formats_nav =
3614                         $cgi->a({-href => href(action=>"commitdiff_plain",
3615                                                hash=>$hash, hash_parent=>$hash_parent)},
3616                                 "raw");
3618                 if (defined $hash_parent) {
3619                         # commitdiff with two commits given
3620                         my $hash_parent_short = $hash_parent;
3621                         if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3622                                 $hash_parent_short = substr($hash_parent, 0, 7);
3623                         }
3624                         $formats_nav .=
3625                                 ' (from: ' .
3626                                 $cgi->a({-href => href(action=>"commitdiff",
3627                                                        hash=>$hash_parent)},
3628                                         esc_html($hash_parent_short)) .
3629                                 ')';
3630                 } elsif (!$co{'parent'}) {
3631                         # --root commitdiff
3632                         $formats_nav .= ' (initial)';
3633                 } elsif (scalar @{$co{'parents'}} == 1) {
3634                         # single parent commit
3635                         $formats_nav .=
3636                                 ' (parent: ' .
3637                                 $cgi->a({-href => href(action=>"commitdiff",
3638                                                        hash=>$co{'parent'})},
3639                                         esc_html(substr($co{'parent'}, 0, 7))) .
3640                                 ')';
3641                 } else {
3642                         # merge commit
3643                         $formats_nav .=
3644                                 ' (merge: ' .
3645                                 join(' ', map {
3646                                         $cgi->a({-href => href(action=>"commitdiff",
3647                                                                hash=>$_)},
3648                                                 esc_html(substr($_, 0, 7)));
3649                                 } @{$co{'parents'}} ) .
3650                                 ')';
3651                 }
3652         }
3654         if (!defined $hash_parent) {
3655                 $hash_parent = $co{'parent'} || '--root';
3656         }
3658         # read commitdiff
3659         my $fd;
3660         my @difftree;
3661         if ($format eq 'html') {
3662                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3663                         "--no-commit-id", "--patch-with-raw", "--full-index",
3664                         $hash_parent, $hash, "--"
3665                         or die_error(undef, "Open git-diff-tree failed");
3667                 while (chomp(my $line = <$fd>)) {
3668                         # empty line ends raw part of diff-tree output
3669                         last unless $line;
3670                         push @difftree, $line;
3671                 }
3673         } elsif ($format eq 'plain') {
3674                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3675                         '-p', $hash_parent, $hash, "--"
3676                         or die_error(undef, "Open git-diff-tree failed");
3678         } else {
3679                 die_error(undef, "Unknown commitdiff format");
3680         }
3682         # non-textual hash id's can be cached
3683         my $expires;
3684         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3685                 $expires = "+1d";
3686         }
3688         # write commit message
3689         if ($format eq 'html') {
3690                 my $refs = git_get_references();
3691                 my $ref = format_ref_marker($refs, $co{'id'});
3693                 git_header_html(undef, $expires);
3694                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
3695                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
3696                 git_print_authorship(\%co);
3697                 print "<div class=\"page_body\">\n";
3698                 if (@{$co{'comment'}} > 1) {
3699                         print "<div class=\"log\">\n";
3700                         git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
3701                         print "</div>\n"; # class="log"
3702                 }
3704         } elsif ($format eq 'plain') {
3705                 my $refs = git_get_references("tags");
3706                 my $tagname = git_get_rev_name_tags($hash);
3707                 my $filename = basename($project) . "-$hash.patch";
3709                 print $cgi->header(
3710                         -type => 'text/plain',
3711                         -charset => 'utf-8',
3712                         -expires => $expires,
3713                         -content_disposition => 'inline; filename="' . "$filename" . '"');
3714                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3715                 print <<TEXT;
3716 From: $co{'author'}
3717 Date: $ad{'rfc2822'} ($ad{'tz_local'})
3718 Subject: $co{'title'}
3719 TEXT
3720                 print "X-Git-Tag: $tagname\n" if $tagname;
3721                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3723                 foreach my $line (@{$co{'comment'}}) {
3724                         print "$line\n";
3725                 }
3726                 print "---\n\n";
3727         }
3729         # write patch
3730         if ($format eq 'html') {
3731                 git_difftree_body(\@difftree, $hash, $hash_parent);
3732                 print "<br/>\n";
3734                 git_patchset_body($fd, \@difftree, $hash, $hash_parent);
3735                 close $fd;
3736                 print "</div>\n"; # class="page_body"
3737                 git_footer_html();
3739         } elsif ($format eq 'plain') {
3740                 local $/ = undef;
3741                 print <$fd>;
3742                 close $fd
3743                         or print "Reading git-diff-tree failed\n";
3744         }
3747 sub git_commitdiff_plain {
3748         git_commitdiff('plain');
3751 sub git_history {
3752         if (!defined $hash_base) {
3753                 $hash_base = git_get_head_hash($project);
3754         }
3755         if (!defined $page) {
3756                 $page = 0;
3757         }
3758         my $ftype;
3759         my %co = parse_commit($hash_base);
3760         if (!%co) {
3761                 die_error(undef, "Unknown commit object");
3762         }
3764         my $refs = git_get_references();
3765         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3767         if (!defined $hash && defined $file_name) {
3768                 $hash = git_get_hash_by_path($hash_base, $file_name);
3769         }
3770         if (defined $hash) {
3771                 $ftype = git_get_type($hash);
3772         }
3774         open my $fd, "-|",
3775                 git_cmd(), "rev-list", $limit, "--full-history", $hash_base, "--", $file_name
3776                         or die_error(undef, "Open git-rev-list-failed");
3777         my @revlist = map { chomp; $_ } <$fd>;
3778         close $fd
3779                 or die_error(undef, "Reading git-rev-list failed");
3781         my $paging_nav = '';
3782         if ($page > 0) {
3783                 $paging_nav .=
3784                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3785                                                file_name=>$file_name)},
3786                                 "first");
3787                 $paging_nav .= " &sdot; " .
3788                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3789                                                file_name=>$file_name, page=>$page-1),
3790                                  -accesskey => "p", -title => "Alt-p"}, "prev");
3791         } else {
3792                 $paging_nav .= "first";
3793                 $paging_nav .= " &sdot; prev";
3794         }
3795         if ($#revlist >= (100 * ($page+1)-1)) {
3796                 $paging_nav .= " &sdot; " .
3797                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3798                                                file_name=>$file_name, page=>$page+1),
3799                                  -accesskey => "n", -title => "Alt-n"}, "next");
3800         } else {
3801                 $paging_nav .= " &sdot; next";
3802         }
3803         my $next_link = '';
3804         if ($#revlist >= (100 * ($page+1)-1)) {
3805                 $next_link =
3806                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3807                                                file_name=>$file_name, page=>$page+1),
3808                                  -title => "Alt-n"}, "next");
3809         }
3811         git_header_html();
3812         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
3813         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3814         git_print_page_path($file_name, $ftype, $hash_base);
3816         git_history_body(\@revlist, ($page * 100), $#revlist,
3817                          $refs, $hash_base, $ftype, $next_link);
3819         git_footer_html();
3822 sub git_search {
3823         if (!defined $searchtext) {
3824                 die_error(undef, "Text field empty");
3825         }
3826         if (!defined $hash) {
3827                 $hash = git_get_head_hash($project);
3828         }
3829         my %co = parse_commit($hash);
3830         if (!%co) {
3831                 die_error(undef, "Unknown commit object");
3832         }
3834         $searchtype ||= 'commit';
3835         if ($searchtype eq 'pickaxe') {
3836                 # pickaxe may take all resources of your box and run for several minutes
3837                 # with every query - so decide by yourself how public you make this feature
3838                 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
3839                 if (!$have_pickaxe) {
3840                         die_error('403 Permission denied', "Permission denied");
3841                 }
3842         }
3844         git_header_html();
3845         git_print_page_nav('','', $hash,$co{'tree'},$hash);
3846         git_print_header_div('commit', esc_html($co{'title'}), $hash);
3848         print "<table cellspacing=\"0\">\n";
3849         my $alternate = 1;
3850         if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
3851                 $/ = "\0";
3852                 open my $fd, "-|", git_cmd(), "rev-list",
3853                         "--header", "--parents", $hash, "--"
3854                         or next;
3855                 while (my $commit_text = <$fd>) {
3856                         if (!grep m/$searchtext/i, $commit_text) {
3857                                 next;
3858                         }
3859                         if ($searchtype eq 'author' && !grep m/\nauthor .*$searchtext/i, $commit_text) {
3860                                 next;
3861                         }
3862                         if ($searchtype eq 'committer' && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
3863                                 next;
3864                         }
3865                         my @commit_lines = split "\n", $commit_text;
3866                         my %co = parse_commit(undef, \@commit_lines);
3867                         if (!%co) {
3868                                 next;
3869                         }
3870                         if ($alternate) {
3871                                 print "<tr class=\"dark\">\n";
3872                         } else {
3873                                 print "<tr class=\"light\">\n";
3874                         }
3875                         $alternate ^= 1;
3876                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3877                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3878                               "<td>" .
3879                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3880                                        esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3881                         my $comment = $co{'comment'};
3882                         foreach my $line (@$comment) {
3883                                 if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
3884                                         my $lead = esc_html($1) || "";
3885                                         $lead = chop_str($lead, 30, 10);
3886                                         my $match = esc_html($2) || "";
3887                                         my $trail = esc_html($3) || "";
3888                                         $trail = chop_str($trail, 30, 10);
3889                                         my $text = "$lead<span class=\"match\">$match</span>$trail";
3890                                         print chop_str($text, 80, 5) . "<br/>\n";
3891                                 }
3892                         }
3893                         print "</td>\n" .
3894                               "<td class=\"link\">" .
3895                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3896                               " | " .
3897                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3898                         print "</td>\n" .
3899                               "</tr>\n";
3900                 }
3901                 close $fd;
3902         }
3904         if ($searchtype eq 'pickaxe') {
3905                 $/ = "\n";
3906                 my $git_command = git_cmd_str();
3907                 open my $fd, "-|", "$git_command rev-list $hash | " .
3908                         "$git_command diff-tree -r --stdin -S\'$searchtext\'";
3909                 undef %co;
3910                 my @files;
3911                 while (my $line = <$fd>) {
3912                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
3913                                 my %set;
3914                                 $set{'file'} = $6;
3915                                 $set{'from_id'} = $3;
3916                                 $set{'to_id'} = $4;
3917                                 $set{'id'} = $set{'to_id'};
3918                                 if ($set{'id'} =~ m/0{40}/) {
3919                                         $set{'id'} = $set{'from_id'};
3920                                 }
3921                                 if ($set{'id'} =~ m/0{40}/) {
3922                                         next;
3923                                 }
3924                                 push @files, \%set;
3925                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
3926                                 if (%co) {
3927                                         if ($alternate) {
3928                                                 print "<tr class=\"dark\">\n";
3929                                         } else {
3930                                                 print "<tr class=\"light\">\n";
3931                                         }
3932                                         $alternate ^= 1;
3933                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3934                                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3935                                               "<td>" .
3936                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
3937                                                       -class => "list subject"},
3938                                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3939                                         while (my $setref = shift @files) {
3940                                                 my %set = %$setref;
3941                                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
3942                                                                              hash=>$set{'id'}, file_name=>$set{'file'}),
3943                                                               -class => "list"},
3944                                                               "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
3945                                                       "<br/>\n";
3946                                         }
3947                                         print "</td>\n" .
3948                                               "<td class=\"link\">" .
3949                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3950                                               " | " .
3951                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3952                                         print "</td>\n" .
3953                                               "</tr>\n";
3954                                 }
3955                                 %co = parse_commit($1);
3956                         }
3957                 }
3958                 close $fd;
3959         }
3960         print "</table>\n";
3961         git_footer_html();
3964 sub git_search_help {
3965         git_header_html();
3966         git_print_page_nav('','', $hash,$hash,$hash);
3967         print <<EOT;
3968 <dl>
3969 <dt><b>commit</b></dt>
3970 <dd>The commit messages and authorship information will be scanned for the given string.</dd>
3971 <dt><b>author</b></dt>
3972 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given string.</dd>
3973 <dt><b>committer</b></dt>
3974 <dd>Name and e-mail of the committer and date of commit will be scanned for the given string.</dd>
3975 EOT
3976         my ($have_pickaxe) = gitweb_check_feature('pickaxe');
3977         if ($have_pickaxe) {
3978                 print <<EOT;
3979 <dt><b>pickaxe</b></dt>
3980 <dd>All commits that caused the string to appear or disappear from any file (changes that
3981 added, removed or "modified" the string) will be listed. This search can take a while and
3982 takes a lot of strain on the server, so please use it wisely.</dd>
3983 EOT
3984         }
3985         print "</dl>\n";
3986         git_footer_html();
3989 sub git_shortlog {
3990         my $head = git_get_head_hash($project);
3991         if (!defined $hash) {
3992                 $hash = $head;
3993         }
3994         if (!defined $page) {
3995                 $page = 0;
3996         }
3997         my $refs = git_get_references();
3999         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
4000         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash, "--"
4001                 or die_error(undef, "Open git-rev-list failed");
4002         my @revlist = map { chomp; $_ } <$fd>;
4003         close $fd;
4005         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
4006         my $next_link = '';
4007         if ($#revlist >= (100 * ($page+1)-1)) {
4008                 $next_link =
4009                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
4010                                  -title => "Alt-n"}, "next");
4011         }
4014         git_header_html();
4015         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
4016         git_print_header_div('summary', $project);
4018         git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
4020         git_footer_html();
4023 ## ......................................................................
4024 ## feeds (RSS, OPML)
4026 sub git_rss {
4027         # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
4028         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=150",
4029                 git_get_head_hash($project), "--"
4030                 or die_error(undef, "Open git-rev-list failed");
4031         my @revlist = map { chomp; $_ } <$fd>;
4032         close $fd or die_error(undef, "Reading git-rev-list failed");
4033         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
4034         print <<XML;
4035 <?xml version="1.0" encoding="utf-8"?>
4036 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
4037 <channel>
4038 <title>$project $my_uri $my_url</title>
4039 <link>${\esc_html("$my_url?p=$project;a=summary")}</link>
4040 <description>$project log</description>
4041 <language>en</language>
4042 XML
4044         for (my $i = 0; $i <= $#revlist; $i++) {
4045                 my $commit = $revlist[$i];
4046                 my %co = parse_commit($commit);
4047                 # we read 150, we always show 30 and the ones more recent than 48 hours
4048                 if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
4049                         last;
4050                 }
4051                 my %cd = parse_date($co{'committer_epoch'});
4052                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4053                         $co{'parent'}, $co{'id'}, "--"
4054                         or next;
4055                 my @difftree = map { chomp; $_ } <$fd>;
4056                 close $fd
4057                         or next;
4058                 print "<item>\n" .
4059                       "<title>" .
4060                       sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
4061                       "</title>\n" .
4062                       "<author>" . esc_html($co{'author'}) . "</author>\n" .
4063                       "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
4064                       "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
4065                       "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
4066                       "<description>" . esc_html($co{'title'}) . "</description>\n" .
4067                       "<content:encoded>" .
4068                       "<![CDATA[\n";
4069                 my $comment = $co{'comment'};
4070                 foreach my $line (@$comment) {
4071                         $line = to_utf8($line);
4072                         print "$line<br/>\n";
4073                 }
4074                 print "<br/>\n";
4075                 foreach my $line (@difftree) {
4076                         if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
4077                                 next;
4078                         }
4079                         my $file = esc_path(unquote($7));
4080                         $file = to_utf8($file);
4081                         print "$file<br/>\n";
4082                 }
4083                 print "]]>\n" .
4084                       "</content:encoded>\n" .
4085                       "</item>\n";
4086         }
4087         print "</channel></rss>";
4090 sub git_opml {
4091         my @list = git_get_projects_list();
4093         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
4094         print <<XML;
4095 <?xml version="1.0" encoding="utf-8"?>
4096 <opml version="1.0">
4097 <head>
4098   <title>$site_name OPML Export</title>
4099 </head>
4100 <body>
4101 <outline text="git RSS feeds">
4102 XML
4104         foreach my $pr (@list) {
4105                 my %proj = %$pr;
4106                 my $head = git_get_head_hash($proj{'path'});
4107                 if (!defined $head) {
4108                         next;
4109                 }
4110                 $git_dir = "$projectroot/$proj{'path'}";
4111                 my %co = parse_commit($head);
4112                 if (!%co) {
4113                         next;
4114                 }
4116                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
4117                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
4118                 my $html = "$my_url?p=$proj{'path'};a=summary";
4119                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
4120         }
4121         print <<XML;
4122 </outline>
4123 </body>
4124 </opml>
4125 XML