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