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