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