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