gitweb: unify boolean feature subroutines
[git] / gitweb / gitweb.perl
1 #!/usr/bin/perl
2
3 # gitweb - simple web interface to track changes in git repositories
4 #
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
7 #
8 # This program is licensed under the GPLv2
9
10 use strict;
11 use warnings;
12 use CGI qw(:standard :escapeHTML -nosticky);
13 use CGI::Util qw(unescape);
14 use CGI::Carp qw(fatalsToBrowser);
15 use Encode;
16 use Fcntl ':mode';
17 use File::Find qw();
18 use File::Basename qw(basename);
19 binmode STDOUT, ':utf8';
20
21 BEGIN {
22         CGI->compile() if $ENV{'MOD_PERL'};
23 }
24
25 our $cgi = new CGI;
26 our $version = "++GIT_VERSION++";
27 our $my_url = $cgi->url();
28 our $my_uri = $cgi->url(-absolute => 1);
29
30 # if we're called with PATH_INFO, we have to strip that
31 # from the URL to find our real URL
32 # we make $path_info global because it's also used later on
33 our $path_info = $ENV{"PATH_INFO"};
34 if ($path_info) {
35         $my_url =~ s,\Q$path_info\E$,,;
36         $my_uri =~ s,\Q$path_info\E$,,;
37 }
38
39 # core git executable to use
40 # this can just be "git" if your webserver has a sensible PATH
41 our $GIT = "++GIT_BINDIR++/git";
42
43 # absolute fs-path which will be prepended to the project path
44 #our $projectroot = "/pub/scm";
45 our $projectroot = "++GITWEB_PROJECTROOT++";
46
47 # fs traversing limit for getting project list
48 # the number is relative to the projectroot
49 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
50
51 # target of the home link on top of all pages
52 our $home_link = $my_uri || "/";
53
54 # string of the home link on top of all pages
55 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
56
57 # name of your site or organization to appear in page titles
58 # replace this with something more descriptive for clearer bookmarks
59 our $site_name = "++GITWEB_SITENAME++"
60                  || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
61
62 # filename of html text to include at top of each page
63 our $site_header = "++GITWEB_SITE_HEADER++";
64 # html text to include at home page
65 our $home_text = "++GITWEB_HOMETEXT++";
66 # filename of html text to include at bottom of each page
67 our $site_footer = "++GITWEB_SITE_FOOTER++";
68
69 # URI of stylesheets
70 our @stylesheets = ("++GITWEB_CSS++");
71 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
72 our $stylesheet = undef;
73 # URI of GIT logo (72x27 size)
74 our $logo = "++GITWEB_LOGO++";
75 # URI of GIT favicon, assumed to be image/png type
76 our $favicon = "++GITWEB_FAVICON++";
77
78 # URI and label (title) of GIT logo link
79 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
80 #our $logo_label = "git documentation";
81 our $logo_url = "http://git.or.cz/";
82 our $logo_label = "git homepage";
83
84 # source of projects list
85 our $projects_list = "++GITWEB_LIST++";
86
87 # the width (in characters) of the projects list "Description" column
88 our $projects_list_description_width = 25;
89
90 # default order of projects list
91 # valid values are none, project, descr, owner, and age
92 our $default_projects_order = "project";
93
94 # show repository only if this file exists
95 # (only effective if this variable evaluates to true)
96 our $export_ok = "++GITWEB_EXPORT_OK++";
97
98 # show repository only if this subroutine returns true
99 # when given the path to the project, for example:
100 #    sub { return -e "$_[0]/git-daemon-export-ok"; }
101 our $export_auth_hook = undef;
102
103 # only allow viewing of repositories also shown on the overview page
104 our $strict_export = "++GITWEB_STRICT_EXPORT++";
105
106 # list of git base URLs used for URL to where fetch project from,
107 # i.e. full URL is "$git_base_url/$project"
108 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
109
110 # default blob_plain mimetype and default charset for text/plain blob
111 our $default_blob_plain_mimetype = 'text/plain';
112 our $default_text_plain_charset  = undef;
113
114 # file to use for guessing MIME types before trying /etc/mime.types
115 # (relative to the current git repository)
116 our $mimetypes_file = undef;
117
118 # assume this charset if line contains non-UTF-8 characters;
119 # it should be valid encoding (see Encoding::Supported(3pm) for list),
120 # for which encoding all byte sequences are valid, for example
121 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
122 # could be even 'utf-8' for the old behavior)
123 our $fallback_encoding = 'latin1';
124
125 # rename detection options for git-diff and git-diff-tree
126 # - default is '-M', with the cost proportional to
127 #   (number of removed files) * (number of new files).
128 # - more costly is '-C' (which implies '-M'), with the cost proportional to
129 #   (number of changed files + number of removed files) * (number of new files)
130 # - even more costly is '-C', '--find-copies-harder' with cost
131 #   (number of files in the original tree) * (number of new files)
132 # - one might want to include '-B' option, e.g. '-B', '-M'
133 our @diff_opts = ('-M'); # taken from git_commit
134
135 # information about snapshot formats that gitweb is capable of serving
136 our %known_snapshot_formats = (
137         # name => {
138         #       'display' => display name,
139         #       'type' => mime type,
140         #       'suffix' => filename suffix,
141         #       'format' => --format for git-archive,
142         #       'compressor' => [compressor command and arguments]
143         #                       (array reference, optional)}
144         #
145         'tgz' => {
146                 'display' => 'tar.gz',
147                 'type' => 'application/x-gzip',
148                 'suffix' => '.tar.gz',
149                 'format' => 'tar',
150                 'compressor' => ['gzip']},
151
152         'tbz2' => {
153                 'display' => 'tar.bz2',
154                 'type' => 'application/x-bzip2',
155                 'suffix' => '.tar.bz2',
156                 'format' => 'tar',
157                 'compressor' => ['bzip2']},
158
159         'zip' => {
160                 'display' => 'zip',
161                 'type' => 'application/x-zip',
162                 'suffix' => '.zip',
163                 'format' => 'zip'},
164 );
165
166 # Aliases so we understand old gitweb.snapshot values in repository
167 # configuration.
168 our %known_snapshot_format_aliases = (
169         'gzip'  => 'tgz',
170         'bzip2' => 'tbz2',
171
172         # backward compatibility: legacy gitweb config support
173         'x-gzip' => undef, 'gz' => undef,
174         'x-bzip2' => undef, 'bz2' => undef,
175         'x-zip' => undef, '' => undef,
176 );
177
178 # You define site-wide feature defaults here; override them with
179 # $GITWEB_CONFIG as necessary.
180 our %feature = (
181         # feature => {
182         #       'sub' => feature-sub (subroutine),
183         #       'override' => allow-override (boolean),
184         #       'default' => [ default options...] (array reference)}
185         #
186         # if feature is overridable (it means that allow-override has true value),
187         # then feature-sub will be called with default options as parameters;
188         # return value of feature-sub indicates if to enable specified feature
189         #
190         # if there is no 'sub' key (no feature-sub), then feature cannot be
191         # overriden
192         #
193         # use gitweb_get_feature(<feature>) to retrieve the <feature> value
194         # (an array) or gitweb_check_feature(<feature>) to check if <feature>
195         # is enabled
196
197         # Enable the 'blame' blob view, showing the last commit that modified
198         # each line in the file. This can be very CPU-intensive.
199
200         # To enable system wide have in $GITWEB_CONFIG
201         # $feature{'blame'}{'default'} = [1];
202         # To have project specific config enable override in $GITWEB_CONFIG
203         # $feature{'blame'}{'override'} = 1;
204         # and in project config gitweb.blame = 0|1;
205         'blame' => {
206                 'sub' => sub { feature_bool('blame', @_) },
207                 'override' => 0,
208                 'default' => [0]},
209
210         # Enable the 'snapshot' link, providing a compressed archive of any
211         # tree. This can potentially generate high traffic if you have large
212         # project.
213
214         # Value is a list of formats defined in %known_snapshot_formats that
215         # you wish to offer.
216         # To disable system wide have in $GITWEB_CONFIG
217         # $feature{'snapshot'}{'default'} = [];
218         # To have project specific config enable override in $GITWEB_CONFIG
219         # $feature{'snapshot'}{'override'} = 1;
220         # and in project config, a comma-separated list of formats or "none"
221         # to disable.  Example: gitweb.snapshot = tbz2,zip;
222         'snapshot' => {
223                 'sub' => \&feature_snapshot,
224                 'override' => 0,
225                 'default' => ['tgz']},
226
227         # Enable text search, which will list the commits which match author,
228         # committer or commit text to a given string.  Enabled by default.
229         # Project specific override is not supported.
230         'search' => {
231                 'override' => 0,
232                 'default' => [1]},
233
234         # Enable grep search, which will list the files in currently selected
235         # tree containing the given string. Enabled by default. This can be
236         # potentially CPU-intensive, of course.
237
238         # To enable system wide have in $GITWEB_CONFIG
239         # $feature{'grep'}{'default'} = [1];
240         # To have project specific config enable override in $GITWEB_CONFIG
241         # $feature{'grep'}{'override'} = 1;
242         # and in project config gitweb.grep = 0|1;
243         'grep' => {
244                 'sub' => sub { feature_bool('grep', @_) },
245                 'override' => 0,
246                 'default' => [1]},
247
248         # Enable the pickaxe search, which will list the commits that modified
249         # a given string in a file. This can be practical and quite faster
250         # alternative to 'blame', but still potentially CPU-intensive.
251
252         # To enable system wide have in $GITWEB_CONFIG
253         # $feature{'pickaxe'}{'default'} = [1];
254         # To have project specific config enable override in $GITWEB_CONFIG
255         # $feature{'pickaxe'}{'override'} = 1;
256         # and in project config gitweb.pickaxe = 0|1;
257         'pickaxe' => {
258                 'sub' => sub { feature_bool('pickaxe', @_) },
259                 'override' => 0,
260                 'default' => [1]},
261
262         # Make gitweb use an alternative format of the URLs which can be
263         # more readable and natural-looking: project name is embedded
264         # directly in the path and the query string contains other
265         # auxiliary information. All gitweb installations recognize
266         # URL in either format; this configures in which formats gitweb
267         # generates links.
268
269         # To enable system wide have in $GITWEB_CONFIG
270         # $feature{'pathinfo'}{'default'} = [1];
271         # Project specific override is not supported.
272
273         # Note that you will need to change the default location of CSS,
274         # favicon, logo and possibly other files to an absolute URL. Also,
275         # if gitweb.cgi serves as your indexfile, you will need to force
276         # $my_uri to contain the script name in your $GITWEB_CONFIG.
277         'pathinfo' => {
278                 'override' => 0,
279                 'default' => [0]},
280
281         # Make gitweb consider projects in project root subdirectories
282         # to be forks of existing projects. Given project $projname.git,
283         # projects matching $projname/*.git will not be shown in the main
284         # projects list, instead a '+' mark will be added to $projname
285         # there and a 'forks' view will be enabled for the project, listing
286         # all the forks. If project list is taken from a file, forks have
287         # to be listed after the main project.
288
289         # To enable system wide have in $GITWEB_CONFIG
290         # $feature{'forks'}{'default'} = [1];
291         # Project specific override is not supported.
292         'forks' => {
293                 'override' => 0,
294                 'default' => [0]},
295
296         # Insert custom links to the action bar of all project pages.
297         # This enables you mainly to link to third-party scripts integrating
298         # into gitweb; e.g. git-browser for graphical history representation
299         # or custom web-based repository administration interface.
300
301         # The 'default' value consists of a list of triplets in the form
302         # (label, link, position) where position is the label after which
303         # to insert the link and link is a format string where %n expands
304         # to the project name, %f to the project path within the filesystem,
305         # %h to the current hash (h gitweb parameter) and %b to the current
306         # hash base (hb gitweb parameter); %% expands to %.
307
308         # To enable system wide have in $GITWEB_CONFIG e.g.
309         # $feature{'actions'}{'default'} = [('graphiclog',
310         #       '/git-browser/by-commit.html?r=%n', 'summary')];
311         # Project specific override is not supported.
312         'actions' => {
313                 'override' => 0,
314                 'default' => []},
315
316         # Allow gitweb scan project content tags described in ctags/
317         # of project repository, and display the popular Web 2.0-ish
318         # "tag cloud" near the project list. Note that this is something
319         # COMPLETELY different from the normal Git tags.
320
321         # gitweb by itself can show existing tags, but it does not handle
322         # tagging itself; you need an external application for that.
323         # For an example script, check Girocco's cgi/tagproj.cgi.
324         # You may want to install the HTML::TagCloud Perl module to get
325         # a pretty tag cloud instead of just a list of tags.
326
327         # To enable system wide have in $GITWEB_CONFIG
328         # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
329         # Project specific override is not supported.
330         'ctags' => {
331                 'override' => 0,
332                 'default' => [0]},
333 );
334
335 sub gitweb_get_feature {
336         my ($name) = @_;
337         return unless exists $feature{$name};
338         my ($sub, $override, @defaults) = (
339                 $feature{$name}{'sub'},
340                 $feature{$name}{'override'},
341                 @{$feature{$name}{'default'}});
342         if (!$override) { return @defaults; }
343         if (!defined $sub) {
344                 warn "feature $name is not overrideable";
345                 return @defaults;
346         }
347         return $sub->(@defaults);
348 }
349
350 # A wrapper to check if a given feature is enabled.
351 # With this, you can say
352 #
353 #   my $bool_feat = gitweb_check_feature('bool_feat');
354 #   gitweb_check_feature('bool_feat') or somecode;
355 #
356 # instead of
357 #
358 #   my ($bool_feat) = gitweb_get_feature('bool_feat');
359 #   (gitweb_get_feature('bool_feat'))[0] or somecode;
360 #
361 sub gitweb_check_feature {
362         return (gitweb_get_feature(@_))[0];
363 }
364
365
366 sub feature_bool {
367         my $key = shift;
368         my ($val) = git_get_project_config($key, '--bool');
369
370         if ($val eq 'true') {
371                 return (1);
372         } elsif ($val eq 'false') {
373                 return (0);
374         }
375
376         return ($_[0]);
377 }
378
379 sub feature_snapshot {
380         my (@fmts) = @_;
381
382         my ($val) = git_get_project_config('snapshot');
383
384         if ($val) {
385                 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
386         }
387
388         return @fmts;
389 }
390
391 # checking HEAD file with -e is fragile if the repository was
392 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
393 # and then pruned.
394 sub check_head_link {
395         my ($dir) = @_;
396         my $headfile = "$dir/HEAD";
397         return ((-e $headfile) ||
398                 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
399 }
400
401 sub check_export_ok {
402         my ($dir) = @_;
403         return (check_head_link($dir) &&
404                 (!$export_ok || -e "$dir/$export_ok") &&
405                 (!$export_auth_hook || $export_auth_hook->($dir)));
406 }
407
408 # process alternate names for backward compatibility
409 # filter out unsupported (unknown) snapshot formats
410 sub filter_snapshot_fmts {
411         my @fmts = @_;
412
413         @fmts = map {
414                 exists $known_snapshot_format_aliases{$_} ?
415                        $known_snapshot_format_aliases{$_} : $_} @fmts;
416         @fmts = grep(exists $known_snapshot_formats{$_}, @fmts);
417
418 }
419
420 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
421 if (-e $GITWEB_CONFIG) {
422         do $GITWEB_CONFIG;
423 } else {
424         our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
425         do $GITWEB_CONFIG_SYSTEM if -e $GITWEB_CONFIG_SYSTEM;
426 }
427
428 # version of the core git binary
429 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
430
431 $projects_list ||= $projectroot;
432
433 # ======================================================================
434 # input validation and dispatch
435
436 # input parameters can be collected from a variety of sources (presently, CGI
437 # and PATH_INFO), so we define an %input_params hash that collects them all
438 # together during validation: this allows subsequent uses (e.g. href()) to be
439 # agnostic of the parameter origin
440
441 our %input_params = ();
442
443 # input parameters are stored with the long parameter name as key. This will
444 # also be used in the href subroutine to convert parameters to their CGI
445 # equivalent, and since the href() usage is the most frequent one, we store
446 # the name -> CGI key mapping here, instead of the reverse.
447 #
448 # XXX: Warning: If you touch this, check the search form for updating,
449 # too.
450
451 our @cgi_param_mapping = (
452         project => "p",
453         action => "a",
454         file_name => "f",
455         file_parent => "fp",
456         hash => "h",
457         hash_parent => "hp",
458         hash_base => "hb",
459         hash_parent_base => "hpb",
460         page => "pg",
461         order => "o",
462         searchtext => "s",
463         searchtype => "st",
464         snapshot_format => "sf",
465         extra_options => "opt",
466         search_use_regexp => "sr",
467 );
468 our %cgi_param_mapping = @cgi_param_mapping;
469
470 # we will also need to know the possible actions, for validation
471 our %actions = (
472         "blame" => \&git_blame,
473         "blobdiff" => \&git_blobdiff,
474         "blobdiff_plain" => \&git_blobdiff_plain,
475         "blob" => \&git_blob,
476         "blob_plain" => \&git_blob_plain,
477         "commitdiff" => \&git_commitdiff,
478         "commitdiff_plain" => \&git_commitdiff_plain,
479         "commit" => \&git_commit,
480         "forks" => \&git_forks,
481         "heads" => \&git_heads,
482         "history" => \&git_history,
483         "log" => \&git_log,
484         "rss" => \&git_rss,
485         "atom" => \&git_atom,
486         "search" => \&git_search,
487         "search_help" => \&git_search_help,
488         "shortlog" => \&git_shortlog,
489         "summary" => \&git_summary,
490         "tag" => \&git_tag,
491         "tags" => \&git_tags,
492         "tree" => \&git_tree,
493         "snapshot" => \&git_snapshot,
494         "object" => \&git_object,
495         # those below don't need $project
496         "opml" => \&git_opml,
497         "project_list" => \&git_project_list,
498         "project_index" => \&git_project_index,
499 );
500
501 # finally, we have the hash of allowed extra_options for the commands that
502 # allow them
503 our %allowed_options = (
504         "--no-merges" => [ qw(rss atom log shortlog history) ],
505 );
506
507 # fill %input_params with the CGI parameters. All values except for 'opt'
508 # should be single values, but opt can be an array. We should probably
509 # build an array of parameters that can be multi-valued, but since for the time
510 # being it's only this one, we just single it out
511 while (my ($name, $symbol) = each %cgi_param_mapping) {
512         if ($symbol eq 'opt') {
513                 $input_params{$name} = [ $cgi->param($symbol) ];
514         } else {
515                 $input_params{$name} = $cgi->param($symbol);
516         }
517 }
518
519 # now read PATH_INFO and update the parameter list for missing parameters
520 sub evaluate_path_info {
521         return if defined $input_params{'project'};
522         return if !$path_info;
523         $path_info =~ s,^/+,,;
524         return if !$path_info;
525
526         # find which part of PATH_INFO is project
527         my $project = $path_info;
528         $project =~ s,/+$,,;
529         while ($project && !check_head_link("$projectroot/$project")) {
530                 $project =~ s,/*[^/]*$,,;
531         }
532         return unless $project;
533         $input_params{'project'} = $project;
534
535         # do not change any parameters if an action is given using the query string
536         return if $input_params{'action'};
537         $path_info =~ s,^\Q$project\E/*,,;
538
539         # next, check if we have an action
540         my $action = $path_info;
541         $action =~ s,/.*$,,;
542         if (exists $actions{$action}) {
543                 $path_info =~ s,^$action/*,,;
544                 $input_params{'action'} = $action;
545         }
546
547         # list of actions that want hash_base instead of hash, but can have no
548         # pathname (f) parameter
549         my @wants_base = (
550                 'tree',
551                 'history',
552         );
553
554         # we want to catch
555         # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
556         my ($parentrefname, $parentpathname, $refname, $pathname) =
557                 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/);
558
559         # first, analyze the 'current' part
560         if (defined $pathname) {
561                 # we got "branch:filename" or "branch:dir/"
562                 # we could use git_get_type(branch:pathname), but:
563                 # - it needs $git_dir
564                 # - it does a git() call
565                 # - the convention of terminating directories with a slash
566                 #   makes it superfluous
567                 # - embedding the action in the PATH_INFO would make it even
568                 #   more superfluous
569                 $pathname =~ s,^/+,,;
570                 if (!$pathname || substr($pathname, -1) eq "/") {
571                         $input_params{'action'} ||= "tree";
572                         $pathname =~ s,/$,,;
573                 } else {
574                         # the default action depends on whether we had parent info
575                         # or not
576                         if ($parentrefname) {
577                                 $input_params{'action'} ||= "blobdiff_plain";
578                         } else {
579                                 $input_params{'action'} ||= "blob_plain";
580                         }
581                 }
582                 $input_params{'hash_base'} ||= $refname;
583                 $input_params{'file_name'} ||= $pathname;
584         } elsif (defined $refname) {
585                 # we got "branch". In this case we have to choose if we have to
586                 # set hash or hash_base.
587                 #
588                 # Most of the actions without a pathname only want hash to be
589                 # set, except for the ones specified in @wants_base that want
590                 # hash_base instead. It should also be noted that hand-crafted
591                 # links having 'history' as an action and no pathname or hash
592                 # set will fail, but that happens regardless of PATH_INFO.
593                 $input_params{'action'} ||= "shortlog";
594                 if (grep { $_ eq $input_params{'action'} } @wants_base) {
595                         $input_params{'hash_base'} ||= $refname;
596                 } else {
597                         $input_params{'hash'} ||= $refname;
598                 }
599         }
600
601         # next, handle the 'parent' part, if present
602         if (defined $parentrefname) {
603                 # a missing pathspec defaults to the 'current' filename, allowing e.g.
604                 # someproject/blobdiff/oldrev..newrev:/filename
605                 if ($parentpathname) {
606                         $parentpathname =~ s,^/+,,;
607                         $parentpathname =~ s,/$,,;
608                         $input_params{'file_parent'} ||= $parentpathname;
609                 } else {
610                         $input_params{'file_parent'} ||= $input_params{'file_name'};
611                 }
612                 # we assume that hash_parent_base is wanted if a path was specified,
613                 # or if the action wants hash_base instead of hash
614                 if (defined $input_params{'file_parent'} ||
615                         grep { $_ eq $input_params{'action'} } @wants_base) {
616                         $input_params{'hash_parent_base'} ||= $parentrefname;
617                 } else {
618                         $input_params{'hash_parent'} ||= $parentrefname;
619                 }
620         }
621
622         # for the snapshot action, we allow URLs in the form
623         # $project/snapshot/$hash.ext
624         # where .ext determines the snapshot and gets removed from the
625         # passed $refname to provide the $hash.
626         #
627         # To be able to tell that $refname includes the format extension, we
628         # require the following two conditions to be satisfied:
629         # - the hash input parameter MUST have been set from the $refname part
630         #   of the URL (i.e. they must be equal)
631         # - the snapshot format MUST NOT have been defined already (e.g. from
632         #   CGI parameter sf)
633         # It's also useless to try any matching unless $refname has a dot,
634         # so we check for that too
635         if (defined $input_params{'action'} &&
636                 $input_params{'action'} eq 'snapshot' &&
637                 defined $refname && index($refname, '.') != -1 &&
638                 $refname eq $input_params{'hash'} &&
639                 !defined $input_params{'snapshot_format'}) {
640                 # We loop over the known snapshot formats, checking for
641                 # extensions. Allowed extensions are both the defined suffix
642                 # (which includes the initial dot already) and the snapshot
643                 # format key itself, with a prepended dot
644                 while (my ($fmt, %opt) = each %known_snapshot_formats) {
645                         my $hash = $refname;
646                         my $sfx;
647                         $hash =~ s/(\Q$opt{'suffix'}\E|\Q.$fmt\E)$//;
648                         next unless $sfx = $1;
649                         # a valid suffix was found, so set the snapshot format
650                         # and reset the hash parameter
651                         $input_params{'snapshot_format'} = $fmt;
652                         $input_params{'hash'} = $hash;
653                         # we also set the format suffix to the one requested
654                         # in the URL: this way a request for e.g. .tgz returns
655                         # a .tgz instead of a .tar.gz
656                         $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
657                         last;
658                 }
659         }
660 }
661 evaluate_path_info();
662
663 our $action = $input_params{'action'};
664 if (defined $action) {
665         if (!validate_action($action)) {
666                 die_error(400, "Invalid action parameter");
667         }
668 }
669
670 # parameters which are pathnames
671 our $project = $input_params{'project'};
672 if (defined $project) {
673         if (!validate_project($project)) {
674                 undef $project;
675                 die_error(404, "No such project");
676         }
677 }
678
679 our $file_name = $input_params{'file_name'};
680 if (defined $file_name) {
681         if (!validate_pathname($file_name)) {
682                 die_error(400, "Invalid file parameter");
683         }
684 }
685
686 our $file_parent = $input_params{'file_parent'};
687 if (defined $file_parent) {
688         if (!validate_pathname($file_parent)) {
689                 die_error(400, "Invalid file parent parameter");
690         }
691 }
692
693 # parameters which are refnames
694 our $hash = $input_params{'hash'};
695 if (defined $hash) {
696         if (!validate_refname($hash)) {
697                 die_error(400, "Invalid hash parameter");
698         }
699 }
700
701 our $hash_parent = $input_params{'hash_parent'};
702 if (defined $hash_parent) {
703         if (!validate_refname($hash_parent)) {
704                 die_error(400, "Invalid hash parent parameter");
705         }
706 }
707
708 our $hash_base = $input_params{'hash_base'};
709 if (defined $hash_base) {
710         if (!validate_refname($hash_base)) {
711                 die_error(400, "Invalid hash base parameter");
712         }
713 }
714
715 our @extra_options = @{$input_params{'extra_options'}};
716 # @extra_options is always defined, since it can only be (currently) set from
717 # CGI, and $cgi->param() returns the empty array in array context if the param
718 # is not set
719 foreach my $opt (@extra_options) {
720         if (not exists $allowed_options{$opt}) {
721                 die_error(400, "Invalid option parameter");
722         }
723         if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
724                 die_error(400, "Invalid option parameter for this action");
725         }
726 }
727
728 our $hash_parent_base = $input_params{'hash_parent_base'};
729 if (defined $hash_parent_base) {
730         if (!validate_refname($hash_parent_base)) {
731                 die_error(400, "Invalid hash parent base parameter");
732         }
733 }
734
735 # other parameters
736 our $page = $input_params{'page'};
737 if (defined $page) {
738         if ($page =~ m/[^0-9]/) {
739                 die_error(400, "Invalid page parameter");
740         }
741 }
742
743 our $searchtype = $input_params{'searchtype'};
744 if (defined $searchtype) {
745         if ($searchtype =~ m/[^a-z]/) {
746                 die_error(400, "Invalid searchtype parameter");
747         }
748 }
749
750 our $search_use_regexp = $input_params{'search_use_regexp'};
751
752 our $searchtext = $input_params{'searchtext'};
753 our $search_regexp;
754 if (defined $searchtext) {
755         if (length($searchtext) < 2) {
756                 die_error(403, "At least two characters are required for search parameter");
757         }
758         $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
759 }
760
761 # path to the current git repository
762 our $git_dir;
763 $git_dir = "$projectroot/$project" if $project;
764
765 # list of supported snapshot formats
766 our @snapshot_fmts = gitweb_get_feature('snapshot');
767 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
768
769 # dispatch
770 if (!defined $action) {
771         if (defined $hash) {
772                 $action = git_get_type($hash);
773         } elsif (defined $hash_base && defined $file_name) {
774                 $action = git_get_type("$hash_base:$file_name");
775         } elsif (defined $project) {
776                 $action = 'summary';
777         } else {
778                 $action = 'project_list';
779         }
780 }
781 if (!defined($actions{$action})) {
782         die_error(400, "Unknown action");
783 }
784 if ($action !~ m/^(opml|project_list|project_index)$/ &&
785     !$project) {
786         die_error(400, "Project needed");
787 }
788 $actions{$action}->();
789 exit;
790
791 ## ======================================================================
792 ## action links
793
794 sub href (%) {
795         my %params = @_;
796         # default is to use -absolute url() i.e. $my_uri
797         my $href = $params{-full} ? $my_url : $my_uri;
798
799         $params{'project'} = $project unless exists $params{'project'};
800
801         if ($params{-replay}) {
802                 while (my ($name, $symbol) = each %cgi_param_mapping) {
803                         if (!exists $params{$name}) {
804                                 $params{$name} = $input_params{$name};
805                         }
806                 }
807         }
808
809         my $use_pathinfo = gitweb_check_feature('pathinfo');
810         if ($use_pathinfo) {
811                 # try to put as many parameters as possible in PATH_INFO:
812                 #   - project name
813                 #   - action
814                 #   - hash_parent or hash_parent_base:/file_parent
815                 #   - hash or hash_base:/filename
816                 #   - the snapshot_format as an appropriate suffix
817
818                 # When the script is the root DirectoryIndex for the domain,
819                 # $href here would be something like http://gitweb.example.com/
820                 # Thus, we strip any trailing / from $href, to spare us double
821                 # slashes in the final URL
822                 $href =~ s,/$,,;
823
824                 # Then add the project name, if present
825                 $href .= "/".esc_url($params{'project'}) if defined $params{'project'};
826                 delete $params{'project'};
827
828                 # since we destructively absorb parameters, we keep this
829                 # boolean that remembers if we're handling a snapshot
830                 my $is_snapshot = $params{'action'} eq 'snapshot';
831
832                 # Summary just uses the project path URL, any other action is
833                 # added to the URL
834                 if (defined $params{'action'}) {
835                         $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
836                         delete $params{'action'};
837                 }
838
839                 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
840                 # stripping nonexistent or useless pieces
841                 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
842                         || $params{'hash_parent'} || $params{'hash'});
843                 if (defined $params{'hash_base'}) {
844                         if (defined $params{'hash_parent_base'}) {
845                                 $href .= esc_url($params{'hash_parent_base'});
846                                 # skip the file_parent if it's the same as the file_name
847                                 delete $params{'file_parent'} if $params{'file_parent'} eq $params{'file_name'};
848                                 if (defined $params{'file_parent'} && $params{'file_parent'} !~ /\.\./) {
849                                         $href .= ":/".esc_url($params{'file_parent'});
850                                         delete $params{'file_parent'};
851                                 }
852                                 $href .= "..";
853                                 delete $params{'hash_parent'};
854                                 delete $params{'hash_parent_base'};
855                         } elsif (defined $params{'hash_parent'}) {
856                                 $href .= esc_url($params{'hash_parent'}). "..";
857                                 delete $params{'hash_parent'};
858                         }
859
860                         $href .= esc_url($params{'hash_base'});
861                         if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
862                                 $href .= ":/".esc_url($params{'file_name'});
863                                 delete $params{'file_name'};
864                         }
865                         delete $params{'hash'};
866                         delete $params{'hash_base'};
867                 } elsif (defined $params{'hash'}) {
868                         $href .= esc_url($params{'hash'});
869                         delete $params{'hash'};
870                 }
871
872                 # If the action was a snapshot, we can absorb the
873                 # snapshot_format parameter too
874                 if ($is_snapshot) {
875                         my $fmt = $params{'snapshot_format'};
876                         # snapshot_format should always be defined when href()
877                         # is called, but just in case some code forgets, we
878                         # fall back to the default
879                         $fmt ||= $snapshot_fmts[0];
880                         $href .= $known_snapshot_formats{$fmt}{'suffix'};
881                         delete $params{'snapshot_format'};
882                 }
883         }
884
885         # now encode the parameters explicitly
886         my @result = ();
887         for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
888                 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
889                 if (defined $params{$name}) {
890                         if (ref($params{$name}) eq "ARRAY") {
891                                 foreach my $par (@{$params{$name}}) {
892                                         push @result, $symbol . "=" . esc_param($par);
893                                 }
894                         } else {
895                                 push @result, $symbol . "=" . esc_param($params{$name});
896                         }
897                 }
898         }
899         $href .= "?" . join(';', @result) if scalar @result;
900
901         return $href;
902 }
903
904
905 ## ======================================================================
906 ## validation, quoting/unquoting and escaping
907
908 sub validate_action {
909         my $input = shift || return undef;
910         return undef unless exists $actions{$input};
911         return $input;
912 }
913
914 sub validate_project {
915         my $input = shift || return undef;
916         if (!validate_pathname($input) ||
917                 !(-d "$projectroot/$input") ||
918                 !check_export_ok("$projectroot/$input") ||
919                 ($strict_export && !project_in_list($input))) {
920                 return undef;
921         } else {
922                 return $input;
923         }
924 }
925
926 sub validate_pathname {
927         my $input = shift || return undef;
928
929         # no '.' or '..' as elements of path, i.e. no '.' nor '..'
930         # at the beginning, at the end, and between slashes.
931         # also this catches doubled slashes
932         if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
933                 return undef;
934         }
935         # no null characters
936         if ($input =~ m!\0!) {
937                 return undef;
938         }
939         return $input;
940 }
941
942 sub validate_refname {
943         my $input = shift || return undef;
944
945         # textual hashes are O.K.
946         if ($input =~ m/^[0-9a-fA-F]{40}$/) {
947                 return $input;
948         }
949         # it must be correct pathname
950         $input = validate_pathname($input)
951                 or return undef;
952         # restrictions on ref name according to git-check-ref-format
953         if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
954                 return undef;
955         }
956         return $input;
957 }
958
959 # decode sequences of octets in utf8 into Perl's internal form,
960 # which is utf-8 with utf8 flag set if needed.  gitweb writes out
961 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
962 sub to_utf8 {
963         my $str = shift;
964         if (utf8::valid($str)) {
965                 utf8::decode($str);
966                 return $str;
967         } else {
968                 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
969         }
970 }
971
972 # quote unsafe chars, but keep the slash, even when it's not
973 # correct, but quoted slashes look too horrible in bookmarks
974 sub esc_param {
975         my $str = shift;
976         $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
977         $str =~ s/\+/%2B/g;
978         $str =~ s/ /\+/g;
979         return $str;
980 }
981
982 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
983 sub esc_url {
984         my $str = shift;
985         $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
986         $str =~ s/\+/%2B/g;
987         $str =~ s/ /\+/g;
988         return $str;
989 }
990
991 # replace invalid utf8 character with SUBSTITUTION sequence
992 sub esc_html ($;%) {
993         my $str = shift;
994         my %opts = @_;
995
996         $str = to_utf8($str);
997         $str = $cgi->escapeHTML($str);
998         if ($opts{'-nbsp'}) {
999                 $str =~ s/ /&nbsp;/g;
1000         }
1001         $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1002         return $str;
1003 }
1004
1005 # quote control characters and escape filename to HTML
1006 sub esc_path {
1007         my $str = shift;
1008         my %opts = @_;
1009
1010         $str = to_utf8($str);
1011         $str = $cgi->escapeHTML($str);
1012         if ($opts{'-nbsp'}) {
1013                 $str =~ s/ /&nbsp;/g;
1014         }
1015         $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1016         return $str;
1017 }
1018
1019 # Make control characters "printable", using character escape codes (CEC)
1020 sub quot_cec {
1021         my $cntrl = shift;
1022         my %opts = @_;
1023         my %es = ( # character escape codes, aka escape sequences
1024                 "\t" => '\t',   # tab            (HT)
1025                 "\n" => '\n',   # line feed      (LF)
1026                 "\r" => '\r',   # carrige return (CR)
1027                 "\f" => '\f',   # form feed      (FF)
1028                 "\b" => '\b',   # backspace      (BS)
1029                 "\a" => '\a',   # alarm (bell)   (BEL)
1030                 "\e" => '\e',   # escape         (ESC)
1031                 "\013" => '\v', # vertical tab   (VT)
1032                 "\000" => '\0', # nul character  (NUL)
1033         );
1034         my $chr = ( (exists $es{$cntrl})
1035                     ? $es{$cntrl}
1036                     : sprintf('\%2x', ord($cntrl)) );
1037         if ($opts{-nohtml}) {
1038                 return $chr;
1039         } else {
1040                 return "<span class=\"cntrl\">$chr</span>";
1041         }
1042 }
1043
1044 # Alternatively use unicode control pictures codepoints,
1045 # Unicode "printable representation" (PR)
1046 sub quot_upr {
1047         my $cntrl = shift;
1048         my %opts = @_;
1049
1050         my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1051         if ($opts{-nohtml}) {
1052                 return $chr;
1053         } else {
1054                 return "<span class=\"cntrl\">$chr</span>";
1055         }
1056 }
1057
1058 # git may return quoted and escaped filenames
1059 sub unquote {
1060         my $str = shift;
1061
1062         sub unq {
1063                 my $seq = shift;
1064                 my %es = ( # character escape codes, aka escape sequences
1065                         't' => "\t",   # tab            (HT, TAB)
1066                         'n' => "\n",   # newline        (NL)
1067                         'r' => "\r",   # return         (CR)
1068                         'f' => "\f",   # form feed      (FF)
1069                         'b' => "\b",   # backspace      (BS)
1070                         'a' => "\a",   # alarm (bell)   (BEL)
1071                         'e' => "\e",   # escape         (ESC)
1072                         'v' => "\013", # vertical tab   (VT)
1073                 );
1074
1075                 if ($seq =~ m/^[0-7]{1,3}$/) {
1076                         # octal char sequence
1077                         return chr(oct($seq));
1078                 } elsif (exists $es{$seq}) {
1079                         # C escape sequence, aka character escape code
1080                         return $es{$seq};
1081                 }
1082                 # quoted ordinary character
1083                 return $seq;
1084         }
1085
1086         if ($str =~ m/^"(.*)"$/) {
1087                 # needs unquoting
1088                 $str = $1;
1089                 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1090         }
1091         return $str;
1092 }
1093
1094 # escape tabs (convert tabs to spaces)
1095 sub untabify {
1096         my $line = shift;
1097
1098         while ((my $pos = index($line, "\t")) != -1) {
1099                 if (my $count = (8 - ($pos % 8))) {
1100                         my $spaces = ' ' x $count;
1101                         $line =~ s/\t/$spaces/;
1102                 }
1103         }
1104
1105         return $line;
1106 }
1107
1108 sub project_in_list {
1109         my $project = shift;
1110         my @list = git_get_projects_list();
1111         return @list && scalar(grep { $_->{'path'} eq $project } @list);
1112 }
1113
1114 ## ----------------------------------------------------------------------
1115 ## HTML aware string manipulation
1116
1117 # Try to chop given string on a word boundary between position
1118 # $len and $len+$add_len. If there is no word boundary there,
1119 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1120 # (marking chopped part) would be longer than given string.
1121 sub chop_str {
1122         my $str = shift;
1123         my $len = shift;
1124         my $add_len = shift || 10;
1125         my $where = shift || 'right'; # 'left' | 'center' | 'right'
1126
1127         # Make sure perl knows it is utf8 encoded so we don't
1128         # cut in the middle of a utf8 multibyte char.
1129         $str = to_utf8($str);
1130
1131         # allow only $len chars, but don't cut a word if it would fit in $add_len
1132         # if it doesn't fit, cut it if it's still longer than the dots we would add
1133         # remove chopped character entities entirely
1134
1135         # when chopping in the middle, distribute $len into left and right part
1136         # return early if chopping wouldn't make string shorter
1137         if ($where eq 'center') {
1138                 return $str if ($len + 5 >= length($str)); # filler is length 5
1139                 $len = int($len/2);
1140         } else {
1141                 return $str if ($len + 4 >= length($str)); # filler is length 4
1142         }
1143
1144         # regexps: ending and beginning with word part up to $add_len
1145         my $endre = qr/.{$len}\w{0,$add_len}/;
1146         my $begre = qr/\w{0,$add_len}.{$len}/;
1147
1148         if ($where eq 'left') {
1149                 $str =~ m/^(.*?)($begre)$/;
1150                 my ($lead, $body) = ($1, $2);
1151                 if (length($lead) > 4) {
1152                         $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
1153                         $lead = " ...";
1154                 }
1155                 return "$lead$body";
1156
1157         } elsif ($where eq 'center') {
1158                 $str =~ m/^($endre)(.*)$/;
1159                 my ($left, $str)  = ($1, $2);
1160                 $str =~ m/^(.*?)($begre)$/;
1161                 my ($mid, $right) = ($1, $2);
1162                 if (length($mid) > 5) {
1163                         $left  =~ s/&[^;]*$//;
1164                         $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
1165                         $mid = " ... ";
1166                 }
1167                 return "$left$mid$right";
1168
1169         } else {
1170                 $str =~ m/^($endre)(.*)$/;
1171                 my $body = $1;
1172                 my $tail = $2;
1173                 if (length($tail) > 4) {
1174                         $body =~ s/&[^;]*$//;
1175                         $tail = "... ";
1176                 }
1177                 return "$body$tail";
1178         }
1179 }
1180
1181 # takes the same arguments as chop_str, but also wraps a <span> around the
1182 # result with a title attribute if it does get chopped. Additionally, the
1183 # string is HTML-escaped.
1184 sub chop_and_escape_str {
1185         my ($str) = @_;
1186
1187         my $chopped = chop_str(@_);
1188         if ($chopped eq $str) {
1189                 return esc_html($chopped);
1190         } else {
1191                 $str =~ s/([[:cntrl:]])/?/g;
1192                 return $cgi->span({-title=>$str}, esc_html($chopped));
1193         }
1194 }
1195
1196 ## ----------------------------------------------------------------------
1197 ## functions returning short strings
1198
1199 # CSS class for given age value (in seconds)
1200 sub age_class {
1201         my $age = shift;
1202
1203         if (!defined $age) {
1204                 return "noage";
1205         } elsif ($age < 60*60*2) {
1206                 return "age0";
1207         } elsif ($age < 60*60*24*2) {
1208                 return "age1";
1209         } else {
1210                 return "age2";
1211         }
1212 }
1213
1214 # convert age in seconds to "nn units ago" string
1215 sub age_string {
1216         my $age = shift;
1217         my $age_str;
1218
1219         if ($age > 60*60*24*365*2) {
1220                 $age_str = (int $age/60/60/24/365);
1221                 $age_str .= " years ago";
1222         } elsif ($age > 60*60*24*(365/12)*2) {
1223                 $age_str = int $age/60/60/24/(365/12);
1224                 $age_str .= " months ago";
1225         } elsif ($age > 60*60*24*7*2) {
1226                 $age_str = int $age/60/60/24/7;
1227                 $age_str .= " weeks ago";
1228         } elsif ($age > 60*60*24*2) {
1229                 $age_str = int $age/60/60/24;
1230                 $age_str .= " days ago";
1231         } elsif ($age > 60*60*2) {
1232                 $age_str = int $age/60/60;
1233                 $age_str .= " hours ago";
1234         } elsif ($age > 60*2) {
1235                 $age_str = int $age/60;
1236                 $age_str .= " min ago";
1237         } elsif ($age > 2) {
1238                 $age_str = int $age;
1239                 $age_str .= " sec ago";
1240         } else {
1241                 $age_str .= " right now";
1242         }
1243         return $age_str;
1244 }
1245
1246 use constant {
1247         S_IFINVALID => 0030000,
1248         S_IFGITLINK => 0160000,
1249 };
1250
1251 # submodule/subproject, a commit object reference
1252 sub S_ISGITLINK($) {
1253         my $mode = shift;
1254
1255         return (($mode & S_IFMT) == S_IFGITLINK)
1256 }
1257
1258 # convert file mode in octal to symbolic file mode string
1259 sub mode_str {
1260         my $mode = oct shift;
1261
1262         if (S_ISGITLINK($mode)) {
1263                 return 'm---------';
1264         } elsif (S_ISDIR($mode & S_IFMT)) {
1265                 return 'drwxr-xr-x';
1266         } elsif (S_ISLNK($mode)) {
1267                 return 'lrwxrwxrwx';
1268         } elsif (S_ISREG($mode)) {
1269                 # git cares only about the executable bit
1270                 if ($mode & S_IXUSR) {
1271                         return '-rwxr-xr-x';
1272                 } else {
1273                         return '-rw-r--r--';
1274                 };
1275         } else {
1276                 return '----------';
1277         }
1278 }
1279
1280 # convert file mode in octal to file type string
1281 sub file_type {
1282         my $mode = shift;
1283
1284         if ($mode !~ m/^[0-7]+$/) {
1285                 return $mode;
1286         } else {
1287                 $mode = oct $mode;
1288         }
1289
1290         if (S_ISGITLINK($mode)) {
1291                 return "submodule";
1292         } elsif (S_ISDIR($mode & S_IFMT)) {
1293                 return "directory";
1294         } elsif (S_ISLNK($mode)) {
1295                 return "symlink";
1296         } elsif (S_ISREG($mode)) {
1297                 return "file";
1298         } else {
1299                 return "unknown";
1300         }
1301 }
1302
1303 # convert file mode in octal to file type description string
1304 sub file_type_long {
1305         my $mode = shift;
1306
1307         if ($mode !~ m/^[0-7]+$/) {
1308                 return $mode;
1309         } else {
1310                 $mode = oct $mode;
1311         }
1312
1313         if (S_ISGITLINK($mode)) {
1314                 return "submodule";
1315         } elsif (S_ISDIR($mode & S_IFMT)) {
1316                 return "directory";
1317         } elsif (S_ISLNK($mode)) {
1318                 return "symlink";
1319         } elsif (S_ISREG($mode)) {
1320                 if ($mode & S_IXUSR) {
1321                         return "executable";
1322                 } else {
1323                         return "file";
1324                 };
1325         } else {
1326                 return "unknown";
1327         }
1328 }
1329
1330
1331 ## ----------------------------------------------------------------------
1332 ## functions returning short HTML fragments, or transforming HTML fragments
1333 ## which don't belong to other sections
1334
1335 # format line of commit message.
1336 sub format_log_line_html {
1337         my $line = shift;
1338
1339         $line = esc_html($line, -nbsp=>1);
1340         if ($line =~ m/([0-9a-fA-F]{8,40})/) {
1341                 my $hash_text = $1;
1342                 my $link =
1343                         $cgi->a({-href => href(action=>"object", hash=>$hash_text),
1344                                 -class => "text"}, $hash_text);
1345                 $line =~ s/$hash_text/$link/;
1346         }
1347         return $line;
1348 }
1349
1350 # format marker of refs pointing to given object
1351
1352 # the destination action is chosen based on object type and current context:
1353 # - for annotated tags, we choose the tag view unless it's the current view
1354 #   already, in which case we go to shortlog view
1355 # - for other refs, we keep the current view if we're in history, shortlog or
1356 #   log view, and select shortlog otherwise
1357 sub format_ref_marker {
1358         my ($refs, $id) = @_;
1359         my $markers = '';
1360
1361         if (defined $refs->{$id}) {
1362                 foreach my $ref (@{$refs->{$id}}) {
1363                         # this code exploits the fact that non-lightweight tags are the
1364                         # only indirect objects, and that they are the only objects for which
1365                         # we want to use tag instead of shortlog as action
1366                         my ($type, $name) = qw();
1367                         my $indirect = ($ref =~ s/\^\{\}$//);
1368                         # e.g. tags/v2.6.11 or heads/next
1369                         if ($ref =~ m!^(.*?)s?/(.*)$!) {
1370                                 $type = $1;
1371                                 $name = $2;
1372                         } else {
1373                                 $type = "ref";
1374                                 $name = $ref;
1375                         }
1376
1377                         my $class = $type;
1378                         $class .= " indirect" if $indirect;
1379
1380                         my $dest_action = "shortlog";
1381
1382                         if ($indirect) {
1383                                 $dest_action = "tag" unless $action eq "tag";
1384                         } elsif ($action =~ /^(history|(short)?log)$/) {
1385                                 $dest_action = $action;
1386                         }
1387
1388                         my $dest = "";
1389                         $dest .= "refs/" unless $ref =~ m!^refs/!;
1390                         $dest .= $ref;
1391
1392                         my $link = $cgi->a({
1393                                 -href => href(
1394                                         action=>$dest_action,
1395                                         hash=>$dest
1396                                 )}, $name);
1397
1398                         $markers .= " <span class=\"$class\" title=\"$ref\">" .
1399                                 $link . "</span>";
1400                 }
1401         }
1402
1403         if ($markers) {
1404                 return ' <span class="refs">'. $markers . '</span>';
1405         } else {
1406                 return "";
1407         }
1408 }
1409
1410 # format, perhaps shortened and with markers, title line
1411 sub format_subject_html {
1412         my ($long, $short, $href, $extra) = @_;
1413         $extra = '' unless defined($extra);
1414
1415         if (length($short) < length($long)) {
1416                 return $cgi->a({-href => $href, -class => "list subject",
1417                                 -title => to_utf8($long)},
1418                        esc_html($short) . $extra);
1419         } else {
1420                 return $cgi->a({-href => $href, -class => "list subject"},
1421                        esc_html($long)  . $extra);
1422         }
1423 }
1424
1425 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1426 sub format_git_diff_header_line {
1427         my $line = shift;
1428         my $diffinfo = shift;
1429         my ($from, $to) = @_;
1430
1431         if ($diffinfo->{'nparents'}) {
1432                 # combined diff
1433                 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1434                 if ($to->{'href'}) {
1435                         $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1436                                          esc_path($to->{'file'}));
1437                 } else { # file was deleted (no href)
1438                         $line .= esc_path($to->{'file'});
1439                 }
1440         } else {
1441                 # "ordinary" diff
1442                 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1443                 if ($from->{'href'}) {
1444                         $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1445                                          'a/' . esc_path($from->{'file'}));
1446                 } else { # file was added (no href)
1447                         $line .= 'a/' . esc_path($from->{'file'});
1448                 }
1449                 $line .= ' ';
1450                 if ($to->{'href'}) {
1451                         $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1452                                          'b/' . esc_path($to->{'file'}));
1453                 } else { # file was deleted
1454                         $line .= 'b/' . esc_path($to->{'file'});
1455                 }
1456         }
1457
1458         return "<div class=\"diff header\">$line</div>\n";
1459 }
1460
1461 # format extended diff header line, before patch itself
1462 sub format_extended_diff_header_line {
1463         my $line = shift;
1464         my $diffinfo = shift;
1465         my ($from, $to) = @_;
1466
1467         # match <path>
1468         if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1469                 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1470                                        esc_path($from->{'file'}));
1471         }
1472         if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1473                 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1474                                  esc_path($to->{'file'}));
1475         }
1476         # match single <mode>
1477         if ($line =~ m/\s(\d{6})$/) {
1478                 $line .= '<span class="info"> (' .
1479                          file_type_long($1) .
1480                          ')</span>';
1481         }
1482         # match <hash>
1483         if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1484                 # can match only for combined diff
1485                 $line = 'index ';
1486                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1487                         if ($from->{'href'}[$i]) {
1488                                 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1489                                                   -class=>"hash"},
1490                                                  substr($diffinfo->{'from_id'}[$i],0,7));
1491                         } else {
1492                                 $line .= '0' x 7;
1493                         }
1494                         # separator
1495                         $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1496                 }
1497                 $line .= '..';
1498                 if ($to->{'href'}) {
1499                         $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1500                                          substr($diffinfo->{'to_id'},0,7));
1501                 } else {
1502                         $line .= '0' x 7;
1503                 }
1504
1505         } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1506                 # can match only for ordinary diff
1507                 my ($from_link, $to_link);
1508                 if ($from->{'href'}) {
1509                         $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1510                                              substr($diffinfo->{'from_id'},0,7));
1511                 } else {
1512                         $from_link = '0' x 7;
1513                 }
1514                 if ($to->{'href'}) {
1515                         $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1516                                            substr($diffinfo->{'to_id'},0,7));
1517                 } else {
1518                         $to_link = '0' x 7;
1519                 }
1520                 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1521                 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1522         }
1523
1524         return $line . "<br/>\n";
1525 }
1526
1527 # format from-file/to-file diff header
1528 sub format_diff_from_to_header {
1529         my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1530         my $line;
1531         my $result = '';
1532
1533         $line = $from_line;
1534         #assert($line =~ m/^---/) if DEBUG;
1535         # no extra formatting for "^--- /dev/null"
1536         if (! $diffinfo->{'nparents'}) {
1537                 # ordinary (single parent) diff
1538                 if ($line =~ m!^--- "?a/!) {
1539                         if ($from->{'href'}) {
1540                                 $line = '--- a/' .
1541                                         $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1542                                                 esc_path($from->{'file'}));
1543                         } else {
1544                                 $line = '--- a/' .
1545                                         esc_path($from->{'file'});
1546                         }
1547                 }
1548                 $result .= qq!<div class="diff from_file">$line</div>\n!;
1549
1550         } else {
1551                 # combined diff (merge commit)
1552                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1553                         if ($from->{'href'}[$i]) {
1554                                 $line = '--- ' .
1555                                         $cgi->a({-href=>href(action=>"blobdiff",
1556                                                              hash_parent=>$diffinfo->{'from_id'}[$i],
1557                                                              hash_parent_base=>$parents[$i],
1558                                                              file_parent=>$from->{'file'}[$i],
1559                                                              hash=>$diffinfo->{'to_id'},
1560                                                              hash_base=>$hash,
1561                                                              file_name=>$to->{'file'}),
1562                                                  -class=>"path",
1563                                                  -title=>"diff" . ($i+1)},
1564                                                 $i+1) .
1565                                         '/' .
1566                                         $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1567                                                 esc_path($from->{'file'}[$i]));
1568                         } else {
1569                                 $line = '--- /dev/null';
1570                         }
1571                         $result .= qq!<div class="diff from_file">$line</div>\n!;
1572                 }
1573         }
1574
1575         $line = $to_line;
1576         #assert($line =~ m/^\+\+\+/) if DEBUG;
1577         # no extra formatting for "^+++ /dev/null"
1578         if ($line =~ m!^\+\+\+ "?b/!) {
1579                 if ($to->{'href'}) {
1580                         $line = '+++ b/' .
1581                                 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1582                                         esc_path($to->{'file'}));
1583                 } else {
1584                         $line = '+++ b/' .
1585                                 esc_path($to->{'file'});
1586                 }
1587         }
1588         $result .= qq!<div class="diff to_file">$line</div>\n!;
1589
1590         return $result;
1591 }
1592
1593 # create note for patch simplified by combined diff
1594 sub format_diff_cc_simplified {
1595         my ($diffinfo, @parents) = @_;
1596         my $result = '';
1597
1598         $result .= "<div class=\"diff header\">" .
1599                    "diff --cc ";
1600         if (!is_deleted($diffinfo)) {
1601                 $result .= $cgi->a({-href => href(action=>"blob",
1602                                                   hash_base=>$hash,
1603                                                   hash=>$diffinfo->{'to_id'},
1604                                                   file_name=>$diffinfo->{'to_file'}),
1605                                     -class => "path"},
1606                                    esc_path($diffinfo->{'to_file'}));
1607         } else {
1608                 $result .= esc_path($diffinfo->{'to_file'});
1609         }
1610         $result .= "</div>\n" . # class="diff header"
1611                    "<div class=\"diff nodifferences\">" .
1612                    "Simple merge" .
1613                    "</div>\n"; # class="diff nodifferences"
1614
1615         return $result;
1616 }
1617
1618 # format patch (diff) line (not to be used for diff headers)
1619 sub format_diff_line {
1620         my $line = shift;
1621         my ($from, $to) = @_;
1622         my $diff_class = "";
1623
1624         chomp $line;
1625
1626         if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1627                 # combined diff
1628                 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1629                 if ($line =~ m/^\@{3}/) {
1630                         $diff_class = " chunk_header";
1631                 } elsif ($line =~ m/^\\/) {
1632                         $diff_class = " incomplete";
1633                 } elsif ($prefix =~ tr/+/+/) {
1634                         $diff_class = " add";
1635                 } elsif ($prefix =~ tr/-/-/) {
1636                         $diff_class = " rem";
1637                 }
1638         } else {
1639                 # assume ordinary diff
1640                 my $char = substr($line, 0, 1);
1641                 if ($char eq '+') {
1642                         $diff_class = " add";
1643                 } elsif ($char eq '-') {
1644                         $diff_class = " rem";
1645                 } elsif ($char eq '@') {
1646                         $diff_class = " chunk_header";
1647                 } elsif ($char eq "\\") {
1648                         $diff_class = " incomplete";
1649                 }
1650         }
1651         $line = untabify($line);
1652         if ($from && $to && $line =~ m/^\@{2} /) {
1653                 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1654                         $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1655
1656                 $from_lines = 0 unless defined $from_lines;
1657                 $to_lines   = 0 unless defined $to_lines;
1658
1659                 if ($from->{'href'}) {
1660                         $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1661                                              -class=>"list"}, $from_text);
1662                 }
1663                 if ($to->{'href'}) {
1664                         $to_text   = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1665                                              -class=>"list"}, $to_text);
1666                 }
1667                 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1668                         "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1669                 return "<div class=\"diff$diff_class\">$line</div>\n";
1670         } elsif ($from && $to && $line =~ m/^\@{3}/) {
1671                 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1672                 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1673
1674                 @from_text = split(' ', $ranges);
1675                 for (my $i = 0; $i < @from_text; ++$i) {
1676                         ($from_start[$i], $from_nlines[$i]) =
1677                                 (split(',', substr($from_text[$i], 1)), 0);
1678                 }
1679
1680                 $to_text   = pop @from_text;
1681                 $to_start  = pop @from_start;
1682                 $to_nlines = pop @from_nlines;
1683
1684                 $line = "<span class=\"chunk_info\">$prefix ";
1685                 for (my $i = 0; $i < @from_text; ++$i) {
1686                         if ($from->{'href'}[$i]) {
1687                                 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1688                                                   -class=>"list"}, $from_text[$i]);
1689                         } else {
1690                                 $line .= $from_text[$i];
1691                         }
1692                         $line .= " ";
1693                 }
1694                 if ($to->{'href'}) {
1695                         $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1696                                           -class=>"list"}, $to_text);
1697                 } else {
1698                         $line .= $to_text;
1699                 }
1700                 $line .= " $prefix</span>" .
1701                          "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1702                 return "<div class=\"diff$diff_class\">$line</div>\n";
1703         }
1704         return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1705 }
1706
1707 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1708 # linked.  Pass the hash of the tree/commit to snapshot.
1709 sub format_snapshot_links {
1710         my ($hash) = @_;
1711         my $num_fmts = @snapshot_fmts;
1712         if ($num_fmts > 1) {
1713                 # A parenthesized list of links bearing format names.
1714                 # e.g. "snapshot (_tar.gz_ _zip_)"
1715                 return "snapshot (" . join(' ', map
1716                         $cgi->a({
1717                                 -href => href(
1718                                         action=>"snapshot",
1719                                         hash=>$hash,
1720                                         snapshot_format=>$_
1721                                 )
1722                         }, $known_snapshot_formats{$_}{'display'})
1723                 , @snapshot_fmts) . ")";
1724         } elsif ($num_fmts == 1) {
1725                 # A single "snapshot" link whose tooltip bears the format name.
1726                 # i.e. "_snapshot_"
1727                 my ($fmt) = @snapshot_fmts;
1728                 return
1729                         $cgi->a({
1730                                 -href => href(
1731                                         action=>"snapshot",
1732                                         hash=>$hash,
1733                                         snapshot_format=>$fmt
1734                                 ),
1735                                 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1736                         }, "snapshot");
1737         } else { # $num_fmts == 0
1738                 return undef;
1739         }
1740 }
1741
1742 ## ......................................................................
1743 ## functions returning values to be passed, perhaps after some
1744 ## transformation, to other functions; e.g. returning arguments to href()
1745
1746 # returns hash to be passed to href to generate gitweb URL
1747 # in -title key it returns description of link
1748 sub get_feed_info {
1749         my $format = shift || 'Atom';
1750         my %res = (action => lc($format));
1751
1752         # feed links are possible only for project views
1753         return unless (defined $project);
1754         # some views should link to OPML, or to generic project feed,
1755         # or don't have specific feed yet (so they should use generic)
1756         return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
1757
1758         my $branch;
1759         # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
1760         # from tag links; this also makes possible to detect branch links
1761         if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
1762             (defined $hash      && $hash      =~ m!^refs/heads/(.*)$!)) {
1763                 $branch = $1;
1764         }
1765         # find log type for feed description (title)
1766         my $type = 'log';
1767         if (defined $file_name) {
1768                 $type  = "history of $file_name";
1769                 $type .= "/" if ($action eq 'tree');
1770                 $type .= " on '$branch'" if (defined $branch);
1771         } else {
1772                 $type = "log of $branch" if (defined $branch);
1773         }
1774
1775         $res{-title} = $type;
1776         $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
1777         $res{'file_name'} = $file_name;
1778
1779         return %res;
1780 }
1781
1782 ## ----------------------------------------------------------------------
1783 ## git utility subroutines, invoking git commands
1784
1785 # returns path to the core git executable and the --git-dir parameter as list
1786 sub git_cmd {
1787         return $GIT, '--git-dir='.$git_dir;
1788 }
1789
1790 # quote the given arguments for passing them to the shell
1791 # quote_command("command", "arg 1", "arg with ' and ! characters")
1792 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
1793 # Try to avoid using this function wherever possible.
1794 sub quote_command {
1795         return join(' ',
1796                     map( { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ ));
1797 }
1798
1799 # get HEAD ref of given project as hash
1800 sub git_get_head_hash {
1801         my $project = shift;
1802         my $o_git_dir = $git_dir;
1803         my $retval = undef;
1804         $git_dir = "$projectroot/$project";
1805         if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
1806                 my $head = <$fd>;
1807                 close $fd;
1808                 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
1809                         $retval = $1;
1810                 }
1811         }
1812         if (defined $o_git_dir) {
1813                 $git_dir = $o_git_dir;
1814         }
1815         return $retval;
1816 }
1817
1818 # get type of given object
1819 sub git_get_type {
1820         my $hash = shift;
1821
1822         open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
1823         my $type = <$fd>;
1824         close $fd or return;
1825         chomp $type;
1826         return $type;
1827 }
1828
1829 # repository configuration
1830 our $config_file = '';
1831 our %config;
1832
1833 # store multiple values for single key as anonymous array reference
1834 # single values stored directly in the hash, not as [ <value> ]
1835 sub hash_set_multi {
1836         my ($hash, $key, $value) = @_;
1837
1838         if (!exists $hash->{$key}) {
1839                 $hash->{$key} = $value;
1840         } elsif (!ref $hash->{$key}) {
1841                 $hash->{$key} = [ $hash->{$key}, $value ];
1842         } else {
1843                 push @{$hash->{$key}}, $value;
1844         }
1845 }
1846
1847 # return hash of git project configuration
1848 # optionally limited to some section, e.g. 'gitweb'
1849 sub git_parse_project_config {
1850         my $section_regexp = shift;
1851         my %config;
1852
1853         local $/ = "\0";
1854
1855         open my $fh, "-|", git_cmd(), "config", '-z', '-l',
1856                 or return;
1857
1858         while (my $keyval = <$fh>) {
1859                 chomp $keyval;
1860                 my ($key, $value) = split(/\n/, $keyval, 2);
1861
1862                 hash_set_multi(\%config, $key, $value)
1863                         if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
1864         }
1865         close $fh;
1866
1867         return %config;
1868 }
1869
1870 # convert config value to boolean, 'true' or 'false'
1871 # no value, number > 0, 'true' and 'yes' values are true
1872 # rest of values are treated as false (never as error)
1873 sub config_to_bool {
1874         my $val = shift;
1875
1876         # strip leading and trailing whitespace
1877         $val =~ s/^\s+//;
1878         $val =~ s/\s+$//;
1879
1880         return (!defined $val ||               # section.key
1881                 ($val =~ /^\d+$/ && $val) ||   # section.key = 1
1882                 ($val =~ /^(?:true|yes)$/i));  # section.key = true
1883 }
1884
1885 # convert config value to simple decimal number
1886 # an optional value suffix of 'k', 'm', or 'g' will cause the value
1887 # to be multiplied by 1024, 1048576, or 1073741824
1888 sub config_to_int {
1889         my $val = shift;
1890
1891         # strip leading and trailing whitespace
1892         $val =~ s/^\s+//;
1893         $val =~ s/\s+$//;
1894
1895         if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
1896                 $unit = lc($unit);
1897                 # unknown unit is treated as 1
1898                 return $num * ($unit eq 'g' ? 1073741824 :
1899                                $unit eq 'm' ?    1048576 :
1900                                $unit eq 'k' ?       1024 : 1);
1901         }
1902         return $val;
1903 }
1904
1905 # convert config value to array reference, if needed
1906 sub config_to_multi {
1907         my $val = shift;
1908
1909         return ref($val) ? $val : (defined($val) ? [ $val ] : []);
1910 }
1911
1912 sub git_get_project_config {
1913         my ($key, $type) = @_;
1914
1915         # key sanity check
1916         return unless ($key);
1917         $key =~ s/^gitweb\.//;
1918         return if ($key =~ m/\W/);
1919
1920         # type sanity check
1921         if (defined $type) {
1922                 $type =~ s/^--//;
1923                 $type = undef
1924                         unless ($type eq 'bool' || $type eq 'int');
1925         }
1926
1927         # get config
1928         if (!defined $config_file ||
1929             $config_file ne "$git_dir/config") {
1930                 %config = git_parse_project_config('gitweb');
1931                 $config_file = "$git_dir/config";
1932         }
1933
1934         # ensure given type
1935         if (!defined $type) {
1936                 return $config{"gitweb.$key"};
1937         } elsif ($type eq 'bool') {
1938                 # backward compatibility: 'git config --bool' returns true/false
1939                 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
1940         } elsif ($type eq 'int') {
1941                 return config_to_int($config{"gitweb.$key"});
1942         }
1943         return $config{"gitweb.$key"};
1944 }
1945
1946 # get hash of given path at given ref
1947 sub git_get_hash_by_path {
1948         my $base = shift;
1949         my $path = shift || return undef;
1950         my $type = shift;
1951
1952         $path =~ s,/+$,,;
1953
1954         open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
1955                 or die_error(500, "Open git-ls-tree failed");
1956         my $line = <$fd>;
1957         close $fd or return undef;
1958
1959         if (!defined $line) {
1960                 # there is no tree or hash given by $path at $base
1961                 return undef;
1962         }
1963
1964         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1965         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
1966         if (defined $type && $type ne $2) {
1967                 # type doesn't match
1968                 return undef;
1969         }
1970         return $3;
1971 }
1972
1973 # get path of entry with given hash at given tree-ish (ref)
1974 # used to get 'from' filename for combined diff (merge commit) for renames
1975 sub git_get_path_by_hash {
1976         my $base = shift || return;
1977         my $hash = shift || return;
1978
1979         local $/ = "\0";
1980
1981         open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
1982                 or return undef;
1983         while (my $line = <$fd>) {
1984                 chomp $line;
1985
1986                 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423  gitweb'
1987                 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f  gitweb/README'
1988                 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
1989                         close $fd;
1990                         return $1;
1991                 }
1992         }
1993         close $fd;
1994         return undef;
1995 }
1996
1997 ## ......................................................................
1998 ## git utility functions, directly accessing git repository
1999
2000 sub git_get_project_description {
2001         my $path = shift;
2002
2003         $git_dir = "$projectroot/$path";
2004         open my $fd, "$git_dir/description"
2005                 or return git_get_project_config('description');
2006         my $descr = <$fd>;
2007         close $fd;
2008         if (defined $descr) {
2009                 chomp $descr;
2010         }
2011         return $descr;
2012 }
2013
2014 sub git_get_project_ctags {
2015         my $path = shift;
2016         my $ctags = {};
2017
2018         $git_dir = "$projectroot/$path";
2019         unless (opendir D, "$git_dir/ctags") {
2020                 return $ctags;
2021         }
2022         foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir(D)) {
2023                 open CT, $_ or next;
2024                 my $val = <CT>;
2025                 chomp $val;
2026                 close CT;
2027                 my $ctag = $_; $ctag =~ s#.*/##;
2028                 $ctags->{$ctag} = $val;
2029         }
2030         closedir D;
2031         $ctags;
2032 }
2033
2034 sub git_populate_project_tagcloud {
2035         my $ctags = shift;
2036
2037         # First, merge different-cased tags; tags vote on casing
2038         my %ctags_lc;
2039         foreach (keys %$ctags) {
2040                 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2041                 if (not $ctags_lc{lc $_}->{topcount}
2042                     or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2043                         $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2044                         $ctags_lc{lc $_}->{topname} = $_;
2045                 }
2046         }
2047
2048         my $cloud;
2049         if (eval { require HTML::TagCloud; 1; }) {
2050                 $cloud = HTML::TagCloud->new;
2051                 foreach (sort keys %ctags_lc) {
2052                         # Pad the title with spaces so that the cloud looks
2053                         # less crammed.
2054                         my $title = $ctags_lc{$_}->{topname};
2055                         $title =~ s/ /&nbsp;/g;
2056                         $title =~ s/^/&nbsp;/g;
2057                         $title =~ s/$/&nbsp;/g;
2058                         $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2059                 }
2060         } else {
2061                 $cloud = \%ctags_lc;
2062         }
2063         $cloud;
2064 }
2065
2066 sub git_show_project_tagcloud {
2067         my ($cloud, $count) = @_;
2068         print STDERR ref($cloud)."..\n";
2069         if (ref $cloud eq 'HTML::TagCloud') {
2070                 return $cloud->html_and_css($count);
2071         } else {
2072                 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2073                 return '<p align="center">' . join (', ', map {
2074                         "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2075                 } splice(@tags, 0, $count)) . '</p>';
2076         }
2077 }
2078
2079 sub git_get_project_url_list {
2080         my $path = shift;
2081
2082         $git_dir = "$projectroot/$path";
2083         open my $fd, "$git_dir/cloneurl"
2084                 or return wantarray ?
2085                 @{ config_to_multi(git_get_project_config('url')) } :
2086                    config_to_multi(git_get_project_config('url'));
2087         my @git_project_url_list = map { chomp; $_ } <$fd>;
2088         close $fd;
2089
2090         return wantarray ? @git_project_url_list : \@git_project_url_list;
2091 }
2092
2093 sub git_get_projects_list {
2094         my ($filter) = @_;
2095         my @list;
2096
2097         $filter ||= '';
2098         $filter =~ s/\.git$//;
2099
2100         my $check_forks = gitweb_check_feature('forks');
2101
2102         if (-d $projects_list) {
2103                 # search in directory
2104                 my $dir = $projects_list . ($filter ? "/$filter" : '');
2105                 # remove the trailing "/"
2106                 $dir =~ s!/+$!!;
2107                 my $pfxlen = length("$dir");
2108                 my $pfxdepth = ($dir =~ tr!/!!);
2109
2110                 File::Find::find({
2111                         follow_fast => 1, # follow symbolic links
2112                         follow_skip => 2, # ignore duplicates
2113                         dangling_symlinks => 0, # ignore dangling symlinks, silently
2114                         wanted => sub {
2115                                 # skip project-list toplevel, if we get it.
2116                                 return if (m!^[/.]$!);
2117                                 # only directories can be git repositories
2118                                 return unless (-d $_);
2119                                 # don't traverse too deep (Find is super slow on os x)
2120                                 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2121                                         $File::Find::prune = 1;
2122                                         return;
2123                                 }
2124
2125                                 my $subdir = substr($File::Find::name, $pfxlen + 1);
2126                                 # we check related file in $projectroot
2127                                 if (check_export_ok("$projectroot/$filter/$subdir")) {
2128                                         push @list, { path => ($filter ? "$filter/" : '') . $subdir };
2129                                         $File::Find::prune = 1;
2130                                 }
2131                         },
2132                 }, "$dir");
2133
2134         } elsif (-f $projects_list) {
2135                 # read from file(url-encoded):
2136                 # 'git%2Fgit.git Linus+Torvalds'
2137                 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2138                 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2139                 my %paths;
2140                 open my ($fd), $projects_list or return;
2141         PROJECT:
2142                 while (my $line = <$fd>) {
2143                         chomp $line;
2144                         my ($path, $owner) = split ' ', $line;
2145                         $path = unescape($path);
2146                         $owner = unescape($owner);
2147                         if (!defined $path) {
2148                                 next;
2149                         }
2150                         if ($filter ne '') {
2151                                 # looking for forks;
2152                                 my $pfx = substr($path, 0, length($filter));
2153                                 if ($pfx ne $filter) {
2154                                         next PROJECT;
2155                                 }
2156                                 my $sfx = substr($path, length($filter));
2157                                 if ($sfx !~ /^\/.*\.git$/) {
2158                                         next PROJECT;
2159                                 }
2160                         } elsif ($check_forks) {
2161                         PATH:
2162                                 foreach my $filter (keys %paths) {
2163                                         # looking for forks;
2164                                         my $pfx = substr($path, 0, length($filter));
2165                                         if ($pfx ne $filter) {
2166                                                 next PATH;
2167                                         }
2168                                         my $sfx = substr($path, length($filter));
2169                                         if ($sfx !~ /^\/.*\.git$/) {
2170                                                 next PATH;
2171                                         }
2172                                         # is a fork, don't include it in
2173                                         # the list
2174                                         next PROJECT;
2175                                 }
2176                         }
2177                         if (check_export_ok("$projectroot/$path")) {
2178                                 my $pr = {
2179                                         path => $path,
2180                                         owner => to_utf8($owner),
2181                                 };
2182                                 push @list, $pr;
2183                                 (my $forks_path = $path) =~ s/\.git$//;
2184                                 $paths{$forks_path}++;
2185                         }
2186                 }
2187                 close $fd;
2188         }
2189         return @list;
2190 }
2191
2192 our $gitweb_project_owner = undef;
2193 sub git_get_project_list_from_file {
2194
2195         return if (defined $gitweb_project_owner);
2196
2197         $gitweb_project_owner = {};
2198         # read from file (url-encoded):
2199         # 'git%2Fgit.git Linus+Torvalds'
2200         # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2201         # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2202         if (-f $projects_list) {
2203                 open (my $fd , $projects_list);
2204                 while (my $line = <$fd>) {
2205                         chomp $line;
2206                         my ($pr, $ow) = split ' ', $line;
2207                         $pr = unescape($pr);
2208                         $ow = unescape($ow);
2209                         $gitweb_project_owner->{$pr} = to_utf8($ow);
2210                 }
2211                 close $fd;
2212         }
2213 }
2214
2215 sub git_get_project_owner {
2216         my $project = shift;
2217         my $owner;
2218
2219         return undef unless $project;
2220         $git_dir = "$projectroot/$project";
2221
2222         if (!defined $gitweb_project_owner) {
2223                 git_get_project_list_from_file();
2224         }
2225
2226         if (exists $gitweb_project_owner->{$project}) {
2227                 $owner = $gitweb_project_owner->{$project};
2228         }
2229         if (!defined $owner){
2230                 $owner = git_get_project_config('owner');
2231         }
2232         if (!defined $owner) {
2233                 $owner = get_file_owner("$git_dir");
2234         }
2235
2236         return $owner;
2237 }
2238
2239 sub git_get_last_activity {
2240         my ($path) = @_;
2241         my $fd;
2242
2243         $git_dir = "$projectroot/$path";
2244         open($fd, "-|", git_cmd(), 'for-each-ref',
2245              '--format=%(committer)',
2246              '--sort=-committerdate',
2247              '--count=1',
2248              'refs/heads') or return;
2249         my $most_recent = <$fd>;
2250         close $fd or return;
2251         if (defined $most_recent &&
2252             $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2253                 my $timestamp = $1;
2254                 my $age = time - $timestamp;
2255                 return ($age, age_string($age));
2256         }
2257         return (undef, undef);
2258 }
2259
2260 sub git_get_references {
2261         my $type = shift || "";
2262         my %refs;
2263         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2264         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2265         open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2266                 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2267                 or return;
2268
2269         while (my $line = <$fd>) {
2270                 chomp $line;
2271                 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2272                         if (defined $refs{$1}) {
2273                                 push @{$refs{$1}}, $2;
2274                         } else {
2275                                 $refs{$1} = [ $2 ];
2276                         }
2277                 }
2278         }
2279         close $fd or return;
2280         return \%refs;
2281 }
2282
2283 sub git_get_rev_name_tags {
2284         my $hash = shift || return undef;
2285
2286         open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2287                 or return;
2288         my $name_rev = <$fd>;
2289         close $fd;
2290
2291         if ($name_rev =~ m|^$hash tags/(.*)$|) {
2292                 return $1;
2293         } else {
2294                 # catches also '$hash undefined' output
2295                 return undef;
2296         }
2297 }
2298
2299 ## ----------------------------------------------------------------------
2300 ## parse to hash functions
2301
2302 sub parse_date {
2303         my $epoch = shift;
2304         my $tz = shift || "-0000";
2305
2306         my %date;
2307         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2308         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2309         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2310         $date{'hour'} = $hour;
2311         $date{'minute'} = $min;
2312         $date{'mday'} = $mday;
2313         $date{'day'} = $days[$wday];
2314         $date{'month'} = $months[$mon];
2315         $date{'rfc2822'}   = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2316                              $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2317         $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2318                              $mday, $months[$mon], $hour ,$min;
2319         $date{'iso-8601'}  = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2320                              1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2321
2322         $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2323         my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2324         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2325         $date{'hour_local'} = $hour;
2326         $date{'minute_local'} = $min;
2327         $date{'tz_local'} = $tz;
2328         $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2329                                   1900+$year, $mon+1, $mday,
2330                                   $hour, $min, $sec, $tz);
2331         return %date;
2332 }
2333
2334 sub parse_tag {
2335         my $tag_id = shift;
2336         my %tag;
2337         my @comment;
2338
2339         open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2340         $tag{'id'} = $tag_id;
2341         while (my $line = <$fd>) {
2342                 chomp $line;
2343                 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2344                         $tag{'object'} = $1;
2345                 } elsif ($line =~ m/^type (.+)$/) {
2346                         $tag{'type'} = $1;
2347                 } elsif ($line =~ m/^tag (.+)$/) {
2348                         $tag{'name'} = $1;
2349                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2350                         $tag{'author'} = $1;
2351                         $tag{'epoch'} = $2;
2352                         $tag{'tz'} = $3;
2353                 } elsif ($line =~ m/--BEGIN/) {
2354                         push @comment, $line;
2355                         last;
2356                 } elsif ($line eq "") {
2357                         last;
2358                 }
2359         }
2360         push @comment, <$fd>;
2361         $tag{'comment'} = \@comment;
2362         close $fd or return;
2363         if (!defined $tag{'name'}) {
2364                 return
2365         };
2366         return %tag
2367 }
2368
2369 sub parse_commit_text {
2370         my ($commit_text, $withparents) = @_;
2371         my @commit_lines = split '\n', $commit_text;
2372         my %co;
2373
2374         pop @commit_lines; # Remove '\0'
2375
2376         if (! @commit_lines) {
2377                 return;
2378         }
2379
2380         my $header = shift @commit_lines;
2381         if ($header !~ m/^[0-9a-fA-F]{40}/) {
2382                 return;
2383         }
2384         ($co{'id'}, my @parents) = split ' ', $header;
2385         while (my $line = shift @commit_lines) {
2386                 last if $line eq "\n";
2387                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2388                         $co{'tree'} = $1;
2389                 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2390                         push @parents, $1;
2391                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2392                         $co{'author'} = $1;
2393                         $co{'author_epoch'} = $2;
2394                         $co{'author_tz'} = $3;
2395                         if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2396                                 $co{'author_name'}  = $1;
2397                                 $co{'author_email'} = $2;
2398                         } else {
2399                                 $co{'author_name'} = $co{'author'};
2400                         }
2401                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2402                         $co{'committer'} = $1;
2403                         $co{'committer_epoch'} = $2;
2404                         $co{'committer_tz'} = $3;
2405                         $co{'committer_name'} = $co{'committer'};
2406                         if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2407                                 $co{'committer_name'}  = $1;
2408                                 $co{'committer_email'} = $2;
2409                         } else {
2410                                 $co{'committer_name'} = $co{'committer'};
2411                         }
2412                 }
2413         }
2414         if (!defined $co{'tree'}) {
2415                 return;
2416         };
2417         $co{'parents'} = \@parents;
2418         $co{'parent'} = $parents[0];
2419
2420         foreach my $title (@commit_lines) {
2421                 $title =~ s/^    //;
2422                 if ($title ne "") {
2423                         $co{'title'} = chop_str($title, 80, 5);
2424                         # remove leading stuff of merges to make the interesting part visible
2425                         if (length($title) > 50) {
2426                                 $title =~ s/^Automatic //;
2427                                 $title =~ s/^merge (of|with) /Merge ... /i;
2428                                 if (length($title) > 50) {
2429                                         $title =~ s/(http|rsync):\/\///;
2430                                 }
2431                                 if (length($title) > 50) {
2432                                         $title =~ s/(master|www|rsync)\.//;
2433                                 }
2434                                 if (length($title) > 50) {
2435                                         $title =~ s/kernel.org:?//;
2436                                 }
2437                                 if (length($title) > 50) {
2438                                         $title =~ s/\/pub\/scm//;
2439                                 }
2440                         }
2441                         $co{'title_short'} = chop_str($title, 50, 5);
2442                         last;
2443                 }
2444         }
2445         if (! defined $co{'title'} || $co{'title'} eq "") {
2446                 $co{'title'} = $co{'title_short'} = '(no commit message)';
2447         }
2448         # remove added spaces
2449         foreach my $line (@commit_lines) {
2450                 $line =~ s/^    //;
2451         }
2452         $co{'comment'} = \@commit_lines;
2453
2454         my $age = time - $co{'committer_epoch'};
2455         $co{'age'} = $age;
2456         $co{'age_string'} = age_string($age);
2457         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2458         if ($age > 60*60*24*7*2) {
2459                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2460                 $co{'age_string_age'} = $co{'age_string'};
2461         } else {
2462                 $co{'age_string_date'} = $co{'age_string'};
2463                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2464         }
2465         return %co;
2466 }
2467
2468 sub parse_commit {
2469         my ($commit_id) = @_;
2470         my %co;
2471
2472         local $/ = "\0";
2473
2474         open my $fd, "-|", git_cmd(), "rev-list",
2475                 "--parents",
2476                 "--header",
2477                 "--max-count=1",
2478                 $commit_id,
2479                 "--",
2480                 or die_error(500, "Open git-rev-list failed");
2481         %co = parse_commit_text(<$fd>, 1);
2482         close $fd;
2483
2484         return %co;
2485 }
2486
2487 sub parse_commits {
2488         my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2489         my @cos;
2490
2491         $maxcount ||= 1;
2492         $skip ||= 0;
2493
2494         local $/ = "\0";
2495
2496         open my $fd, "-|", git_cmd(), "rev-list",
2497                 "--header",
2498                 @args,
2499                 ("--max-count=" . $maxcount),
2500                 ("--skip=" . $skip),
2501                 @extra_options,
2502                 $commit_id,
2503                 "--",
2504                 ($filename ? ($filename) : ())
2505                 or die_error(500, "Open git-rev-list failed");
2506         while (my $line = <$fd>) {
2507                 my %co = parse_commit_text($line);
2508                 push @cos, \%co;
2509         }
2510         close $fd;
2511
2512         return wantarray ? @cos : \@cos;
2513 }
2514
2515 # parse line of git-diff-tree "raw" output
2516 sub parse_difftree_raw_line {
2517         my $line = shift;
2518         my %res;
2519
2520         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
2521         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
2522         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2523                 $res{'from_mode'} = $1;
2524                 $res{'to_mode'} = $2;
2525                 $res{'from_id'} = $3;
2526                 $res{'to_id'} = $4;
2527                 $res{'status'} = $5;
2528                 $res{'similarity'} = $6;
2529                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2530                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2531                 } else {
2532                         $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2533                 }
2534         }
2535         # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2536         # combined diff (for merge commit)
2537         elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2538                 $res{'nparents'}  = length($1);
2539                 $res{'from_mode'} = [ split(' ', $2) ];
2540                 $res{'to_mode'} = pop @{$res{'from_mode'}};
2541                 $res{'from_id'} = [ split(' ', $3) ];
2542                 $res{'to_id'} = pop @{$res{'from_id'}};
2543                 $res{'status'} = [ split('', $4) ];
2544                 $res{'to_file'} = unquote($5);
2545         }
2546         # 'c512b523472485aef4fff9e57b229d9d243c967f'
2547         elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2548                 $res{'commit'} = $1;
2549         }
2550
2551         return wantarray ? %res : \%res;
2552 }
2553
2554 # wrapper: return parsed line of git-diff-tree "raw" output
2555 # (the argument might be raw line, or parsed info)
2556 sub parsed_difftree_line {
2557         my $line_or_ref = shift;
2558
2559         if (ref($line_or_ref) eq "HASH") {
2560                 # pre-parsed (or generated by hand)
2561                 return $line_or_ref;
2562         } else {
2563                 return parse_difftree_raw_line($line_or_ref);
2564         }
2565 }
2566
2567 # parse line of git-ls-tree output
2568 sub parse_ls_tree_line ($;%) {
2569         my $line = shift;
2570         my %opts = @_;
2571         my %res;
2572
2573         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
2574         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2575
2576         $res{'mode'} = $1;
2577         $res{'type'} = $2;
2578         $res{'hash'} = $3;
2579         if ($opts{'-z'}) {
2580                 $res{'name'} = $4;
2581         } else {
2582                 $res{'name'} = unquote($4);
2583         }
2584
2585         return wantarray ? %res : \%res;
2586 }
2587
2588 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2589 sub parse_from_to_diffinfo {
2590         my ($diffinfo, $from, $to, @parents) = @_;
2591
2592         if ($diffinfo->{'nparents'}) {
2593                 # combined diff
2594                 $from->{'file'} = [];
2595                 $from->{'href'} = [];
2596                 fill_from_file_info($diffinfo, @parents)
2597                         unless exists $diffinfo->{'from_file'};
2598                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2599                         $from->{'file'}[$i] =
2600                                 defined $diffinfo->{'from_file'}[$i] ?
2601                                         $diffinfo->{'from_file'}[$i] :
2602                                         $diffinfo->{'to_file'};
2603                         if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2604                                 $from->{'href'}[$i] = href(action=>"blob",
2605                                                            hash_base=>$parents[$i],
2606                                                            hash=>$diffinfo->{'from_id'}[$i],
2607                                                            file_name=>$from->{'file'}[$i]);
2608                         } else {
2609                                 $from->{'href'}[$i] = undef;
2610                         }
2611                 }
2612         } else {
2613                 # ordinary (not combined) diff
2614                 $from->{'file'} = $diffinfo->{'from_file'};
2615                 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2616                         $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2617                                                hash=>$diffinfo->{'from_id'},
2618                                                file_name=>$from->{'file'});
2619                 } else {
2620                         delete $from->{'href'};
2621                 }
2622         }
2623
2624         $to->{'file'} = $diffinfo->{'to_file'};
2625         if (!is_deleted($diffinfo)) { # file exists in result
2626                 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2627                                      hash=>$diffinfo->{'to_id'},
2628                                      file_name=>$to->{'file'});
2629         } else {
2630                 delete $to->{'href'};
2631         }
2632 }
2633
2634 ## ......................................................................
2635 ## parse to array of hashes functions
2636
2637 sub git_get_heads_list {
2638         my $limit = shift;
2639         my @headslist;
2640
2641         open my $fd, '-|', git_cmd(), 'for-each-ref',
2642                 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2643                 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2644                 'refs/heads'
2645                 or return;
2646         while (my $line = <$fd>) {
2647                 my %ref_item;
2648
2649                 chomp $line;
2650                 my ($refinfo, $committerinfo) = split(/\0/, $line);
2651                 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2652                 my ($committer, $epoch, $tz) =
2653                         ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2654                 $ref_item{'fullname'}  = $name;
2655                 $name =~ s!^refs/heads/!!;
2656
2657                 $ref_item{'name'}  = $name;
2658                 $ref_item{'id'}    = $hash;
2659                 $ref_item{'title'} = $title || '(no commit message)';
2660                 $ref_item{'epoch'} = $epoch;
2661                 if ($epoch) {
2662                         $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2663                 } else {
2664                         $ref_item{'age'} = "unknown";
2665                 }
2666
2667                 push @headslist, \%ref_item;
2668         }
2669         close $fd;
2670
2671         return wantarray ? @headslist : \@headslist;
2672 }
2673
2674 sub git_get_tags_list {
2675         my $limit = shift;
2676         my @tagslist;
2677
2678         open my $fd, '-|', git_cmd(), 'for-each-ref',
2679                 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2680                 '--format=%(objectname) %(objecttype) %(refname) '.
2681                 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2682                 'refs/tags'
2683                 or return;
2684         while (my $line = <$fd>) {
2685                 my %ref_item;
2686
2687                 chomp $line;
2688                 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2689                 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2690                 my ($creator, $epoch, $tz) =
2691                         ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2692                 $ref_item{'fullname'} = $name;
2693                 $name =~ s!^refs/tags/!!;
2694
2695                 $ref_item{'type'} = $type;
2696                 $ref_item{'id'} = $id;
2697                 $ref_item{'name'} = $name;
2698                 if ($type eq "tag") {
2699                         $ref_item{'subject'} = $title;
2700                         $ref_item{'reftype'} = $reftype;
2701                         $ref_item{'refid'}   = $refid;
2702                 } else {
2703                         $ref_item{'reftype'} = $type;
2704                         $ref_item{'refid'}   = $id;
2705                 }
2706
2707                 if ($type eq "tag" || $type eq "commit") {
2708                         $ref_item{'epoch'} = $epoch;
2709                         if ($epoch) {
2710                                 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2711                         } else {
2712                                 $ref_item{'age'} = "unknown";
2713                         }
2714                 }
2715
2716                 push @tagslist, \%ref_item;
2717         }
2718         close $fd;
2719
2720         return wantarray ? @tagslist : \@tagslist;
2721 }
2722
2723 ## ----------------------------------------------------------------------
2724 ## filesystem-related functions
2725
2726 sub get_file_owner {
2727         my $path = shift;
2728
2729         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2730         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2731         if (!defined $gcos) {
2732                 return undef;
2733         }
2734         my $owner = $gcos;
2735         $owner =~ s/[,;].*$//;
2736         return to_utf8($owner);
2737 }
2738
2739 # assume that file exists
2740 sub insert_file {
2741         my $filename = shift;
2742
2743         open my $fd, '<', $filename;
2744         print map { to_utf8($_) } <$fd>;
2745         close $fd;
2746 }
2747
2748 ## ......................................................................
2749 ## mimetype related functions
2750
2751 sub mimetype_guess_file {
2752         my $filename = shift;
2753         my $mimemap = shift;
2754         -r $mimemap or return undef;
2755
2756         my %mimemap;
2757         open(MIME, $mimemap) or return undef;
2758         while (<MIME>) {
2759                 next if m/^#/; # skip comments
2760                 my ($mime, $exts) = split(/\t+/);
2761                 if (defined $exts) {
2762                         my @exts = split(/\s+/, $exts);
2763                         foreach my $ext (@exts) {
2764                                 $mimemap{$ext} = $mime;
2765                         }
2766                 }
2767         }
2768         close(MIME);
2769
2770         $filename =~ /\.([^.]*)$/;
2771         return $mimemap{$1};
2772 }
2773
2774 sub mimetype_guess {
2775         my $filename = shift;
2776         my $mime;
2777         $filename =~ /\./ or return undef;
2778
2779         if ($mimetypes_file) {
2780                 my $file = $mimetypes_file;
2781                 if ($file !~ m!^/!) { # if it is relative path
2782                         # it is relative to project
2783                         $file = "$projectroot/$project/$file";
2784                 }
2785                 $mime = mimetype_guess_file($filename, $file);
2786         }
2787         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
2788         return $mime;
2789 }
2790
2791 sub blob_mimetype {
2792         my $fd = shift;
2793         my $filename = shift;
2794
2795         if ($filename) {
2796                 my $mime = mimetype_guess($filename);
2797                 $mime and return $mime;
2798         }
2799
2800         # just in case
2801         return $default_blob_plain_mimetype unless $fd;
2802
2803         if (-T $fd) {
2804                 return 'text/plain';
2805         } elsif (! $filename) {
2806                 return 'application/octet-stream';
2807         } elsif ($filename =~ m/\.png$/i) {
2808                 return 'image/png';
2809         } elsif ($filename =~ m/\.gif$/i) {
2810                 return 'image/gif';
2811         } elsif ($filename =~ m/\.jpe?g$/i) {
2812                 return 'image/jpeg';
2813         } else {
2814                 return 'application/octet-stream';
2815         }
2816 }
2817
2818 sub blob_contenttype {
2819         my ($fd, $file_name, $type) = @_;
2820
2821         $type ||= blob_mimetype($fd, $file_name);
2822         if ($type eq 'text/plain' && defined $default_text_plain_charset) {
2823                 $type .= "; charset=$default_text_plain_charset";
2824         }
2825
2826         return $type;
2827 }
2828
2829 ## ======================================================================
2830 ## functions printing HTML: header, footer, error page
2831
2832 sub git_header_html {
2833         my $status = shift || "200 OK";
2834         my $expires = shift;
2835
2836         my $title = "$site_name";
2837         if (defined $project) {
2838                 $title .= " - " . to_utf8($project);
2839                 if (defined $action) {
2840                         $title .= "/$action";
2841                         if (defined $file_name) {
2842                                 $title .= " - " . esc_path($file_name);
2843                                 if ($action eq "tree" && $file_name !~ m|/$|) {
2844                                         $title .= "/";
2845                                 }
2846                         }
2847                 }
2848         }
2849         my $content_type;
2850         # require explicit support from the UA if we are to send the page as
2851         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
2852         # we have to do this because MSIE sometimes globs '*/*', pretending to
2853         # support xhtml+xml but choking when it gets what it asked for.
2854         if (defined $cgi->http('HTTP_ACCEPT') &&
2855             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
2856             $cgi->Accept('application/xhtml+xml') != 0) {
2857                 $content_type = 'application/xhtml+xml';
2858         } else {
2859                 $content_type = 'text/html';
2860         }
2861         print $cgi->header(-type=>$content_type, -charset => 'utf-8',
2862                            -status=> $status, -expires => $expires);
2863         my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
2864         print <<EOF;
2865 <?xml version="1.0" encoding="utf-8"?>
2866 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2867 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
2868 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
2869 <!-- git core binaries version $git_version -->
2870 <head>
2871 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
2872 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
2873 <meta name="robots" content="index, nofollow"/>
2874 <title>$title</title>
2875 EOF
2876 # print out each stylesheet that exist
2877         if (defined $stylesheet) {
2878 #provides backwards capability for those people who define style sheet in a config file
2879                 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2880         } else {
2881                 foreach my $stylesheet (@stylesheets) {
2882                         next unless $stylesheet;
2883                         print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2884                 }
2885         }
2886         if (defined $project) {
2887                 my %href_params = get_feed_info();
2888                 if (!exists $href_params{'-title'}) {
2889                         $href_params{'-title'} = 'log';
2890                 }
2891
2892                 foreach my $format qw(RSS Atom) {
2893                         my $type = lc($format);
2894                         my %link_attr = (
2895                                 '-rel' => 'alternate',
2896                                 '-title' => "$project - $href_params{'-title'} - $format feed",
2897                                 '-type' => "application/$type+xml"
2898                         );
2899
2900                         $href_params{'action'} = $type;
2901                         $link_attr{'-href'} = href(%href_params);
2902                         print "<link ".
2903                               "rel=\"$link_attr{'-rel'}\" ".
2904                               "title=\"$link_attr{'-title'}\" ".
2905                               "href=\"$link_attr{'-href'}\" ".
2906                               "type=\"$link_attr{'-type'}\" ".
2907                               "/>\n";
2908
2909                         $href_params{'extra_options'} = '--no-merges';
2910                         $link_attr{'-href'} = href(%href_params);
2911                         $link_attr{'-title'} .= ' (no merges)';
2912                         print "<link ".
2913                               "rel=\"$link_attr{'-rel'}\" ".
2914                               "title=\"$link_attr{'-title'}\" ".
2915                               "href=\"$link_attr{'-href'}\" ".
2916                               "type=\"$link_attr{'-type'}\" ".
2917                               "/>\n";
2918                 }
2919
2920         } else {
2921                 printf('<link rel="alternate" title="%s projects list" '.
2922                        'href="%s" type="text/plain; charset=utf-8" />'."\n",
2923                        $site_name, href(project=>undef, action=>"project_index"));
2924                 printf('<link rel="alternate" title="%s projects feeds" '.
2925                        'href="%s" type="text/x-opml" />'."\n",
2926                        $site_name, href(project=>undef, action=>"opml"));
2927         }
2928         if (defined $favicon) {
2929                 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
2930         }
2931
2932         print "</head>\n" .
2933               "<body>\n";
2934
2935         if (-f $site_header) {
2936                 insert_file($site_header);
2937         }
2938
2939         print "<div class=\"page_header\">\n" .
2940               $cgi->a({-href => esc_url($logo_url),
2941                        -title => $logo_label},
2942                       qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
2943         print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
2944         if (defined $project) {
2945                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
2946                 if (defined $action) {
2947                         print " / $action";
2948                 }
2949                 print "\n";
2950         }
2951         print "</div>\n";
2952
2953         my $have_search = gitweb_check_feature('search');
2954         if (defined $project && $have_search) {
2955                 if (!defined $searchtext) {
2956                         $searchtext = "";
2957                 }
2958                 my $search_hash;
2959                 if (defined $hash_base) {
2960                         $search_hash = $hash_base;
2961                 } elsif (defined $hash) {
2962                         $search_hash = $hash;
2963                 } else {
2964                         $search_hash = "HEAD";
2965                 }
2966                 my $action = $my_uri;
2967                 my $use_pathinfo = gitweb_check_feature('pathinfo');
2968                 if ($use_pathinfo) {
2969                         $action .= "/".esc_url($project);
2970                 }
2971                 print $cgi->startform(-method => "get", -action => $action) .
2972                       "<div class=\"search\">\n" .
2973                       (!$use_pathinfo &&
2974                       $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
2975                       $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
2976                       $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
2977                       $cgi->popup_menu(-name => 'st', -default => 'commit',
2978                                        -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
2979                       $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
2980                       " search:\n",
2981                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
2982                       "<span title=\"Extended regular expression\">" .
2983                       $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
2984                                      -checked => $search_use_regexp) .
2985                       "</span>" .
2986                       "</div>" .
2987                       $cgi->end_form() . "\n";
2988         }
2989 }
2990
2991 sub git_footer_html {
2992         my $feed_class = 'rss_logo';
2993
2994         print "<div class=\"page_footer\">\n";
2995         if (defined $project) {
2996                 my $descr = git_get_project_description($project);
2997                 if (defined $descr) {
2998                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
2999                 }
3000
3001                 my %href_params = get_feed_info();
3002                 if (!%href_params) {
3003                         $feed_class .= ' generic';
3004                 }
3005                 $href_params{'-title'} ||= 'log';
3006
3007                 foreach my $format qw(RSS Atom) {
3008                         $href_params{'action'} = lc($format);
3009                         print $cgi->a({-href => href(%href_params),
3010                                       -title => "$href_params{'-title'} $format feed",
3011                                       -class => $feed_class}, $format)."\n";
3012                 }
3013
3014         } else {
3015                 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3016                               -class => $feed_class}, "OPML") . " ";
3017                 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3018                               -class => $feed_class}, "TXT") . "\n";
3019         }
3020         print "</div>\n"; # class="page_footer"
3021
3022         if (-f $site_footer) {
3023                 insert_file($site_footer);
3024         }
3025
3026         print "</body>\n" .
3027               "</html>";
3028 }
3029
3030 # die_error(<http_status_code>, <error_message>)
3031 # Example: die_error(404, 'Hash not found')
3032 # By convention, use the following status codes (as defined in RFC 2616):
3033 # 400: Invalid or missing CGI parameters, or
3034 #      requested object exists but has wrong type.
3035 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3036 #      this server or project.
3037 # 404: Requested object/revision/project doesn't exist.
3038 # 500: The server isn't configured properly, or
3039 #      an internal error occurred (e.g. failed assertions caused by bugs), or
3040 #      an unknown error occurred (e.g. the git binary died unexpectedly).
3041 sub die_error {
3042         my $status = shift || 500;
3043         my $error = shift || "Internal server error";
3044
3045         my %http_responses = (400 => '400 Bad Request',
3046                               403 => '403 Forbidden',
3047                               404 => '404 Not Found',
3048                               500 => '500 Internal Server Error');
3049         git_header_html($http_responses{$status});
3050         print <<EOF;
3051 <div class="page_body">
3052 <br /><br />
3053 $status - $error
3054 <br />
3055 </div>
3056 EOF
3057         git_footer_html();
3058         exit;
3059 }
3060
3061 ## ----------------------------------------------------------------------
3062 ## functions printing or outputting HTML: navigation
3063
3064 sub git_print_page_nav {
3065         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3066         $extra = '' if !defined $extra; # pager or formats
3067
3068         my @navs = qw(summary shortlog log commit commitdiff tree);
3069         if ($suppress) {
3070                 @navs = grep { $_ ne $suppress } @navs;
3071         }
3072
3073         my %arg = map { $_ => {action=>$_} } @navs;
3074         if (defined $head) {
3075                 for (qw(commit commitdiff)) {
3076                         $arg{$_}{'hash'} = $head;
3077                 }
3078                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3079                         for (qw(shortlog log)) {
3080                                 $arg{$_}{'hash'} = $head;
3081                         }
3082                 }
3083         }
3084
3085         $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3086         $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3087
3088         my @actions = gitweb_get_feature('actions');
3089         my %repl = (
3090                 '%' => '%',
3091                 'n' => $project,         # project name
3092                 'f' => $git_dir,         # project path within filesystem
3093                 'h' => $treehead || '',  # current hash ('h' parameter)
3094                 'b' => $treebase || '',  # hash base ('hb' parameter)
3095         );
3096         while (@actions) {
3097                 my ($label, $link, $pos) = splice(@actions,0,3);
3098                 # insert
3099                 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3100                 # munch munch
3101                 $link =~ s/%([%nfhb])/$repl{$1}/g;
3102                 $arg{$label}{'_href'} = $link;
3103         }
3104
3105         print "<div class=\"page_nav\">\n" .
3106                 (join " | ",
3107                  map { $_ eq $current ?
3108                        $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3109                  } @navs);
3110         print "<br/>\n$extra<br/>\n" .
3111               "</div>\n";
3112 }
3113
3114 sub format_paging_nav {
3115         my ($action, $hash, $head, $page, $has_next_link) = @_;
3116         my $paging_nav;
3117
3118
3119         if ($hash ne $head || $page) {
3120                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
3121         } else {
3122                 $paging_nav .= "HEAD";
3123         }
3124
3125         if ($page > 0) {
3126                 $paging_nav .= " &sdot; " .
3127                         $cgi->a({-href => href(-replay=>1, page=>$page-1),
3128                                  -accesskey => "p", -title => "Alt-p"}, "prev");
3129         } else {
3130                 $paging_nav .= " &sdot; prev";
3131         }
3132
3133         if ($has_next_link) {
3134                 $paging_nav .= " &sdot; " .
3135                         $cgi->a({-href => href(-replay=>1, page=>$page+1),
3136                                  -accesskey => "n", -title => "Alt-n"}, "next");
3137         } else {
3138                 $paging_nav .= " &sdot; next";
3139         }
3140
3141         return $paging_nav;
3142 }
3143
3144 ## ......................................................................
3145 ## functions printing or outputting HTML: div
3146
3147 sub git_print_header_div {
3148         my ($action, $title, $hash, $hash_base) = @_;
3149         my %args = ();
3150
3151         $args{'action'} = $action;
3152         $args{'hash'} = $hash if $hash;
3153         $args{'hash_base'} = $hash_base if $hash_base;
3154
3155         print "<div class=\"header\">\n" .
3156               $cgi->a({-href => href(%args), -class => "title"},
3157               $title ? $title : $action) .
3158               "\n</div>\n";
3159 }
3160
3161 #sub git_print_authorship (\%) {
3162 sub git_print_authorship {
3163         my $co = shift;
3164
3165         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3166         print "<div class=\"author_date\">" .
3167               esc_html($co->{'author_name'}) .
3168               " [$ad{'rfc2822'}";
3169         if ($ad{'hour_local'} < 6) {
3170                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3171                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3172         } else {
3173                 printf(" (%02d:%02d %s)",
3174                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3175         }
3176         print "]</div>\n";
3177 }
3178
3179 sub git_print_page_path {
3180         my $name = shift;
3181         my $type = shift;
3182         my $hb = shift;
3183
3184
3185         print "<div class=\"page_path\">";
3186         print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3187                       -title => 'tree root'}, to_utf8("[$project]"));
3188         print " / ";
3189         if (defined $name) {
3190                 my @dirname = split '/', $name;
3191                 my $basename = pop @dirname;
3192                 my $fullname = '';
3193
3194                 foreach my $dir (@dirname) {
3195                         $fullname .= ($fullname ? '/' : '') . $dir;
3196                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3197                                                      hash_base=>$hb),
3198                                       -title => $fullname}, esc_path($dir));
3199                         print " / ";
3200                 }
3201                 if (defined $type && $type eq 'blob') {
3202                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3203                                                      hash_base=>$hb),
3204                                       -title => $name}, esc_path($basename));
3205                 } elsif (defined $type && $type eq 'tree') {
3206                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3207                                                      hash_base=>$hb),
3208                                       -title => $name}, esc_path($basename));
3209                         print " / ";
3210                 } else {
3211                         print esc_path($basename);
3212                 }
3213         }
3214         print "<br/></div>\n";
3215 }
3216
3217 # sub git_print_log (\@;%) {
3218 sub git_print_log ($;%) {
3219         my $log = shift;
3220         my %opts = @_;
3221
3222         if ($opts{'-remove_title'}) {
3223                 # remove title, i.e. first line of log
3224                 shift @$log;
3225         }
3226         # remove leading empty lines
3227         while (defined $log->[0] && $log->[0] eq "") {
3228                 shift @$log;
3229         }
3230
3231         # print log
3232         my $signoff = 0;
3233         my $empty = 0;
3234         foreach my $line (@$log) {
3235                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3236                         $signoff = 1;
3237                         $empty = 0;
3238                         if (! $opts{'-remove_signoff'}) {
3239                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3240                                 next;
3241                         } else {
3242                                 # remove signoff lines
3243                                 next;
3244                         }
3245                 } else {
3246                         $signoff = 0;
3247                 }
3248
3249                 # print only one empty line
3250                 # do not print empty line after signoff
3251                 if ($line eq "") {
3252                         next if ($empty || $signoff);
3253                         $empty = 1;
3254                 } else {
3255                         $empty = 0;
3256                 }
3257
3258                 print format_log_line_html($line) . "<br/>\n";
3259         }
3260
3261         if ($opts{'-final_empty_line'}) {
3262                 # end with single empty line
3263                 print "<br/>\n" unless $empty;
3264         }
3265 }
3266
3267 # return link target (what link points to)
3268 sub git_get_link_target {
3269         my $hash = shift;
3270         my $link_target;
3271
3272         # read link
3273         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3274                 or return;
3275         {
3276                 local $/;
3277                 $link_target = <$fd>;
3278         }
3279         close $fd
3280                 or return;
3281
3282         return $link_target;
3283 }
3284
3285 # given link target, and the directory (basedir) the link is in,
3286 # return target of link relative to top directory (top tree);
3287 # return undef if it is not possible (including absolute links).
3288 sub normalize_link_target {
3289         my ($link_target, $basedir, $hash_base) = @_;
3290
3291         # we can normalize symlink target only if $hash_base is provided
3292         return unless $hash_base;
3293
3294         # absolute symlinks (beginning with '/') cannot be normalized
3295         return if (substr($link_target, 0, 1) eq '/');
3296
3297         # normalize link target to path from top (root) tree (dir)
3298         my $path;
3299         if ($basedir) {
3300                 $path = $basedir . '/' . $link_target;
3301         } else {
3302                 # we are in top (root) tree (dir)
3303                 $path = $link_target;
3304         }
3305
3306         # remove //, /./, and /../
3307         my @path_parts;
3308         foreach my $part (split('/', $path)) {
3309                 # discard '.' and ''
3310                 next if (!$part || $part eq '.');
3311                 # handle '..'
3312                 if ($part eq '..') {
3313                         if (@path_parts) {
3314                                 pop @path_parts;
3315                         } else {
3316                                 # link leads outside repository (outside top dir)
3317                                 return;
3318                         }
3319                 } else {
3320                         push @path_parts, $part;
3321                 }
3322         }
3323         $path = join('/', @path_parts);
3324
3325         return $path;
3326 }
3327
3328 # print tree entry (row of git_tree), but without encompassing <tr> element
3329 sub git_print_tree_entry {
3330         my ($t, $basedir, $hash_base, $have_blame) = @_;
3331
3332         my %base_key = ();
3333         $base_key{'hash_base'} = $hash_base if defined $hash_base;
3334
3335         # The format of a table row is: mode list link.  Where mode is
3336         # the mode of the entry, list is the name of the entry, an href,
3337         # and link is the action links of the entry.
3338
3339         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3340         if ($t->{'type'} eq "blob") {
3341                 print "<td class=\"list\">" .
3342                         $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3343                                                file_name=>"$basedir$t->{'name'}", %base_key),
3344                                 -class => "list"}, esc_path($t->{'name'}));
3345                 if (S_ISLNK(oct $t->{'mode'})) {
3346                         my $link_target = git_get_link_target($t->{'hash'});
3347                         if ($link_target) {
3348                                 my $norm_target = normalize_link_target($link_target, $basedir, $hash_base);
3349                                 if (defined $norm_target) {
3350                                         print " -> " .
3351                                               $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3352                                                                      file_name=>$norm_target),
3353                                                        -title => $norm_target}, esc_path($link_target));
3354                                 } else {
3355                                         print " -> " . esc_path($link_target);
3356                                 }
3357                         }
3358                 }
3359                 print "</td>\n";
3360                 print "<td class=\"link\">";
3361                 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3362                                              file_name=>"$basedir$t->{'name'}", %base_key)},
3363                               "blob");
3364                 if ($have_blame) {
3365                         print " | " .
3366                               $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3367                                                      file_name=>"$basedir$t->{'name'}", %base_key)},
3368                                       "blame");
3369                 }
3370                 if (defined $hash_base) {
3371                         print " | " .
3372                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3373                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3374                                       "history");
3375                 }
3376                 print " | " .
3377                         $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3378                                                file_name=>"$basedir$t->{'name'}")},
3379                                 "raw");
3380                 print "</td>\n";
3381
3382         } elsif ($t->{'type'} eq "tree") {
3383                 print "<td class=\"list\">";
3384                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3385                                              file_name=>"$basedir$t->{'name'}", %base_key)},
3386                               esc_path($t->{'name'}));
3387                 print "</td>\n";
3388                 print "<td class=\"link\">";
3389                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3390                                              file_name=>"$basedir$t->{'name'}", %base_key)},
3391                               "tree");
3392                 if (defined $hash_base) {
3393                         print " | " .
3394                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3395                                                      file_name=>"$basedir$t->{'name'}")},
3396                                       "history");
3397                 }
3398                 print "</td>\n";
3399         } else {
3400                 # unknown object: we can only present history for it
3401                 # (this includes 'commit' object, i.e. submodule support)
3402                 print "<td class=\"list\">" .
3403                       esc_path($t->{'name'}) .
3404                       "</td>\n";
3405                 print "<td class=\"link\">";
3406                 if (defined $hash_base) {
3407                         print $cgi->a({-href => href(action=>"history",
3408                                                      hash_base=>$hash_base,
3409                                                      file_name=>"$basedir$t->{'name'}")},
3410                                       "history");
3411                 }
3412                 print "</td>\n";
3413         }
3414 }
3415
3416 ## ......................................................................
3417 ## functions printing large fragments of HTML
3418
3419 # get pre-image filenames for merge (combined) diff
3420 sub fill_from_file_info {
3421         my ($diff, @parents) = @_;
3422
3423         $diff->{'from_file'} = [ ];
3424         $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
3425         for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3426                 if ($diff->{'status'}[$i] eq 'R' ||
3427                     $diff->{'status'}[$i] eq 'C') {
3428                         $diff->{'from_file'}[$i] =
3429                                 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
3430                 }
3431         }
3432
3433         return $diff;
3434 }
3435
3436 # is current raw difftree line of file deletion
3437 sub is_deleted {
3438         my $diffinfo = shift;
3439
3440         return $diffinfo->{'to_id'} eq ('0' x 40);
3441 }
3442
3443 # does patch correspond to [previous] difftree raw line
3444 # $diffinfo  - hashref of parsed raw diff format
3445 # $patchinfo - hashref of parsed patch diff format
3446 #              (the same keys as in $diffinfo)
3447 sub is_patch_split {
3448         my ($diffinfo, $patchinfo) = @_;
3449
3450         return defined $diffinfo && defined $patchinfo
3451                 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
3452 }
3453
3454
3455 sub git_difftree_body {
3456         my ($difftree, $hash, @parents) = @_;
3457         my ($parent) = $parents[0];
3458         my $have_blame = gitweb_check_feature('blame');
3459         print "<div class=\"list_head\">\n";
3460         if ($#{$difftree} > 10) {
3461                 print(($#{$difftree} + 1) . " files changed:\n");
3462         }
3463         print "</div>\n";
3464
3465         print "<table class=\"" .
3466               (@parents > 1 ? "combined " : "") .
3467               "diff_tree\">\n";
3468
3469         # header only for combined diff in 'commitdiff' view
3470         my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
3471         if ($has_header) {
3472                 # table header
3473                 print "<thead><tr>\n" .
3474                        "<th></th><th></th>\n"; # filename, patchN link
3475                 for (my $i = 0; $i < @parents; $i++) {
3476                         my $par = $parents[$i];
3477                         print "<th>" .
3478                               $cgi->a({-href => href(action=>"commitdiff",
3479                                                      hash=>$hash, hash_parent=>$par),
3480                                        -title => 'commitdiff to parent number ' .
3481                                                   ($i+1) . ': ' . substr($par,0,7)},
3482                                       $i+1) .
3483                               "&nbsp;</th>\n";
3484                 }
3485                 print "</tr></thead>\n<tbody>\n";
3486         }
3487
3488         my $alternate = 1;
3489         my $patchno = 0;
3490         foreach my $line (@{$difftree}) {
3491                 my $diff = parsed_difftree_line($line);
3492
3493                 if ($alternate) {
3494                         print "<tr class=\"dark\">\n";
3495                 } else {
3496                         print "<tr class=\"light\">\n";
3497                 }
3498                 $alternate ^= 1;
3499
3500                 if (exists $diff->{'nparents'}) { # combined diff
3501
3502                         fill_from_file_info($diff, @parents)
3503                                 unless exists $diff->{'from_file'};
3504
3505                         if (!is_deleted($diff)) {
3506                                 # file exists in the result (child) commit
3507                                 print "<td>" .
3508                                       $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3509                                                              file_name=>$diff->{'to_file'},
3510                                                              hash_base=>$hash),
3511                                               -class => "list"}, esc_path($diff->{'to_file'})) .
3512                                       "</td>\n";
3513                         } else {
3514                                 print "<td>" .
3515                                       esc_path($diff->{'to_file'}) .
3516                                       "</td>\n";
3517                         }
3518
3519                         if ($action eq 'commitdiff') {
3520                                 # link to patch
3521                                 $patchno++;
3522                                 print "<td class=\"link\">" .
3523                                       $cgi->a({-href => "#patch$patchno"}, "patch") .
3524                                       " | " .
3525                                       "</td>\n";
3526                         }
3527
3528                         my $has_history = 0;
3529                         my $not_deleted = 0;
3530                         for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3531                                 my $hash_parent = $parents[$i];
3532                                 my $from_hash = $diff->{'from_id'}[$i];
3533                                 my $from_path = $diff->{'from_file'}[$i];
3534                                 my $status = $diff->{'status'}[$i];
3535
3536                                 $has_history ||= ($status ne 'A');
3537                                 $not_deleted ||= ($status ne 'D');
3538
3539                                 if ($status eq 'A') {
3540                                         print "<td  class=\"link\" align=\"right\"> | </td>\n";
3541                                 } elsif ($status eq 'D') {
3542                                         print "<td class=\"link\">" .
3543                                               $cgi->a({-href => href(action=>"blob",
3544                                                                      hash_base=>$hash,
3545                                                                      hash=>$from_hash,
3546                                                                      file_name=>$from_path)},
3547                                                       "blob" . ($i+1)) .
3548                                               " | </td>\n";
3549                                 } else {
3550                                         if ($diff->{'to_id'} eq $from_hash) {
3551                                                 print "<td class=\"link nochange\">";
3552                                         } else {
3553                                                 print "<td class=\"link\">";
3554                                         }
3555                                         print $cgi->a({-href => href(action=>"blobdiff",
3556                                                                      hash=>$diff->{'to_id'},
3557                                                                      hash_parent=>$from_hash,
3558                                                                      hash_base=>$hash,
3559                                                                      hash_parent_base=>$hash_parent,
3560                                                                      file_name=>$diff->{'to_file'},
3561                                                                      file_parent=>$from_path)},
3562                                                       "diff" . ($i+1)) .
3563                                               " | </td>\n";
3564                                 }
3565                         }
3566
3567                         print "<td class=\"link\">";
3568                         if ($not_deleted) {
3569                                 print $cgi->a({-href => href(action=>"blob",
3570                                                              hash=>$diff->{'to_id'},
3571                                                              file_name=>$diff->{'to_file'},
3572                                                              hash_base=>$hash)},
3573                                               "blob");
3574                                 print " | " if ($has_history);
3575                         }
3576                         if ($has_history) {
3577                                 print $cgi->a({-href => href(action=>"history",
3578                                                              file_name=>$diff->{'to_file'},
3579                                                              hash_base=>$hash)},
3580                                               "history");
3581                         }
3582                         print "</td>\n";
3583
3584                         print "</tr>\n";
3585                         next; # instead of 'else' clause, to avoid extra indent
3586                 }
3587                 # else ordinary diff
3588
3589                 my ($to_mode_oct, $to_mode_str, $to_file_type);
3590                 my ($from_mode_oct, $from_mode_str, $from_file_type);
3591                 if ($diff->{'to_mode'} ne ('0' x 6)) {
3592                         $to_mode_oct = oct $diff->{'to_mode'};
3593                         if (S_ISREG($to_mode_oct)) { # only for regular file
3594                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
3595                         }
3596                         $to_file_type = file_type($diff->{'to_mode'});
3597                 }
3598                 if ($diff->{'from_mode'} ne ('0' x 6)) {
3599                         $from_mode_oct = oct $diff->{'from_mode'};
3600                         if (S_ISREG($to_mode_oct)) { # only for regular file
3601                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
3602                         }
3603                         $from_file_type = file_type($diff->{'from_mode'});
3604                 }
3605
3606                 if ($diff->{'status'} eq "A") { # created
3607                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
3608                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
3609                         $mode_chng   .= "]</span>";
3610                         print "<td>";
3611                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3612                                                      hash_base=>$hash, file_name=>$diff->{'file'}),
3613                                       -class => "list"}, esc_path($diff->{'file'}));
3614                         print "</td>\n";
3615                         print "<td>$mode_chng</td>\n";
3616                         print "<td class=\"link\">";
3617                         if ($action eq 'commitdiff') {
3618                                 # link to patch
3619                                 $patchno++;
3620                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
3621                                 print " | ";
3622                         }
3623                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3624                                                      hash_base=>$hash, file_name=>$diff->{'file'})},
3625                                       "blob");
3626                         print "</td>\n";
3627
3628                 } elsif ($diff->{'status'} eq "D") { # deleted
3629                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
3630                         print "<td>";
3631                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3632                                                      hash_base=>$parent, file_name=>$diff->{'file'}),
3633                                        -class => "list"}, esc_path($diff->{'file'}));
3634                         print "</td>\n";
3635                         print "<td>$mode_chng</td>\n";
3636                         print "<td class=\"link\">";
3637                         if ($action eq 'commitdiff') {
3638                                 # link to patch
3639                                 $patchno++;
3640                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
3641                                 print " | ";
3642                         }
3643                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3644                                                      hash_base=>$parent, file_name=>$diff->{'file'})},
3645                                       "blob") . " | ";
3646                         if ($have_blame) {
3647                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
3648                                                              file_name=>$diff->{'file'})},
3649                                               "blame") . " | ";
3650                         }
3651                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
3652                                                      file_name=>$diff->{'file'})},
3653                                       "history");
3654                         print "</td>\n";
3655
3656                 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
3657                         my $mode_chnge = "";
3658                         if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3659                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
3660                                 if ($from_file_type ne $to_file_type) {
3661                                         $mode_chnge .= " from $from_file_type to $to_file_type";
3662                                 }
3663                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3664                                         if ($from_mode_str && $to_mode_str) {
3665                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3666                                         } elsif ($to_mode_str) {
3667                                                 $mode_chnge .= " mode: $to_mode_str";
3668                                         }
3669                                 }
3670                                 $mode_chnge .= "]</span>\n";
3671                         }
3672                         print "<td>";
3673                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3674                                                      hash_base=>$hash, file_name=>$diff->{'file'}),
3675                                       -class => "list"}, esc_path($diff->{'file'}));
3676                         print "</td>\n";
3677                         print "<td>$mode_chnge</td>\n";
3678                         print "<td class=\"link\">";
3679                         if ($action eq 'commitdiff') {
3680                                 # link to patch
3681                                 $patchno++;
3682                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3683                                       " | ";
3684                         } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3685                                 # "commit" view and modified file (not onlu mode changed)
3686                                 print $cgi->a({-href => href(action=>"blobdiff",
3687                                                              hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3688                                                              hash_base=>$hash, hash_parent_base=>$parent,
3689                                                              file_name=>$diff->{'file'})},
3690                                               "diff") .
3691                                       " | ";
3692                         }
3693                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3694                                                      hash_base=>$hash, file_name=>$diff->{'file'})},
3695                                        "blob") . " | ";
3696                         if ($have_blame) {
3697                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3698                                                              file_name=>$diff->{'file'})},
3699                                               "blame") . " | ";
3700                         }
3701                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3702                                                      file_name=>$diff->{'file'})},
3703                                       "history");
3704                         print "</td>\n";
3705
3706                 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
3707                         my %status_name = ('R' => 'moved', 'C' => 'copied');
3708                         my $nstatus = $status_name{$diff->{'status'}};
3709                         my $mode_chng = "";
3710                         if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3711                                 # mode also for directories, so we cannot use $to_mode_str
3712                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
3713                         }
3714                         print "<td>" .
3715                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
3716                                                      hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
3717                                       -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
3718                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
3719                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
3720                                                      hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
3721                                       -class => "list"}, esc_path($diff->{'from_file'})) .
3722                               " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
3723                               "<td class=\"link\">";
3724                         if ($action eq 'commitdiff') {
3725                                 # link to patch
3726                                 $patchno++;
3727                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3728                                       " | ";
3729                         } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3730                                 # "commit" view and modified file (not only pure rename or copy)
3731                                 print $cgi->a({-href => href(action=>"blobdiff",
3732                                                              hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3733                                                              hash_base=>$hash, hash_parent_base=>$parent,
3734                                                              file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
3735                                               "diff") .
3736                                       " | ";
3737                         }
3738                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3739                                                      hash_base=>$parent, file_name=>$diff->{'to_file'})},
3740                                       "blob") . " | ";
3741                         if ($have_blame) {
3742                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3743                                                              file_name=>$diff->{'to_file'})},
3744                                               "blame") . " | ";
3745                         }
3746                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3747                                                     file_name=>$diff->{'to_file'})},
3748                                       "history");
3749                         print "</td>\n";
3750
3751                 } # we should not encounter Unmerged (U) or Unknown (X) status
3752                 print "</tr>\n";
3753         }
3754         print "</tbody>" if $has_header;
3755         print "</table>\n";
3756 }
3757
3758 sub git_patchset_body {
3759         my ($fd, $difftree, $hash, @hash_parents) = @_;
3760         my ($hash_parent) = $hash_parents[0];
3761
3762         my $is_combined = (@hash_parents > 1);
3763         my $patch_idx = 0;
3764         my $patch_number = 0;
3765         my $patch_line;
3766         my $diffinfo;
3767         my $to_name;
3768         my (%from, %to);
3769
3770         print "<div class=\"patchset\">\n";
3771
3772         # skip to first patch
3773         while ($patch_line = <$fd>) {
3774                 chomp $patch_line;
3775
3776                 last if ($patch_line =~ m/^diff /);
3777         }
3778
3779  PATCH:
3780         while ($patch_line) {
3781
3782                 # parse "git diff" header line
3783                 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
3784                         # $1 is from_name, which we do not use
3785                         $to_name = unquote($2);
3786                         $to_name =~ s!^b/!!;
3787                 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
3788                         # $1 is 'cc' or 'combined', which we do not use
3789                         $to_name = unquote($2);
3790                 } else {
3791                         $to_name = undef;
3792                 }
3793
3794                 # check if current patch belong to current raw line
3795                 # and parse raw git-diff line if needed
3796                 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
3797                         # this is continuation of a split patch
3798                         print "<div class=\"patch cont\">\n";
3799                 } else {
3800                         # advance raw git-diff output if needed
3801                         $patch_idx++ if defined $diffinfo;
3802
3803                         # read and prepare patch information
3804                         $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3805
3806                         # compact combined diff output can have some patches skipped
3807                         # find which patch (using pathname of result) we are at now;
3808                         if ($is_combined) {
3809                                 while ($to_name ne $diffinfo->{'to_file'}) {
3810                                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3811                                               format_diff_cc_simplified($diffinfo, @hash_parents) .
3812                                               "</div>\n";  # class="patch"
3813
3814                                         $patch_idx++;
3815                                         $patch_number++;
3816
3817                                         last if $patch_idx > $#$difftree;
3818                                         $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3819                                 }
3820                         }
3821
3822                         # modifies %from, %to hashes
3823                         parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
3824
3825                         # this is first patch for raw difftree line with $patch_idx index
3826                         # we index @$difftree array from 0, but number patches from 1
3827                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
3828                 }
3829
3830                 # git diff header
3831                 #assert($patch_line =~ m/^diff /) if DEBUG;
3832                 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
3833                 $patch_number++;
3834                 # print "git diff" header
3835                 print format_git_diff_header_line($patch_line, $diffinfo,
3836                                                   \%from, \%to);
3837
3838                 # print extended diff header
3839                 print "<div class=\"diff extended_header\">\n";
3840         EXTENDED_HEADER:
3841                 while ($patch_line = <$fd>) {
3842                         chomp $patch_line;
3843
3844                         last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
3845
3846                         print format_extended_diff_header_line($patch_line, $diffinfo,
3847                                                                \%from, \%to);
3848                 }
3849                 print "</div>\n"; # class="diff extended_header"
3850
3851                 # from-file/to-file diff header
3852                 if (! $patch_line) {
3853                         print "</div>\n"; # class="patch"
3854                         last PATCH;
3855                 }
3856                 next PATCH if ($patch_line =~ m/^diff /);
3857                 #assert($patch_line =~ m/^---/) if DEBUG;
3858
3859                 my $last_patch_line = $patch_line;
3860                 $patch_line = <$fd>;
3861                 chomp $patch_line;
3862                 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
3863
3864                 print format_diff_from_to_header($last_patch_line, $patch_line,
3865                                                  $diffinfo, \%from, \%to,
3866                                                  @hash_parents);
3867
3868                 # the patch itself
3869         LINE:
3870                 while ($patch_line = <$fd>) {
3871                         chomp $patch_line;
3872
3873                         next PATCH if ($patch_line =~ m/^diff /);
3874
3875                         print format_diff_line($patch_line, \%from, \%to);
3876                 }
3877
3878         } continue {
3879                 print "</div>\n"; # class="patch"
3880         }
3881
3882         # for compact combined (--cc) format, with chunk and patch simpliciaction
3883         # patchset might be empty, but there might be unprocessed raw lines
3884         for (++$patch_idx if $patch_number > 0;
3885              $patch_idx < @$difftree;
3886              ++$patch_idx) {
3887                 # read and prepare patch information
3888                 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3889
3890                 # generate anchor for "patch" links in difftree / whatchanged part
3891                 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3892                       format_diff_cc_simplified($diffinfo, @hash_parents) .
3893                       "</div>\n";  # class="patch"
3894
3895                 $patch_number++;
3896         }
3897
3898         if ($patch_number == 0) {
3899                 if (@hash_parents > 1) {
3900                         print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
3901                 } else {
3902                         print "<div class=\"diff nodifferences\">No differences found</div>\n";
3903                 }
3904         }
3905
3906         print "</div>\n"; # class="patchset"
3907 }
3908
3909 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3910
3911 # fills project list info (age, description, owner, forks) for each
3912 # project in the list, removing invalid projects from returned list
3913 # NOTE: modifies $projlist, but does not remove entries from it
3914 sub fill_project_list_info {
3915         my ($projlist, $check_forks) = @_;
3916         my @projects;
3917
3918         my $show_ctags = gitweb_check_feature('ctags');
3919  PROJECT:
3920         foreach my $pr (@$projlist) {
3921                 my (@activity) = git_get_last_activity($pr->{'path'});
3922                 unless (@activity) {
3923                         next PROJECT;
3924                 }
3925                 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
3926                 if (!defined $pr->{'descr'}) {
3927                         my $descr = git_get_project_description($pr->{'path'}) || "";
3928                         $descr = to_utf8($descr);
3929                         $pr->{'descr_long'} = $descr;
3930                         $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
3931                 }
3932                 if (!defined $pr->{'owner'}) {
3933                         $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
3934                 }
3935                 if ($check_forks) {
3936                         my $pname = $pr->{'path'};
3937                         if (($pname =~ s/\.git$//) &&
3938                             ($pname !~ /\/$/) &&
3939                             (-d "$projectroot/$pname")) {
3940                                 $pr->{'forks'} = "-d $projectroot/$pname";
3941                         }       else {
3942                                 $pr->{'forks'} = 0;
3943                         }
3944                 }
3945                 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
3946                 push @projects, $pr;
3947         }
3948
3949         return @projects;
3950 }
3951
3952 # print 'sort by' <th> element, generating 'sort by $name' replay link
3953 # if that order is not selected
3954 sub print_sort_th {
3955         my ($name, $order, $header) = @_;
3956         $header ||= ucfirst($name);
3957
3958         if ($order eq $name) {
3959                 print "<th>$header</th>\n";
3960         } else {
3961                 print "<th>" .
3962                       $cgi->a({-href => href(-replay=>1, order=>$name),
3963                                -class => "header"}, $header) .
3964                       "</th>\n";
3965         }
3966 }
3967
3968 sub git_project_list_body {
3969         # actually uses global variable $project
3970         my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
3971
3972         my $check_forks = gitweb_check_feature('forks');
3973         my @projects = fill_project_list_info($projlist, $check_forks);
3974
3975         $order ||= $default_projects_order;
3976         $from = 0 unless defined $from;
3977         $to = $#projects if (!defined $to || $#projects < $to);
3978
3979         my %order_info = (
3980                 project => { key => 'path', type => 'str' },
3981                 descr => { key => 'descr_long', type => 'str' },
3982                 owner => { key => 'owner', type => 'str' },
3983                 age => { key => 'age', type => 'num' }
3984         );
3985         my $oi = $order_info{$order};
3986         if ($oi->{'type'} eq 'str') {
3987                 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
3988         } else {
3989                 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
3990         }
3991
3992         my $show_ctags = gitweb_check_feature('ctags');
3993         if ($show_ctags) {
3994                 my %ctags;
3995                 foreach my $p (@projects) {
3996                         foreach my $ct (keys %{$p->{'ctags'}}) {
3997                                 $ctags{$ct} += $p->{'ctags'}->{$ct};
3998                         }
3999                 }
4000                 my $cloud = git_populate_project_tagcloud(\%ctags);
4001                 print git_show_project_tagcloud($cloud, 64);
4002         }
4003
4004         print "<table class=\"project_list\">\n";
4005         unless ($no_header) {
4006                 print "<tr>\n";
4007                 if ($check_forks) {
4008                         print "<th></th>\n";
4009                 }
4010                 print_sort_th('project', $order, 'Project');
4011                 print_sort_th('descr', $order, 'Description');
4012                 print_sort_th('owner', $order, 'Owner');
4013                 print_sort_th('age', $order, 'Last Change');
4014                 print "<th></th>\n" . # for links
4015                       "</tr>\n";
4016         }
4017         my $alternate = 1;
4018         my $tagfilter = $cgi->param('by_tag');
4019         for (my $i = $from; $i <= $to; $i++) {
4020                 my $pr = $projects[$i];
4021
4022                 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4023                 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4024                         and not $pr->{'descr_long'} =~ /$searchtext/;
4025                 # Weed out forks or non-matching entries of search
4026                 if ($check_forks) {
4027                         my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4028                         $forkbase="^$forkbase" if $forkbase;
4029                         next if not $searchtext and not $tagfilter and $show_ctags
4030                                 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4031                 }
4032
4033                 if ($alternate) {
4034                         print "<tr class=\"dark\">\n";
4035                 } else {
4036                         print "<tr class=\"light\">\n";
4037                 }
4038                 $alternate ^= 1;
4039                 if ($check_forks) {
4040                         print "<td>";
4041                         if ($pr->{'forks'}) {
4042                                 print "<!-- $pr->{'forks'} -->\n";
4043                                 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4044                         }
4045                         print "</td>\n";
4046                 }
4047                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4048                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4049                       "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4050                                         -class => "list", -title => $pr->{'descr_long'}},
4051                                         esc_html($pr->{'descr'})) . "</td>\n" .
4052                       "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4053                 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4054                       (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4055                       "<td class=\"link\">" .
4056                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
4057                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4058                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4059                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4060                       ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4061                       "</td>\n" .
4062                       "</tr>\n";
4063         }
4064         if (defined $extra) {
4065                 print "<tr>\n";
4066                 if ($check_forks) {
4067                         print "<td></td>\n";
4068                 }
4069                 print "<td colspan=\"5\">$extra</td>\n" .
4070                       "</tr>\n";
4071         }
4072         print "</table>\n";
4073 }
4074
4075 sub git_shortlog_body {
4076         # uses global variable $project
4077         my ($commitlist, $from, $to, $refs, $extra) = @_;
4078
4079         $from = 0 unless defined $from;
4080         $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4081
4082         print "<table class=\"shortlog\">\n";
4083         my $alternate = 1;
4084         for (my $i = $from; $i <= $to; $i++) {
4085                 my %co = %{$commitlist->[$i]};
4086                 my $commit = $co{'id'};
4087                 my $ref = format_ref_marker($refs, $commit);
4088                 if ($alternate) {
4089                         print "<tr class=\"dark\">\n";
4090                 } else {
4091                         print "<tr class=\"light\">\n";
4092                 }
4093                 $alternate ^= 1;
4094                 my $author = chop_and_escape_str($co{'author_name'}, 10);
4095                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4096                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4097                       "<td><i>" . $author . "</i></td>\n" .
4098                       "<td>";
4099                 print format_subject_html($co{'title'}, $co{'title_short'},
4100                                           href(action=>"commit", hash=>$commit), $ref);
4101                 print "</td>\n" .
4102                       "<td class=\"link\">" .
4103                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4104                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4105                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4106                 my $snapshot_links = format_snapshot_links($commit);
4107                 if (defined $snapshot_links) {
4108                         print " | " . $snapshot_links;
4109                 }
4110                 print "</td>\n" .
4111                       "</tr>\n";
4112         }
4113         if (defined $extra) {
4114                 print "<tr>\n" .
4115                       "<td colspan=\"4\">$extra</td>\n" .
4116                       "</tr>\n";
4117         }
4118         print "</table>\n";
4119 }
4120
4121 sub git_history_body {
4122         # Warning: assumes constant type (blob or tree) during history
4123         my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
4124
4125         $from = 0 unless defined $from;
4126         $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4127
4128         print "<table class=\"history\">\n";
4129         my $alternate = 1;
4130         for (my $i = $from; $i <= $to; $i++) {
4131                 my %co = %{$commitlist->[$i]};
4132                 if (!%co) {
4133                         next;
4134                 }
4135                 my $commit = $co{'id'};
4136
4137                 my $ref = format_ref_marker($refs, $commit);
4138
4139                 if ($alternate) {
4140                         print "<tr class=\"dark\">\n";
4141                 } else {
4142                         print "<tr class=\"light\">\n";
4143                 }
4144                 $alternate ^= 1;
4145         # shortlog uses      chop_str($co{'author_name'}, 10)
4146                 my $author = chop_and_escape_str($co{'author_name'}, 15, 3);
4147                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4148                       "<td><i>" . $author . "</i></td>\n" .
4149                       "<td>";
4150                 # originally git_history used chop_str($co{'title'}, 50)
4151                 print format_subject_html($co{'title'}, $co{'title_short'},
4152                                           href(action=>"commit", hash=>$commit), $ref);
4153                 print "</td>\n" .
4154                       "<td class=\"link\">" .
4155                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4156                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4157
4158                 if ($ftype eq 'blob') {
4159                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
4160                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
4161                         if (defined $blob_current && defined $blob_parent &&
4162                                         $blob_current ne $blob_parent) {
4163                                 print " | " .
4164                                         $cgi->a({-href => href(action=>"blobdiff",
4165                                                                hash=>$blob_current, hash_parent=>$blob_parent,
4166                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
4167                                                                file_name=>$file_name)},
4168                                                 "diff to current");
4169                         }
4170                 }
4171                 print "</td>\n" .
4172                       "</tr>\n";
4173         }
4174         if (defined $extra) {
4175                 print "<tr>\n" .
4176                       "<td colspan=\"4\">$extra</td>\n" .
4177                       "</tr>\n";
4178         }
4179         print "</table>\n";
4180 }
4181
4182 sub git_tags_body {
4183         # uses global variable $project
4184         my ($taglist, $from, $to, $extra) = @_;
4185         $from = 0 unless defined $from;
4186         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4187
4188         print "<table class=\"tags\">\n";
4189         my $alternate = 1;
4190         for (my $i = $from; $i <= $to; $i++) {
4191                 my $entry = $taglist->[$i];
4192                 my %tag = %$entry;
4193                 my $comment = $tag{'subject'};
4194                 my $comment_short;
4195                 if (defined $comment) {
4196                         $comment_short = chop_str($comment, 30, 5);
4197                 }
4198                 if ($alternate) {
4199                         print "<tr class=\"dark\">\n";
4200                 } else {
4201                         print "<tr class=\"light\">\n";
4202                 }
4203                 $alternate ^= 1;
4204                 if (defined $tag{'age'}) {
4205                         print "<td><i>$tag{'age'}</i></td>\n";
4206                 } else {
4207                         print "<td></td>\n";
4208                 }
4209                 print "<td>" .
4210                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4211                                -class => "list name"}, esc_html($tag{'name'})) .
4212                       "</td>\n" .
4213                       "<td>";
4214                 if (defined $comment) {
4215                         print format_subject_html($comment, $comment_short,
4216                                                   href(action=>"tag", hash=>$tag{'id'}));
4217                 }
4218                 print "</td>\n" .
4219                       "<td class=\"selflink\">";
4220                 if ($tag{'type'} eq "tag") {
4221                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4222                 } else {
4223                         print "&nbsp;";
4224                 }
4225                 print "</td>\n" .
4226                       "<td class=\"link\">" . " | " .
4227                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4228                 if ($tag{'reftype'} eq "commit") {
4229                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4230                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4231                 } elsif ($tag{'reftype'} eq "blob") {
4232                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4233                 }
4234                 print "</td>\n" .
4235                       "</tr>";
4236         }
4237         if (defined $extra) {
4238                 print "<tr>\n" .
4239                       "<td colspan=\"5\">$extra</td>\n" .
4240                       "</tr>\n";
4241         }
4242         print "</table>\n";
4243 }
4244
4245 sub git_heads_body {
4246         # uses global variable $project
4247         my ($headlist, $head, $from, $to, $extra) = @_;
4248         $from = 0 unless defined $from;
4249         $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4250
4251         print "<table class=\"heads\">\n";
4252         my $alternate = 1;
4253         for (my $i = $from; $i <= $to; $i++) {
4254                 my $entry = $headlist->[$i];
4255                 my %ref = %$entry;
4256                 my $curr = $ref{'id'} eq $head;
4257                 if ($alternate) {
4258                         print "<tr class=\"dark\">\n";
4259                 } else {
4260                         print "<tr class=\"light\">\n";
4261                 }
4262                 $alternate ^= 1;
4263                 print "<td><i>$ref{'age'}</i></td>\n" .
4264                       ($curr ? "<td class=\"current_head\">" : "<td>") .
4265                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4266                                -class => "list name"},esc_html($ref{'name'})) .
4267                       "</td>\n" .
4268                       "<td class=\"link\">" .
4269                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4270                       $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4271                       $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4272                       "</td>\n" .
4273                       "</tr>";
4274         }
4275         if (defined $extra) {
4276                 print "<tr>\n" .
4277                       "<td colspan=\"3\">$extra</td>\n" .
4278                       "</tr>\n";
4279         }
4280         print "</table>\n";
4281 }
4282
4283 sub git_search_grep_body {
4284         my ($commitlist, $from, $to, $extra) = @_;
4285         $from = 0 unless defined $from;
4286         $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4287
4288         print "<table class=\"commit_search\">\n";
4289         my $alternate = 1;
4290         for (my $i = $from; $i <= $to; $i++) {
4291                 my %co = %{$commitlist->[$i]};
4292                 if (!%co) {
4293                         next;
4294                 }
4295                 my $commit = $co{'id'};
4296                 if ($alternate) {
4297                         print "<tr class=\"dark\">\n";
4298                 } else {
4299                         print "<tr class=\"light\">\n";
4300                 }
4301                 $alternate ^= 1;
4302                 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
4303                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4304                       "<td><i>" . $author . "</i></td>\n" .
4305                       "<td>" .
4306                       $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4307                                -class => "list subject"},
4308                               chop_and_escape_str($co{'title'}, 50) . "<br/>");
4309                 my $comment = $co{'comment'};
4310                 foreach my $line (@$comment) {
4311                         if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4312                                 my ($lead, $match, $trail) = ($1, $2, $3);
4313                                 $match = chop_str($match, 70, 5, 'center');
4314                                 my $contextlen = int((80 - length($match))/2);
4315                                 $contextlen = 30 if ($contextlen > 30);
4316                                 $lead  = chop_str($lead,  $contextlen, 10, 'left');
4317                                 $trail = chop_str($trail, $contextlen, 10, 'right');
4318
4319                                 $lead  = esc_html($lead);
4320                                 $match = esc_html($match);
4321                                 $trail = esc_html($trail);
4322
4323                                 print "$lead<span class=\"match\">$match</span>$trail<br />";
4324                         }
4325                 }
4326                 print "</td>\n" .
4327                       "<td class=\"link\">" .
4328                       $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4329                       " | " .
4330                       $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4331                       " | " .
4332                       $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4333                 print "</td>\n" .
4334                       "</tr>\n";
4335         }
4336         if (defined $extra) {
4337                 print "<tr>\n" .
4338                       "<td colspan=\"3\">$extra</td>\n" .
4339                       "</tr>\n";
4340         }
4341         print "</table>\n";
4342 }
4343
4344 ## ======================================================================
4345 ## ======================================================================
4346 ## actions
4347
4348 sub git_project_list {
4349         my $order = $input_params{'order'};
4350         if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4351                 die_error(400, "Unknown order parameter");
4352         }
4353
4354         my @list = git_get_projects_list();
4355         if (!@list) {
4356                 die_error(404, "No projects found");
4357         }
4358
4359         git_header_html();
4360         if (-f $home_text) {
4361                 print "<div class=\"index_include\">\n";
4362                 insert_file($home_text);
4363                 print "</div>\n";
4364         }
4365         print $cgi->startform(-method => "get") .
4366               "<p class=\"projsearch\">Search:\n" .
4367               $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
4368               "</p>" .
4369               $cgi->end_form() . "\n";
4370         git_project_list_body(\@list, $order);
4371         git_footer_html();
4372 }
4373
4374 sub git_forks {
4375         my $order = $input_params{'order'};
4376         if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4377                 die_error(400, "Unknown order parameter");
4378         }
4379
4380         my @list = git_get_projects_list($project);
4381         if (!@list) {
4382                 die_error(404, "No forks found");
4383         }
4384
4385         git_header_html();
4386         git_print_page_nav('','');
4387         git_print_header_div('summary', "$project forks");
4388         git_project_list_body(\@list, $order);
4389         git_footer_html();
4390 }
4391
4392 sub git_project_index {
4393         my @projects = git_get_projects_list($project);
4394
4395         print $cgi->header(
4396                 -type => 'text/plain',
4397                 -charset => 'utf-8',
4398                 -content_disposition => 'inline; filename="index.aux"');
4399
4400         foreach my $pr (@projects) {
4401                 if (!exists $pr->{'owner'}) {
4402                         $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
4403                 }
4404
4405                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
4406                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
4407                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4408                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4409                 $path  =~ s/ /\+/g;
4410                 $owner =~ s/ /\+/g;
4411
4412                 print "$path $owner\n";
4413         }
4414 }
4415
4416 sub git_summary {
4417         my $descr = git_get_project_description($project) || "none";
4418         my %co = parse_commit("HEAD");
4419         my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
4420         my $head = $co{'id'};
4421
4422         my $owner = git_get_project_owner($project);
4423
4424         my $refs = git_get_references();
4425         # These get_*_list functions return one more to allow us to see if
4426         # there are more ...
4427         my @taglist  = git_get_tags_list(16);
4428         my @headlist = git_get_heads_list(16);
4429         my @forklist;
4430         my $check_forks = gitweb_check_feature('forks');
4431
4432         if ($check_forks) {
4433                 @forklist = git_get_projects_list($project);
4434         }
4435
4436         git_header_html();
4437         git_print_page_nav('summary','', $head);
4438
4439         print "<div class=\"title\">&nbsp;</div>\n";
4440         print "<table class=\"projects_list\">\n" .
4441               "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
4442               "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
4443         if (defined $cd{'rfc2822'}) {
4444                 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
4445         }
4446
4447         # use per project git URL list in $projectroot/$project/cloneurl
4448         # or make project git URL from git base URL and project name
4449         my $url_tag = "URL";
4450         my @url_list = git_get_project_url_list($project);
4451         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
4452         foreach my $git_url (@url_list) {
4453                 next unless $git_url;
4454                 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
4455                 $url_tag = "";
4456         }
4457
4458         # Tag cloud
4459         my $show_ctags = gitweb_check_feature('ctags');
4460         if ($show_ctags) {
4461                 my $ctags = git_get_project_ctags($project);
4462                 my $cloud = git_populate_project_tagcloud($ctags);
4463                 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
4464                 print "</td>\n<td>" unless %$ctags;
4465                 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
4466                 print "</td>\n<td>" if %$ctags;
4467                 print git_show_project_tagcloud($cloud, 48);
4468                 print "</td></tr>";
4469         }
4470
4471         print "</table>\n";
4472
4473         if (-s "$projectroot/$project/README.html") {
4474                 print "<div class=\"title\">readme</div>\n" .
4475                       "<div class=\"readme\">\n";
4476                 insert_file("$projectroot/$project/README.html");
4477                 print "\n</div>\n"; # class="readme"
4478         }
4479
4480         # we need to request one more than 16 (0..15) to check if
4481         # those 16 are all
4482         my @commitlist = $head ? parse_commits($head, 17) : ();
4483         if (@commitlist) {
4484                 git_print_header_div('shortlog');
4485                 git_shortlog_body(\@commitlist, 0, 15, $refs,
4486                                   $#commitlist <=  15 ? undef :
4487                                   $cgi->a({-href => href(action=>"shortlog")}, "..."));
4488         }
4489
4490         if (@taglist) {
4491                 git_print_header_div('tags');
4492                 git_tags_body(\@taglist, 0, 15,
4493                               $#taglist <=  15 ? undef :
4494                               $cgi->a({-href => href(action=>"tags")}, "..."));
4495         }
4496
4497         if (@headlist) {
4498                 git_print_header_div('heads');
4499                 git_heads_body(\@headlist, $head, 0, 15,
4500                                $#headlist <= 15 ? undef :
4501                                $cgi->a({-href => href(action=>"heads")}, "..."));
4502         }
4503
4504         if (@forklist) {
4505                 git_print_header_div('forks');
4506                 git_project_list_body(\@forklist, 'age', 0, 15,
4507                                       $#forklist <= 15 ? undef :
4508                                       $cgi->a({-href => href(action=>"forks")}, "..."),
4509                                       'no_header');
4510         }
4511
4512         git_footer_html();
4513 }
4514
4515 sub git_tag {
4516         my $head = git_get_head_hash($project);
4517         git_header_html();
4518         git_print_page_nav('','', $head,undef,$head);
4519         my %tag = parse_tag($hash);
4520
4521         if (! %tag) {
4522                 die_error(404, "Unknown tag object");
4523         }
4524
4525         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
4526         print "<div class=\"title_text\">\n" .
4527               "<table class=\"object_header\">\n" .
4528               "<tr>\n" .
4529               "<td>object</td>\n" .
4530               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4531                                $tag{'object'}) . "</td>\n" .
4532               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4533                                               $tag{'type'}) . "</td>\n" .
4534               "</tr>\n";
4535         if (defined($tag{'author'})) {
4536                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
4537                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
4538                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
4539                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
4540                         "</td></tr>\n";
4541         }
4542         print "</table>\n\n" .
4543               "</div>\n";
4544         print "<div class=\"page_body\">";
4545         my $comment = $tag{'comment'};
4546         foreach my $line (@$comment) {
4547                 chomp $line;
4548                 print esc_html($line, -nbsp=>1) . "<br/>\n";
4549         }
4550         print "</div>\n";
4551         git_footer_html();
4552 }
4553
4554 sub git_blame {
4555         my $fd;
4556         my $ftype;
4557
4558         gitweb_check_feature('blame')
4559             or die_error(403, "Blame view not allowed");
4560
4561         die_error(400, "No file name given") unless $file_name;
4562         $hash_base ||= git_get_head_hash($project);
4563         die_error(404, "Couldn't find base commit") unless ($hash_base);
4564         my %co = parse_commit($hash_base)
4565                 or die_error(404, "Commit not found");
4566         if (!defined $hash) {
4567                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4568                         or die_error(404, "Error looking up file");
4569         }
4570         $ftype = git_get_type($hash);
4571         if ($ftype !~ "blob") {
4572                 die_error(400, "Object is not a blob");
4573         }
4574         open ($fd, "-|", git_cmd(), "blame", '-p', '--',
4575               $file_name, $hash_base)
4576                 or die_error(500, "Open git-blame failed");
4577         git_header_html();
4578         my $formats_nav =
4579                 $cgi->a({-href => href(action=>"blob", -replay=>1)},
4580                         "blob") .
4581                 " | " .
4582                 $cgi->a({-href => href(action=>"history", -replay=>1)},
4583                         "history") .
4584                 " | " .
4585                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
4586                         "HEAD");
4587         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4588         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4589         git_print_page_path($file_name, $ftype, $hash_base);
4590         my @rev_color = (qw(light2 dark2));
4591         my $num_colors = scalar(@rev_color);
4592         my $current_color = 0;
4593         my $last_rev;
4594         print <<HTML;
4595 <div class="page_body">
4596 <table class="blame">
4597 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
4598 HTML
4599         my %metainfo = ();
4600         while (1) {
4601                 $_ = <$fd>;
4602                 last unless defined $_;
4603                 my ($full_rev, $orig_lineno, $lineno, $group_size) =
4604                     /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
4605                 if (!exists $metainfo{$full_rev}) {
4606                         $metainfo{$full_rev} = {};
4607                 }
4608                 my $meta = $metainfo{$full_rev};
4609                 while (<$fd>) {
4610                         last if (s/^\t//);
4611                         if (/^(\S+) (.*)$/) {
4612                                 $meta->{$1} = $2;
4613                         }
4614                 }
4615                 my $data = $_;
4616                 chomp $data;
4617                 my $rev = substr($full_rev, 0, 8);
4618                 my $author = $meta->{'author'};
4619                 my %date = parse_date($meta->{'author-time'},
4620                                       $meta->{'author-tz'});
4621                 my $date = $date{'iso-tz'};
4622                 if ($group_size) {
4623                         $current_color = ++$current_color % $num_colors;
4624                 }
4625                 print "<tr class=\"$rev_color[$current_color]\">\n";
4626                 if ($group_size) {
4627                         print "<td class=\"sha1\"";
4628                         print " title=\"". esc_html($author) . ", $date\"";
4629                         print " rowspan=\"$group_size\"" if ($group_size > 1);
4630                         print ">";
4631                         print $cgi->a({-href => href(action=>"commit",
4632                                                      hash=>$full_rev,
4633                                                      file_name=>$file_name)},
4634                                       esc_html($rev));
4635                         print "</td>\n";
4636                 }
4637                 open (my $dd, "-|", git_cmd(), "rev-parse", "$full_rev^")
4638                         or die_error(500, "Open git-rev-parse failed");
4639                 my $parent_commit = <$dd>;
4640                 close $dd;
4641                 chomp($parent_commit);
4642                 my $blamed = href(action => 'blame',
4643                                   file_name => $meta->{'filename'},
4644                                   hash_base => $parent_commit);
4645                 print "<td class=\"linenr\">";
4646                 print $cgi->a({ -href => "$blamed#l$orig_lineno",
4647                                 -id => "l$lineno",
4648                                 -class => "linenr" },
4649                               esc_html($lineno));
4650                 print "</td>";
4651                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
4652                 print "</tr>\n";
4653         }
4654         print "</table>\n";
4655         print "</div>";
4656         close $fd
4657                 or print "Reading blob failed\n";
4658         git_footer_html();
4659 }
4660
4661 sub git_tags {
4662         my $head = git_get_head_hash($project);
4663         git_header_html();
4664         git_print_page_nav('','', $head,undef,$head);
4665         git_print_header_div('summary', $project);
4666
4667         my @tagslist = git_get_tags_list();
4668         if (@tagslist) {
4669                 git_tags_body(\@tagslist);
4670         }
4671         git_footer_html();
4672 }
4673
4674 sub git_heads {
4675         my $head = git_get_head_hash($project);
4676         git_header_html();
4677         git_print_page_nav('','', $head,undef,$head);
4678         git_print_header_div('summary', $project);
4679
4680         my @headslist = git_get_heads_list();
4681         if (@headslist) {
4682                 git_heads_body(\@headslist, $head);
4683         }
4684         git_footer_html();
4685 }
4686
4687 sub git_blob_plain {
4688         my $type = shift;
4689         my $expires;
4690
4691         if (!defined $hash) {
4692                 if (defined $file_name) {
4693                         my $base = $hash_base || git_get_head_hash($project);
4694                         $hash = git_get_hash_by_path($base, $file_name, "blob")
4695                                 or die_error(404, "Cannot find file");
4696                 } else {
4697                         die_error(400, "No file name defined");
4698                 }
4699         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4700                 # blobs defined by non-textual hash id's can be cached
4701                 $expires = "+1d";
4702         }
4703
4704         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4705                 or die_error(500, "Open git-cat-file blob '$hash' failed");
4706
4707         # content-type (can include charset)
4708         $type = blob_contenttype($fd, $file_name, $type);
4709
4710         # "save as" filename, even when no $file_name is given
4711         my $save_as = "$hash";
4712         if (defined $file_name) {
4713                 $save_as = $file_name;
4714         } elsif ($type =~ m/^text\//) {
4715                 $save_as .= '.txt';
4716         }
4717
4718         print $cgi->header(
4719                 -type => $type,
4720                 -expires => $expires,
4721                 -content_disposition => 'inline; filename="' . $save_as . '"');
4722         undef $/;
4723         binmode STDOUT, ':raw';
4724         print <$fd>;
4725         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4726         $/ = "\n";
4727         close $fd;
4728 }
4729
4730 sub git_blob {
4731         my $expires;
4732
4733         if (!defined $hash) {
4734                 if (defined $file_name) {
4735                         my $base = $hash_base || git_get_head_hash($project);
4736                         $hash = git_get_hash_by_path($base, $file_name, "blob")
4737                                 or die_error(404, "Cannot find file");
4738                 } else {
4739                         die_error(400, "No file name defined");
4740                 }
4741         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4742                 # blobs defined by non-textual hash id's can be cached
4743                 $expires = "+1d";
4744         }
4745
4746         my $have_blame = gitweb_check_feature('blame');
4747         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4748                 or die_error(500, "Couldn't cat $file_name, $hash");
4749         my $mimetype = blob_mimetype($fd, $file_name);
4750         if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
4751                 close $fd;
4752                 return git_blob_plain($mimetype);
4753         }
4754         # we can have blame only for text/* mimetype
4755         $have_blame &&= ($mimetype =~ m!^text/!);
4756
4757         git_header_html(undef, $expires);
4758         my $formats_nav = '';
4759         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4760                 if (defined $file_name) {
4761                         if ($have_blame) {
4762                                 $formats_nav .=
4763                                         $cgi->a({-href => href(action=>"blame", -replay=>1)},
4764                                                 "blame") .
4765                                         " | ";
4766                         }
4767                         $formats_nav .=
4768                                 $cgi->a({-href => href(action=>"history", -replay=>1)},
4769                                         "history") .
4770                                 " | " .
4771                                 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
4772                                         "raw") .
4773                                 " | " .
4774                                 $cgi->a({-href => href(action=>"blob",
4775                                                        hash_base=>"HEAD", file_name=>$file_name)},
4776                                         "HEAD");
4777                 } else {
4778                         $formats_nav .=
4779                                 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
4780                                         "raw");
4781                 }
4782                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4783                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4784         } else {
4785                 print "<div class=\"page_nav\">\n" .
4786                       "<br/><br/></div>\n" .
4787                       "<div class=\"title\">$hash</div>\n";
4788         }
4789         git_print_page_path($file_name, "blob", $hash_base);
4790         print "<div class=\"page_body\">\n";
4791         if ($mimetype =~ m!^image/!) {
4792                 print qq!<img type="$mimetype"!;
4793                 if ($file_name) {
4794                         print qq! alt="$file_name" title="$file_name"!;
4795                 }
4796                 print qq! src="! .
4797                       href(action=>"blob_plain", hash=>$hash,
4798                            hash_base=>$hash_base, file_name=>$file_name) .
4799                       qq!" />\n!;
4800         } else {
4801                 my $nr;
4802                 while (my $line = <$fd>) {
4803                         chomp $line;
4804                         $nr++;
4805                         $line = untabify($line);
4806                         printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
4807                                $nr, $nr, $nr, esc_html($line, -nbsp=>1);
4808                 }
4809         }
4810         close $fd
4811                 or print "Reading blob failed.\n";
4812         print "</div>";
4813         git_footer_html();
4814 }
4815
4816 sub git_tree {
4817         if (!defined $hash_base) {
4818                 $hash_base = "HEAD";
4819         }
4820         if (!defined $hash) {
4821                 if (defined $file_name) {
4822                         $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
4823                 } else {
4824                         $hash = $hash_base;
4825                 }
4826         }
4827         die_error(404, "No such tree") unless defined($hash);
4828         $/ = "\0";
4829         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
4830                 or die_error(500, "Open git-ls-tree failed");
4831         my @entries = map { chomp; $_ } <$fd>;
4832         close $fd or die_error(404, "Reading tree failed");
4833         $/ = "\n";
4834
4835         my $refs = git_get_references();
4836         my $ref = format_ref_marker($refs, $hash_base);
4837         git_header_html();
4838         my $basedir = '';
4839         my $have_blame = gitweb_check_feature('blame');
4840         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4841                 my @views_nav = ();
4842                 if (defined $file_name) {
4843                         push @views_nav,
4844                                 $cgi->a({-href => href(action=>"history", -replay=>1)},
4845                                         "history"),
4846                                 $cgi->a({-href => href(action=>"tree",
4847                                                        hash_base=>"HEAD", file_name=>$file_name)},
4848                                         "HEAD"),
4849                 }
4850                 my $snapshot_links = format_snapshot_links($hash);
4851                 if (defined $snapshot_links) {
4852                         # FIXME: Should be available when we have no hash base as well.
4853                         push @views_nav, $snapshot_links;
4854                 }
4855                 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
4856                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
4857         } else {
4858                 undef $hash_base;
4859                 print "<div class=\"page_nav\">\n";
4860                 print "<br/><br/></div>\n";
4861                 print "<div class=\"title\">$hash</div>\n";
4862         }
4863         if (defined $file_name) {
4864                 $basedir = $file_name;
4865                 if ($basedir ne '' && substr($basedir, -1) ne '/') {
4866                         $basedir .= '/';
4867                 }
4868                 git_print_page_path($file_name, 'tree', $hash_base);
4869         }
4870         print "<div class=\"page_body\">\n";
4871         print "<table class=\"tree\">\n";
4872         my $alternate = 1;
4873         # '..' (top directory) link if possible
4874         if (defined $hash_base &&
4875             defined $file_name && $file_name =~ m![^/]+$!) {
4876                 if ($alternate) {
4877                         print "<tr class=\"dark\">\n";
4878                 } else {
4879                         print "<tr class=\"light\">\n";
4880                 }
4881                 $alternate ^= 1;
4882
4883                 my $up = $file_name;
4884                 $up =~ s!/?[^/]+$!!;
4885                 undef $up unless $up;
4886                 # based on git_print_tree_entry
4887                 print '<td class="mode">' . mode_str('040000') . "</td>\n";
4888                 print '<td class="list">';
4889                 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
4890                                              file_name=>$up)},
4891                               "..");
4892                 print "</td>\n";
4893                 print "<td class=\"link\"></td>\n";
4894
4895                 print "</tr>\n";
4896         }
4897         foreach my $line (@entries) {
4898                 my %t = parse_ls_tree_line($line, -z => 1);
4899
4900                 if ($alternate) {
4901                         print "<tr class=\"dark\">\n";
4902                 } else {
4903                         print "<tr class=\"light\">\n";
4904                 }
4905                 $alternate ^= 1;
4906
4907                 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
4908
4909                 print "</tr>\n";
4910         }
4911         print "</table>\n" .
4912               "</div>";
4913         git_footer_html();
4914 }
4915
4916 sub git_snapshot {
4917         my $format = $input_params{'snapshot_format'};
4918         if (!@snapshot_fmts) {
4919                 die_error(403, "Snapshots not allowed");
4920         }
4921         # default to first supported snapshot format
4922         $format ||= $snapshot_fmts[0];
4923         if ($format !~ m/^[a-z0-9]+$/) {
4924                 die_error(400, "Invalid snapshot format parameter");
4925         } elsif (!exists($known_snapshot_formats{$format})) {
4926                 die_error(400, "Unknown snapshot format");
4927         } elsif (!grep($_ eq $format, @snapshot_fmts)) {
4928                 die_error(403, "Unsupported snapshot format");
4929         }
4930
4931         if (!defined $hash) {
4932                 $hash = git_get_head_hash($project);
4933         }
4934
4935         my $name = $project;
4936         $name =~ s,([^/])/*\.git$,$1,;
4937         $name = basename($name);
4938         my $filename = to_utf8($name);
4939         $name =~ s/\047/\047\\\047\047/g;
4940         my $cmd;
4941         $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
4942         $cmd = quote_command(
4943                 git_cmd(), 'archive',
4944                 "--format=$known_snapshot_formats{$format}{'format'}",
4945                 "--prefix=$name/", $hash);
4946         if (exists $known_snapshot_formats{$format}{'compressor'}) {
4947                 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
4948         }
4949
4950         print $cgi->header(
4951                 -type => $known_snapshot_formats{$format}{'type'},
4952                 -content_disposition => 'inline; filename="' . "$filename" . '"',
4953                 -status => '200 OK');
4954
4955         open my $fd, "-|", $cmd
4956                 or die_error(500, "Execute git-archive failed");
4957         binmode STDOUT, ':raw';
4958         print <$fd>;
4959         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4960         close $fd;
4961 }
4962
4963 sub git_log {
4964         my $head = git_get_head_hash($project);
4965         if (!defined $hash) {
4966                 $hash = $head;
4967         }
4968         if (!defined $page) {
4969                 $page = 0;
4970         }
4971         my $refs = git_get_references();
4972
4973         my @commitlist = parse_commits($hash, 101, (100 * $page));
4974
4975         my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#commitlist >= 100);
4976
4977         git_header_html();
4978         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
4979
4980         if (!@commitlist) {
4981                 my %co = parse_commit($hash);
4982
4983                 git_print_header_div('summary', $project);
4984                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
4985         }
4986         my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
4987         for (my $i = 0; $i <= $to; $i++) {
4988                 my %co = %{$commitlist[$i]};
4989                 next if !%co;
4990                 my $commit = $co{'id'};
4991                 my $ref = format_ref_marker($refs, $commit);
4992                 my %ad = parse_date($co{'author_epoch'});
4993                 git_print_header_div('commit',
4994                                "<span class=\"age\">$co{'age_string'}</span>" .
4995                                esc_html($co{'title'}) . $ref,
4996                                $commit);
4997                 print "<div class=\"title_text\">\n" .
4998                       "<div class=\"log_link\">\n" .
4999                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5000                       " | " .
5001                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5002                       " | " .
5003                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5004                       "<br/>\n" .
5005                       "</div>\n" .
5006                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
5007                       "</div>\n";
5008
5009                 print "<div class=\"log_body\">\n";
5010                 git_print_log($co{'comment'}, -final_empty_line=> 1);
5011                 print "</div>\n";
5012         }
5013         if ($#commitlist >= 100) {
5014                 print "<div class=\"page_nav\">\n";
5015                 print $cgi->a({-href => href(-replay=>1, page=>$page+1),
5016                                -accesskey => "n", -title => "Alt-n"}, "next");
5017                 print "</div>\n";
5018         }
5019         git_footer_html();
5020 }
5021
5022 sub git_commit {
5023         $hash ||= $hash_base || "HEAD";
5024         my %co = parse_commit($hash)
5025             or die_error(404, "Unknown commit object");
5026         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5027         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
5028
5029         my $parent  = $co{'parent'};
5030         my $parents = $co{'parents'}; # listref
5031
5032         # we need to prepare $formats_nav before any parameter munging
5033         my $formats_nav;
5034         if (!defined $parent) {
5035                 # --root commitdiff
5036                 $formats_nav .= '(initial)';
5037         } elsif (@$parents == 1) {
5038                 # single parent commit
5039                 $formats_nav .=
5040                         '(parent: ' .
5041                         $cgi->a({-href => href(action=>"commit",
5042                                                hash=>$parent)},
5043                                 esc_html(substr($parent, 0, 7))) .
5044                         ')';
5045         } else {
5046                 # merge commit
5047                 $formats_nav .=
5048                         '(merge: ' .
5049                         join(' ', map {
5050                                 $cgi->a({-href => href(action=>"commit",
5051                                                        hash=>$_)},
5052                                         esc_html(substr($_, 0, 7)));
5053                         } @$parents ) .
5054                         ')';
5055         }
5056
5057         if (!defined $parent) {
5058                 $parent = "--root";
5059         }
5060         my @difftree;
5061         open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
5062                 @diff_opts,
5063                 (@$parents <= 1 ? $parent : '-c'),
5064                 $hash, "--"
5065                 or die_error(500, "Open git-diff-tree failed");
5066         @difftree = map { chomp; $_ } <$fd>;
5067         close $fd or die_error(404, "Reading git-diff-tree failed");
5068
5069         # non-textual hash id's can be cached
5070         my $expires;
5071         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5072                 $expires = "+1d";
5073         }
5074         my $refs = git_get_references();
5075         my $ref = format_ref_marker($refs, $co{'id'});
5076
5077         git_header_html(undef, $expires);
5078         git_print_page_nav('commit', '',
5079                            $hash, $co{'tree'}, $hash,
5080                            $formats_nav);
5081
5082         if (defined $co{'parent'}) {
5083                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
5084         } else {
5085                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
5086         }
5087         print "<div class=\"title_text\">\n" .
5088               "<table class=\"object_header\">\n";
5089         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
5090               "<tr>" .
5091               "<td></td><td> $ad{'rfc2822'}";
5092         if ($ad{'hour_local'} < 6) {
5093                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
5094                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
5095         } else {
5096                 printf(" (%02d:%02d %s)",
5097                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
5098         }
5099         print "</td>" .
5100               "</tr>\n";
5101         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
5102         print "<tr><td></td><td> $cd{'rfc2822'}" .
5103               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
5104               "</td></tr>\n";
5105         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
5106         print "<tr>" .
5107               "<td>tree</td>" .
5108               "<td class=\"sha1\">" .
5109               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
5110                        class => "list"}, $co{'tree'}) .
5111               "</td>" .
5112               "<td class=\"link\">" .
5113               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
5114                       "tree");
5115         my $snapshot_links = format_snapshot_links($hash);
5116         if (defined $snapshot_links) {
5117                 print " | " . $snapshot_links;
5118         }
5119         print "</td>" .
5120               "</tr>\n";
5121
5122         foreach my $par (@$parents) {
5123                 print "<tr>" .
5124                       "<td>parent</td>" .
5125                       "<td class=\"sha1\">" .
5126                       $cgi->a({-href => href(action=>"commit", hash=>$par),
5127                                class => "list"}, $par) .
5128                       "</td>" .
5129                       "<td class=\"link\">" .
5130                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5131                       " | " .
5132                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5133                       "</td>" .
5134                       "</tr>\n";
5135         }
5136         print "</table>".
5137               "</div>\n";
5138
5139         print "<div class=\"page_body\">\n";
5140         git_print_log($co{'comment'});
5141         print "</div>\n";
5142
5143         git_difftree_body(\@difftree, $hash, @$parents);
5144
5145         git_footer_html();
5146 }
5147
5148 sub git_object {
5149         # object is defined by:
5150         # - hash or hash_base alone
5151         # - hash_base and file_name
5152         my $type;
5153
5154         # - hash or hash_base alone
5155         if ($hash || ($hash_base && !defined $file_name)) {
5156                 my $object_id = $hash || $hash_base;
5157
5158                 open my $fd, "-|", quote_command(
5159                         git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
5160                         or die_error(404, "Object does not exist");
5161                 $type = <$fd>;
5162                 chomp $type;
5163                 close $fd
5164                         or die_error(404, "Object does not exist");
5165
5166         # - hash_base and file_name
5167         } elsif ($hash_base && defined $file_name) {
5168                 $file_name =~ s,/+$,,;
5169
5170                 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
5171                         or die_error(404, "Base object does not exist");
5172
5173                 # here errors should not hapen
5174                 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
5175                         or die_error(500, "Open git-ls-tree failed");
5176                 my $line = <$fd>;
5177                 close $fd;
5178
5179                 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
5180                 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
5181                         die_error(404, "File or directory for given base does not exist");
5182                 }
5183                 $type = $2;
5184                 $hash = $3;
5185         } else {
5186                 die_error(400, "Not enough information to find object");
5187         }
5188
5189         print $cgi->redirect(-uri => href(action=>$type, -full=>1,
5190                                           hash=>$hash, hash_base=>$hash_base,
5191                                           file_name=>$file_name),
5192                              -status => '302 Found');
5193 }
5194
5195 sub git_blobdiff {
5196         my $format = shift || 'html';
5197
5198         my $fd;
5199         my @difftree;
5200         my %diffinfo;
5201         my $expires;
5202
5203         # preparing $fd and %diffinfo for git_patchset_body
5204         # new style URI
5205         if (defined $hash_base && defined $hash_parent_base) {
5206                 if (defined $file_name) {
5207                         # read raw output
5208                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5209                                 $hash_parent_base, $hash_base,
5210                                 "--", (defined $file_parent ? $file_parent : ()), $file_name
5211                                 or die_error(500, "Open git-diff-tree failed");
5212                         @difftree = map { chomp; $_ } <$fd>;
5213                         close $fd
5214                                 or die_error(404, "Reading git-diff-tree failed");
5215                         @difftree
5216                                 or die_error(404, "Blob diff not found");
5217
5218                 } elsif (defined $hash &&
5219                          $hash =~ /[0-9a-fA-F]{40}/) {
5220                         # try to find filename from $hash
5221
5222                         # read filtered raw output
5223                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5224                                 $hash_parent_base, $hash_base, "--"
5225                                 or die_error(500, "Open git-diff-tree failed");
5226                         @difftree =
5227                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
5228                                 # $hash == to_id
5229                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
5230                                 map { chomp; $_ } <$fd>;
5231                         close $fd
5232                                 or die_error(404, "Reading git-diff-tree failed");
5233                         @difftree
5234                                 or die_error(404, "Blob diff not found");
5235
5236                 } else {
5237                         die_error(400, "Missing one of the blob diff parameters");
5238                 }
5239
5240                 if (@difftree > 1) {
5241                         die_error(400, "Ambiguous blob diff specification");
5242                 }
5243
5244                 %diffinfo = parse_difftree_raw_line($difftree[0]);
5245                 $file_parent ||= $diffinfo{'from_file'} || $file_name;
5246                 $file_name   ||= $diffinfo{'to_file'};
5247
5248                 $hash_parent ||= $diffinfo{'from_id'};
5249                 $hash        ||= $diffinfo{'to_id'};
5250
5251                 # non-textual hash id's can be cached
5252                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
5253                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
5254                         $expires = '+1d';
5255                 }
5256
5257                 # open patch output
5258                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5259                         '-p', ($format eq 'html' ? "--full-index" : ()),
5260                         $hash_parent_base, $hash_base,
5261                         "--", (defined $file_parent ? $file_parent : ()), $file_name
5262                         or die_error(500, "Open git-diff-tree failed");
5263         }
5264
5265         # old/legacy style URI
5266         if (!%diffinfo && # if new style URI failed
5267             defined $hash && defined $hash_parent) {
5268                 # fake git-diff-tree raw output
5269                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
5270                 $diffinfo{'from_id'} = $hash_parent;
5271                 $diffinfo{'to_id'}   = $hash;
5272                 if (defined $file_name) {
5273                         if (defined $file_parent) {
5274                                 $diffinfo{'status'} = '2';
5275                                 $diffinfo{'from_file'} = $file_parent;
5276                                 $diffinfo{'to_file'}   = $file_name;
5277                         } else { # assume not renamed
5278                                 $diffinfo{'status'} = '1';
5279                                 $diffinfo{'from_file'} = $file_name;
5280                                 $diffinfo{'to_file'}   = $file_name;
5281                         }
5282                 } else { # no filename given
5283                         $diffinfo{'status'} = '2';
5284                         $diffinfo{'from_file'} = $hash_parent;
5285                         $diffinfo{'to_file'}   = $hash;
5286                 }
5287
5288                 # non-textual hash id's can be cached
5289                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
5290                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5291                         $expires = '+1d';
5292                 }
5293
5294                 # open patch output
5295                 open $fd, "-|", git_cmd(), "diff", @diff_opts,
5296                         '-p', ($format eq 'html' ? "--full-index" : ()),
5297                         $hash_parent, $hash, "--"
5298                         or die_error(500, "Open git-diff failed");
5299         } else  {
5300                 die_error(400, "Missing one of the blob diff parameters")
5301                         unless %diffinfo;
5302         }
5303
5304         # header
5305         if ($format eq 'html') {
5306                 my $formats_nav =
5307                         $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
5308                                 "raw");
5309                 git_header_html(undef, $expires);
5310                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5311                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5312                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5313                 } else {
5314                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
5315                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
5316                 }
5317                 if (defined $file_name) {
5318                         git_print_page_path($file_name, "blob", $hash_base);
5319                 } else {
5320                         print "<div class=\"page_path\"></div>\n";
5321                 }
5322
5323         } elsif ($format eq 'plain') {
5324                 print $cgi->header(
5325                         -type => 'text/plain',
5326                         -charset => 'utf-8',
5327                         -expires => $expires,
5328                         -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
5329
5330                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5331
5332         } else {
5333                 die_error(400, "Unknown blobdiff format");
5334         }
5335
5336         # patch
5337         if ($format eq 'html') {
5338                 print "<div class=\"page_body\">\n";
5339
5340                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
5341                 close $fd;
5342
5343                 print "</div>\n"; # class="page_body"
5344                 git_footer_html();
5345
5346         } else {
5347                 while (my $line = <$fd>) {
5348                         $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
5349                         $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
5350
5351                         print $line;
5352
5353                         last if $line =~ m!^\+\+\+!;
5354                 }
5355                 local $/ = undef;
5356                 print <$fd>;
5357                 close $fd;
5358         }
5359 }
5360
5361 sub git_blobdiff_plain {
5362         git_blobdiff('plain');
5363 }
5364
5365 sub git_commitdiff {
5366         my $format = shift || 'html';
5367         $hash ||= $hash_base || "HEAD";
5368         my %co = parse_commit($hash)
5369             or die_error(404, "Unknown commit object");
5370
5371         # choose format for commitdiff for merge
5372         if (! defined $hash_parent && @{$co{'parents'}} > 1) {
5373                 $hash_parent = '--cc';
5374         }
5375         # we need to prepare $formats_nav before almost any parameter munging
5376         my $formats_nav;
5377         if ($format eq 'html') {
5378                 $formats_nav =
5379                         $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
5380                                 "raw");
5381
5382                 if (defined $hash_parent &&
5383                     $hash_parent ne '-c' && $hash_parent ne '--cc') {
5384                         # commitdiff with two commits given
5385                         my $hash_parent_short = $hash_parent;
5386                         if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5387                                 $hash_parent_short = substr($hash_parent, 0, 7);
5388                         }
5389                         $formats_nav .=
5390                                 ' (from';
5391                         for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
5392                                 if ($co{'parents'}[$i] eq $hash_parent) {
5393                                         $formats_nav .= ' parent ' . ($i+1);
5394                                         last;
5395                                 }
5396                         }
5397                         $formats_nav .= ': ' .
5398                                 $cgi->a({-href => href(action=>"commitdiff",
5399                                                        hash=>$hash_parent)},
5400                                         esc_html($hash_parent_short)) .
5401                                 ')';
5402                 } elsif (!$co{'parent'}) {
5403                         # --root commitdiff
5404                         $formats_nav .= ' (initial)';
5405                 } elsif (scalar @{$co{'parents'}} == 1) {
5406                         # single parent commit
5407                         $formats_nav .=
5408                                 ' (parent: ' .
5409                                 $cgi->a({-href => href(action=>"commitdiff",
5410                                                        hash=>$co{'parent'})},
5411                                         esc_html(substr($co{'parent'}, 0, 7))) .
5412                                 ')';
5413                 } else {
5414                         # merge commit
5415                         if ($hash_parent eq '--cc') {
5416                                 $formats_nav .= ' | ' .
5417                                         $cgi->a({-href => href(action=>"commitdiff",
5418                                                                hash=>$hash, hash_parent=>'-c')},
5419                                                 'combined');
5420                         } else { # $hash_parent eq '-c'
5421                                 $formats_nav .= ' | ' .
5422                                         $cgi->a({-href => href(action=>"commitdiff",
5423                                                                hash=>$hash, hash_parent=>'--cc')},
5424                                                 'compact');
5425                         }
5426                         $formats_nav .=
5427                                 ' (merge: ' .
5428                                 join(' ', map {
5429                                         $cgi->a({-href => href(action=>"commitdiff",
5430                                                                hash=>$_)},
5431                                                 esc_html(substr($_, 0, 7)));
5432                                 } @{$co{'parents'}} ) .
5433                                 ')';
5434                 }
5435         }
5436
5437         my $hash_parent_param = $hash_parent;
5438         if (!defined $hash_parent_param) {
5439                 # --cc for multiple parents, --root for parentless
5440                 $hash_parent_param =
5441                         @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
5442         }
5443
5444         # read commitdiff
5445         my $fd;
5446         my @difftree;
5447         if ($format eq 'html') {
5448                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5449                         "--no-commit-id", "--patch-with-raw", "--full-index",
5450                         $hash_parent_param, $hash, "--"
5451                         or die_error(500, "Open git-diff-tree failed");
5452
5453                 while (my $line = <$fd>) {
5454                         chomp $line;
5455                         # empty line ends raw part of diff-tree output
5456                         last unless $line;
5457                         push @difftree, scalar parse_difftree_raw_line($line);
5458                 }
5459
5460         } elsif ($format eq 'plain') {
5461                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5462                         '-p', $hash_parent_param, $hash, "--"
5463                         or die_error(500, "Open git-diff-tree failed");
5464
5465         } else {
5466                 die_error(400, "Unknown commitdiff format");
5467         }
5468
5469         # non-textual hash id's can be cached
5470         my $expires;
5471         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5472                 $expires = "+1d";
5473         }
5474
5475         # write commit message
5476         if ($format eq 'html') {
5477                 my $refs = git_get_references();
5478                 my $ref = format_ref_marker($refs, $co{'id'});
5479
5480                 git_header_html(undef, $expires);
5481                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
5482                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
5483                 git_print_authorship(\%co);
5484                 print "<div class=\"page_body\">\n";
5485                 if (@{$co{'comment'}} > 1) {
5486                         print "<div class=\"log\">\n";
5487                         git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
5488                         print "</div>\n"; # class="log"
5489                 }
5490
5491         } elsif ($format eq 'plain') {
5492                 my $refs = git_get_references("tags");
5493                 my $tagname = git_get_rev_name_tags($hash);
5494                 my $filename = basename($project) . "-$hash.patch";
5495
5496                 print $cgi->header(
5497                         -type => 'text/plain',
5498                         -charset => 'utf-8',
5499                         -expires => $expires,
5500                         -content_disposition => 'inline; filename="' . "$filename" . '"');
5501                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5502                 print "From: " . to_utf8($co{'author'}) . "\n";
5503                 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
5504                 print "Subject: " . to_utf8($co{'title'}) . "\n";
5505
5506                 print "X-Git-Tag: $tagname\n" if $tagname;
5507                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5508
5509                 foreach my $line (@{$co{'comment'}}) {
5510                         print to_utf8($line) . "\n";
5511                 }
5512                 print "---\n\n";
5513         }
5514
5515         # write patch
5516         if ($format eq 'html') {
5517                 my $use_parents = !defined $hash_parent ||
5518                         $hash_parent eq '-c' || $hash_parent eq '--cc';
5519                 git_difftree_body(\@difftree, $hash,
5520                                   $use_parents ? @{$co{'parents'}} : $hash_parent);
5521                 print "<br/>\n";
5522
5523                 git_patchset_body($fd, \@difftree, $hash,
5524                                   $use_parents ? @{$co{'parents'}} : $hash_parent);
5525                 close $fd;
5526                 print "</div>\n"; # class="page_body"
5527                 git_footer_html();
5528
5529         } elsif ($format eq 'plain') {
5530                 local $/ = undef;
5531                 print <$fd>;
5532                 close $fd
5533                         or print "Reading git-diff-tree failed\n";
5534         }
5535 }
5536
5537 sub git_commitdiff_plain {
5538         git_commitdiff('plain');
5539 }
5540
5541 sub git_history {
5542         if (!defined $hash_base) {
5543                 $hash_base = git_get_head_hash($project);
5544         }
5545         if (!defined $page) {
5546                 $page = 0;
5547         }
5548         my $ftype;
5549         my %co = parse_commit($hash_base)
5550             or die_error(404, "Unknown commit object");
5551
5552         my $refs = git_get_references();
5553         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
5554
5555         my @commitlist = parse_commits($hash_base, 101, (100 * $page),
5556                                        $file_name, "--full-history")
5557             or die_error(404, "No such file or directory on given branch");
5558
5559         if (!defined $hash && defined $file_name) {
5560                 # some commits could have deleted file in question,
5561                 # and not have it in tree, but one of them has to have it
5562                 for (my $i = 0; $i <= @commitlist; $i++) {
5563                         $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5564                         last if defined $hash;
5565                 }
5566         }
5567         if (defined $hash) {
5568                 $ftype = git_get_type($hash);
5569         }
5570         if (!defined $ftype) {
5571                 die_error(500, "Unknown type of object");
5572         }
5573
5574         my $paging_nav = '';
5575         if ($page > 0) {
5576                 $paging_nav .=
5577                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5578                                                file_name=>$file_name)},
5579                                 "first");
5580                 $paging_nav .= " &sdot; " .
5581                         $cgi->a({-href => href(-replay=>1, page=>$page-1),
5582                                  -accesskey => "p", -title => "Alt-p"}, "prev");
5583         } else {
5584                 $paging_nav .= "first";
5585                 $paging_nav .= " &sdot; prev";
5586         }
5587         my $next_link = '';
5588         if ($#commitlist >= 100) {
5589                 $next_link =
5590                         $cgi->a({-href => href(-replay=>1, page=>$page+1),
5591                                  -accesskey => "n", -title => "Alt-n"}, "next");
5592                 $paging_nav .= " &sdot; $next_link";
5593         } else {
5594                 $paging_nav .= " &sdot; next";
5595         }
5596
5597         git_header_html();
5598         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
5599         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5600         git_print_page_path($file_name, $ftype, $hash_base);
5601
5602         git_history_body(\@commitlist, 0, 99,
5603                          $refs, $hash_base, $ftype, $next_link);
5604
5605         git_footer_html();
5606 }
5607
5608 sub git_search {
5609         gitweb_check_feature('search') or die_error(403, "Search is disabled");
5610         if (!defined $searchtext) {
5611                 die_error(400, "Text field is empty");
5612         }
5613         if (!defined $hash) {
5614                 $hash = git_get_head_hash($project);
5615         }
5616         my %co = parse_commit($hash);
5617         if (!%co) {
5618                 die_error(404, "Unknown commit object");
5619         }
5620         if (!defined $page) {
5621                 $page = 0;
5622         }
5623
5624         $searchtype ||= 'commit';
5625         if ($searchtype eq 'pickaxe') {
5626                 # pickaxe may take all resources of your box and run for several minutes
5627                 # with every query - so decide by yourself how public you make this feature
5628                 gitweb_check_feature('pickaxe')
5629                     or die_error(403, "Pickaxe is disabled");
5630         }
5631         if ($searchtype eq 'grep') {
5632                 gitweb_check_feature('grep')
5633                     or die_error(403, "Grep is disabled");
5634         }
5635
5636         git_header_html();
5637
5638         if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
5639                 my $greptype;
5640                 if ($searchtype eq 'commit') {
5641                         $greptype = "--grep=";
5642                 } elsif ($searchtype eq 'author') {
5643                         $greptype = "--author=";
5644                 } elsif ($searchtype eq 'committer') {
5645                         $greptype = "--committer=";
5646                 }
5647                 $greptype .= $searchtext;
5648                 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
5649                                                $greptype, '--regexp-ignore-case',
5650                                                $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
5651
5652                 my $paging_nav = '';
5653                 if ($page > 0) {
5654                         $paging_nav .=
5655                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
5656                                                        searchtext=>$searchtext,
5657                                                        searchtype=>$searchtype)},
5658                                         "first");
5659                         $paging_nav .= " &sdot; " .
5660                                 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5661                                          -accesskey => "p", -title => "Alt-p"}, "prev");
5662                 } else {
5663                         $paging_nav .= "first";
5664                         $paging_nav .= " &sdot; prev";
5665                 }
5666                 my $next_link = '';
5667                 if ($#commitlist >= 100) {
5668                         $next_link =
5669                                 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5670                                          -accesskey => "n", -title => "Alt-n"}, "next");
5671                         $paging_nav .= " &sdot; $next_link";
5672                 } else {
5673                         $paging_nav .= " &sdot; next";
5674                 }
5675
5676                 if ($#commitlist >= 100) {
5677                 }
5678
5679                 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
5680                 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5681                 git_search_grep_body(\@commitlist, 0, 99, $next_link);
5682         }
5683
5684         if ($searchtype eq 'pickaxe') {
5685                 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5686                 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5687
5688                 print "<table class=\"pickaxe search\">\n";
5689                 my $alternate = 1;
5690                 $/ = "\n";
5691                 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
5692                         '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
5693                         ($search_use_regexp ? '--pickaxe-regex' : ());
5694                 undef %co;
5695                 my @files;
5696                 while (my $line = <$fd>) {
5697                         chomp $line;
5698                         next unless $line;
5699
5700                         my %set = parse_difftree_raw_line($line);
5701                         if (defined $set{'commit'}) {
5702                                 # finish previous commit
5703                                 if (%co) {
5704                                         print "</td>\n" .
5705                                               "<td class=\"link\">" .
5706                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5707                                               " | " .
5708                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5709                                         print "</td>\n" .
5710                                               "</tr>\n";
5711                                 }
5712
5713                                 if ($alternate) {
5714                                         print "<tr class=\"dark\">\n";
5715                                 } else {
5716                                         print "<tr class=\"light\">\n";
5717                                 }
5718                                 $alternate ^= 1;
5719                                 %co = parse_commit($set{'commit'});
5720                                 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
5721                                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5722                                       "<td><i>$author</i></td>\n" .
5723                                       "<td>" .
5724                                       $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5725                                               -class => "list subject"},
5726                                               chop_and_escape_str($co{'title'}, 50) . "<br/>");
5727                         } elsif (defined $set{'to_id'}) {
5728                                 next if ($set{'to_id'} =~ m/^0{40}$/);
5729
5730                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
5731                                                              hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
5732                                               -class => "list"},
5733                                               "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
5734                                       "<br/>\n";
5735                         }
5736                 }
5737                 close $fd;
5738
5739                 # finish last commit (warning: repetition!)
5740                 if (%co) {
5741                         print "</td>\n" .
5742                               "<td class=\"link\">" .
5743                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5744                               " | " .
5745                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5746                         print "</td>\n" .
5747                               "</tr>\n";
5748                 }
5749
5750                 print "</table>\n";
5751         }
5752
5753         if ($searchtype eq 'grep') {
5754                 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5755                 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5756
5757                 print "<table class=\"grep_search\">\n";
5758                 my $alternate = 1;
5759                 my $matches = 0;
5760                 $/ = "\n";
5761                 open my $fd, "-|", git_cmd(), 'grep', '-n',
5762                         $search_use_regexp ? ('-E', '-i') : '-F',
5763                         $searchtext, $co{'tree'};
5764                 my $lastfile = '';
5765                 while (my $line = <$fd>) {
5766                         chomp $line;
5767                         my ($file, $lno, $ltext, $binary);
5768                         last if ($matches++ > 1000);
5769                         if ($line =~ /^Binary file (.+) matches$/) {
5770                                 $file = $1;
5771                                 $binary = 1;
5772                         } else {
5773                                 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
5774                         }
5775                         if ($file ne $lastfile) {
5776                                 $lastfile and print "</td></tr>\n";
5777                                 if ($alternate++) {
5778                                         print "<tr class=\"dark\">\n";
5779                                 } else {
5780                                         print "<tr class=\"light\">\n";
5781                                 }
5782                                 print "<td class=\"list\">".
5783                                         $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5784                                                                file_name=>"$file"),
5785                                                 -class => "list"}, esc_path($file));
5786                                 print "</td><td>\n";
5787                                 $lastfile = $file;
5788                         }
5789                         if ($binary) {
5790                                 print "<div class=\"binary\">Binary file</div>\n";
5791                         } else {
5792                                 $ltext = untabify($ltext);
5793                                 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
5794                                         $ltext = esc_html($1, -nbsp=>1);
5795                                         $ltext .= '<span class="match">';
5796                                         $ltext .= esc_html($2, -nbsp=>1);
5797                                         $ltext .= '</span>';
5798                                         $ltext .= esc_html($3, -nbsp=>1);
5799                                 } else {
5800                                         $ltext = esc_html($ltext, -nbsp=>1);
5801                                 }
5802                                 print "<div class=\"pre\">" .
5803                                         $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5804                                                                file_name=>"$file").'#l'.$lno,
5805                                                 -class => "linenr"}, sprintf('%4i', $lno))
5806                                         . ' ' .  $ltext . "</div>\n";
5807                         }
5808                 }
5809                 if ($lastfile) {
5810                         print "</td></tr>\n";
5811                         if ($matches > 1000) {
5812                                 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
5813                         }
5814                 } else {
5815                         print "<div class=\"diff nodifferences\">No matches found</div>\n";
5816                 }
5817                 close $fd;
5818
5819                 print "</table>\n";
5820         }
5821         git_footer_html();
5822 }
5823
5824 sub git_search_help {
5825         git_header_html();
5826         git_print_page_nav('','', $hash,$hash,$hash);
5827         print <<EOT;
5828 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
5829 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
5830 the pattern entered is recognized as the POSIX extended
5831 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
5832 insensitive).</p>
5833 <dl>
5834 <dt><b>commit</b></dt>
5835 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
5836 EOT
5837         my $have_grep = gitweb_check_feature('grep');
5838         if ($have_grep) {
5839                 print <<EOT;
5840 <dt><b>grep</b></dt>
5841 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
5842     a different one) are searched for the given pattern. On large trees, this search can take
5843 a while and put some strain on the server, so please use it with some consideration. Note that
5844 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
5845 case-sensitive.</dd>
5846 EOT
5847         }
5848         print <<EOT;
5849 <dt><b>author</b></dt>
5850 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
5851 <dt><b>committer</b></dt>
5852 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
5853 EOT
5854         my $have_pickaxe = gitweb_check_feature('pickaxe');
5855         if ($have_pickaxe) {
5856                 print <<EOT;
5857 <dt><b>pickaxe</b></dt>
5858 <dd>All commits that caused the string to appear or disappear from any file (changes that
5859 added, removed or "modified" the string) will be listed. This search can take a while and
5860 takes a lot of strain on the server, so please use it wisely. Note that since you may be
5861 interested even in changes just changing the case as well, this search is case sensitive.</dd>
5862 EOT
5863         }
5864         print "</dl>\n";
5865         git_footer_html();
5866 }
5867
5868 sub git_shortlog {
5869         my $head = git_get_head_hash($project);
5870         if (!defined $hash) {
5871                 $hash = $head;
5872         }
5873         if (!defined $page) {
5874                 $page = 0;
5875         }
5876         my $refs = git_get_references();
5877
5878         my $commit_hash = $hash;
5879         if (defined $hash_parent) {
5880                 $commit_hash = "$hash_parent..$hash";
5881         }
5882         my @commitlist = parse_commits($commit_hash, 101, (100 * $page));
5883
5884         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
5885         my $next_link = '';
5886         if ($#commitlist >= 100) {
5887                 $next_link =
5888                         $cgi->a({-href => href(-replay=>1, page=>$page+1),
5889                                  -accesskey => "n", -title => "Alt-n"}, "next");
5890         }
5891
5892         git_header_html();
5893         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
5894         git_print_header_div('summary', $project);
5895
5896         git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
5897
5898         git_footer_html();
5899 }
5900
5901 ## ......................................................................
5902 ## feeds (RSS, Atom; OPML)
5903
5904 sub git_feed {
5905         my $format = shift || 'atom';
5906         my $have_blame = gitweb_check_feature('blame');
5907
5908         # Atom: http://www.atomenabled.org/developers/syndication/
5909         # RSS:  http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
5910         if ($format ne 'rss' && $format ne 'atom') {
5911                 die_error(400, "Unknown web feed format");
5912         }
5913
5914         # log/feed of current (HEAD) branch, log of given branch, history of file/directory
5915         my $head = $hash || 'HEAD';
5916         my @commitlist = parse_commits($head, 150, 0, $file_name);
5917
5918         my %latest_commit;
5919         my %latest_date;
5920         my $content_type = "application/$format+xml";
5921         if (defined $cgi->http('HTTP_ACCEPT') &&
5922                  $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
5923                 # browser (feed reader) prefers text/xml
5924                 $content_type = 'text/xml';
5925         }
5926         if (defined($commitlist[0])) {
5927                 %latest_commit = %{$commitlist[0]};
5928                 %latest_date   = parse_date($latest_commit{'author_epoch'});
5929                 print $cgi->header(
5930                         -type => $content_type,
5931                         -charset => 'utf-8',
5932                         -last_modified => $latest_date{'rfc2822'});
5933         } else {
5934                 print $cgi->header(
5935                         -type => $content_type,
5936                         -charset => 'utf-8');
5937         }
5938
5939         # Optimization: skip generating the body if client asks only
5940         # for Last-Modified date.
5941         return if ($cgi->request_method() eq 'HEAD');
5942
5943         # header variables
5944         my $title = "$site_name - $project/$action";
5945         my $feed_type = 'log';
5946         if (defined $hash) {
5947                 $title .= " - '$hash'";
5948                 $feed_type = 'branch log';
5949                 if (defined $file_name) {
5950                         $title .= " :: $file_name";
5951                         $feed_type = 'history';
5952                 }
5953         } elsif (defined $file_name) {
5954                 $title .= " - $file_name";
5955                 $feed_type = 'history';
5956         }
5957         $title .= " $feed_type";
5958         my $descr = git_get_project_description($project);
5959         if (defined $descr) {
5960                 $descr = esc_html($descr);
5961         } else {
5962                 $descr = "$project " .
5963                          ($format eq 'rss' ? 'RSS' : 'Atom') .
5964                          " feed";
5965         }
5966         my $owner = git_get_project_owner($project);
5967         $owner = esc_html($owner);
5968
5969         #header
5970         my $alt_url;
5971         if (defined $file_name) {
5972                 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
5973         } elsif (defined $hash) {
5974                 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
5975         } else {
5976                 $alt_url = href(-full=>1, action=>"summary");
5977         }
5978         print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
5979         if ($format eq 'rss') {
5980                 print <<XML;
5981 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
5982 <channel>
5983 XML
5984                 print "<title>$title</title>\n" .
5985                       "<link>$alt_url</link>\n" .
5986                       "<description>$descr</description>\n" .
5987                       "<language>en</language>\n";
5988         } elsif ($format eq 'atom') {
5989                 print <<XML;
5990 <feed xmlns="http://www.w3.org/2005/Atom">
5991 XML
5992                 print "<title>$title</title>\n" .
5993                       "<subtitle>$descr</subtitle>\n" .
5994                       '<link rel="alternate" type="text/html" href="' .
5995                       $alt_url . '" />' . "\n" .
5996                       '<link rel="self" type="' . $content_type . '" href="' .
5997                       $cgi->self_url() . '" />' . "\n" .
5998                       "<id>" . href(-full=>1) . "</id>\n" .
5999                       # use project owner for feed author
6000                       "<author><name>$owner</name></author>\n";
6001                 if (defined $favicon) {
6002                         print "<icon>" . esc_url($favicon) . "</icon>\n";
6003                 }
6004                 if (defined $logo_url) {
6005                         # not twice as wide as tall: 72 x 27 pixels
6006                         print "<logo>" . esc_url($logo) . "</logo>\n";
6007                 }
6008                 if (! %latest_date) {
6009                         # dummy date to keep the feed valid until commits trickle in:
6010                         print "<updated>1970-01-01T00:00:00Z</updated>\n";
6011                 } else {
6012                         print "<updated>$latest_date{'iso-8601'}</updated>\n";
6013                 }
6014         }
6015
6016         # contents
6017         for (my $i = 0; $i <= $#commitlist; $i++) {
6018                 my %co = %{$commitlist[$i]};
6019                 my $commit = $co{'id'};
6020                 # we read 150, we always show 30 and the ones more recent than 48 hours
6021                 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6022                         last;
6023                 }
6024                 my %cd = parse_date($co{'author_epoch'});
6025
6026                 # get list of changed files
6027                 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6028                         $co{'parent'} || "--root",
6029                         $co{'id'}, "--", (defined $file_name ? $file_name : ())
6030                         or next;
6031                 my @difftree = map { chomp; $_ } <$fd>;
6032                 close $fd
6033                         or next;
6034
6035                 # print element (entry, item)
6036                 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6037                 if ($format eq 'rss') {
6038                         print "<item>\n" .
6039                               "<title>" . esc_html($co{'title'}) . "</title>\n" .
6040                               "<author>" . esc_html($co{'author'}) . "</author>\n" .
6041                               "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6042                               "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6043                               "<link>$co_url</link>\n" .
6044                               "<description>" . esc_html($co{'title'}) . "</description>\n" .
6045                               "<content:encoded>" .
6046                               "<![CDATA[\n";
6047                 } elsif ($format eq 'atom') {
6048                         print "<entry>\n" .
6049                               "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6050                               "<updated>$cd{'iso-8601'}</updated>\n" .
6051                               "<author>\n" .
6052                               "  <name>" . esc_html($co{'author_name'}) . "</name>\n";
6053                         if ($co{'author_email'}) {
6054                                 print "  <email>" . esc_html($co{'author_email'}) . "</email>\n";
6055                         }
6056                         print "</author>\n" .
6057                               # use committer for contributor
6058                               "<contributor>\n" .
6059                               "  <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6060                         if ($co{'committer_email'}) {
6061                                 print "  <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6062                         }
6063                         print "</contributor>\n" .
6064                               "<published>$cd{'iso-8601'}</published>\n" .
6065                               "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6066                               "<id>$co_url</id>\n" .
6067                               "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6068                               "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6069                 }
6070                 my $comment = $co{'comment'};
6071                 print "<pre>\n";
6072                 foreach my $line (@$comment) {
6073                         $line = esc_html($line);
6074                         print "$line\n";
6075                 }
6076                 print "</pre><ul>\n";
6077                 foreach my $difftree_line (@difftree) {
6078                         my %difftree = parse_difftree_raw_line($difftree_line);
6079                         next if !$difftree{'from_id'};
6080
6081                         my $file = $difftree{'file'} || $difftree{'to_file'};
6082
6083                         print "<li>" .
6084                               "[" .
6085                               $cgi->a({-href => href(-full=>1, action=>"blobdiff",
6086                                                      hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
6087                                                      hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
6088                                                      file_name=>$file, file_parent=>$difftree{'from_file'}),
6089                                       -title => "diff"}, 'D');
6090                         if ($have_blame) {
6091                                 print $cgi->a({-href => href(-full=>1, action=>"blame",
6092                                                              file_name=>$file, hash_base=>$commit),
6093                                               -title => "blame"}, 'B');
6094                         }
6095                         # if this is not a feed of a file history
6096                         if (!defined $file_name || $file_name ne $file) {
6097                                 print $cgi->a({-href => href(-full=>1, action=>"history",
6098                                                              file_name=>$file, hash=>$commit),
6099                                               -title => "history"}, 'H');
6100                         }
6101                         $file = esc_path($file);
6102                         print "] ".
6103                               "$file</li>\n";
6104                 }
6105                 if ($format eq 'rss') {
6106                         print "</ul>]]>\n" .
6107                               "</content:encoded>\n" .
6108                               "</item>\n";
6109                 } elsif ($format eq 'atom') {
6110                         print "</ul>\n</div>\n" .
6111                               "</content>\n" .
6112                               "</entry>\n";
6113                 }
6114         }
6115
6116         # end of feed
6117         if ($format eq 'rss') {
6118                 print "</channel>\n</rss>\n";
6119         }       elsif ($format eq 'atom') {
6120                 print "</feed>\n";
6121         }
6122 }
6123
6124 sub git_rss {
6125         git_feed('rss');
6126 }
6127
6128 sub git_atom {
6129         git_feed('atom');
6130 }
6131
6132 sub git_opml {
6133         my @list = git_get_projects_list();
6134
6135         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
6136         print <<XML;
6137 <?xml version="1.0" encoding="utf-8"?>
6138 <opml version="1.0">
6139 <head>
6140   <title>$site_name OPML Export</title>
6141 </head>
6142 <body>
6143 <outline text="git RSS feeds">
6144 XML
6145
6146         foreach my $pr (@list) {
6147                 my %proj = %$pr;
6148                 my $head = git_get_head_hash($proj{'path'});
6149                 if (!defined $head) {
6150                         next;
6151                 }
6152                 $git_dir = "$projectroot/$proj{'path'}";
6153                 my %co = parse_commit($head);
6154                 if (!%co) {
6155                         next;
6156                 }
6157
6158                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
6159                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
6160                 my $html = "$my_url?p=$proj{'path'};a=summary";
6161                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
6162         }
6163         print <<XML;
6164 </outline>
6165 </body>
6166 </opml>
6167 XML
6168 }