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