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