]> gitweb.ps.run Git - ps-gitweb/blob - gitweb/gitweb.perl
gitweb patch to display markdown
[ps-gitweb] / 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 require v5.26;
11 use strict;
12 use warnings;
13 # handle ACL in file access tests
14 use filetest 'access';
15 use CGI qw(:standard :escapeHTML -nosticky);
16 use CGI::Util qw(unescape);
17 use CGI::Carp qw(fatalsToBrowser set_message);
18 use Encode;
19 use Fcntl ':mode';
20 use File::Find qw();
21 use File::Basename qw(basename dirname);
22 use File::Spec;
23 use Time::HiRes qw(gettimeofday tv_interval);
24 use Digest::MD5 qw(md5_hex);
25
26 binmode STDOUT, ':utf8';
27
28 if (!defined($CGI::VERSION) || $CGI::VERSION < 4.08) {
29         eval 'sub CGI::multi_param { CGI::param(@_) }'
30 }
31
32 our $t0 = [ gettimeofday() ];
33 our $number_of_git_cmds = 0;
34
35 BEGIN {
36         CGI->compile() if $ENV{'MOD_PERL'};
37 }
38
39 our $version = "@GIT_VERSION@";
40
41 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
42 sub evaluate_uri {
43         our $cgi;
44
45         our $my_url = $cgi->url();
46         our $my_uri = $cgi->url(-absolute => 1);
47
48         # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
49         # needed and used only for URLs with nonempty PATH_INFO
50         our $base_url = $my_url;
51
52         # When the script is used as DirectoryIndex, the URL does not contain the name
53         # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
54         # have to do it ourselves. We make $path_info global because it's also used
55         # later on.
56         #
57         # Another issue with the script being the DirectoryIndex is that the resulting
58         # $my_url data is not the full script URL: this is good, because we want
59         # generated links to keep implying the script name if it wasn't explicitly
60         # indicated in the URL we're handling, but it means that $my_url cannot be used
61         # as base URL.
62         # Therefore, if we needed to strip PATH_INFO, then we know that we have
63         # to build the base URL ourselves:
64         our $path_info = decode_utf8($ENV{"PATH_INFO"});
65         if ($path_info) {
66                 # $path_info has already been URL-decoded by the web server, but
67                 # $my_url and $my_uri have not. URL-decode them so we can properly
68                 # strip $path_info.
69                 $my_url = unescape($my_url);
70                 $my_uri = unescape($my_uri);
71                 if ($my_url =~ s,\Q$path_info\E$,, &&
72                     $my_uri =~ s,\Q$path_info\E$,, &&
73                     defined $ENV{'SCRIPT_NAME'}) {
74                         $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
75                 }
76         }
77
78         # target of the home link on top of all pages
79         our $home_link = $my_uri || "/";
80 }
81
82 # core git executable to use
83 # this can just be "git" if your webserver has a sensible PATH
84 our $GIT = "@GIT_BINDIR@/git";
85
86 # absolute fs-path which will be prepended to the project path
87 #our $projectroot = "/pub/scm";
88 our $projectroot = "@GITWEB_PROJECTROOT@";
89
90 # fs traversing limit for getting project list
91 # the number is relative to the projectroot
92 our $project_maxdepth = @GITWEB_PROJECT_MAXDEPTH@;
93
94 # string of the home link on top of all pages
95 our $home_link_str = "@GITWEB_HOME_LINK_STR@";
96
97 # extra breadcrumbs preceding the home link
98 our @extra_breadcrumbs = ();
99
100 # name of your site or organization to appear in page titles
101 # replace this with something more descriptive for clearer bookmarks
102 our $site_name = "@GITWEB_SITENAME@"
103                  || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
104
105 # html snippet to include in the <head> section of each page
106 our $site_html_head_string = "@GITWEB_SITE_HTML_HEAD_STRING@";
107 # filename of html text to include at top of each page
108 our $site_header = "@GITWEB_SITE_HEADER@";
109 # html text to include at home page
110 our $home_text = "@GITWEB_HOMETEXT@";
111 # filename of html text to include at bottom of each page
112 our $site_footer = "@GITWEB_SITE_FOOTER@";
113
114 # URI of stylesheets
115 our @stylesheets = ("@GITWEB_CSS@");
116 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
117 our $stylesheet = undef;
118 # URI of GIT logo (72x27 size)
119 our $logo = "@GITWEB_LOGO@";
120 # URI of GIT favicon, assumed to be image/png type
121 our $favicon = "@GITWEB_FAVICON@";
122 # URI of gitweb.js (JavaScript code for gitweb)
123 our $javascript = "@GITWEB_JS@";
124
125 # URI and label (title) of GIT logo link
126 #our $logo_url = "https://www.kernel.org/pub/software/scm/git/docs/";
127 #our $logo_label = "git documentation";
128 our $logo_url = "https://git-scm.com/";
129 our $logo_label = "git homepage";
130
131 # source of projects list
132 our $projects_list = "@GITWEB_LIST@";
133
134 # the width (in characters) of the projects list "Description" column
135 our $projects_list_description_width = 25;
136
137 # group projects by category on the projects list
138 # (enabled if this variable evaluates to true)
139 our $projects_list_group_categories = 0;
140
141 # default category if none specified
142 # (leave the empty string for no category)
143 our $project_list_default_category = "";
144
145 # default order of projects list
146 # valid values are none, project, descr, owner, and age
147 our $default_projects_order = "project";
148
149 # show repository only if this file exists
150 # (only effective if this variable evaluates to true)
151 our $export_ok = "@GITWEB_EXPORT_OK@";
152
153 # don't generate age column on the projects list page
154 our $omit_age_column = 0;
155
156 # don't generate information about owners of repositories
157 our $omit_owner=0;
158
159 # show repository only if this subroutine returns true
160 # when given the path to the project, for example:
161 #    sub { return -e "$_[0]/git-daemon-export-ok"; }
162 our $export_auth_hook = undef;
163
164 # only allow viewing of repositories also shown on the overview page
165 our $strict_export = "@GITWEB_STRICT_EXPORT@";
166
167 # list of git base URLs used for URL to where fetch project from,
168 # i.e. full URL is "$git_base_url/$project"
169 our @git_base_url_list = grep { $_ ne '' } ("@GITWEB_BASE_URL@");
170
171 # default blob_plain mimetype and default charset for text/plain blob
172 our $default_blob_plain_mimetype = 'text/plain';
173 our $default_text_plain_charset  = undef;
174
175 # file to use for guessing MIME types before trying /etc/mime.types
176 # (relative to the current git repository)
177 our $mimetypes_file = undef;
178
179 # assume this charset if line contains non-UTF-8 characters;
180 # it should be valid encoding (see Encoding::Supported(3pm) for list),
181 # for which encoding all byte sequences are valid, for example
182 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
183 # could be even 'utf-8' for the old behavior)
184 our $fallback_encoding = 'latin1';
185
186 # rename detection options for git-diff and git-diff-tree
187 # - default is '-M', with the cost proportional to
188 #   (number of removed files) * (number of new files).
189 # - more costly is '-C' (which implies '-M'), with the cost proportional to
190 #   (number of changed files + number of removed files) * (number of new files)
191 # - even more costly is '-C', '--find-copies-harder' with cost
192 #   (number of files in the original tree) * (number of new files)
193 # - one might want to include '-B' option, e.g. '-B', '-M'
194 our @diff_opts = ('-M'); # taken from git_commit
195
196 # Disables features that would allow repository owners to inject script into
197 # the gitweb domain.
198 our $prevent_xss = 0;
199
200 # Path to the highlight executable to use (must be the one from
201 # http://andre-simon.de/zip/download.php due to assumptions about parameters and output).
202 # Useful if highlight is not installed on your webserver's PATH.
203 # [Default: highlight]
204 our $highlight_bin = "@HIGHLIGHT_BIN@";
205
206 # information about snapshot formats that gitweb is capable of serving
207 our %known_snapshot_formats = (
208         # name => {
209         #       'display' => display name,
210         #       'type' => mime type,
211         #       'suffix' => filename suffix,
212         #       'format' => --format for git-archive,
213         #       'compressor' => [compressor command and arguments]
214         #                       (array reference, optional)
215         #       'disabled' => boolean (optional)}
216         #
217         'tgz' => {
218                 'display' => 'tar.gz',
219                 'type' => 'application/x-gzip',
220                 'suffix' => '.tar.gz',
221                 'format' => 'tar',
222                 'compressor' => ['gzip', '-n']},
223
224         'tbz2' => {
225                 'display' => 'tar.bz2',
226                 'type' => 'application/x-bzip2',
227                 'suffix' => '.tar.bz2',
228                 'format' => 'tar',
229                 'compressor' => ['bzip2']},
230
231         'txz' => {
232                 'display' => 'tar.xz',
233                 'type' => 'application/x-xz',
234                 'suffix' => '.tar.xz',
235                 'format' => 'tar',
236                 'compressor' => ['xz'],
237                 'disabled' => 1},
238
239         'zip' => {
240                 'display' => 'zip',
241                 'type' => 'application/x-zip',
242                 'suffix' => '.zip',
243                 'format' => 'zip'},
244 );
245
246 # Aliases so we understand old gitweb.snapshot values in repository
247 # configuration.
248 our %known_snapshot_format_aliases = (
249         'gzip'  => 'tgz',
250         'bzip2' => 'tbz2',
251         'xz'    => 'txz',
252
253         # backward compatibility: legacy gitweb config support
254         'x-gzip' => undef, 'gz' => undef,
255         'x-bzip2' => undef, 'bz2' => undef,
256         'x-zip' => undef, '' => undef,
257 );
258
259 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
260 # are changed, it may be appropriate to change these values too via
261 # $GITWEB_CONFIG.
262 our %avatar_size = (
263         'default' => 16,
264         'double'  => 32
265 );
266
267 # Used to set the maximum load that we will still respond to gitweb queries.
268 # If server load exceed this value then return "503 server busy" error.
269 # If gitweb cannot determined server load, it is taken to be 0.
270 # Leave it undefined (or set to 'undef') to turn off load checking.
271 our $maxload = 300;
272
273 # configuration for 'highlight' (http://andre-simon.de/doku/highlight/en/highlight.php)
274 # match by basename
275 our %highlight_basename = (
276         #'Program' => 'py',
277         #'Library' => 'py',
278         'SConstruct' => 'py', # SCons equivalent of Makefile
279         'Makefile' => 'make',
280 );
281 # match by extension
282 our %highlight_ext = (
283         # main extensions, defining name of syntax;
284         # see files in /usr/share/highlight/langDefs/ directory
285         (map { $_ => $_ } qw(py rb java css js tex bib xml awk bat ini spec tcl sql)),
286         # alternate extensions, see /etc/highlight/filetypes.conf
287         (map { $_ => 'c'   } qw(c h)),
288         (map { $_ => 'sh'  } qw(sh bash zsh ksh)),
289         (map { $_ => 'cpp' } qw(cpp cxx c++ cc)),
290         (map { $_ => 'php' } qw(php php3 php4 php5 phps)),
291         (map { $_ => 'pl'  } qw(pl perl pm)), # perhaps also 'cgi'
292         (map { $_ => 'make'} qw(make mak mk)),
293         (map { $_ => 'xml' } qw(xml xhtml html htm)),
294 );
295
296 # You define site-wide feature defaults here; override them with
297 # $GITWEB_CONFIG as necessary.
298 our %feature = (
299         # feature => {
300         #       'sub' => feature-sub (subroutine),
301         #       'override' => allow-override (boolean),
302         #       'default' => [ default options...] (array reference)}
303         #
304         # if feature is overridable (it means that allow-override has true value),
305         # then feature-sub will be called with default options as parameters;
306         # return value of feature-sub indicates if to enable specified feature
307         #
308         # if there is no 'sub' key (no feature-sub), then feature cannot be
309         # overridden
310         #
311         # use gitweb_get_feature(<feature>) to retrieve the <feature> value
312         # (an array) or gitweb_check_feature(<feature>) to check if <feature>
313         # is enabled
314
315         # Enable the 'blame' blob view, showing the last commit that modified
316         # each line in the file. This can be very CPU-intensive.
317
318         # To enable system wide have in $GITWEB_CONFIG
319         # $feature{'blame'}{'default'} = [1];
320         # To have project specific config enable override in $GITWEB_CONFIG
321         # $feature{'blame'}{'override'} = 1;
322         # and in project config gitweb.blame = 0|1;
323         'blame' => {
324                 'sub' => sub { feature_bool('blame', @_) },
325                 'override' => 0,
326                 'default' => [0]},
327
328         # Enable the 'snapshot' link, providing a compressed archive of any
329         # tree. This can potentially generate high traffic if you have large
330         # project.
331
332         # Value is a list of formats defined in %known_snapshot_formats that
333         # you wish to offer.
334         # To disable system wide have in $GITWEB_CONFIG
335         # $feature{'snapshot'}{'default'} = [];
336         # To have project specific config enable override in $GITWEB_CONFIG
337         # $feature{'snapshot'}{'override'} = 1;
338         # and in project config, a comma-separated list of formats or "none"
339         # to disable.  Example: gitweb.snapshot = tbz2,zip;
340         'snapshot' => {
341                 'sub' => \&feature_snapshot,
342                 'override' => 0,
343                 'default' => ['tgz']},
344
345         # Enable text search, which will list the commits which match author,
346         # committer or commit text to a given string.  Enabled by default.
347         # Project specific override is not supported.
348         #
349         # Note that this controls all search features, which means that if
350         # it is disabled, then 'grep' and 'pickaxe' search would also be
351         # disabled.
352         'search' => {
353                 'override' => 0,
354                 'default' => [1]},
355
356         # Enable grep search, which will list the files in currently selected
357         # tree containing the given string. Enabled by default. This can be
358         # potentially CPU-intensive, of course.
359         # Note that you need to have 'search' feature enabled too.
360
361         # To enable system wide have in $GITWEB_CONFIG
362         # $feature{'grep'}{'default'} = [1];
363         # To have project specific config enable override in $GITWEB_CONFIG
364         # $feature{'grep'}{'override'} = 1;
365         # and in project config gitweb.grep = 0|1;
366         'grep' => {
367                 'sub' => sub { feature_bool('grep', @_) },
368                 'override' => 0,
369                 'default' => [1]},
370
371         # Enable the pickaxe search, which will list the commits that modified
372         # a given string in a file. This can be practical and quite faster
373         # alternative to 'blame', but still potentially CPU-intensive.
374         # Note that you need to have 'search' feature enabled too.
375
376         # To enable system wide have in $GITWEB_CONFIG
377         # $feature{'pickaxe'}{'default'} = [1];
378         # To have project specific config enable override in $GITWEB_CONFIG
379         # $feature{'pickaxe'}{'override'} = 1;
380         # and in project config gitweb.pickaxe = 0|1;
381         'pickaxe' => {
382                 'sub' => sub { feature_bool('pickaxe', @_) },
383                 'override' => 0,
384                 'default' => [1]},
385
386         # Enable showing size of blobs in a 'tree' view, in a separate
387         # column, similar to what 'ls -l' does.  This cost a bit of IO.
388
389         # To disable system wide have in $GITWEB_CONFIG
390         # $feature{'show-sizes'}{'default'} = [0];
391         # To have project specific config enable override in $GITWEB_CONFIG
392         # $feature{'show-sizes'}{'override'} = 1;
393         # and in project config gitweb.showsizes = 0|1;
394         'show-sizes' => {
395                 'sub' => sub { feature_bool('showsizes', @_) },
396                 'override' => 0,
397                 'default' => [1]},
398
399         # Make gitweb use an alternative format of the URLs which can be
400         # more readable and natural-looking: project name is embedded
401         # directly in the path and the query string contains other
402         # auxiliary information. All gitweb installations recognize
403         # URL in either format; this configures in which formats gitweb
404         # generates links.
405
406         # To enable system wide have in $GITWEB_CONFIG
407         # $feature{'pathinfo'}{'default'} = [1];
408         # Project specific override is not supported.
409
410         # Note that you will need to change the default location of CSS,
411         # favicon, logo and possibly other files to an absolute URL. Also,
412         # if gitweb.cgi serves as your indexfile, you will need to force
413         # $my_uri to contain the script name in your $GITWEB_CONFIG.
414         'pathinfo' => {
415                 'override' => 0,
416                 'default' => [0]},
417
418         # Make gitweb consider projects in project root subdirectories
419         # to be forks of existing projects. Given project $projname.git,
420         # projects matching $projname/*.git will not be shown in the main
421         # projects list, instead a '+' mark will be added to $projname
422         # there and a 'forks' view will be enabled for the project, listing
423         # all the forks. If project list is taken from a file, forks have
424         # to be listed after the main project.
425
426         # To enable system wide have in $GITWEB_CONFIG
427         # $feature{'forks'}{'default'} = [1];
428         # Project specific override is not supported.
429         'forks' => {
430                 'override' => 0,
431                 'default' => [0]},
432
433         # Insert custom links to the action bar of all project pages.
434         # This enables you mainly to link to third-party scripts integrating
435         # into gitweb; e.g. git-browser for graphical history representation
436         # or custom web-based repository administration interface.
437
438         # The 'default' value consists of a list of triplets in the form
439         # (label, link, position) where position is the label after which
440         # to insert the link and link is a format string where %n expands
441         # to the project name, %f to the project path within the filesystem,
442         # %h to the current hash (h gitweb parameter) and %b to the current
443         # hash base (hb gitweb parameter); %% expands to %.
444
445         # To enable system wide have in $GITWEB_CONFIG e.g.
446         # $feature{'actions'}{'default'} = [('graphiclog',
447         #       '/git-browser/by-commit.html?r=%n', 'summary')];
448         # Project specific override is not supported.
449         'actions' => {
450                 'override' => 0,
451                 'default' => []},
452
453         # Allow gitweb scan project content tags of project repository,
454         # and display the popular Web 2.0-ish "tag cloud" near the projects
455         # list.  Note that this is something COMPLETELY different from the
456         # normal Git tags.
457
458         # gitweb by itself can show existing tags, but it does not handle
459         # tagging itself; you need to do it externally, outside gitweb.
460         # The format is described in git_get_project_ctags() subroutine.
461         # You may want to install the HTML::TagCloud Perl module to get
462         # a pretty tag cloud instead of just a list of tags.
463
464         # To enable system wide have in $GITWEB_CONFIG
465         # $feature{'ctags'}{'default'} = [1];
466         # Project specific override is not supported.
467
468         # In the future whether ctags editing is enabled might depend
469         # on the value, but using 1 should always mean no editing of ctags.
470         'ctags' => {
471                 'override' => 0,
472                 'default' => [0]},
473
474         # The maximum number of patches in a patchset generated in patch
475         # view. Set this to 0 or undef to disable patch view, or to a
476         # negative number to remove any limit.
477
478         # To disable system wide have in $GITWEB_CONFIG
479         # $feature{'patches'}{'default'} = [0];
480         # To have project specific config enable override in $GITWEB_CONFIG
481         # $feature{'patches'}{'override'} = 1;
482         # and in project config gitweb.patches = 0|n;
483         # where n is the maximum number of patches allowed in a patchset.
484         'patches' => {
485                 'sub' => \&feature_patches,
486                 'override' => 0,
487                 'default' => [16]},
488
489         # Avatar support. When this feature is enabled, views such as
490         # shortlog or commit will display an avatar associated with
491         # the email of the committer(s) and/or author(s).
492
493         # Currently available providers are gravatar and picon.
494         # If an unknown provider is specified, the feature is disabled.
495
496         # Picon currently relies on the indiana.edu database.
497
498         # To enable system wide have in $GITWEB_CONFIG
499         # $feature{'avatar'}{'default'} = ['<provider>'];
500         # where <provider> is either gravatar or picon.
501         # To have project specific config enable override in $GITWEB_CONFIG
502         # $feature{'avatar'}{'override'} = 1;
503         # and in project config gitweb.avatar = <provider>;
504         'avatar' => {
505                 'sub' => \&feature_avatar,
506                 'override' => 0,
507                 'default' => ['']},
508
509         # Enable displaying how much time and how many git commands
510         # it took to generate and display page.  Disabled by default.
511         # Project specific override is not supported.
512         'timed' => {
513                 'override' => 0,
514                 'default' => [0]},
515
516         # Enable turning some links into links to actions which require
517         # JavaScript to run (like 'blame_incremental').  Not enabled by
518         # default.  Project specific override is currently not supported.
519         'javascript-actions' => {
520                 'override' => 0,
521                 'default' => [0]},
522
523         # Enable and configure ability to change common timezone for dates
524         # in gitweb output via JavaScript.  Enabled by default.
525         # Project specific override is not supported.
526         'javascript-timezone' => {
527                 'override' => 0,
528                 'default' => [
529                         'local',     # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
530                                      # or undef to turn off this feature
531                         'gitweb_tz', # name of cookie where to store selected timezone
532                         'datetime',  # CSS class used to mark up dates for manipulation
533                 ]},
534
535         # Syntax highlighting support. This is based on Daniel Svensson's
536         # and Sham Chukoury's work in gitweb-xmms2.git.
537         # It requires the 'highlight' program present in $PATH,
538         # and therefore is disabled by default.
539
540         # To enable system wide have in $GITWEB_CONFIG
541         # $feature{'highlight'}{'default'} = [1];
542
543         'highlight' => {
544                 'sub' => sub { feature_bool('highlight', @_) },
545                 'override' => 0,
546                 'default' => [0]},
547
548         # Enable displaying of remote heads in the heads list
549
550         # To enable system wide have in $GITWEB_CONFIG
551         # $feature{'remote_heads'}{'default'} = [1];
552         # To have project specific config enable override in $GITWEB_CONFIG
553         # $feature{'remote_heads'}{'override'} = 1;
554         # and in project config gitweb.remoteheads = 0|1;
555         'remote_heads' => {
556                 'sub' => sub { feature_bool('remote_heads', @_) },
557                 'override' => 0,
558                 'default' => [0]},
559
560         # Enable showing branches under other refs in addition to heads
561
562         # To set system wide extra branch refs have in $GITWEB_CONFIG
563         # $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice'];
564         # To have project specific config enable override in $GITWEB_CONFIG
565         # $feature{'extra-branch-refs'}{'override'} = 1;
566         # and in project config gitweb.extrabranchrefs = dirs of choice
567         # Every directory is separated with whitespace.
568
569         'extra-branch-refs' => {
570                 'sub' => \&feature_extra_branch_refs,
571                 'override' => 0,
572                 'default' => []},
573
574         # Redact e-mail addresses.
575
576         # To enable system wide have in $GITWEB_CONFIG
577         # $feature{'email-privacy'}{'default'} = [1];
578         'email-privacy' => {
579                 'sub' => sub { feature_bool('email-privacy', @_) },
580                 'override' => 1,
581                 'default' => [0]},
582 );
583
584 sub gitweb_get_feature {
585         my ($name) = @_;
586         return unless exists $feature{$name};
587         my ($sub, $override, @defaults) = (
588                 $feature{$name}{'sub'},
589                 $feature{$name}{'override'},
590                 @{$feature{$name}{'default'}});
591         # project specific override is possible only if we have project
592         our $git_dir; # global variable, declared later
593         if (!$override || !defined $git_dir) {
594                 return @defaults;
595         }
596         if (!defined $sub) {
597                 warn "feature $name is not overridable";
598                 return @defaults;
599         }
600         return $sub->(@defaults);
601 }
602
603 # A wrapper to check if a given feature is enabled.
604 # With this, you can say
605 #
606 #   my $bool_feat = gitweb_check_feature('bool_feat');
607 #   gitweb_check_feature('bool_feat') or somecode;
608 #
609 # instead of
610 #
611 #   my ($bool_feat) = gitweb_get_feature('bool_feat');
612 #   (gitweb_get_feature('bool_feat'))[0] or somecode;
613 #
614 sub gitweb_check_feature {
615         return (gitweb_get_feature(@_))[0];
616 }
617
618
619 sub feature_bool {
620         my $key = shift;
621         my ($val) = git_get_project_config($key, '--bool');
622
623         if (!defined $val) {
624                 return ($_[0]);
625         } elsif ($val eq 'true') {
626                 return (1);
627         } elsif ($val eq 'false') {
628                 return (0);
629         }
630 }
631
632 sub feature_snapshot {
633         my (@fmts) = @_;
634
635         my ($val) = git_get_project_config('snapshot');
636
637         if ($val) {
638                 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
639         }
640
641         return @fmts;
642 }
643
644 sub feature_patches {
645         my @val = (git_get_project_config('patches', '--int'));
646
647         if (@val) {
648                 return @val;
649         }
650
651         return ($_[0]);
652 }
653
654 sub feature_avatar {
655         my @val = (git_get_project_config('avatar'));
656
657         return @val ? @val : @_;
658 }
659
660 sub feature_extra_branch_refs {
661         my (@branch_refs) = @_;
662         my $values = git_get_project_config('extrabranchrefs');
663
664         if ($values) {
665                 $values = config_to_multi ($values);
666                 @branch_refs = ();
667                 foreach my $value (@{$values}) {
668                         push @branch_refs, split /\s+/, $value;
669                 }
670         }
671
672         return @branch_refs;
673 }
674
675 # checking HEAD file with -e is fragile if the repository was
676 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
677 # and then pruned.
678 sub check_head_link {
679         my ($dir) = @_;
680         my $headfile = "$dir/HEAD";
681         return ((-e $headfile) ||
682                 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
683 }
684
685 sub check_export_ok {
686         my ($dir) = @_;
687         return (check_head_link($dir) &&
688                 (!$export_ok || -e "$dir/$export_ok") &&
689                 (!$export_auth_hook || $export_auth_hook->($dir)));
690 }
691
692 # process alternate names for backward compatibility
693 # filter out unsupported (unknown) snapshot formats
694 sub filter_snapshot_fmts {
695         my @fmts = @_;
696
697         @fmts = map {
698                 exists $known_snapshot_format_aliases{$_} ?
699                        $known_snapshot_format_aliases{$_} : $_} @fmts;
700         @fmts = grep {
701                 exists $known_snapshot_formats{$_} &&
702                 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
703 }
704
705 sub filter_and_validate_refs {
706         my @refs = @_;
707         my %unique_refs = ();
708
709         foreach my $ref (@refs) {
710                 die_error(500, "Invalid ref '$ref' in 'extra-branch-refs' feature") unless (is_valid_ref_format($ref));
711                 # 'heads' are added implicitly in get_branch_refs().
712                 $unique_refs{$ref} = 1 if ($ref ne 'heads');
713         }
714         return sort keys %unique_refs;
715 }
716
717 # If it is set to code reference, it is code that it is to be run once per
718 # request, allowing updating configurations that change with each request,
719 # while running other code in config file only once.
720 #
721 # Otherwise, if it is false then gitweb would process config file only once;
722 # if it is true then gitweb config would be run for each request.
723 our $per_request_config = 1;
724
725 # read and parse gitweb config file given by its parameter.
726 # returns true on success, false on recoverable error, allowing
727 # to chain this subroutine, using first file that exists.
728 # dies on errors during parsing config file, as it is unrecoverable.
729 sub read_config_file {
730         my $filename = shift;
731         return unless defined $filename;
732         if (-e $filename) {
733                 do $filename;
734                 # die if there is a problem accessing the file
735                 die $! if $!;
736                 # die if there are errors parsing config file
737                 die $@ if $@;
738                 return 1;
739         }
740         return;
741 }
742
743 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
744 sub evaluate_gitweb_config {
745         our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "@GITWEB_CONFIG@";
746         our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "@GITWEB_CONFIG_SYSTEM@";
747         our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "@GITWEB_CONFIG_COMMON@";
748
749         # Protect against duplications of file names, to not read config twice.
750         # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
751         # there possibility of duplication of filename there doesn't matter.
752         $GITWEB_CONFIG = ""        if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
753         $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
754
755         # Common system-wide settings for convenience.
756         # Those settings can be overridden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
757         read_config_file($GITWEB_CONFIG_COMMON);
758
759         # Use first config file that exists.  This means use the per-instance
760         # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
761         read_config_file($GITWEB_CONFIG) and return;
762         read_config_file($GITWEB_CONFIG_SYSTEM);
763 }
764
765 # Get loadavg of system, to compare against $maxload.
766 # Currently it requires '/proc/loadavg' present to get loadavg;
767 # if it is not present it returns 0, which means no load checking.
768 sub get_loadavg {
769         if( -e '/proc/loadavg' ){
770                 open my $fd, '<', '/proc/loadavg'
771                         or return 0;
772                 my @load = split(/\s+/, scalar <$fd>);
773                 close $fd;
774
775                 # The first three columns measure CPU and IO utilization of the last one,
776                 # five, and 10 minute periods.  The fourth column shows the number of
777                 # currently running processes and the total number of processes in the m/n
778                 # format.  The last column displays the last process ID used.
779                 return $load[0] || 0;
780         }
781         # additional checks for load average should go here for things that don't export
782         # /proc/loadavg
783
784         return 0;
785 }
786
787 # version of the core git binary
788 our $git_version;
789 sub evaluate_git_version {
790         our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
791         $number_of_git_cmds++;
792 }
793
794 sub check_loadavg {
795         if (defined $maxload && get_loadavg() > $maxload) {
796                 die_error(503, "The load average on the server is too high");
797         }
798 }
799
800 # ======================================================================
801 # input validation and dispatch
802
803 # Various hash size-related values.
804 my $sha1_len = 40;
805 my $sha256_extra_len = 24;
806 my $sha256_len = $sha1_len + $sha256_extra_len;
807
808 # A regex matching $len hex characters. $len may be a range (e.g. 7,64).
809 sub oid_nlen_regex {
810         my $len = shift;
811         my $hchr = qr/[0-9a-fA-F]/;
812         return qr/(?:(?:$hchr){$len})/;
813 }
814
815 # A regex matching two sets of $nlen hex characters, prefixed by the literal
816 # string $prefix and with the literal string $infix between them.
817 sub oid_nlen_prefix_infix_regex {
818         my $nlen = shift;
819         my $prefix = shift;
820         my $infix = shift;
821
822         my $rx = oid_nlen_regex($nlen);
823
824         return qr/^\Q$prefix\E$rx\Q$infix\E$rx$/;
825 }
826
827 # A regex matching a valid object ID.
828 our $oid_regex;
829 {
830         my $x = oid_nlen_regex($sha1_len);
831         my $y = oid_nlen_regex($sha256_extra_len);
832         $oid_regex = qr/(?:$x(?:$y)?)/;
833 }
834
835 # input parameters can be collected from a variety of sources (presently, CGI
836 # and PATH_INFO), so we define an %input_params hash that collects them all
837 # together during validation: this allows subsequent uses (e.g. href()) to be
838 # agnostic of the parameter origin
839
840 our %input_params = ();
841
842 # input parameters are stored with the long parameter name as key. This will
843 # also be used in the href subroutine to convert parameters to their CGI
844 # equivalent, and since the href() usage is the most frequent one, we store
845 # the name -> CGI key mapping here, instead of the reverse.
846 #
847 # XXX: Warning: If you touch this, check the search form for updating,
848 # too.
849
850 our @cgi_param_mapping = (
851         project => "p",
852         action => "a",
853         file_name => "f",
854         file_parent => "fp",
855         hash => "h",
856         hash_parent => "hp",
857         hash_base => "hb",
858         hash_parent_base => "hpb",
859         page => "pg",
860         order => "o",
861         searchtext => "s",
862         searchtype => "st",
863         snapshot_format => "sf",
864         extra_options => "opt",
865         search_use_regexp => "sr",
866         ctag => "by_tag",
867         diff_style => "ds",
868         project_filter => "pf",
869         # this must be last entry (for manipulation from JavaScript)
870         javascript => "js"
871 );
872 our %cgi_param_mapping = @cgi_param_mapping;
873
874 # we will also need to know the possible actions, for validation
875 our %actions = (
876         "blame" => \&git_blame,
877         "blame_incremental" => \&git_blame_incremental,
878         "blame_data" => \&git_blame_data,
879         "blobdiff" => \&git_blobdiff,
880         "blobdiff_plain" => \&git_blobdiff_plain,
881         "blob" => \&git_blob,
882         "blob_plain" => \&git_blob_plain,
883         "commitdiff" => \&git_commitdiff,
884         "commitdiff_plain" => \&git_commitdiff_plain,
885         "commit" => \&git_commit,
886         "forks" => \&git_forks,
887         "heads" => \&git_heads,
888         "history" => \&git_history,
889         "log" => \&git_log,
890         "patch" => \&git_patch,
891         "patches" => \&git_patches,
892         "remotes" => \&git_remotes,
893         "rss" => \&git_rss,
894         "atom" => \&git_atom,
895         "search" => \&git_search,
896         "search_help" => \&git_search_help,
897         "shortlog" => \&git_shortlog,
898         "summary" => \&git_summary,
899         "tag" => \&git_tag,
900         "tags" => \&git_tags,
901         "tree" => \&git_tree,
902         "snapshot" => \&git_snapshot,
903         "object" => \&git_object,
904         # those below don't need $project
905         "opml" => \&git_opml,
906         "project_list" => \&git_project_list,
907         "project_index" => \&git_project_index,
908 );
909
910 # finally, we have the hash of allowed extra_options for the commands that
911 # allow them
912 our %allowed_options = (
913         "--no-merges" => [ qw(rss atom log shortlog history) ],
914 );
915
916 # fill %input_params with the CGI parameters. All values except for 'opt'
917 # should be single values, but opt can be an array. We should probably
918 # build an array of parameters that can be multi-valued, but since for the time
919 # being it's only this one, we just single it out
920 sub evaluate_query_params {
921         our $cgi;
922
923         while (my ($name, $symbol) = each %cgi_param_mapping) {
924                 if ($symbol eq 'opt') {
925                         $input_params{$name} = [ map { decode_utf8($_) } $cgi->multi_param($symbol) ];
926                 } else {
927                         $input_params{$name} = decode_utf8($cgi->param($symbol));
928                 }
929         }
930 }
931
932 # now read PATH_INFO and update the parameter list for missing parameters
933 sub evaluate_path_info {
934         return if defined $input_params{'project'};
935         return if !$path_info;
936         $path_info =~ s,^/+,,;
937         return if !$path_info;
938
939         # find which part of PATH_INFO is project
940         my $project = $path_info;
941         $project =~ s,/+$,,;
942         while ($project && !check_head_link("$projectroot/$project")) {
943                 $project =~ s,/*[^/]*$,,;
944         }
945         return unless $project;
946         $input_params{'project'} = $project;
947
948         # do not change any parameters if an action is given using the query string
949         return if $input_params{'action'};
950         $path_info =~ s,^\Q$project\E/*,,;
951
952         # next, check if we have an action
953         my $action = $path_info;
954         $action =~ s,/.*$,,;
955         if (exists $actions{$action}) {
956                 $path_info =~ s,^$action/*,,;
957                 $input_params{'action'} = $action;
958         }
959
960         # list of actions that want hash_base instead of hash, but can have no
961         # pathname (f) parameter
962         my @wants_base = (
963                 'tree',
964                 'history',
965         );
966
967         # we want to catch, among others
968         # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
969         my ($parentrefname, $parentpathname, $refname, $pathname) =
970                 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
971
972         # first, analyze the 'current' part
973         if (defined $pathname) {
974                 # we got "branch:filename" or "branch:dir/"
975                 # we could use git_get_type(branch:pathname), but:
976                 # - it needs $git_dir
977                 # - it does a git() call
978                 # - the convention of terminating directories with a slash
979                 #   makes it superfluous
980                 # - embedding the action in the PATH_INFO would make it even
981                 #   more superfluous
982                 $pathname =~ s,^/+,,;
983                 if (!$pathname || substr($pathname, -1) eq "/") {
984                         $input_params{'action'} ||= "tree";
985                         $pathname =~ s,/$,,;
986                 } else {
987                         # the default action depends on whether we had parent info
988                         # or not
989                         if ($parentrefname) {
990                                 $input_params{'action'} ||= "blobdiff_plain";
991                         } else {
992                                 $input_params{'action'} ||= "blob_plain";
993                         }
994                 }
995                 $input_params{'hash_base'} ||= $refname;
996                 $input_params{'file_name'} ||= $pathname;
997         } elsif (defined $refname) {
998                 # we got "branch". In this case we have to choose if we have to
999                 # set hash or hash_base.
1000                 #
1001                 # Most of the actions without a pathname only want hash to be
1002                 # set, except for the ones specified in @wants_base that want
1003                 # hash_base instead. It should also be noted that hand-crafted
1004                 # links having 'history' as an action and no pathname or hash
1005                 # set will fail, but that happens regardless of PATH_INFO.
1006                 if (defined $parentrefname) {
1007                         # if there is parent let the default be 'shortlog' action
1008                         # (for http://git.example.com/repo.git/A..B links); if there
1009                         # is no parent, dispatch will detect type of object and set
1010                         # action appropriately if required (if action is not set)
1011                         $input_params{'action'} ||= "shortlog";
1012                 }
1013                 if ($input_params{'action'} &&
1014                     grep { $_ eq $input_params{'action'} } @wants_base) {
1015                         $input_params{'hash_base'} ||= $refname;
1016                 } else {
1017                         $input_params{'hash'} ||= $refname;
1018                 }
1019         }
1020
1021         # next, handle the 'parent' part, if present
1022         if (defined $parentrefname) {
1023                 # a missing pathspec defaults to the 'current' filename, allowing e.g.
1024                 # someproject/blobdiff/oldrev..newrev:/filename
1025                 if ($parentpathname) {
1026                         $parentpathname =~ s,^/+,,;
1027                         $parentpathname =~ s,/$,,;
1028                         $input_params{'file_parent'} ||= $parentpathname;
1029                 } else {
1030                         $input_params{'file_parent'} ||= $input_params{'file_name'};
1031                 }
1032                 # we assume that hash_parent_base is wanted if a path was specified,
1033                 # or if the action wants hash_base instead of hash
1034                 if (defined $input_params{'file_parent'} ||
1035                         grep { $_ eq $input_params{'action'} } @wants_base) {
1036                         $input_params{'hash_parent_base'} ||= $parentrefname;
1037                 } else {
1038                         $input_params{'hash_parent'} ||= $parentrefname;
1039                 }
1040         }
1041
1042         # for the snapshot action, we allow URLs in the form
1043         # $project/snapshot/$hash.ext
1044         # where .ext determines the snapshot and gets removed from the
1045         # passed $refname to provide the $hash.
1046         #
1047         # To be able to tell that $refname includes the format extension, we
1048         # require the following two conditions to be satisfied:
1049         # - the hash input parameter MUST have been set from the $refname part
1050         #   of the URL (i.e. they must be equal)
1051         # - the snapshot format MUST NOT have been defined already (e.g. from
1052         #   CGI parameter sf)
1053         # It's also useless to try any matching unless $refname has a dot,
1054         # so we check for that too
1055         if (defined $input_params{'action'} &&
1056                 $input_params{'action'} eq 'snapshot' &&
1057                 defined $refname && index($refname, '.') != -1 &&
1058                 $refname eq $input_params{'hash'} &&
1059                 !defined $input_params{'snapshot_format'}) {
1060                 # We loop over the known snapshot formats, checking for
1061                 # extensions. Allowed extensions are both the defined suffix
1062                 # (which includes the initial dot already) and the snapshot
1063                 # format key itself, with a prepended dot
1064                 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1065                         my $hash = $refname;
1066                         unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1067                                 next;
1068                         }
1069                         my $sfx = $1;
1070                         # a valid suffix was found, so set the snapshot format
1071                         # and reset the hash parameter
1072                         $input_params{'snapshot_format'} = $fmt;
1073                         $input_params{'hash'} = $hash;
1074                         # we also set the format suffix to the one requested
1075                         # in the URL: this way a request for e.g. .tgz returns
1076                         # a .tgz instead of a .tar.gz
1077                         $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1078                         last;
1079                 }
1080         }
1081 }
1082
1083 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1084      $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1085      $searchtext, $search_regexp, $project_filter);
1086 sub evaluate_and_validate_params {
1087         our $action = $input_params{'action'};
1088         if (defined $action) {
1089                 if (!is_valid_action($action)) {
1090                         die_error(400, "Invalid action parameter");
1091                 }
1092         }
1093
1094         # parameters which are pathnames
1095         our $project = $input_params{'project'};
1096         if (defined $project) {
1097                 if (!is_valid_project($project)) {
1098                         undef $project;
1099                         die_error(404, "No such project");
1100                 }
1101         }
1102
1103         our $project_filter = $input_params{'project_filter'};
1104         if (defined $project_filter) {
1105                 if (!is_valid_pathname($project_filter)) {
1106                         die_error(404, "Invalid project_filter parameter");
1107                 }
1108         }
1109
1110         our $file_name = $input_params{'file_name'};
1111         if (defined $file_name) {
1112                 if (!is_valid_pathname($file_name)) {
1113                         die_error(400, "Invalid file parameter");
1114                 }
1115         }
1116
1117         our $file_parent = $input_params{'file_parent'};
1118         if (defined $file_parent) {
1119                 if (!is_valid_pathname($file_parent)) {
1120                         die_error(400, "Invalid file parent parameter");
1121                 }
1122         }
1123
1124         # parameters which are refnames
1125         our $hash = $input_params{'hash'};
1126         if (defined $hash) {
1127                 if (!is_valid_refname($hash)) {
1128                         die_error(400, "Invalid hash parameter");
1129                 }
1130         }
1131
1132         our $hash_parent = $input_params{'hash_parent'};
1133         if (defined $hash_parent) {
1134                 if (!is_valid_refname($hash_parent)) {
1135                         die_error(400, "Invalid hash parent parameter");
1136                 }
1137         }
1138
1139         our $hash_base = $input_params{'hash_base'};
1140         if (defined $hash_base) {
1141                 if (!is_valid_refname($hash_base)) {
1142                         die_error(400, "Invalid hash base parameter");
1143                 }
1144         }
1145
1146         our @extra_options = @{$input_params{'extra_options'}};
1147         # @extra_options is always defined, since it can only be (currently) set from
1148         # CGI, and $cgi->param() returns the empty array in array context if the param
1149         # is not set
1150         foreach my $opt (@extra_options) {
1151                 if (not exists $allowed_options{$opt}) {
1152                         die_error(400, "Invalid option parameter");
1153                 }
1154                 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1155                         die_error(400, "Invalid option parameter for this action");
1156                 }
1157         }
1158
1159         our $hash_parent_base = $input_params{'hash_parent_base'};
1160         if (defined $hash_parent_base) {
1161                 if (!is_valid_refname($hash_parent_base)) {
1162                         die_error(400, "Invalid hash parent base parameter");
1163                 }
1164         }
1165
1166         # other parameters
1167         our $page = $input_params{'page'};
1168         if (defined $page) {
1169                 if ($page =~ m/[^0-9]/) {
1170                         die_error(400, "Invalid page parameter");
1171                 }
1172         }
1173
1174         our $searchtype = $input_params{'searchtype'};
1175         if (defined $searchtype) {
1176                 if ($searchtype =~ m/[^a-z]/) {
1177                         die_error(400, "Invalid searchtype parameter");
1178                 }
1179         }
1180
1181         our $search_use_regexp = $input_params{'search_use_regexp'};
1182
1183         our $searchtext = $input_params{'searchtext'};
1184         our $search_regexp = undef;
1185         if (defined $searchtext) {
1186                 if (length($searchtext) < 2) {
1187                         die_error(403, "At least two characters are required for search parameter");
1188                 }
1189                 if ($search_use_regexp) {
1190                         $search_regexp = $searchtext;
1191                         if (!eval { qr/$search_regexp/; 1; }) {
1192                                 my $error = $@ =~ s/ at \S+ line \d+.*\n?//r;
1193                                 die_error(400, "Invalid search regexp '$search_regexp'",
1194                                           esc_html($error));
1195                         }
1196                 } else {
1197                         $search_regexp = quotemeta $searchtext;
1198                 }
1199         }
1200 }
1201
1202 # path to the current git repository
1203 our $git_dir;
1204 sub evaluate_git_dir {
1205         our $git_dir = "$projectroot/$project" if $project;
1206 }
1207
1208 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1209 sub configure_gitweb_features {
1210         # list of supported snapshot formats
1211         our @snapshot_fmts = gitweb_get_feature('snapshot');
1212         @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1213
1214         our ($git_avatar) = gitweb_get_feature('avatar');
1215         $git_avatar = '' unless $git_avatar =~ /^(?:gravatar|picon)$/s;
1216
1217         our @extra_branch_refs = gitweb_get_feature('extra-branch-refs');
1218         @extra_branch_refs = filter_and_validate_refs (@extra_branch_refs);
1219 }
1220
1221 sub get_branch_refs {
1222         return ('heads', @extra_branch_refs);
1223 }
1224
1225 # custom error handler: 'die <message>' is Internal Server Error
1226 sub handle_errors_html {
1227         my $msg = shift; # it is already HTML escaped
1228
1229         # to avoid infinite loop where error occurs in die_error,
1230         # change handler to default handler, disabling handle_errors_html
1231         set_message("Error occurred when inside die_error:\n$msg");
1232
1233         # you cannot jump out of die_error when called as error handler;
1234         # the subroutine set via CGI::Carp::set_message is called _after_
1235         # HTTP headers are already written, so it cannot write them itself
1236         die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1237 }
1238 set_message(\&handle_errors_html);
1239
1240 # dispatch
1241 sub dispatch {
1242         if (!defined $action) {
1243                 if (defined $hash) {
1244                         $action = git_get_type($hash);
1245                         $action or die_error(404, "Object does not exist");
1246                 } elsif (defined $hash_base && defined $file_name) {
1247                         $action = git_get_type("$hash_base:$file_name");
1248                         $action or die_error(404, "File or directory does not exist");
1249                 } elsif (defined $project) {
1250                         $action = 'summary';
1251                 } else {
1252                         $action = 'project_list';
1253                 }
1254         }
1255         if (!defined($actions{$action})) {
1256                 die_error(400, "Unknown action");
1257         }
1258         if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1259             !$project) {
1260                 die_error(400, "Project needed");
1261         }
1262         $actions{$action}->();
1263 }
1264
1265 sub reset_timer {
1266         our $t0 = [ gettimeofday() ]
1267                 if defined $t0;
1268         our $number_of_git_cmds = 0;
1269 }
1270
1271 our $first_request = 1;
1272 sub run_request {
1273         reset_timer();
1274
1275         evaluate_uri();
1276         if ($first_request) {
1277                 evaluate_gitweb_config();
1278                 evaluate_git_version();
1279         }
1280         if ($per_request_config) {
1281                 if (ref($per_request_config) eq 'CODE') {
1282                         $per_request_config->();
1283                 } elsif (!$first_request) {
1284                         evaluate_gitweb_config();
1285                 }
1286         }
1287         check_loadavg();
1288
1289         # $projectroot and $projects_list might be set in gitweb config file
1290         $projects_list ||= $projectroot;
1291
1292         evaluate_query_params();
1293         evaluate_path_info();
1294         evaluate_and_validate_params();
1295         evaluate_git_dir();
1296
1297         configure_gitweb_features();
1298
1299         dispatch();
1300 }
1301
1302 our $is_last_request = sub { 1 };
1303 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1304 our $CGI = 'CGI';
1305 our $cgi;
1306 our $FCGI_Stream_PRINT_raw = \&FCGI::Stream::PRINT;
1307 sub configure_as_fcgi {
1308         require CGI::Fast;
1309         our $CGI = 'CGI::Fast';
1310         # FCGI is not Unicode aware hence the UTF-8 encoding must be done manually.
1311         # However no encoding must be done within git_blob_plain() and git_snapshot()
1312         # which must still output in raw binary mode.
1313         no warnings 'redefine';
1314         my $enc = Encode::find_encoding('UTF-8');
1315         *FCGI::Stream::PRINT = sub {
1316                 my @OUTPUT = @_;
1317                 for (my $i = 1; $i < @_; $i++) {
1318                         $OUTPUT[$i] = $enc->encode($_[$i], Encode::FB_CROAK|Encode::LEAVE_SRC);
1319                 }
1320                 @_ = @OUTPUT;
1321                 goto $FCGI_Stream_PRINT_raw;
1322         };
1323
1324         my $request_number = 0;
1325         # let each child service 100 requests
1326         our $is_last_request = sub { ++$request_number > 100 };
1327 }
1328 sub evaluate_argv {
1329         my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1330         configure_as_fcgi()
1331                 if $script_name =~ /\.fcgi$/;
1332
1333         return unless (@ARGV);
1334
1335         require Getopt::Long;
1336         Getopt::Long::GetOptions(
1337                 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1338                 'nproc|n=i' => sub {
1339                         my ($arg, $val) = @_;
1340                         return unless eval { require FCGI::ProcManager; 1; };
1341                         my $proc_manager = FCGI::ProcManager->new({
1342                                 n_processes => $val,
1343                         });
1344                         our $pre_listen_hook    = sub { $proc_manager->pm_manage()        };
1345                         our $pre_dispatch_hook  = sub { $proc_manager->pm_pre_dispatch()  };
1346                         our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1347                 },
1348         );
1349 }
1350
1351 sub run {
1352         evaluate_argv();
1353
1354         $first_request = 1;
1355         $pre_listen_hook->()
1356                 if $pre_listen_hook;
1357
1358  REQUEST:
1359         while ($cgi = $CGI->new()) {
1360                 $pre_dispatch_hook->()
1361                         if $pre_dispatch_hook;
1362
1363                 run_request();
1364
1365                 $post_dispatch_hook->()
1366                         if $post_dispatch_hook;
1367                 $first_request = 0;
1368
1369                 last REQUEST if ($is_last_request->());
1370         }
1371
1372  DONE_GITWEB:
1373         1;
1374 }
1375
1376 run();
1377
1378 if (defined caller) {
1379         # wrapped in a subroutine processing requests,
1380         # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1381         return;
1382 } else {
1383         # pure CGI script, serving single request
1384         exit;
1385 }
1386
1387 ## ======================================================================
1388 ## action links
1389
1390 # possible values of extra options
1391 # -full => 0|1      - use absolute/full URL ($my_uri/$my_url as base)
1392 # -replay => 1      - start from a current view (replay with modifications)
1393 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1394 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1395 sub href {
1396         my %params = @_;
1397         # default is to use -absolute url() i.e. $my_uri
1398         my $href = $params{-full} ? $my_url : $my_uri;
1399
1400         # implicit -replay, must be first of implicit params
1401         $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1402
1403         $params{'project'} = $project unless exists $params{'project'};
1404
1405         if ($params{-replay}) {
1406                 while (my ($name, $symbol) = each %cgi_param_mapping) {
1407                         if (!exists $params{$name}) {
1408                                 $params{$name} = $input_params{$name};
1409                         }
1410                 }
1411         }
1412
1413         my $use_pathinfo = gitweb_check_feature('pathinfo');
1414         if (defined $params{'project'} &&
1415             (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1416                 # try to put as many parameters as possible in PATH_INFO:
1417                 #   - project name
1418                 #   - action
1419                 #   - hash_parent or hash_parent_base:/file_parent
1420                 #   - hash or hash_base:/filename
1421                 #   - the snapshot_format as an appropriate suffix
1422
1423                 # When the script is the root DirectoryIndex for the domain,
1424                 # $href here would be something like http://gitweb.example.com/
1425                 # Thus, we strip any trailing / from $href, to spare us double
1426                 # slashes in the final URL
1427                 $href =~ s,/$,,;
1428
1429                 # Then add the project name, if present
1430                 $href .= "/".esc_path_info($params{'project'});
1431                 delete $params{'project'};
1432
1433                 # since we destructively absorb parameters, we keep this
1434                 # boolean that remembers if we're handling a snapshot
1435                 my $is_snapshot = $params{'action'} eq 'snapshot';
1436
1437                 # Summary just uses the project path URL, any other action is
1438                 # added to the URL
1439                 if (defined $params{'action'}) {
1440                         $href .= "/".esc_path_info($params{'action'})
1441                                 unless $params{'action'} eq 'summary';
1442                         delete $params{'action'};
1443                 }
1444
1445                 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1446                 # stripping nonexistent or useless pieces
1447                 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1448                         || $params{'hash_parent'} || $params{'hash'});
1449                 if (defined $params{'hash_base'}) {
1450                         if (defined $params{'hash_parent_base'}) {
1451                                 $href .= esc_path_info($params{'hash_parent_base'});
1452                                 # skip the file_parent if it's the same as the file_name
1453                                 if (defined $params{'file_parent'}) {
1454                                         if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1455                                                 delete $params{'file_parent'};
1456                                         } elsif ($params{'file_parent'} !~ /\.\./) {
1457                                                 $href .= ":/".esc_path_info($params{'file_parent'});
1458                                                 delete $params{'file_parent'};
1459                                         }
1460                                 }
1461                                 $href .= "..";
1462                                 delete $params{'hash_parent'};
1463                                 delete $params{'hash_parent_base'};
1464                         } elsif (defined $params{'hash_parent'}) {
1465                                 $href .= esc_path_info($params{'hash_parent'}). "..";
1466                                 delete $params{'hash_parent'};
1467                         }
1468
1469                         $href .= esc_path_info($params{'hash_base'});
1470                         if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1471                                 $href .= ":/".esc_path_info($params{'file_name'});
1472                                 delete $params{'file_name'};
1473                         }
1474                         delete $params{'hash'};
1475                         delete $params{'hash_base'};
1476                 } elsif (defined $params{'hash'}) {
1477                         $href .= esc_path_info($params{'hash'});
1478                         delete $params{'hash'};
1479                 }
1480
1481                 # If the action was a snapshot, we can absorb the
1482                 # snapshot_format parameter too
1483                 if ($is_snapshot) {
1484                         my $fmt = $params{'snapshot_format'};
1485                         # snapshot_format should always be defined when href()
1486                         # is called, but just in case some code forgets, we
1487                         # fall back to the default
1488                         $fmt ||= $snapshot_fmts[0];
1489                         $href .= $known_snapshot_formats{$fmt}{'suffix'};
1490                         delete $params{'snapshot_format'};
1491                 }
1492         }
1493
1494         # now encode the parameters explicitly
1495         my @result = ();
1496         for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1497                 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1498                 if (defined $params{$name}) {
1499                         if (ref($params{$name}) eq "ARRAY") {
1500                                 foreach my $par (@{$params{$name}}) {
1501                                         push @result, $symbol . "=" . esc_param($par);
1502                                 }
1503                         } else {
1504                                 push @result, $symbol . "=" . esc_param($params{$name});
1505                         }
1506                 }
1507         }
1508         $href .= "?" . join(';', @result) if scalar @result;
1509
1510         # final transformation: trailing spaces must be escaped (URI-encoded)
1511         $href =~ s/(\s+)$/CGI::escape($1)/e;
1512
1513         if ($params{-anchor}) {
1514                 $href .= "#".esc_param($params{-anchor});
1515         }
1516
1517         return $href;
1518 }
1519
1520
1521 ## ======================================================================
1522 ## validation, quoting/unquoting and escaping
1523
1524 sub is_valid_action {
1525         my $input = shift;
1526         return undef unless exists $actions{$input};
1527         return 1;
1528 }
1529
1530 sub is_valid_project {
1531         my $input = shift;
1532
1533         return unless defined $input;
1534         if (!is_valid_pathname($input) ||
1535                 !(-d "$projectroot/$input") ||
1536                 !check_export_ok("$projectroot/$input") ||
1537                 ($strict_export && !project_in_list($input))) {
1538                 return undef;
1539         } else {
1540                 return 1;
1541         }
1542 }
1543
1544 sub is_valid_pathname {
1545         my $input = shift;
1546
1547         return undef unless defined $input;
1548         # no '.' or '..' as elements of path, i.e. no '.' or '..'
1549         # at the beginning, at the end, and between slashes.
1550         # also this catches doubled slashes
1551         if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1552                 return undef;
1553         }
1554         # no null characters
1555         if ($input =~ m!\0!) {
1556                 return undef;
1557         }
1558         return 1;
1559 }
1560
1561 sub is_valid_ref_format {
1562         my $input = shift;
1563
1564         return undef unless defined $input;
1565         # restrictions on ref name according to git-check-ref-format
1566         if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1567                 return undef;
1568         }
1569         return 1;
1570 }
1571
1572 sub is_valid_refname {
1573         my $input = shift;
1574
1575         return undef unless defined $input;
1576         # textual hashes are O.K.
1577         if ($input =~ m/^$oid_regex$/) {
1578                 return 1;
1579         }
1580         # it must be correct pathname
1581         is_valid_pathname($input) or return undef;
1582         # check git-check-ref-format restrictions
1583         is_valid_ref_format($input) or return undef;
1584         return 1;
1585 }
1586
1587 # decode sequences of octets in utf8 into Perl's internal form,
1588 # which is utf-8 with utf8 flag set if needed.  gitweb writes out
1589 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1590 sub to_utf8 {
1591         my $str = shift;
1592         return undef unless defined $str;
1593
1594         if (utf8::is_utf8($str) || utf8::decode($str)) {
1595                 return $str;
1596         } else {
1597                 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1598         }
1599 }
1600
1601 # quote unsafe chars, but keep the slash, even when it's not
1602 # correct, but quoted slashes look too horrible in bookmarks
1603 sub esc_param {
1604         my $str = shift;
1605         return undef unless defined $str;
1606         $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1607         $str =~ s/ /\+/g;
1608         return $str;
1609 }
1610
1611 # the quoting rules for path_info fragment are slightly different
1612 sub esc_path_info {
1613         my $str = shift;
1614         return undef unless defined $str;
1615
1616         # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1617         $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1618
1619         return $str;
1620 }
1621
1622 # quote unsafe chars in whole URL, so some characters cannot be quoted
1623 sub esc_url {
1624         my $str = shift;
1625         return undef unless defined $str;
1626         $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1627         $str =~ s/ /\+/g;
1628         return $str;
1629 }
1630
1631 # quote unsafe characters in HTML attributes
1632 sub esc_attr {
1633
1634         # for XHTML conformance escaping '"' to '&quot;' is not enough
1635         return esc_html(@_);
1636 }
1637
1638 # replace invalid utf8 character with SUBSTITUTION sequence
1639 sub esc_html {
1640         my $str = shift;
1641         my %opts = @_;
1642
1643         return undef unless defined $str;
1644
1645         $str = to_utf8($str);
1646         $str = $cgi->escapeHTML($str);
1647         if ($opts{'-nbsp'}) {
1648                 $str =~ s/ /&nbsp;/g;
1649         }
1650         $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1651         return $str;
1652 }
1653
1654 # quote control characters and escape filename to HTML
1655 sub esc_path {
1656         my $str = shift;
1657         my %opts = @_;
1658
1659         return undef unless defined $str;
1660
1661         $str = to_utf8($str);
1662         $str = $cgi->escapeHTML($str);
1663         if ($opts{'-nbsp'}) {
1664                 $str =~ s/ /&nbsp;/g;
1665         }
1666         $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1667         return $str;
1668 }
1669
1670 # Sanitize for use in XHTML + application/xml+xhtml (valid XML 1.0)
1671 sub sanitize {
1672         my $str = shift;
1673
1674         return undef unless defined $str;
1675
1676         $str = to_utf8($str);
1677         $str =~ s|([[:cntrl:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec($1))|eg;
1678         return $str;
1679 }
1680
1681 # Make control characters "printable", using character escape codes (CEC)
1682 sub quot_cec {
1683         my $cntrl = shift;
1684         my %opts = @_;
1685         my %es = ( # character escape codes, aka escape sequences
1686                 "\t" => '\t',   # tab             (HT)
1687                 "\n" => '\n',   # line feed       (LF)
1688                 "\r" => '\r',   # carriage return (CR)
1689                 "\f" => '\f',   # form feed       (FF)
1690                 "\b" => '\b',   # backspace       (BS)
1691                 "\a" => '\a',   # alarm (bell)    (BEL)
1692                 "\e" => '\e',   # escape          (ESC)
1693                 "\013" => '\v', # vertical tab    (VT)
1694                 "\000" => '\0', # nul character   (NUL)
1695         );
1696         my $chr = ( (exists $es{$cntrl})
1697                     ? $es{$cntrl}
1698                     : sprintf('\%2x', ord($cntrl)) );
1699         if ($opts{-nohtml}) {
1700                 return $chr;
1701         } else {
1702                 return "<span class=\"cntrl\">$chr</span>";
1703         }
1704 }
1705
1706 # Alternatively use unicode control pictures codepoints,
1707 # Unicode "printable representation" (PR)
1708 sub quot_upr {
1709         my $cntrl = shift;
1710         my %opts = @_;
1711
1712         my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1713         if ($opts{-nohtml}) {
1714                 return $chr;
1715         } else {
1716                 return "<span class=\"cntrl\">$chr</span>";
1717         }
1718 }
1719
1720 # git may return quoted and escaped filenames
1721 sub unquote {
1722         my $str = shift;
1723
1724         sub unq {
1725                 my $seq = shift;
1726                 my %es = ( # character escape codes, aka escape sequences
1727                         't' => "\t",   # tab            (HT, TAB)
1728                         'n' => "\n",   # newline        (NL)
1729                         'r' => "\r",   # return         (CR)
1730                         'f' => "\f",   # form feed      (FF)
1731                         'b' => "\b",   # backspace      (BS)
1732                         'a' => "\a",   # alarm (bell)   (BEL)
1733                         'e' => "\e",   # escape         (ESC)
1734                         'v' => "\013", # vertical tab   (VT)
1735                 );
1736
1737                 if ($seq =~ m/^[0-7]{1,3}$/) {
1738                         # octal char sequence
1739                         return chr(oct($seq));
1740                 } elsif (exists $es{$seq}) {
1741                         # C escape sequence, aka character escape code
1742                         return $es{$seq};
1743                 }
1744                 # quoted ordinary character
1745                 return $seq;
1746         }
1747
1748         if ($str =~ m/^"(.*)"$/) {
1749                 # needs unquoting
1750                 $str = $1;
1751                 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1752         }
1753         return $str;
1754 }
1755
1756 # escape tabs (convert tabs to spaces)
1757 sub untabify {
1758         my $line = shift;
1759
1760         while ((my $pos = index($line, "\t")) != -1) {
1761                 if (my $count = (8 - ($pos % 8))) {
1762                         my $spaces = ' ' x $count;
1763                         $line =~ s/\t/$spaces/;
1764                 }
1765         }
1766
1767         return $line;
1768 }
1769
1770 sub project_in_list {
1771         my $project = shift;
1772         my @list = git_get_projects_list();
1773         return @list && scalar(grep { $_->{'path'} eq $project } @list);
1774 }
1775
1776 ## ----------------------------------------------------------------------
1777 ## HTML aware string manipulation
1778
1779 # Try to chop given string on a word boundary between position
1780 # $len and $len+$add_len. If there is no word boundary there,
1781 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1782 # (marking chopped part) would be longer than given string.
1783 sub chop_str {
1784         my $str = shift;
1785         my $len = shift;
1786         my $add_len = shift || 10;
1787         my $where = shift || 'right'; # 'left' | 'center' | 'right'
1788
1789         # Make sure perl knows it is utf8 encoded so we don't
1790         # cut in the middle of a utf8 multibyte char.
1791         $str = to_utf8($str);
1792
1793         # allow only $len chars, but don't cut a word if it would fit in $add_len
1794         # if it doesn't fit, cut it if it's still longer than the dots we would add
1795         # remove chopped character entities entirely
1796
1797         # when chopping in the middle, distribute $len into left and right part
1798         # return early if chopping wouldn't make string shorter
1799         if ($where eq 'center') {
1800                 return $str if ($len + 5 >= length($str)); # filler is length 5
1801                 $len = int($len/2);
1802         } else {
1803                 return $str if ($len + 4 >= length($str)); # filler is length 4
1804         }
1805
1806         # regexps: ending and beginning with word part up to $add_len
1807         my $endre = qr/.{$len}\w{0,$add_len}/;
1808         my $begre = qr/\w{0,$add_len}.{$len}/;
1809
1810         if ($where eq 'left') {
1811                 $str =~ m/^(.*?)($begre)$/;
1812                 my ($lead, $body) = ($1, $2);
1813                 if (length($lead) > 4) {
1814                         $lead = " ...";
1815                 }
1816                 return "$lead$body";
1817
1818         } elsif ($where eq 'center') {
1819                 $str =~ m/^($endre)(.*)$/;
1820                 my ($left, $str)  = ($1, $2);
1821                 $str =~ m/^(.*?)($begre)$/;
1822                 my ($mid, $right) = ($1, $2);
1823                 if (length($mid) > 5) {
1824                         $mid = " ... ";
1825                 }
1826                 return "$left$mid$right";
1827
1828         } else {
1829                 $str =~ m/^($endre)(.*)$/;
1830                 my $body = $1;
1831                 my $tail = $2;
1832                 if (length($tail) > 4) {
1833                         $tail = "... ";
1834                 }
1835                 return "$body$tail";
1836         }
1837 }
1838
1839 # takes the same arguments as chop_str, but also wraps a <span> around the
1840 # result with a title attribute if it does get chopped. Additionally, the
1841 # string is HTML-escaped.
1842 sub chop_and_escape_str {
1843         my ($str) = @_;
1844
1845         my $chopped = chop_str(@_);
1846         $str = to_utf8($str);
1847         if ($chopped eq $str) {
1848                 return esc_html($chopped);
1849         } else {
1850                 $str =~ s/[[:cntrl:]]/?/g;
1851                 return $cgi->span({-title=>$str}, esc_html($chopped));
1852         }
1853 }
1854
1855 # Highlight selected fragments of string, using given CSS class,
1856 # and escape HTML.  It is assumed that fragments do not overlap.
1857 # Regions are passed as list of pairs (array references).
1858 #
1859 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1860 # '<span class="mark">foo</span>bar'
1861 sub esc_html_hl_regions {
1862         my ($str, $css_class, @sel) = @_;
1863         my %opts = grep { ref($_) ne 'ARRAY' } @sel;
1864         @sel     = grep { ref($_) eq 'ARRAY' } @sel;
1865         return esc_html($str, %opts) unless @sel;
1866
1867         my $out = '';
1868         my $pos = 0;
1869
1870         for my $s (@sel) {
1871                 my ($begin, $end) = @$s;
1872
1873                 # Don't create empty <span> elements.
1874                 next if $end <= $begin;
1875
1876                 my $escaped = esc_html(substr($str, $begin, $end - $begin),
1877                                        %opts);
1878
1879                 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
1880                         if ($begin - $pos > 0);
1881                 $out .= $cgi->span({-class => $css_class}, $escaped);
1882
1883                 $pos = $end;
1884         }
1885         $out .= esc_html(substr($str, $pos), %opts)
1886                 if ($pos < length($str));
1887
1888         return $out;
1889 }
1890
1891 # return positions of beginning and end of each match
1892 sub matchpos_list {
1893         my ($str, $regexp) = @_;
1894         return unless (defined $str && defined $regexp);
1895
1896         my @matches;
1897         while ($str =~ /$regexp/g) {
1898                 push @matches, [$-[0], $+[0]];
1899         }
1900         return @matches;
1901 }
1902
1903 # highlight match (if any), and escape HTML
1904 sub esc_html_match_hl {
1905         my ($str, $regexp) = @_;
1906         return esc_html($str) unless defined $regexp;
1907
1908         my @matches = matchpos_list($str, $regexp);
1909         return esc_html($str) unless @matches;
1910
1911         return esc_html_hl_regions($str, 'match', @matches);
1912 }
1913
1914
1915 # highlight match (if any) of shortened string, and escape HTML
1916 sub esc_html_match_hl_chopped {
1917         my ($str, $chopped, $regexp) = @_;
1918         return esc_html_match_hl($str, $regexp) unless defined $chopped;
1919
1920         my @matches = matchpos_list($str, $regexp);
1921         return esc_html($chopped) unless @matches;
1922
1923         # filter matches so that we mark chopped string
1924         my $tail = "... "; # see chop_str
1925         unless ($chopped =~ s/\Q$tail\E$//) {
1926                 $tail = '';
1927         }
1928         my $chop_len = length($chopped);
1929         my $tail_len = length($tail);
1930         my @filtered;
1931
1932         for my $m (@matches) {
1933                 if ($m->[0] > $chop_len) {
1934                         push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
1935                         last;
1936                 } elsif ($m->[1] > $chop_len) {
1937                         push @filtered, [ $m->[0], $chop_len + $tail_len ];
1938                         last;
1939                 }
1940                 push @filtered, $m;
1941         }
1942
1943         return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
1944 }
1945
1946 ## ----------------------------------------------------------------------
1947 ## functions returning short strings
1948
1949 # CSS class for given age value (in seconds)
1950 sub age_class {
1951         my $age = shift;
1952
1953         if (!defined $age) {
1954                 return "noage";
1955         } elsif ($age < 60*60*2) {
1956                 return "age0";
1957         } elsif ($age < 60*60*24*2) {
1958                 return "age1";
1959         } else {
1960                 return "age2";
1961         }
1962 }
1963
1964 # convert age in seconds to "nn units ago" string
1965 sub age_string {
1966         my $age = shift;
1967         my $age_str;
1968
1969         if ($age > 60*60*24*365*2) {
1970                 $age_str = (int $age/60/60/24/365);
1971                 $age_str .= " years ago";
1972         } elsif ($age > 60*60*24*(365/12)*2) {
1973                 $age_str = int $age/60/60/24/(365/12);
1974                 $age_str .= " months ago";
1975         } elsif ($age > 60*60*24*7*2) {
1976                 $age_str = int $age/60/60/24/7;
1977                 $age_str .= " weeks ago";
1978         } elsif ($age > 60*60*24*2) {
1979                 $age_str = int $age/60/60/24;
1980                 $age_str .= " days ago";
1981         } elsif ($age > 60*60*2) {
1982                 $age_str = int $age/60/60;
1983                 $age_str .= " hours ago";
1984         } elsif ($age > 60*2) {
1985                 $age_str = int $age/60;
1986                 $age_str .= " min ago";
1987         } elsif ($age > 2) {
1988                 $age_str = int $age;
1989                 $age_str .= " sec ago";
1990         } else {
1991                 $age_str .= " right now";
1992         }
1993         return $age_str;
1994 }
1995
1996 use constant {
1997         S_IFINVALID => 0030000,
1998         S_IFGITLINK => 0160000,
1999 };
2000
2001 # submodule/subproject, a commit object reference
2002 sub S_ISGITLINK {
2003         my $mode = shift;
2004
2005         return (($mode & S_IFMT) == S_IFGITLINK)
2006 }
2007
2008 # convert file mode in octal to symbolic file mode string
2009 sub mode_str {
2010         my $mode = oct shift;
2011
2012         if (S_ISGITLINK($mode)) {
2013                 return 'm---------';
2014         } elsif (S_ISDIR($mode & S_IFMT)) {
2015                 return 'drwxr-xr-x';
2016         } elsif (S_ISLNK($mode)) {
2017                 return 'lrwxrwxrwx';
2018         } elsif (S_ISREG($mode)) {
2019                 # git cares only about the executable bit
2020                 if ($mode & S_IXUSR) {
2021                         return '-rwxr-xr-x';
2022                 } else {
2023                         return '-rw-r--r--';
2024                 };
2025         } else {
2026                 return '----------';
2027         }
2028 }
2029
2030 # convert file mode in octal to file type string
2031 sub file_type {
2032         my $mode = shift;
2033
2034         if ($mode !~ m/^[0-7]+$/) {
2035                 return $mode;
2036         } else {
2037                 $mode = oct $mode;
2038         }
2039
2040         if (S_ISGITLINK($mode)) {
2041                 return "submodule";
2042         } elsif (S_ISDIR($mode & S_IFMT)) {
2043                 return "directory";
2044         } elsif (S_ISLNK($mode)) {
2045                 return "symlink";
2046         } elsif (S_ISREG($mode)) {
2047                 return "file";
2048         } else {
2049                 return "unknown";
2050         }
2051 }
2052
2053 # convert file mode in octal to file type description string
2054 sub file_type_long {
2055         my $mode = shift;
2056
2057         if ($mode !~ m/^[0-7]+$/) {
2058                 return $mode;
2059         } else {
2060                 $mode = oct $mode;
2061         }
2062
2063         if (S_ISGITLINK($mode)) {
2064                 return "submodule";
2065         } elsif (S_ISDIR($mode & S_IFMT)) {
2066                 return "directory";
2067         } elsif (S_ISLNK($mode)) {
2068                 return "symlink";
2069         } elsif (S_ISREG($mode)) {
2070                 if ($mode & S_IXUSR) {
2071                         return "executable";
2072                 } else {
2073                         return "file";
2074                 };
2075         } else {
2076                 return "unknown";
2077         }
2078 }
2079
2080
2081 ## ----------------------------------------------------------------------
2082 ## functions returning short HTML fragments, or transforming HTML fragments
2083 ## which don't belong to other sections
2084
2085 # format line of commit message.
2086 sub format_log_line_html {
2087         my $line = shift;
2088
2089         # Potentially abbreviated OID.
2090         my $regex = oid_nlen_regex("7,64");
2091
2092         $line = esc_html($line, -nbsp=>1);
2093         $line =~ s{
2094         \b
2095         (
2096             # The output of "git describe", e.g. v2.10.0-297-gf6727b0
2097             # or hadoop-20160921-113441-20-g094fb7d
2098             (?<!-) # see check_tag_ref(). Tags can't start with -
2099             [A-Za-z0-9.-]+
2100             (?!\.) # refs can't end with ".", see check_refname_format()
2101             -g$regex
2102             |
2103             # Just a normal looking Git SHA1
2104             $regex
2105         )
2106         \b
2107     }{
2108                 $cgi->a({-href => href(action=>"object", hash=>$1),
2109                                         -class => "text"}, $1);
2110         }egx;
2111
2112         return $line;
2113 }
2114
2115 # format marker of refs pointing to given object
2116
2117 # the destination action is chosen based on object type and current context:
2118 # - for annotated tags, we choose the tag view unless it's the current view
2119 #   already, in which case we go to shortlog view
2120 # - for other refs, we keep the current view if we're in history, shortlog or
2121 #   log view, and select shortlog otherwise
2122 sub format_ref_marker {
2123         my ($refs, $id) = @_;
2124         my $markers = '';
2125
2126         if (defined $refs->{$id}) {
2127                 foreach my $ref (@{$refs->{$id}}) {
2128                         # this code exploits the fact that non-lightweight tags are the
2129                         # only indirect objects, and that they are the only objects for which
2130                         # we want to use tag instead of shortlog as action
2131                         my ($type, $name) = qw();
2132                         my $indirect = ($ref =~ s/\^\{\}$//);
2133                         # e.g. tags/v2.6.11 or heads/next
2134                         if ($ref =~ m!^(.*?)s?/(.*)$!) {
2135                                 $type = $1;
2136                                 $name = $2;
2137                         } else {
2138                                 $type = "ref";
2139                                 $name = $ref;
2140                         }
2141
2142                         my $class = $type;
2143                         $class .= " indirect" if $indirect;
2144
2145                         my $dest_action = "shortlog";
2146
2147                         if ($indirect) {
2148                                 $dest_action = "tag" unless $action eq "tag";
2149                         } elsif ($action =~ /^(history|(short)?log)$/) {
2150                                 $dest_action = $action;
2151                         }
2152
2153                         my $dest = "";
2154                         $dest .= "refs/" unless $ref =~ m!^refs/!;
2155                         $dest .= $ref;
2156
2157                         my $link = $cgi->a({
2158                                 -href => href(
2159                                         action=>$dest_action,
2160                                         hash=>$dest
2161                                 )}, esc_html($name));
2162
2163                         $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2164                                 $link . "</span>";
2165                 }
2166         }
2167
2168         if ($markers) {
2169                 return ' <span class="refs">'. $markers . '</span>';
2170         } else {
2171                 return "";
2172         }
2173 }
2174
2175 # format, perhaps shortened and with markers, title line
2176 sub format_subject_html {
2177         my ($long, $short, $href, $extra) = @_;
2178         $extra = '' unless defined($extra);
2179
2180         if (length($short) < length($long)) {
2181                 $long =~ s/[[:cntrl:]]/?/g;
2182                 return $cgi->a({-href => $href, -class => "list subject",
2183                                 -title => to_utf8($long)},
2184                        esc_html($short)) . $extra;
2185         } else {
2186                 return $cgi->a({-href => $href, -class => "list subject"},
2187                        esc_html($long)) . $extra;
2188         }
2189 }
2190
2191 # Rather than recomputing the url for an email multiple times, we cache it
2192 # after the first hit. This gives a visible benefit in views where the avatar
2193 # for the same email is used repeatedly (e.g. shortlog).
2194 # The cache is shared by all avatar engines (currently gravatar only), which
2195 # are free to use it as preferred. Since only one avatar engine is used for any
2196 # given page, there's no risk for cache conflicts.
2197 our %avatar_cache = ();
2198
2199 # Compute the picon url for a given email, by using the picon search service over at
2200 # http://www.cs.indiana.edu/picons/search.html
2201 sub picon_url {
2202         my $email = lc shift;
2203         if (!$avatar_cache{$email}) {
2204                 my ($user, $domain) = split('@', $email);
2205                 $avatar_cache{$email} =
2206                         "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2207                         "$domain/$user/" .
2208                         "users+domains+unknown/up/single";
2209         }
2210         return $avatar_cache{$email};
2211 }
2212
2213 # Compute the gravatar url for a given email, if it's not in the cache already.
2214 # Gravatar stores only the part of the URL before the size, since that's the
2215 # one computationally more expensive. This also allows reuse of the cache for
2216 # different sizes (for this particular engine).
2217 sub gravatar_url {
2218         my $email = lc shift;
2219         my $size = shift;
2220         $avatar_cache{$email} ||=
2221                 "//www.gravatar.com/avatar/" .
2222                         md5_hex($email) . "?s=";
2223         return $avatar_cache{$email} . $size;
2224 }
2225
2226 # Insert an avatar for the given $email at the given $size if the feature
2227 # is enabled.
2228 sub git_get_avatar {
2229         my ($email, %opts) = @_;
2230         my $pre_white  = ($opts{-pad_before} ? "&nbsp;" : "");
2231         my $post_white = ($opts{-pad_after}  ? "&nbsp;" : "");
2232         $opts{-size} ||= 'default';
2233         my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2234         my $url = "";
2235         if ($git_avatar eq 'gravatar') {
2236                 $url = gravatar_url($email, $size);
2237         } elsif ($git_avatar eq 'picon') {
2238                 $url = picon_url($email);
2239         }
2240         # Other providers can be added by extending the if chain, defining $url
2241         # as needed. If no variant puts something in $url, we assume avatars
2242         # are completely disabled/unavailable.
2243         if ($url) {
2244                 return $pre_white .
2245                        "<img width=\"$size\" " .
2246                             "class=\"avatar\" " .
2247                             "src=\"".esc_url($url)."\" " .
2248                             "alt=\"\" " .
2249                        "/>" . $post_white;
2250         } else {
2251                 return "";
2252         }
2253 }
2254
2255 sub format_search_author {
2256         my ($author, $searchtype, $displaytext) = @_;
2257         my $have_search = gitweb_check_feature('search');
2258
2259         if ($have_search) {
2260                 my $performed = "";
2261                 if ($searchtype eq 'author') {
2262                         $performed = "authored";
2263                 } elsif ($searchtype eq 'committer') {
2264                         $performed = "committed";
2265                 }
2266
2267                 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2268                                 searchtext=>$author,
2269                                 searchtype=>$searchtype), class=>"list",
2270                                 title=>"Search for commits $performed by $author"},
2271                                 $displaytext);
2272
2273         } else {
2274                 return $displaytext;
2275         }
2276 }
2277
2278 # format the author name of the given commit with the given tag
2279 # the author name is chopped and escaped according to the other
2280 # optional parameters (see chop_str).
2281 sub format_author_html {
2282         my $tag = shift;
2283         my $co = shift;
2284         my $author = chop_and_escape_str($co->{'author_name'}, @_);
2285         return "<$tag class=\"author\">" .
2286                format_search_author($co->{'author_name'}, "author",
2287                        git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2288                        $author) .
2289                "</$tag>";
2290 }
2291
2292 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2293 sub format_git_diff_header_line {
2294         my $line = shift;
2295         my $diffinfo = shift;
2296         my ($from, $to) = @_;
2297
2298         if ($diffinfo->{'nparents'}) {
2299                 # combined diff
2300                 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2301                 if ($to->{'href'}) {
2302                         $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2303                                          esc_path($to->{'file'}));
2304                 } else { # file was deleted (no href)
2305                         $line .= esc_path($to->{'file'});
2306                 }
2307         } else {
2308                 # "ordinary" diff
2309                 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2310                 if ($from->{'href'}) {
2311                         $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2312                                          'a/' . esc_path($from->{'file'}));
2313                 } else { # file was added (no href)
2314                         $line .= 'a/' . esc_path($from->{'file'});
2315                 }
2316                 $line .= ' ';
2317                 if ($to->{'href'}) {
2318                         $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2319                                          'b/' . esc_path($to->{'file'}));
2320                 } else { # file was deleted
2321                         $line .= 'b/' . esc_path($to->{'file'});
2322                 }
2323         }
2324
2325         return "<div class=\"diff header\">$line</div>\n";
2326 }
2327
2328 # format extended diff header line, before patch itself
2329 sub format_extended_diff_header_line {
2330         my $line = shift;
2331         my $diffinfo = shift;
2332         my ($from, $to) = @_;
2333
2334         # match <path>
2335         if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2336                 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2337                                        esc_path($from->{'file'}));
2338         }
2339         if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2340                 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2341                                  esc_path($to->{'file'}));
2342         }
2343         # match single <mode>
2344         if ($line =~ m/\s(\d{6})$/) {
2345                 $line .= '<span class="info"> (' .
2346                          file_type_long($1) .
2347                          ')</span>';
2348         }
2349         # match <hash>
2350         if ($line =~ oid_nlen_prefix_infix_regex($sha1_len, "index ", ",") |
2351             $line =~ oid_nlen_prefix_infix_regex($sha256_len, "index ", ",")) {
2352                 # can match only for combined diff
2353                 $line = 'index ';
2354                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2355                         if ($from->{'href'}[$i]) {
2356                                 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2357                                                   -class=>"hash"},
2358                                                  substr($diffinfo->{'from_id'}[$i],0,7));
2359                         } else {
2360                                 $line .= '0' x 7;
2361                         }
2362                         # separator
2363                         $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2364                 }
2365                 $line .= '..';
2366                 if ($to->{'href'}) {
2367                         $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2368                                          substr($diffinfo->{'to_id'},0,7));
2369                 } else {
2370                         $line .= '0' x 7;
2371                 }
2372
2373         } elsif ($line =~ oid_nlen_prefix_infix_regex($sha1_len, "index ", "..") |
2374                  $line =~ oid_nlen_prefix_infix_regex($sha256_len, "index ", "..")) {
2375                 # can match only for ordinary diff
2376                 my ($from_link, $to_link);
2377                 if ($from->{'href'}) {
2378                         $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2379                                              substr($diffinfo->{'from_id'},0,7));
2380                 } else {
2381                         $from_link = '0' x 7;
2382                 }
2383                 if ($to->{'href'}) {
2384                         $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2385                                            substr($diffinfo->{'to_id'},0,7));
2386                 } else {
2387                         $to_link = '0' x 7;
2388                 }
2389                 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2390                 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2391         }
2392
2393         return $line . "<br/>\n";
2394 }
2395
2396 # format from-file/to-file diff header
2397 sub format_diff_from_to_header {
2398         my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2399         my $line;
2400         my $result = '';
2401
2402         $line = $from_line;
2403         #assert($line =~ m/^---/) if DEBUG;
2404         # no extra formatting for "^--- /dev/null"
2405         if (! $diffinfo->{'nparents'}) {
2406                 # ordinary (single parent) diff
2407                 if ($line =~ m!^--- "?a/!) {
2408                         if ($from->{'href'}) {
2409                                 $line = '--- a/' .
2410                                         $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2411                                                 esc_path($from->{'file'}));
2412                         } else {
2413                                 $line = '--- a/' .
2414                                         esc_path($from->{'file'});
2415                         }
2416                 }
2417                 $result .= qq!<div class="diff from_file">$line</div>\n!;
2418
2419         } else {
2420                 # combined diff (merge commit)
2421                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2422                         if ($from->{'href'}[$i]) {
2423                                 $line = '--- ' .
2424                                         $cgi->a({-href=>href(action=>"blobdiff",
2425                                                              hash_parent=>$diffinfo->{'from_id'}[$i],
2426                                                              hash_parent_base=>$parents[$i],
2427                                                              file_parent=>$from->{'file'}[$i],
2428                                                              hash=>$diffinfo->{'to_id'},
2429                                                              hash_base=>$hash,
2430                                                              file_name=>$to->{'file'}),
2431                                                  -class=>"path",
2432                                                  -title=>"diff" . ($i+1)},
2433                                                 $i+1) .
2434                                         '/' .
2435                                         $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2436                                                 esc_path($from->{'file'}[$i]));
2437                         } else {
2438                                 $line = '--- /dev/null';
2439                         }
2440                         $result .= qq!<div class="diff from_file">$line</div>\n!;
2441                 }
2442         }
2443
2444         $line = $to_line;
2445         #assert($line =~ m/^\+\+\+/) if DEBUG;
2446         # no extra formatting for "^+++ /dev/null"
2447         if ($line =~ m!^\+\+\+ "?b/!) {
2448                 if ($to->{'href'}) {
2449                         $line = '+++ b/' .
2450                                 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2451                                         esc_path($to->{'file'}));
2452                 } else {
2453                         $line = '+++ b/' .
2454                                 esc_path($to->{'file'});
2455                 }
2456         }
2457         $result .= qq!<div class="diff to_file">$line</div>\n!;
2458
2459         return $result;
2460 }
2461
2462 # create note for patch simplified by combined diff
2463 sub format_diff_cc_simplified {
2464         my ($diffinfo, @parents) = @_;
2465         my $result = '';
2466
2467         $result .= "<div class=\"diff header\">" .
2468                    "diff --cc ";
2469         if (!is_deleted($diffinfo)) {
2470                 $result .= $cgi->a({-href => href(action=>"blob",
2471                                                   hash_base=>$hash,
2472                                                   hash=>$diffinfo->{'to_id'},
2473                                                   file_name=>$diffinfo->{'to_file'}),
2474                                     -class => "path"},
2475                                    esc_path($diffinfo->{'to_file'}));
2476         } else {
2477                 $result .= esc_path($diffinfo->{'to_file'});
2478         }
2479         $result .= "</div>\n" . # class="diff header"
2480                    "<div class=\"diff nodifferences\">" .
2481                    "Simple merge" .
2482                    "</div>\n"; # class="diff nodifferences"
2483
2484         return $result;
2485 }
2486
2487 sub diff_line_class {
2488         my ($line, $from, $to) = @_;
2489
2490         # ordinary diff
2491         my $num_sign = 1;
2492         # combined diff
2493         if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2494                 $num_sign = scalar @{$from->{'href'}};
2495         }
2496
2497         my @diff_line_classifier = (
2498                 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2499                 { regexp => qr/^\\/,               class => "incomplete"  },
2500                 { regexp => qr/^ {$num_sign}/,     class => "ctx" },
2501                 # classifier for context must come before classifier add/rem,
2502                 # or we would have to use more complicated regexp, for example
2503                 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2504                 { regexp => qr/^[+ ]{$num_sign}/,   class => "add" },
2505                 { regexp => qr/^[- ]{$num_sign}/,   class => "rem" },
2506         );
2507         for my $clsfy (@diff_line_classifier) {
2508                 return $clsfy->{'class'}
2509                         if ($line =~ $clsfy->{'regexp'});
2510         }
2511
2512         # fallback
2513         return "";
2514 }
2515
2516 # assumes that $from and $to are defined and correctly filled,
2517 # and that $line holds a line of chunk header for unified diff
2518 sub format_unidiff_chunk_header {
2519         my ($line, $from, $to) = @_;
2520
2521         my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2522                 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2523
2524         $from_lines = 0 unless defined $from_lines;
2525         $to_lines   = 0 unless defined $to_lines;
2526
2527         if ($from->{'href'}) {
2528                 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2529                                      -class=>"list"}, $from_text);
2530         }
2531         if ($to->{'href'}) {
2532                 $to_text   = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2533                                      -class=>"list"}, $to_text);
2534         }
2535         $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2536                 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2537         return $line;
2538 }
2539
2540 # assumes that $from and $to are defined and correctly filled,
2541 # and that $line holds a line of chunk header for combined diff
2542 sub format_cc_diff_chunk_header {
2543         my ($line, $from, $to) = @_;
2544
2545         my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2546         my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2547
2548         @from_text = split(' ', $ranges);
2549         for (my $i = 0; $i < @from_text; ++$i) {
2550                 ($from_start[$i], $from_nlines[$i]) =
2551                         (split(',', substr($from_text[$i], 1)), 0);
2552         }
2553
2554         $to_text   = pop @from_text;
2555         $to_start  = pop @from_start;
2556         $to_nlines = pop @from_nlines;
2557
2558         $line = "<span class=\"chunk_info\">$prefix ";
2559         for (my $i = 0; $i < @from_text; ++$i) {
2560                 if ($from->{'href'}[$i]) {
2561                         $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2562                                           -class=>"list"}, $from_text[$i]);
2563                 } else {
2564                         $line .= $from_text[$i];
2565                 }
2566                 $line .= " ";
2567         }
2568         if ($to->{'href'}) {
2569                 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2570                                   -class=>"list"}, $to_text);
2571         } else {
2572                 $line .= $to_text;
2573         }
2574         $line .= " $prefix</span>" .
2575                  "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2576         return $line;
2577 }
2578
2579 # process patch (diff) line (not to be used for diff headers),
2580 # returning HTML-formatted (but not wrapped) line.
2581 # If the line is passed as a reference, it is treated as HTML and not
2582 # esc_html()'ed.
2583 sub format_diff_line {
2584         my ($line, $diff_class, $from, $to) = @_;
2585
2586         if (ref($line)) {
2587                 $line = $$line;
2588         } else {
2589                 chomp $line;
2590                 $line = untabify($line);
2591
2592                 if ($from && $to && $line =~ m/^\@{2} /) {
2593                         $line = format_unidiff_chunk_header($line, $from, $to);
2594                 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2595                         $line = format_cc_diff_chunk_header($line, $from, $to);
2596                 } else {
2597                         $line = esc_html($line, -nbsp=>1);
2598                 }
2599         }
2600
2601         my $diff_classes = "diff";
2602         $diff_classes .= " $diff_class" if ($diff_class);
2603         $line = "<div class=\"$diff_classes\">$line</div>\n";
2604
2605         return $line;
2606 }
2607
2608 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2609 # linked.  Pass the hash of the tree/commit to snapshot.
2610 sub format_snapshot_links {
2611         my ($hash) = @_;
2612         my $num_fmts = @snapshot_fmts;
2613         if ($num_fmts > 1) {
2614                 # A parenthesized list of links bearing format names.
2615                 # e.g. "snapshot (_tar.gz_ _zip_)"
2616                 return "snapshot (" . join(' ', map
2617                         $cgi->a({
2618                                 -href => href(
2619                                         action=>"snapshot",
2620                                         hash=>$hash,
2621                                         snapshot_format=>$_
2622                                 )
2623                         }, $known_snapshot_formats{$_}{'display'})
2624                 , @snapshot_fmts) . ")";
2625         } elsif ($num_fmts == 1) {
2626                 # A single "snapshot" link whose tooltip bears the format name.
2627                 # i.e. "_snapshot_"
2628                 my ($fmt) = @snapshot_fmts;
2629                 return
2630                         $cgi->a({
2631                                 -href => href(
2632                                         action=>"snapshot",
2633                                         hash=>$hash,
2634                                         snapshot_format=>$fmt
2635                                 ),
2636                                 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2637                         }, "snapshot");
2638         } else { # $num_fmts == 0
2639                 return undef;
2640         }
2641 }
2642
2643 ## ......................................................................
2644 ## functions returning values to be passed, perhaps after some
2645 ## transformation, to other functions; e.g. returning arguments to href()
2646
2647 # returns hash to be passed to href to generate gitweb URL
2648 # in -title key it returns description of link
2649 sub get_feed_info {
2650         my $format = shift || 'Atom';
2651         my %res = (action => lc($format));
2652         my $matched_ref = 0;
2653
2654         # feed links are possible only for project views
2655         return unless (defined $project);
2656         # some views should link to OPML, or to generic project feed,
2657         # or don't have specific feed yet (so they should use generic)
2658         return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2659
2660         my $branch = undef;
2661         # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2662         # (fullname) to differentiate from tag links; this also makes
2663         # possible to detect branch links
2664         for my $ref (get_branch_refs()) {
2665                 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2666                     (defined $hash      && $hash      =~ m!^refs/\Q$ref\E/(.*)$!)) {
2667                         $branch = $1;
2668                         $matched_ref = $ref;
2669                         last;
2670                 }
2671         }
2672         # find log type for feed description (title)
2673         my $type = 'log';
2674         if (defined $file_name) {
2675                 $type  = "history of $file_name";
2676                 $type .= "/" if ($action eq 'tree');
2677                 $type .= " on '$branch'" if (defined $branch);
2678         } else {
2679                 $type = "log of $branch" if (defined $branch);
2680         }
2681
2682         $res{-title} = $type;
2683         $res{'hash'} = (defined $branch ? "refs/$matched_ref/$branch" : undef);
2684         $res{'file_name'} = $file_name;
2685
2686         return %res;
2687 }
2688
2689 ## ----------------------------------------------------------------------
2690 ## git utility subroutines, invoking git commands
2691
2692 # returns path to the core git executable and the --git-dir parameter as list
2693 sub git_cmd {
2694         $number_of_git_cmds++;
2695         return $GIT, '--git-dir='.$git_dir;
2696 }
2697
2698 # quote the given arguments for passing them to the shell
2699 # quote_command("command", "arg 1", "arg with ' and ! characters")
2700 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2701 # Try to avoid using this function wherever possible.
2702 sub quote_command {
2703         return join(' ',
2704                 map { my $a = $_ =~ s/(['!])/'\\$1'/gr; "'$a'" } @_ );
2705 }
2706
2707 # get HEAD ref of given project as hash
2708 sub git_get_head_hash {
2709         return git_get_full_hash(shift, 'HEAD');
2710 }
2711
2712 sub git_get_full_hash {
2713         return git_get_hash(@_);
2714 }
2715
2716 sub git_get_short_hash {
2717         return git_get_hash(@_, '--short=7');
2718 }
2719
2720 sub git_get_hash {
2721         my ($project, $hash, @options) = @_;
2722         my $o_git_dir = $git_dir;
2723         my $retval = undef;
2724         $git_dir = "$projectroot/$project";
2725         if (open my $fd, '-|', git_cmd(), 'rev-parse',
2726             '--verify', '-q', @options, $hash) {
2727                 $retval = <$fd>;
2728                 chomp $retval if defined $retval;
2729                 close $fd;
2730         }
2731         if (defined $o_git_dir) {
2732                 $git_dir = $o_git_dir;
2733         }
2734         return $retval;
2735 }
2736
2737 # get type of given object
2738 sub git_get_type {
2739         my $hash = shift;
2740
2741         open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2742         my $type = <$fd>;
2743         close $fd or return;
2744         chomp $type;
2745         return $type;
2746 }
2747
2748 # repository configuration
2749 our $config_file = '';
2750 our %config;
2751
2752 # store multiple values for single key as anonymous array reference
2753 # single values stored directly in the hash, not as [ <value> ]
2754 sub hash_set_multi {
2755         my ($hash, $key, $value) = @_;
2756
2757         if (!exists $hash->{$key}) {
2758                 $hash->{$key} = $value;
2759         } elsif (!ref $hash->{$key}) {
2760                 $hash->{$key} = [ $hash->{$key}, $value ];
2761         } else {
2762                 push @{$hash->{$key}}, $value;
2763         }
2764 }
2765
2766 # return hash of git project configuration
2767 # optionally limited to some section, e.g. 'gitweb'
2768 sub git_parse_project_config {
2769         my $section_regexp = shift;
2770         my %config;
2771
2772         local $/ = "\0";
2773
2774         open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2775                 or return;
2776
2777         while (my $keyval = <$fh>) {
2778                 chomp $keyval;
2779                 my ($key, $value) = split(/\n/, $keyval, 2);
2780
2781                 hash_set_multi(\%config, $key, $value)
2782                         if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2783         }
2784         close $fh;
2785
2786         return %config;
2787 }
2788
2789 # convert config value to boolean: 'true' or 'false'
2790 # no value, number > 0, 'true' and 'yes' values are true
2791 # rest of values are treated as false (never as error)
2792 sub config_to_bool {
2793         my $val = shift;
2794
2795         return 1 if !defined $val;             # section.key
2796
2797         # strip leading and trailing whitespace
2798         $val =~ s/^\s+//;
2799         $val =~ s/\s+$//;
2800
2801         return (($val =~ /^\d+$/ && $val) ||   # section.key = 1
2802                 ($val =~ /^(?:true|yes)$/i));  # section.key = true
2803 }
2804
2805 # convert config value to simple decimal number
2806 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2807 # to be multiplied by 1024, 1048576, or 1073741824
2808 sub config_to_int {
2809         my $val = shift;
2810
2811         # strip leading and trailing whitespace
2812         $val =~ s/^\s+//;
2813         $val =~ s/\s+$//;
2814
2815         if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2816                 $unit = lc($unit);
2817                 # unknown unit is treated as 1
2818                 return $num * ($unit eq 'g' ? 1073741824 :
2819                                $unit eq 'm' ?    1048576 :
2820                                $unit eq 'k' ?       1024 : 1);
2821         }
2822         return $val;
2823 }
2824
2825 # convert config value to array reference, if needed
2826 sub config_to_multi {
2827         my $val = shift;
2828
2829         return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2830 }
2831
2832 sub git_get_project_config {
2833         my ($key, $type) = @_;
2834
2835         return unless defined $git_dir;
2836
2837         # key sanity check
2838         return unless ($key);
2839         # only subsection, if exists, is case sensitive,
2840         # and not lowercased by 'git config -z -l'
2841         if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2842                 $lo =~ s/_//g;
2843                 $key = join(".", lc($hi), $mi, lc($lo));
2844                 return if ($lo =~ /\W/ || $hi =~ /\W/);
2845         } else {
2846                 $key = lc($key);
2847                 $key =~ s/_//g;
2848                 return if ($key =~ /\W/);
2849         }
2850         $key =~ s/^gitweb\.//;
2851
2852         # type sanity check
2853         if (defined $type) {
2854                 $type =~ s/^--//;
2855                 $type = undef
2856                         unless ($type eq 'bool' || $type eq 'int');
2857         }
2858
2859         # get config
2860         if (!defined $config_file ||
2861             $config_file ne "$git_dir/config") {
2862                 %config = git_parse_project_config('gitweb');
2863                 $config_file = "$git_dir/config";
2864         }
2865
2866         # check if config variable (key) exists
2867         return unless exists $config{"gitweb.$key"};
2868
2869         # ensure given type
2870         if (!defined $type) {
2871                 return $config{"gitweb.$key"};
2872         } elsif ($type eq 'bool') {
2873                 # backward compatibility: 'git config --bool' returns true/false
2874                 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2875         } elsif ($type eq 'int') {
2876                 return config_to_int($config{"gitweb.$key"});
2877         }
2878         return $config{"gitweb.$key"};
2879 }
2880
2881 # get hash of given path at given ref
2882 sub git_get_hash_by_path {
2883         my $base = shift;
2884         my $path = shift || return undef;
2885         my $type = shift;
2886
2887         $path =~ s,/+$,,;
2888
2889         open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2890                 or die_error(500, "Open git-ls-tree failed");
2891         my $line = <$fd>;
2892         close $fd or return undef;
2893
2894         if (!defined $line) {
2895                 # there is no tree or hash given by $path at $base
2896                 return undef;
2897         }
2898
2899         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
2900         $line =~ m/^([0-9]+) (.+) ($oid_regex)\t/;
2901         if (defined $type && $type ne $2) {
2902                 # type doesn't match
2903                 return undef;
2904         }
2905         return $3;
2906 }
2907
2908 # get path of entry with given hash at given tree-ish (ref)
2909 # used to get 'from' filename for combined diff (merge commit) for renames
2910 sub git_get_path_by_hash {
2911         my $base = shift || return;
2912         my $hash = shift || return;
2913
2914         local $/ = "\0";
2915
2916         open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2917                 or return undef;
2918         while (my $line = <$fd>) {
2919                 chomp $line;
2920
2921                 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423  gitweb'
2922                 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f  gitweb/README'
2923                 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2924                         close $fd;
2925                         return $1;
2926                 }
2927         }
2928         close $fd;
2929         return undef;
2930 }
2931
2932 ## ......................................................................
2933 ## git utility functions, directly accessing git repository
2934
2935 # get the value of config variable either from file named as the variable
2936 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2937 # configuration variable in the repository config file.
2938 sub git_get_file_or_project_config {
2939         my ($path, $name) = @_;
2940
2941         $git_dir = "$projectroot/$path";
2942         open my $fd, '<', "$git_dir/$name"
2943                 or return git_get_project_config($name);
2944         my $conf = <$fd>;
2945         close $fd;
2946         if (defined $conf) {
2947                 chomp $conf;
2948         }
2949         return $conf;
2950 }
2951
2952 sub git_get_project_description {
2953         my $path = shift;
2954         return git_get_file_or_project_config($path, 'description');
2955 }
2956
2957 sub git_get_project_category {
2958         my $path = shift;
2959         return git_get_file_or_project_config($path, 'category');
2960 }
2961
2962
2963 # supported formats:
2964 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2965 #   - if its contents is a number, use it as tag weight,
2966 #   - otherwise add a tag with weight 1
2967 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2968 #   the same value multiple times increases tag weight
2969 # * `gitweb.ctag' multi-valued repo config variable
2970 sub git_get_project_ctags {
2971         my $project = shift;
2972         my $ctags = {};
2973
2974         $git_dir = "$projectroot/$project";
2975         if (opendir my $dh, "$git_dir/ctags") {
2976                 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2977                 foreach my $tagfile (@files) {
2978                         open my $ct, '<', $tagfile
2979                                 or next;
2980                         my $val = <$ct>;
2981                         chomp $val if $val;
2982                         close $ct;
2983
2984                         (my $ctag = $tagfile) =~ s#.*/##;
2985                         if ($val =~ /^\d+$/) {
2986                                 $ctags->{$ctag} = $val;
2987                         } else {
2988                                 $ctags->{$ctag} = 1;
2989                         }
2990                 }
2991                 closedir $dh;
2992
2993         } elsif (open my $fh, '<', "$git_dir/ctags") {
2994                 while (my $line = <$fh>) {
2995                         chomp $line;
2996                         $ctags->{$line}++ if $line;
2997                 }
2998                 close $fh;
2999
3000         } else {
3001                 my $taglist = config_to_multi(git_get_project_config('ctag'));
3002                 foreach my $tag (@$taglist) {
3003                         $ctags->{$tag}++;
3004                 }
3005         }
3006
3007         return $ctags;
3008 }
3009
3010 # return hash, where keys are content tags ('ctags'),
3011 # and values are sum of weights of given tag in every project
3012 sub git_gather_all_ctags {
3013         my $projects = shift;
3014         my $ctags = {};
3015
3016         foreach my $p (@$projects) {
3017                 foreach my $ct (keys %{$p->{'ctags'}}) {
3018                         $ctags->{$ct} += $p->{'ctags'}->{$ct};
3019                 }
3020         }
3021
3022         return $ctags;
3023 }
3024
3025 sub git_populate_project_tagcloud {
3026         my $ctags = shift;
3027
3028         # First, merge different-cased tags; tags vote on casing
3029         my %ctags_lc;
3030         foreach (keys %$ctags) {
3031                 $ctags_lc{lc $_}->{count} += $ctags->{$_};
3032                 if (not $ctags_lc{lc $_}->{topcount}
3033                     or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
3034                         $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
3035                         $ctags_lc{lc $_}->{topname} = $_;
3036                 }
3037         }
3038
3039         my $cloud;
3040         my $matched = $input_params{'ctag'};
3041         if (eval { require HTML::TagCloud; 1; }) {
3042                 $cloud = HTML::TagCloud->new;
3043                 foreach my $ctag (sort keys %ctags_lc) {
3044                         # Pad the title with spaces so that the cloud looks
3045                         # less crammed.
3046                         my $title = esc_html($ctags_lc{$ctag}->{topname});
3047                         $title =~ s/ /&nbsp;/g;
3048                         $title =~ s/^/&nbsp;/g;
3049                         $title =~ s/$/&nbsp;/g;
3050                         if (defined $matched && $matched eq $ctag) {
3051                                 $title = qq(<span class="match">$title</span>);
3052                         }
3053                         $cloud->add($title, href(project=>undef, ctag=>$ctag),
3054                                     $ctags_lc{$ctag}->{count});
3055                 }
3056         } else {
3057                 $cloud = {};
3058                 foreach my $ctag (keys %ctags_lc) {
3059                         my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
3060                         if (defined $matched && $matched eq $ctag) {
3061                                 $title = qq(<span class="match">$title</span>);
3062                         }
3063                         $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
3064                         $cloud->{$ctag}{ctag} =
3065                                 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
3066                 }
3067         }
3068         return $cloud;
3069 }
3070
3071 sub git_show_project_tagcloud {
3072         my ($cloud, $count) = @_;
3073         if (ref $cloud eq 'HTML::TagCloud') {
3074                 return $cloud->html_and_css($count);
3075         } else {
3076                 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3077                 return
3078                         '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3079                         join (', ', map {
3080                                 $cloud->{$_}->{'ctag'}
3081                         } splice(@tags, 0, $count)) .
3082                         '</div>';
3083         }
3084 }
3085
3086 sub git_get_project_url_list {
3087         my $path = shift;
3088
3089         $git_dir = "$projectroot/$path";
3090         open my $fd, '<', "$git_dir/cloneurl"
3091                 or return wantarray ?
3092                 @{ config_to_multi(git_get_project_config('url')) } :
3093                    config_to_multi(git_get_project_config('url'));
3094         my @git_project_url_list = map { chomp; $_ } <$fd>;
3095         close $fd;
3096
3097         return wantarray ? @git_project_url_list : \@git_project_url_list;
3098 }
3099
3100 sub git_get_projects_list {
3101         my $filter = shift || '';
3102         my $paranoid = shift;
3103         my @list;
3104
3105         if (-d $projects_list) {
3106                 # search in directory
3107                 my $dir = $projects_list;
3108                 # remove the trailing "/"
3109                 $dir =~ s!/+$!!;
3110                 my $pfxlen = length("$dir");
3111                 my $pfxdepth = ($dir =~ tr!/!!);
3112                 # when filtering, search only given subdirectory
3113                 if ($filter && !$paranoid) {
3114                         $dir .= "/$filter";
3115                         $dir =~ s!/+$!!;
3116                 }
3117
3118                 File::Find::find({
3119                         follow_fast => 1, # follow symbolic links
3120                         follow_skip => 2, # ignore duplicates
3121                         dangling_symlinks => 0, # ignore dangling symlinks, silently
3122                         wanted => sub {
3123                                 # global variables
3124                                 our $project_maxdepth;
3125                                 our $projectroot;
3126                                 # skip project-list toplevel, if we get it.
3127                                 return if (m!^[/.]$!);
3128                                 # only directories can be git repositories
3129                                 return unless (-d $_);
3130                                 # need search permission
3131                                 return unless (-x $_);
3132                                 # don't traverse too deep (Find is super slow on os x)
3133                                 # $project_maxdepth excludes depth of $projectroot
3134                                 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3135                                         $File::Find::prune = 1;
3136                                         return;
3137                                 }
3138
3139                                 my $path = substr($File::Find::name, $pfxlen + 1);
3140                                 # paranoidly only filter here
3141                                 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3142                                         next;
3143                                 }
3144                                 # we check related file in $projectroot
3145                                 if (check_export_ok("$projectroot/$path")) {
3146                                         push @list, { path => $path };
3147                                         $File::Find::prune = 1;
3148                                 }
3149                         },
3150                 }, "$dir");
3151
3152         } elsif (-f $projects_list) {
3153                 # read from file(url-encoded):
3154                 # 'git%2Fgit.git Linus+Torvalds'
3155                 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3156                 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3157                 open my $fd, '<', $projects_list or return;
3158         PROJECT:
3159                 while (my $line = <$fd>) {
3160                         chomp $line;
3161                         my ($path, $owner) = split ' ', $line;
3162                         $path = unescape($path);
3163                         $owner = unescape($owner);
3164                         if (!defined $path) {
3165                                 next;
3166                         }
3167                         # if $filter is rpovided, check if $path begins with $filter
3168                         if ($filter && $path !~ m!^\Q$filter\E/!) {
3169                                 next;
3170                         }
3171                         if (check_export_ok("$projectroot/$path")) {
3172                                 my $pr = {
3173                                         path => $path
3174                                 };
3175                                 if ($owner) {
3176                                         $pr->{'owner'} = to_utf8($owner);
3177                                 }
3178                                 push @list, $pr;
3179                         }
3180                 }
3181                 close $fd;
3182         }
3183         return @list;
3184 }
3185
3186 # written with help of Tree::Trie module (Perl Artistic License, GPL compatible)
3187 # as side effects it sets 'forks' field to list of forks for forked projects
3188 sub filter_forks_from_projects_list {
3189         my $projects = shift;
3190
3191         my %trie; # prefix tree of directories (path components)
3192         # generate trie out of those directories that might contain forks
3193         foreach my $pr (@$projects) {
3194                 my $path = $pr->{'path'};
3195                 $path =~ s/\.git$//;      # forks of 'repo.git' are in 'repo/' directory
3196                 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3197                 next unless ($path);      # skip '.git' repository: tests, git-instaweb
3198                 next unless (-d "$projectroot/$path"); # containing directory exists
3199                 $pr->{'forks'} = [];      # there can be 0 or more forks of project
3200
3201                 # add to trie
3202                 my @dirs = split('/', $path);
3203                 # walk the trie, until either runs out of components or out of trie
3204                 my $ref = \%trie;
3205                 while (scalar @dirs &&
3206                        exists($ref->{$dirs[0]})) {
3207                         $ref = $ref->{shift @dirs};
3208                 }
3209                 # create rest of trie structure from rest of components
3210                 foreach my $dir (@dirs) {
3211                         $ref = $ref->{$dir} = {};
3212                 }
3213                 # create end marker, store $pr as a data
3214                 $ref->{''} = $pr if (!exists $ref->{''});
3215         }
3216
3217         # filter out forks, by finding shortest prefix match for paths
3218         my @filtered;
3219  PROJECT:
3220         foreach my $pr (@$projects) {
3221                 # trie lookup
3222                 my $ref = \%trie;
3223         DIR:
3224                 foreach my $dir (split('/', $pr->{'path'})) {
3225                         if (exists $ref->{''}) {
3226                                 # found [shortest] prefix, is a fork - skip it
3227                                 push @{$ref->{''}{'forks'}}, $pr;
3228                                 next PROJECT;
3229                         }
3230                         if (!exists $ref->{$dir}) {
3231                                 # not in trie, cannot have prefix, not a fork
3232                                 push @filtered, $pr;
3233                                 next PROJECT;
3234                         }
3235                         # If the dir is there, we just walk one step down the trie.
3236                         $ref = $ref->{$dir};
3237                 }
3238                 # we ran out of trie
3239                 # (shouldn't happen: it's either no match, or end marker)
3240                 push @filtered, $pr;
3241         }
3242
3243         return @filtered;
3244 }
3245
3246 # note: fill_project_list_info must be run first,
3247 # for 'descr_long' and 'ctags' to be filled
3248 sub search_projects_list {
3249         my ($projlist, %opts) = @_;
3250         my $tagfilter  = $opts{'tagfilter'};
3251         my $search_re = $opts{'search_regexp'};
3252
3253         return @$projlist
3254                 unless ($tagfilter || $search_re);
3255
3256         # searching projects require filling to be run before it;
3257         fill_project_list_info($projlist,
3258                                $tagfilter  ? 'ctags' : (),
3259                                $search_re ? ('path', 'descr') : ());
3260         my @projects;
3261  PROJECT:
3262         foreach my $pr (@$projlist) {
3263
3264                 if ($tagfilter) {
3265                         next unless ref($pr->{'ctags'}) eq 'HASH';
3266                         next unless
3267                                 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3268                 }
3269
3270                 if ($search_re) {
3271                         next unless
3272                                 $pr->{'path'} =~ /$search_re/ ||
3273                                 $pr->{'descr_long'} =~ /$search_re/;
3274                 }
3275
3276                 push @projects, $pr;
3277         }
3278
3279         return @projects;
3280 }
3281
3282 our $gitweb_project_owner = undef;
3283 sub git_get_project_list_from_file {
3284
3285         return if (defined $gitweb_project_owner);
3286
3287         $gitweb_project_owner = {};
3288         # read from file (url-encoded):
3289         # 'git%2Fgit.git Linus+Torvalds'
3290         # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3291         # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3292         if (-f $projects_list) {
3293                 open(my $fd, '<', $projects_list);
3294                 while (my $line = <$fd>) {
3295                         chomp $line;
3296                         my ($pr, $ow) = split ' ', $line;
3297                         $pr = unescape($pr);
3298                         $ow = unescape($ow);
3299                         $gitweb_project_owner->{$pr} = to_utf8($ow);
3300                 }
3301                 close $fd;
3302         }
3303 }
3304
3305 sub git_get_project_owner {
3306         my $project = shift;
3307         my $owner;
3308
3309         return undef unless $project;
3310         $git_dir = "$projectroot/$project";
3311
3312         if (!defined $gitweb_project_owner) {
3313                 git_get_project_list_from_file();
3314         }
3315
3316         if (exists $gitweb_project_owner->{$project}) {
3317                 $owner = $gitweb_project_owner->{$project};
3318         }
3319         if (!defined $owner){
3320                 $owner = git_get_project_config('owner');
3321         }
3322         if (!defined $owner) {
3323                 $owner = get_file_owner("$git_dir");
3324         }
3325
3326         return $owner;
3327 }
3328
3329 sub git_get_last_activity {
3330         my ($path) = @_;
3331         my $fd;
3332
3333         $git_dir = "$projectroot/$path";
3334         open($fd, "-|", git_cmd(), 'for-each-ref',
3335              '--format=%(committer)',
3336              '--sort=-committerdate',
3337              '--count=1',
3338              map { "refs/$_" } get_branch_refs ()) or return;
3339         my $most_recent = <$fd>;
3340         close $fd or return;
3341         if (defined $most_recent &&
3342             $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3343                 my $timestamp = $1;
3344                 my $age = time - $timestamp;
3345                 return ($age, age_string($age));
3346         }
3347         return (undef, undef);
3348 }
3349
3350 # Implementation note: when a single remote is wanted, we cannot use 'git
3351 # remote show -n' because that command always work (assuming it's a remote URL
3352 # if it's not defined), and we cannot use 'git remote show' because that would
3353 # try to make a network roundtrip. So the only way to find if that particular
3354 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3355 # and when we find what we want.
3356 sub git_get_remotes_list {
3357         my $wanted = shift;
3358         my %remotes = ();
3359
3360         open my $fd, '-|' , git_cmd(), 'remote', '-v';
3361         return unless $fd;
3362         while (my $remote = <$fd>) {
3363                 chomp $remote;
3364                 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3365                 next if $wanted and not $remote eq $wanted;
3366                 my ($url, $key) = ($1, $2);
3367
3368                 $remotes{$remote} ||= { 'heads' => () };
3369                 $remotes{$remote}{$key} = $url;
3370         }
3371         close $fd or return;
3372         return wantarray ? %remotes : \%remotes;
3373 }
3374
3375 # Takes a hash of remotes as first parameter and fills it by adding the
3376 # available remote heads for each of the indicated remotes.
3377 sub fill_remote_heads {
3378         my $remotes = shift;
3379         my @heads = map { "remotes/$_" } keys %$remotes;
3380         my @remoteheads = git_get_heads_list(undef, @heads);
3381         foreach my $remote (keys %$remotes) {
3382                 $remotes->{$remote}{'heads'} = [ grep {
3383                         $_->{'name'} =~ s!^$remote/!!
3384                         } @remoteheads ];
3385         }
3386 }
3387
3388 sub git_get_references {
3389         my $type = shift || "";
3390         my %refs;
3391         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3392         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3393         open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3394                 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3395                 or return;
3396
3397         while (my $line = <$fd>) {
3398                 chomp $line;
3399                 if ($line =~ m!^($oid_regex)\srefs/($type.*)$!) {
3400                         if (defined $refs{$1}) {
3401                                 push @{$refs{$1}}, $2;
3402                         } else {
3403                                 $refs{$1} = [ $2 ];
3404                         }
3405                 }
3406         }
3407         close $fd or return;
3408         return \%refs;
3409 }
3410
3411 sub git_get_rev_name_tags {
3412         my $hash = shift || return undef;
3413
3414         open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3415                 or return;
3416         my $name_rev = <$fd>;
3417         close $fd;
3418
3419         if ($name_rev =~ m|^$hash tags/(.*)$|) {
3420                 return $1;
3421         } else {
3422                 # catches also '$hash undefined' output
3423                 return undef;
3424         }
3425 }
3426
3427 ## ----------------------------------------------------------------------
3428 ## parse to hash functions
3429
3430 sub parse_date {
3431         my $epoch = shift;
3432         my $tz = shift || "-0000";
3433
3434         my %date;
3435         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3436         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3437         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3438         $date{'hour'} = $hour;
3439         $date{'minute'} = $min;
3440         $date{'mday'} = $mday;
3441         $date{'day'} = $days[$wday];
3442         $date{'month'} = $months[$mon];
3443         $date{'rfc2822'}   = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3444                              $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3445         $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3446                              $mday, $months[$mon], $hour ,$min;
3447         $date{'iso-8601'}  = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3448                              1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3449
3450         my ($tz_sign, $tz_hour, $tz_min) =
3451                 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3452         $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3453         my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3454         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3455         $date{'hour_local'} = $hour;
3456         $date{'minute_local'} = $min;
3457         $date{'tz_local'} = $tz;
3458         $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3459                                   1900+$year, $mon+1, $mday,
3460                                   $hour, $min, $sec, $tz);
3461         return %date;
3462 }
3463
3464 sub hide_mailaddrs_if_private {
3465         my $line = shift;
3466         return $line unless gitweb_check_feature('email-privacy');
3467         $line =~ s/<[^@>]+@[^>]+>/<redacted>/g;
3468         return $line;
3469 }
3470
3471 sub parse_tag {
3472         my $tag_id = shift;
3473         my %tag;
3474         my @comment;
3475
3476         open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3477         $tag{'id'} = $tag_id;
3478         while (my $line = <$fd>) {
3479                 chomp $line;
3480                 if ($line =~ m/^object ($oid_regex)$/) {
3481                         $tag{'object'} = $1;
3482                 } elsif ($line =~ m/^type (.+)$/) {
3483                         $tag{'type'} = $1;
3484                 } elsif ($line =~ m/^tag (.+)$/) {
3485                         $tag{'name'} = $1;
3486                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3487                         $tag{'author'} = hide_mailaddrs_if_private($1);
3488                         $tag{'author_epoch'} = $2;
3489                         $tag{'author_tz'} = $3;
3490                         if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3491                                 $tag{'author_name'}  = $1;
3492                                 $tag{'author_email'} = $2;
3493                         } else {
3494                                 $tag{'author_name'} = $tag{'author'};
3495                         }
3496                 } elsif ($line =~ m/--BEGIN/) {
3497                         push @comment, $line;
3498                         last;
3499                 } elsif ($line eq "") {
3500                         last;
3501                 }
3502         }
3503         push @comment, <$fd>;
3504         $tag{'comment'} = \@comment;
3505         close $fd or return;
3506         if (!defined $tag{'name'}) {
3507                 return
3508         };
3509         return %tag
3510 }
3511
3512 sub parse_commit_text {
3513         my ($commit_text, $withparents) = @_;
3514         my @commit_lines = split '\n', $commit_text;
3515         my %co;
3516
3517         pop @commit_lines; # Remove '\0'
3518
3519         if (! @commit_lines) {
3520                 return;
3521         }
3522
3523         my $header = shift @commit_lines;
3524         if ($header !~ m/^$oid_regex/) {
3525                 return;
3526         }
3527         ($co{'id'}, my @parents) = split ' ', $header;
3528         while (my $line = shift @commit_lines) {
3529                 last if $line eq "\n";
3530                 if ($line =~ m/^tree ($oid_regex)$/) {
3531                         $co{'tree'} = $1;
3532                 } elsif ((!defined $withparents) && ($line =~ m/^parent ($oid_regex)$/)) {
3533                         push @parents, $1;
3534                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3535                         $co{'author'} = hide_mailaddrs_if_private(to_utf8($1));
3536                         $co{'author_epoch'} = $2;
3537                         $co{'author_tz'} = $3;
3538                         if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3539                                 $co{'author_name'}  = $1;
3540                                 $co{'author_email'} = $2;
3541                         } else {
3542                                 $co{'author_name'} = $co{'author'};
3543                         }
3544                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3545                         $co{'committer'} = hide_mailaddrs_if_private(to_utf8($1));
3546                         $co{'committer_epoch'} = $2;
3547                         $co{'committer_tz'} = $3;
3548                         if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3549                                 $co{'committer_name'}  = $1;
3550                                 $co{'committer_email'} = $2;
3551                         } else {
3552                                 $co{'committer_name'} = $co{'committer'};
3553                         }
3554                 }
3555         }
3556         if (!defined $co{'tree'}) {
3557                 return;
3558         };
3559         $co{'parents'} = \@parents;
3560         $co{'parent'} = $parents[0];
3561
3562         foreach my $title (@commit_lines) {
3563                 $title =~ s/^    //;
3564                 if ($title ne "") {
3565                         $co{'title'} = chop_str($title, 80, 5);
3566                         $co{'title_short'} = chop_str($title, 50, 5);
3567                         last;
3568                 }
3569         }
3570         if (! defined $co{'title'} || $co{'title'} eq "") {
3571                 $co{'title'} = $co{'title_short'} = '(no commit message)';
3572         }
3573         # remove added spaces, redact e-mail addresses if applicable.
3574         foreach my $line (@commit_lines) {
3575                 $line =~ s/^    //;
3576                 $line = hide_mailaddrs_if_private($line);
3577         }
3578         $co{'comment'} = \@commit_lines;
3579
3580         my $age = time - $co{'committer_epoch'};
3581         $co{'age'} = $age;
3582         $co{'age_string'} = age_string($age);
3583         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3584         if ($age > 60*60*24*7*2) {
3585                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3586                 $co{'age_string_age'} = $co{'age_string'};
3587         } else {
3588                 $co{'age_string_date'} = $co{'age_string'};
3589                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3590         }
3591         return %co;
3592 }
3593
3594 sub parse_commit {
3595         my ($commit_id) = @_;
3596         my %co;
3597
3598         local $/ = "\0";
3599
3600         open my $fd, "-|", git_cmd(), "rev-list",
3601                 "--parents",
3602                 "--header",
3603                 "--max-count=1",
3604                 $commit_id,
3605                 "--",
3606                 or die_error(500, "Open git-rev-list failed");
3607         %co = parse_commit_text(<$fd>, 1);
3608         close $fd;
3609
3610         return %co;
3611 }
3612
3613 sub parse_commits {
3614         my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3615         my @cos;
3616
3617         $maxcount ||= 1;
3618         $skip ||= 0;
3619
3620         local $/ = "\0";
3621
3622         open my $fd, "-|", git_cmd(), "rev-list",
3623                 "--header",
3624                 @args,
3625                 ("--max-count=" . $maxcount),
3626                 ("--skip=" . $skip),
3627                 @extra_options,
3628                 $commit_id,
3629                 "--",
3630                 ($filename ? ($filename) : ())
3631                 or die_error(500, "Open git-rev-list failed");
3632         while (my $line = <$fd>) {
3633                 my %co = parse_commit_text($line);
3634                 push @cos, \%co;
3635         }
3636         close $fd;
3637
3638         return wantarray ? @cos : \@cos;
3639 }
3640
3641 # parse line of git-diff-tree "raw" output
3642 sub parse_difftree_raw_line {
3643         my $line = shift;
3644         my %res;
3645
3646         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
3647         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
3648         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ($oid_regex) ($oid_regex) (.)([0-9]{0,3})\t(.*)$/) {
3649                 $res{'from_mode'} = $1;
3650                 $res{'to_mode'} = $2;
3651                 $res{'from_id'} = $3;
3652                 $res{'to_id'} = $4;
3653                 $res{'status'} = $5;
3654                 $res{'similarity'} = $6;
3655                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3656                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3657                 } else {
3658                         $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3659                 }
3660         }
3661         # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3662         # combined diff (for merge commit)
3663         elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:$oid_regex )+)([a-zA-Z]+)\t(.*)$//) {
3664                 $res{'nparents'}  = length($1);
3665                 $res{'from_mode'} = [ split(' ', $2) ];
3666                 $res{'to_mode'} = pop @{$res{'from_mode'}};
3667                 $res{'from_id'} = [ split(' ', $3) ];
3668                 $res{'to_id'} = pop @{$res{'from_id'}};
3669                 $res{'status'} = [ split('', $4) ];
3670                 $res{'to_file'} = unquote($5);
3671         }
3672         # 'c512b523472485aef4fff9e57b229d9d243c967f'
3673         elsif ($line =~ m/^($oid_regex)$/) {
3674                 $res{'commit'} = $1;
3675         }
3676
3677         return wantarray ? %res : \%res;
3678 }
3679
3680 # wrapper: return parsed line of git-diff-tree "raw" output
3681 # (the argument might be raw line, or parsed info)
3682 sub parsed_difftree_line {
3683         my $line_or_ref = shift;
3684
3685         if (ref($line_or_ref) eq "HASH") {
3686                 # pre-parsed (or generated by hand)
3687                 return $line_or_ref;
3688         } else {
3689                 return parse_difftree_raw_line($line_or_ref);
3690         }
3691 }
3692
3693 # parse line of git-ls-tree output
3694 sub parse_ls_tree_line {
3695         my $line = shift;
3696         my %opts = @_;
3697         my %res;
3698
3699         if ($opts{'-l'}) {
3700                 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa   16717  panic.c'
3701                 $line =~ m/^([0-9]+) (.+) ($oid_regex) +(-|[0-9]+)\t(.+)$/s;
3702
3703                 $res{'mode'} = $1;
3704                 $res{'type'} = $2;
3705                 $res{'hash'} = $3;
3706                 $res{'size'} = $4;
3707                 if ($opts{'-z'}) {
3708                         $res{'name'} = $5;
3709                 } else {
3710                         $res{'name'} = unquote($5);
3711                 }
3712         } else {
3713                 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
3714                 $line =~ m/^([0-9]+) (.+) ($oid_regex)\t(.+)$/s;
3715
3716                 $res{'mode'} = $1;
3717                 $res{'type'} = $2;
3718                 $res{'hash'} = $3;
3719                 if ($opts{'-z'}) {
3720                         $res{'name'} = $4;
3721                 } else {
3722                         $res{'name'} = unquote($4);
3723                 }
3724         }
3725
3726         return wantarray ? %res : \%res;
3727 }
3728
3729 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3730 sub parse_from_to_diffinfo {
3731         my ($diffinfo, $from, $to, @parents) = @_;
3732
3733         if ($diffinfo->{'nparents'}) {
3734                 # combined diff
3735                 $from->{'file'} = [];
3736                 $from->{'href'} = [];
3737                 fill_from_file_info($diffinfo, @parents)
3738                         unless exists $diffinfo->{'from_file'};
3739                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3740                         $from->{'file'}[$i] =
3741                                 defined $diffinfo->{'from_file'}[$i] ?
3742                                         $diffinfo->{'from_file'}[$i] :
3743                                         $diffinfo->{'to_file'};
3744                         if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3745                                 $from->{'href'}[$i] = href(action=>"blob",
3746                                                            hash_base=>$parents[$i],
3747                                                            hash=>$diffinfo->{'from_id'}[$i],
3748                                                            file_name=>$from->{'file'}[$i]);
3749                         } else {
3750                                 $from->{'href'}[$i] = undef;
3751                         }
3752                 }
3753         } else {
3754                 # ordinary (not combined) diff
3755                 $from->{'file'} = $diffinfo->{'from_file'};
3756                 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3757                         $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3758                                                hash=>$diffinfo->{'from_id'},
3759                                                file_name=>$from->{'file'});
3760                 } else {
3761                         delete $from->{'href'};
3762                 }
3763         }
3764
3765         $to->{'file'} = $diffinfo->{'to_file'};
3766         if (!is_deleted($diffinfo)) { # file exists in result
3767                 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3768                                      hash=>$diffinfo->{'to_id'},
3769                                      file_name=>$to->{'file'});
3770         } else {
3771                 delete $to->{'href'};
3772         }
3773 }
3774
3775 ## ......................................................................
3776 ## parse to array of hashes functions
3777
3778 sub git_get_heads_list {
3779         my ($limit, @classes) = @_;
3780         @classes = get_branch_refs() unless @classes;
3781         my @patterns = map { "refs/$_" } @classes;
3782         my @headslist;
3783
3784         open my $fd, '-|', git_cmd(), 'for-each-ref',
3785                 ($limit ? '--count='.($limit+1) : ()),
3786                 '--sort=-HEAD', '--sort=-committerdate',
3787                 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3788                 @patterns
3789                 or return;
3790         while (my $line = <$fd>) {
3791                 my %ref_item;
3792
3793                 chomp $line;
3794                 my ($refinfo, $committerinfo) = split(/\0/, $line);
3795                 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3796                 my ($committer, $epoch, $tz) =
3797                         ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3798                 $ref_item{'fullname'}  = $name;
3799                 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
3800                 $name =~ s!^refs/($strip_refs|remotes)/!!;
3801                 $ref_item{'name'} = $name;
3802                 # for refs neither in 'heads' nor 'remotes' we want to
3803                 # show their ref dir
3804                 my $ref_dir = (defined $1) ? $1 : '';
3805                 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3806                     $ref_item{'name'} .= ' (' . $ref_dir . ')';
3807                 }
3808
3809                 $ref_item{'id'}    = $hash;
3810                 $ref_item{'title'} = $title || '(no commit message)';
3811                 $ref_item{'epoch'} = $epoch;
3812                 if ($epoch) {
3813                         $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3814                 } else {
3815                         $ref_item{'age'} = "unknown";
3816                 }
3817
3818                 push @headslist, \%ref_item;
3819         }
3820         close $fd;
3821
3822         return wantarray ? @headslist : \@headslist;
3823 }
3824
3825 sub git_get_tags_list {
3826         my $limit = shift;
3827         my @tagslist;
3828
3829         open my $fd, '-|', git_cmd(), 'for-each-ref',
3830                 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3831                 '--format=%(objectname) %(objecttype) %(refname) '.
3832                 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3833                 'refs/tags'
3834                 or return;
3835         while (my $line = <$fd>) {
3836                 my %ref_item;
3837
3838                 chomp $line;
3839                 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3840                 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3841                 my ($creator, $epoch, $tz) =
3842                         ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3843                 $ref_item{'fullname'} = $name;
3844                 $name =~ s!^refs/tags/!!;
3845
3846                 $ref_item{'type'} = $type;
3847                 $ref_item{'id'} = $id;
3848                 $ref_item{'name'} = $name;
3849                 if ($type eq "tag") {
3850                         $ref_item{'subject'} = $title;
3851                         $ref_item{'reftype'} = $reftype;
3852                         $ref_item{'refid'}   = $refid;
3853                 } else {
3854                         $ref_item{'reftype'} = $type;
3855                         $ref_item{'refid'}   = $id;
3856                 }
3857
3858                 if ($type eq "tag" || $type eq "commit") {
3859                         $ref_item{'epoch'} = $epoch;
3860                         if ($epoch) {
3861                                 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3862                         } else {
3863                                 $ref_item{'age'} = "unknown";
3864                         }
3865                 }
3866
3867                 push @tagslist, \%ref_item;
3868         }
3869         close $fd;
3870
3871         return wantarray ? @tagslist : \@tagslist;
3872 }
3873
3874 ## ----------------------------------------------------------------------
3875 ## filesystem-related functions
3876
3877 sub get_file_owner {
3878         my $path = shift;
3879
3880         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3881         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3882         if (!defined $gcos) {
3883                 return undef;
3884         }
3885         my $owner = $gcos;
3886         $owner =~ s/[,;].*$//;
3887         return to_utf8($owner);
3888 }
3889
3890 # assume that file exists
3891 sub insert_file {
3892         my $filename = shift;
3893
3894         open my $fd, '<', $filename;
3895         print map { to_utf8($_) } <$fd>;
3896         close $fd;
3897 }
3898
3899 ## ......................................................................
3900 ## mimetype related functions
3901
3902 sub mimetype_guess_file {
3903         my $filename = shift;
3904         my $mimemap = shift;
3905         -r $mimemap or return undef;
3906
3907         my %mimemap;
3908         open(my $mh, '<', $mimemap) or return undef;
3909         while (<$mh>) {
3910                 next if m/^#/; # skip comments
3911                 my ($mimetype, @exts) = split(/\s+/);
3912                 foreach my $ext (@exts) {
3913                         $mimemap{$ext} = $mimetype;
3914                 }
3915         }
3916         close($mh);
3917
3918         $filename =~ /\.([^.]*)$/;
3919         return $mimemap{$1};
3920 }
3921
3922 sub mimetype_guess {
3923         my $filename = shift;
3924         my $mime;
3925         $filename =~ /\./ or return undef;
3926
3927         if ($mimetypes_file) {
3928                 my $file = $mimetypes_file;
3929                 if ($file !~ m!^/!) { # if it is relative path
3930                         # it is relative to project
3931                         $file = "$projectroot/$project/$file";
3932                 }
3933                 $mime = mimetype_guess_file($filename, $file);
3934         }
3935         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3936         return $mime;
3937 }
3938
3939 sub blob_mimetype {
3940         my $fd = shift;
3941         my $filename = shift;
3942
3943         if ($filename) {
3944                 my $mime = mimetype_guess($filename);
3945                 $mime and return $mime;
3946         }
3947
3948         # just in case
3949         return $default_blob_plain_mimetype unless $fd;
3950
3951         if (-T $fd) {
3952                 return 'text/plain';
3953         } elsif (! $filename) {
3954                 return 'application/octet-stream';
3955         } elsif ($filename =~ m/\.png$/i) {
3956                 return 'image/png';
3957         } elsif ($filename =~ m/\.gif$/i) {
3958                 return 'image/gif';
3959         } elsif ($filename =~ m/\.jpe?g$/i) {
3960                 return 'image/jpeg';
3961         } else {
3962                 return 'application/octet-stream';
3963         }
3964 }
3965
3966 sub blob_contenttype {
3967         my ($fd, $file_name, $type) = @_;
3968
3969         $type ||= blob_mimetype($fd, $file_name);
3970         if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3971                 $type .= "; charset=$default_text_plain_charset";
3972         }
3973
3974         return $type;
3975 }
3976
3977 # guess file syntax for syntax highlighting; return undef if no highlighting
3978 # the name of syntax can (in the future) depend on syntax highlighter used
3979 sub guess_file_syntax {
3980         my ($highlight, $file_name) = @_;
3981         return undef unless ($highlight && defined $file_name);
3982         my $basename = basename($file_name, '.in');
3983         return $highlight_basename{$basename}
3984                 if exists $highlight_basename{$basename};
3985
3986         $basename =~ /\.([^.]*)$/;
3987         my $ext = $1 or return undef;
3988         return $highlight_ext{$ext}
3989                 if exists $highlight_ext{$ext};
3990
3991         return undef;
3992 }
3993
3994 # run highlighter and return FD of its output,
3995 # or return original FD if no highlighting
3996 sub run_highlighter {
3997         my ($fd, $highlight, $syntax) = @_;
3998         return $fd unless ($highlight);
3999
4000         close $fd;
4001         my $syntax_arg = (defined $syntax) ? "--syntax $syntax" : "--force";
4002         open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
4003                   quote_command($^X, '-CO', '-MEncode=decode,FB_DEFAULT', '-pse',
4004                     '$_ = decode($fe, $_, FB_DEFAULT) if !utf8::decode($_);',
4005                     '--', "-fe=$fallback_encoding")." | ".
4006                   quote_command($highlight_bin).
4007                   " --replace-tabs=8 --fragment $syntax_arg |"
4008                 or die_error(500, "Couldn't open file or run syntax highlighter");
4009         return $fd;
4010 }
4011
4012 ## ======================================================================
4013 ## functions printing HTML: header, footer, error page
4014
4015 sub get_page_title {
4016         my $title = to_utf8($site_name);
4017
4018         unless (defined $project) {
4019                 if (defined $project_filter) {
4020                         $title .= " - projects in '" . esc_path($project_filter) . "'";
4021                 }
4022                 return $title;
4023         }
4024         $title .= " - " . to_utf8($project);
4025
4026         return $title unless (defined $action);
4027         $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
4028
4029         return $title unless (defined $file_name);
4030         $title .= " - " . esc_path($file_name);
4031         if ($action eq "tree" && $file_name !~ m|/$|) {
4032                 $title .= "/";
4033         }
4034
4035         return $title;
4036 }
4037
4038 sub get_content_type_html {
4039         # require explicit support from the UA if we are to send the page as
4040         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
4041         # we have to do this because MSIE sometimes globs '*/*', pretending to
4042         # support xhtml+xml but choking when it gets what it asked for.
4043         if (defined $cgi->http('HTTP_ACCEPT') &&
4044             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
4045             $cgi->Accept('application/xhtml+xml') != 0) {
4046                 return 'application/xhtml+xml';
4047         } else {
4048                 return 'text/html';
4049         }
4050 }
4051
4052 sub print_feed_meta {
4053         if (defined $project) {
4054                 my %href_params = get_feed_info();
4055                 if (!exists $href_params{'-title'}) {
4056                         $href_params{'-title'} = 'log';
4057                 }
4058
4059                 foreach my $format (qw(RSS Atom)) {
4060                         my $type = lc($format);
4061                         my %link_attr = (
4062                                 '-rel' => 'alternate',
4063                                 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
4064                                 '-type' => "application/$type+xml"
4065                         );
4066
4067                         $href_params{'extra_options'} = undef;
4068                         $href_params{'action'} = $type;
4069                         $link_attr{'-href'} = esc_attr(href(%href_params));
4070                         print "<link ".
4071                               "rel=\"$link_attr{'-rel'}\" ".
4072                               "title=\"$link_attr{'-title'}\" ".
4073                               "href=\"$link_attr{'-href'}\" ".
4074                               "type=\"$link_attr{'-type'}\" ".
4075                               "/>\n";
4076
4077                         $href_params{'extra_options'} = '--no-merges';
4078                         $link_attr{'-href'} = esc_attr(href(%href_params));
4079                         $link_attr{'-title'} .= ' (no merges)';
4080                         print "<link ".
4081                               "rel=\"$link_attr{'-rel'}\" ".
4082                               "title=\"$link_attr{'-title'}\" ".
4083                               "href=\"$link_attr{'-href'}\" ".
4084                               "type=\"$link_attr{'-type'}\" ".
4085                               "/>\n";
4086                 }
4087
4088         } else {
4089                 printf('<link rel="alternate" title="%s projects list" '.
4090                        'href="%s" type="text/plain; charset=utf-8" />'."\n",
4091                        esc_attr($site_name),
4092                        esc_attr(href(project=>undef, action=>"project_index")));
4093                 printf('<link rel="alternate" title="%s projects feeds" '.
4094                        'href="%s" type="text/x-opml" />'."\n",
4095                        esc_attr($site_name),
4096                        esc_attr(href(project=>undef, action=>"opml")));
4097         }
4098 }
4099
4100 sub print_header_links {
4101         my $status = shift;
4102
4103         # print out each stylesheet that exist, providing backwards capability
4104         # for those people who defined $stylesheet in a config file
4105         if (defined $stylesheet) {
4106                 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4107         } else {
4108                 foreach my $stylesheet (@stylesheets) {
4109                         next unless $stylesheet;
4110                         print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4111                 }
4112         }
4113         print_feed_meta()
4114                 if ($status eq '200 OK');
4115         if (defined $favicon) {
4116                 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4117         }
4118 }
4119
4120 sub print_nav_breadcrumbs_path {
4121         my $dirprefix = undef;
4122         while (my $part = shift) {
4123                 $dirprefix .= "/" if defined $dirprefix;
4124                 $dirprefix .= $part;
4125                 print $cgi->a({-href => href(project => undef,
4126                                              project_filter => $dirprefix,
4127                                              action => "project_list")},
4128                               esc_html($part)) . " / ";
4129         }
4130 }
4131
4132 sub print_nav_breadcrumbs {
4133         my %opts = @_;
4134
4135         for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4136                 print $cgi->a({-href => esc_url($crumb->[1])}, $crumb->[0]) . " / ";
4137         }
4138         if (defined $project) {
4139                 my @dirname = split '/', $project;
4140                 my $projectbasename = pop @dirname;
4141                 print_nav_breadcrumbs_path(@dirname);
4142                 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4143                 if (defined $action) {
4144                         my $action_print = $action ;
4145                         if (defined $opts{-action_extra}) {
4146                                 $action_print = $cgi->a({-href => href(action=>$action)},
4147                                         $action);
4148                         }
4149                         print " / $action_print";
4150                 }
4151                 if (defined $opts{-action_extra}) {
4152                         print " / $opts{-action_extra}";
4153                 }
4154                 print "\n";
4155         } elsif (defined $project_filter) {
4156                 print_nav_breadcrumbs_path(split '/', $project_filter);
4157         }
4158 }
4159
4160 sub print_search_form {
4161         if (!defined $searchtext) {
4162                 $searchtext = "";
4163         }
4164         my $search_hash;
4165         if (defined $hash_base) {
4166                 $search_hash = $hash_base;
4167         } elsif (defined $hash) {
4168                 $search_hash = $hash;
4169         } else {
4170                 $search_hash = "HEAD";
4171         }
4172         my $action = $my_uri;
4173         my $use_pathinfo = gitweb_check_feature('pathinfo');
4174         if ($use_pathinfo) {
4175                 $action .= "/".esc_url($project);
4176         }
4177         print $cgi->start_form(-method => "get", -action => $action) .
4178               "<div class=\"search\">\n" .
4179               (!$use_pathinfo &&
4180               $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4181               $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4182               $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4183               $cgi->popup_menu(-name => 'st', -default => 'commit',
4184                                -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4185               " " . $cgi->a({-href => href(action=>"search_help"),
4186                              -title => "search help" }, "?") . " search:\n",
4187               $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4188               "<span title=\"Extended regular expression\">" .
4189               $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4190                              -checked => $search_use_regexp) .
4191               "</span>" .
4192               "</div>" .
4193               $cgi->end_form() . "\n";
4194 }
4195
4196 sub git_header_html {
4197         my $status = shift || "200 OK";
4198         my $expires = shift;
4199         my %opts = @_;
4200
4201         my $title = get_page_title();
4202         print $cgi->header(-type=>get_content_type_html(), -charset => 'utf-8',
4203                            -status=> $status, -expires => $expires)
4204                 unless ($opts{'-no_http_header'});
4205         my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4206         print <<EOF;
4207 <?xml version="1.0" encoding="utf-8"?>
4208 <!DOCTYPE html [
4209         <!ENTITY nbsp "&#xA0;">
4210         <!ENTITY sdot "&#x22C5;">
4211 ]>
4212 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4213 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4214 <!-- git core binaries version $git_version -->
4215 <head>
4216 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4217 <meta name="robots" content="index, nofollow"/>
4218 <title>$title</title>
4219 EOF
4220         # the stylesheet, favicon etc urls won't work correctly with path_info
4221         # unless we set the appropriate base URL
4222         if ($ENV{'PATH_INFO'}) {
4223                 print "<base href=\"".esc_url($base_url)."\" />\n";
4224         }
4225         print_header_links($status);
4226
4227         if (defined $site_html_head_string) {
4228                 print to_utf8($site_html_head_string);
4229         }
4230
4231         print "</head>\n" .
4232               "<body>\n";
4233
4234         if (defined $site_header && -f $site_header) {
4235                 insert_file($site_header);
4236         }
4237
4238         print "<div class=\"page_header\">\n";
4239         if (defined $logo) {
4240                 print $cgi->a({-href => esc_url($logo_url),
4241                                -title => $logo_label},
4242                               $cgi->img({-src => esc_url($logo),
4243                                          -width => 72, -height => 27,
4244                                          -alt => "git",
4245                                          -class => "logo"}));
4246         }
4247         print_nav_breadcrumbs(%opts);
4248         print "</div>\n";
4249
4250         my $have_search = gitweb_check_feature('search');
4251         if (defined $project && $have_search) {
4252                 print_search_form();
4253         }
4254 }
4255
4256 sub git_footer_html {
4257         my $feed_class = 'rss_logo';
4258
4259         print "<div class=\"page_footer\">\n";
4260         if (defined $project) {
4261                 my $descr = git_get_project_description($project);
4262                 if (defined $descr) {
4263                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4264                 }
4265
4266                 my %href_params = get_feed_info();
4267                 if (!%href_params) {
4268                         $feed_class .= ' generic';
4269                 }
4270                 $href_params{'-title'} ||= 'log';
4271
4272                 foreach my $format (qw(RSS Atom)) {
4273                         $href_params{'action'} = lc($format);
4274                         print $cgi->a({-href => href(%href_params),
4275                                       -title => "$href_params{'-title'} $format feed",
4276                                       -class => $feed_class}, $format)."\n";
4277                 }
4278
4279         } else {
4280                 print $cgi->a({-href => href(project=>undef, action=>"opml",
4281                                              project_filter => $project_filter),
4282                               -class => $feed_class}, "OPML") . " ";
4283                 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4284                                              project_filter => $project_filter),
4285                               -class => $feed_class}, "TXT") . "\n";
4286         }
4287         print "</div>\n"; # class="page_footer"
4288
4289         if (defined $t0 && gitweb_check_feature('timed')) {
4290                 print "<div id=\"generating_info\">\n";
4291                 print 'This page took '.
4292                       '<span id="generating_time" class="time_span">'.
4293                       tv_interval($t0, [ gettimeofday() ]).
4294                       ' seconds </span>'.
4295                       ' and '.
4296                       '<span id="generating_cmd">'.
4297                       $number_of_git_cmds.
4298                       '</span> git commands '.
4299                       " to generate.\n";
4300                 print "</div>\n"; # class="page_footer"
4301         }
4302
4303         if (defined $site_footer && -f $site_footer) {
4304                 insert_file($site_footer);
4305         }
4306
4307         print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4308         if (defined $action &&
4309             $action eq 'blame_incremental') {
4310                 print qq!<script type="text/javascript">\n!.
4311                       qq!startBlame("!. esc_attr(href(action=>"blame_data", -replay=>1)) .qq!",\n!.
4312                       qq!           "!. esc_attr(href()) .qq!");\n!.
4313                       qq!</script>\n!;
4314         } else {
4315                 my ($jstimezone, $tz_cookie, $datetime_class) =
4316                         gitweb_get_feature('javascript-timezone');
4317
4318                 print qq!<script type="text/javascript">\n!.
4319                       qq!window.onload = function () {\n!;
4320                 if (gitweb_check_feature('javascript-actions')) {
4321                         print qq!       fixLinks();\n!;
4322                 }
4323                 if ($jstimezone && $tz_cookie && $datetime_class) {
4324                         print qq!       var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4325                               qq!       onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4326                 }
4327                 print qq!};\n!.
4328                       qq!</script>\n!;
4329         }
4330
4331         print "</body>\n" .
4332               "</html>";
4333 }
4334
4335 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4336 # Example: die_error(404, 'Hash not found')
4337 # By convention, use the following status codes (as defined in RFC 2616):
4338 # 400: Invalid or missing CGI parameters, or
4339 #      requested object exists but has wrong type.
4340 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4341 #      this server or project.
4342 # 404: Requested object/revision/project doesn't exist.
4343 # 500: The server isn't configured properly, or
4344 #      an internal error occurred (e.g. failed assertions caused by bugs), or
4345 #      an unknown error occurred (e.g. the git binary died unexpectedly).
4346 # 503: The server is currently unavailable (because it is overloaded,
4347 #      or down for maintenance).  Generally, this is a temporary state.
4348 sub die_error {
4349         my $status = shift || 500;
4350         my $error = esc_html(shift) || "Internal Server Error";
4351         my $extra = shift;
4352         my %opts = @_;
4353
4354         my %http_responses = (
4355                 400 => '400 Bad Request',
4356                 403 => '403 Forbidden',
4357                 404 => '404 Not Found',
4358                 500 => '500 Internal Server Error',
4359                 503 => '503 Service Unavailable',
4360         );
4361         git_header_html($http_responses{$status}, undef, %opts);
4362         print <<EOF;
4363 <div class="page_body">
4364 <br /><br />
4365 $status - $error
4366 <br />
4367 EOF
4368         if (defined $extra) {
4369                 print "<hr />\n" .
4370                       "$extra\n";
4371         }
4372         print "</div>\n";
4373
4374         git_footer_html();
4375         goto DONE_GITWEB
4376                 unless ($opts{'-error_handler'});
4377 }
4378
4379 ## ----------------------------------------------------------------------
4380 ## functions printing or outputting HTML: navigation
4381
4382 sub git_print_page_nav {
4383         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4384         $extra = '' if !defined $extra; # pager or formats
4385
4386         my @navs = qw(summary shortlog log commit commitdiff tree);
4387         if ($suppress) {
4388                 @navs = grep { $_ ne $suppress } @navs;
4389         }
4390
4391         my %arg = map { $_ => {action=>$_} } @navs;
4392         if (defined $head) {
4393                 for (qw(commit commitdiff)) {
4394                         $arg{$_}{'hash'} = $head;
4395                 }
4396                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4397                         for (qw(shortlog log)) {
4398                                 $arg{$_}{'hash'} = $head;
4399                         }
4400                 }
4401         }
4402
4403         $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4404         $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4405
4406         my @actions = gitweb_get_feature('actions');
4407         my %repl = (
4408                 '%' => '%',
4409                 'n' => $project,         # project name
4410                 'f' => $git_dir,         # project path within filesystem
4411                 'h' => $treehead || '',  # current hash ('h' parameter)
4412                 'b' => $treebase || '',  # hash base ('hb' parameter)
4413         );
4414         while (@actions) {
4415                 my ($label, $link, $pos) = splice(@actions,0,3);
4416                 # insert
4417                 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4418                 # munch munch
4419                 $link =~ s/%([%nfhb])/$repl{$1}/g;
4420                 $arg{$label}{'_href'} = $link;
4421         }
4422
4423         print "<div class=\"page_nav\">\n" .
4424                 (join " | ",
4425                  map { $_ eq $current ?
4426                        $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4427                  } @navs);
4428         print "<br/>\n$extra<br/>\n" .
4429               "</div>\n";
4430 }
4431
4432 # returns a submenu for the navigation of the refs views (tags, heads,
4433 # remotes) with the current view disabled and the remotes view only
4434 # available if the feature is enabled
4435 sub format_ref_views {
4436         my ($current) = @_;
4437         my @ref_views = qw{tags heads};
4438         push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4439         return join " | ", map {
4440                 $_ eq $current ? $_ :
4441                 $cgi->a({-href => href(action=>$_)}, $_)
4442         } @ref_views
4443 }
4444
4445 sub format_paging_nav {
4446         my ($action, $page, $has_next_link) = @_;
4447         my $paging_nav;
4448
4449
4450         if ($page > 0) {
4451                 $paging_nav .=
4452                         $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4453                         " &sdot; " .
4454                         $cgi->a({-href => href(-replay=>1, page=>$page-1),
4455                                  -accesskey => "p", -title => "Alt-p"}, "prev");
4456         } else {
4457                 $paging_nav .= "first &sdot; prev";
4458         }
4459
4460         if ($has_next_link) {
4461                 $paging_nav .= " &sdot; " .
4462                         $cgi->a({-href => href(-replay=>1, page=>$page+1),
4463                                  -accesskey => "n", -title => "Alt-n"}, "next");
4464         } else {
4465                 $paging_nav .= " &sdot; next";
4466         }
4467
4468         return $paging_nav;
4469 }
4470
4471 ## ......................................................................
4472 ## functions printing or outputting HTML: div
4473
4474 sub git_print_header_div {
4475         my ($action, $title, $hash, $hash_base) = @_;
4476         my %args = ();
4477
4478         $args{'action'} = $action;
4479         $args{'hash'} = $hash if $hash;
4480         $args{'hash_base'} = $hash_base if $hash_base;
4481
4482         print "<div class=\"header\">\n" .
4483               $cgi->a({-href => href(%args), -class => "title"},
4484               $title ? $title : $action) .
4485               "\n</div>\n";
4486 }
4487
4488 sub format_repo_url {
4489         my ($name, $url) = @_;
4490         return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4491 }
4492
4493 # Group output by placing it in a DIV element and adding a header.
4494 # Options for start_div() can be provided by passing a hash reference as the
4495 # first parameter to the function.
4496 # Options to git_print_header_div() can be provided by passing an array
4497 # reference. This must follow the options to start_div if they are present.
4498 # The content can be a scalar, which is output as-is, a scalar reference, which
4499 # is output after html escaping, an IO handle passed either as *handle or
4500 # *handle{IO}, or a function reference. In the latter case all following
4501 # parameters will be taken as argument to the content function call.
4502 sub git_print_section {
4503         my ($div_args, $header_args, $content);
4504         my $arg = shift;
4505         if (ref($arg) eq 'HASH') {
4506                 $div_args = $arg;
4507                 $arg = shift;
4508         }
4509         if (ref($arg) eq 'ARRAY') {
4510                 $header_args = $arg;
4511                 $arg = shift;
4512         }
4513         $content = $arg;
4514
4515         print $cgi->start_div($div_args);
4516         git_print_header_div(@$header_args);
4517
4518         if (ref($content) eq 'CODE') {
4519                 $content->(@_);
4520         } elsif (ref($content) eq 'SCALAR') {
4521                 print esc_html($$content);
4522         } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4523                 print <$content>;
4524         } elsif (!ref($content) && defined($content)) {
4525                 print $content;
4526         }
4527
4528         print $cgi->end_div;
4529 }
4530
4531 sub format_timestamp_html {
4532         my $date = shift;
4533         my $strtime = $date->{'rfc2822'};
4534
4535         my (undef, undef, $datetime_class) =
4536                 gitweb_get_feature('javascript-timezone');
4537         if ($datetime_class) {
4538                 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4539         }
4540
4541         my $localtime_format = '(%02d:%02d %s)';
4542         if ($date->{'hour_local'} < 6) {
4543                 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4544         }
4545         $strtime .= ' ' .
4546                     sprintf($localtime_format,
4547                             $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4548
4549         return $strtime;
4550 }
4551
4552 # Outputs the author name and date in long form
4553 sub git_print_authorship {
4554         my $co = shift;
4555         my %opts = @_;
4556         my $tag = $opts{-tag} || 'div';
4557         my $author = $co->{'author_name'};
4558
4559         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4560         print "<$tag class=\"author_date\">" .
4561               format_search_author($author, "author", esc_html($author)) .
4562               " [".format_timestamp_html(\%ad)."]".
4563               git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4564               "</$tag>\n";
4565 }
4566
4567 # Outputs table rows containing the full author or committer information,
4568 # in the format expected for 'commit' view (& similar).
4569 # Parameters are a commit hash reference, followed by the list of people
4570 # to output information for. If the list is empty it defaults to both
4571 # author and committer.
4572 sub git_print_authorship_rows {
4573         my $co = shift;
4574         # too bad we can't use @people = @_ || ('author', 'committer')
4575         my @people = @_;
4576         @people = ('author', 'committer') unless @people;
4577         foreach my $who (@people) {
4578                 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4579                 print "<tr><td>$who</td><td>" .
4580                       format_search_author($co->{"${who}_name"}, $who,
4581                                            esc_html($co->{"${who}_name"})) . " " .
4582                       format_search_author($co->{"${who}_email"}, $who,
4583                                            esc_html("<" . $co->{"${who}_email"} . ">")) .
4584                       "</td><td rowspan=\"2\">" .
4585                       git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4586                       "</td></tr>\n" .
4587                       "<tr>" .
4588                       "<td></td><td>" .
4589                       format_timestamp_html(\%wd) .
4590                       "</td>" .
4591                       "</tr>\n";
4592         }
4593 }
4594
4595 sub git_print_page_path {
4596         my $name = shift;
4597         my $type = shift;
4598         my $hb = shift;
4599
4600
4601         print "<div class=\"page_path\">";
4602         print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4603                       -title => 'tree root'}, to_utf8("[$project]"));
4604         print " / ";
4605         if (defined $name) {
4606                 my @dirname = split '/', $name;
4607                 my $basename = pop @dirname;
4608                 my $fullname = '';
4609
4610                 foreach my $dir (@dirname) {
4611                         $fullname .= ($fullname ? '/' : '') . $dir;
4612                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4613                                                      hash_base=>$hb),
4614                                       -title => $fullname}, esc_path($dir));
4615                         print " / ";
4616                 }
4617                 if (defined $type && $type eq 'blob') {
4618                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4619                                                      hash_base=>$hb),
4620                                       -title => $name}, esc_path($basename));
4621                 } elsif (defined $type && $type eq 'tree') {
4622                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4623                                                      hash_base=>$hb),
4624                                       -title => $name}, esc_path($basename));
4625                         print " / ";
4626                 } else {
4627                         print esc_path($basename);
4628                 }
4629         }
4630         print "<br/></div>\n";
4631 }
4632
4633 sub git_print_log {
4634         my $log = shift;
4635         my %opts = @_;
4636
4637         if ($opts{'-remove_title'}) {
4638                 # remove title, i.e. first line of log
4639                 shift @$log;
4640         }
4641         # remove leading empty lines
4642         while (defined $log->[0] && $log->[0] eq "") {
4643                 shift @$log;
4644         }
4645
4646         # print log
4647         my $skip_blank_line = 0;
4648         foreach my $line (@$log) {
4649                 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-([Bb]y|[Tt]o)|C[Cc]|(Clos|Fix)es): /) {
4650                         if (! $opts{'-remove_signoff'}) {
4651                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4652                                 $skip_blank_line = 1;
4653                         }
4654                         next;
4655                 }
4656
4657                 if ($line =~ m,\s*([a-z]*link): (https?://\S+),i) {
4658                         if (! $opts{'-remove_signoff'}) {
4659                                 print "<span class=\"signoff\">" . esc_html($1) . ": " .
4660                                         "<a href=\"" . esc_html($2) . "\">" . esc_html($2) . "</a>" .
4661                                         "</span><br/>\n";
4662                                 $skip_blank_line = 1;
4663                         }
4664                         next;
4665                 }
4666
4667                 # print only one empty line
4668                 # do not print empty line after signoff
4669                 if ($line eq "") {
4670                         next if ($skip_blank_line);
4671                         $skip_blank_line = 1;
4672                 } else {
4673                         $skip_blank_line = 0;
4674                 }
4675
4676                 print format_log_line_html($line) . "<br/>\n";
4677         }
4678
4679         if ($opts{'-final_empty_line'}) {
4680                 # end with single empty line
4681                 print "<br/>\n" unless $skip_blank_line;
4682         }
4683 }
4684
4685 # return link target (what link points to)
4686 sub git_get_link_target {
4687         my $hash = shift;
4688         my $link_target;
4689
4690         # read link
4691         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4692                 or return;
4693         {
4694                 local $/ = undef;
4695                 $link_target = <$fd>;
4696         }
4697         close $fd
4698                 or return;
4699
4700         return $link_target;
4701 }
4702
4703 # given link target, and the directory (basedir) the link is in,
4704 # return target of link relative to top directory (top tree);
4705 # return undef if it is not possible (including absolute links).
4706 sub normalize_link_target {
4707         my ($link_target, $basedir) = @_;
4708
4709         # absolute symlinks (beginning with '/') cannot be normalized
4710         return if (substr($link_target, 0, 1) eq '/');
4711
4712         # normalize link target to path from top (root) tree (dir)
4713         my $path;
4714         if ($basedir) {
4715                 $path = $basedir . '/' . $link_target;
4716         } else {
4717                 # we are in top (root) tree (dir)
4718                 $path = $link_target;
4719         }
4720
4721         # remove //, /./, and /../
4722         my @path_parts;
4723         foreach my $part (split('/', $path)) {
4724                 # discard '.' and ''
4725                 next if (!$part || $part eq '.');
4726                 # handle '..'
4727                 if ($part eq '..') {
4728                         if (@path_parts) {
4729                                 pop @path_parts;
4730                         } else {
4731                                 # link leads outside repository (outside top dir)
4732                                 return;
4733                         }
4734                 } else {
4735                         push @path_parts, $part;
4736                 }
4737         }
4738         $path = join('/', @path_parts);
4739
4740         return $path;
4741 }
4742
4743 # print tree entry (row of git_tree), but without encompassing <tr> element
4744 sub git_print_tree_entry {
4745         my ($t, $basedir, $hash_base, $have_blame) = @_;
4746
4747         my %base_key = ();
4748         $base_key{'hash_base'} = $hash_base if defined $hash_base;
4749
4750         # The format of a table row is: mode list link.  Where mode is
4751         # the mode of the entry, list is the name of the entry, an href,
4752         # and link is the action links of the entry.
4753
4754         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4755         if (exists $t->{'size'}) {
4756                 print "<td class=\"size\">$t->{'size'}</td>\n";
4757         }
4758         if ($t->{'type'} eq "blob") {
4759                 print "<td class=\"list\">" .
4760                         $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4761                                                file_name=>"$basedir$t->{'name'}", %base_key),
4762                                 -class => "list"}, esc_path($t->{'name'}));
4763                 if (S_ISLNK(oct $t->{'mode'})) {
4764                         my $link_target = git_get_link_target($t->{'hash'});
4765                         if ($link_target) {
4766                                 my $norm_target = normalize_link_target($link_target, $basedir);
4767                                 if (defined $norm_target) {
4768                                         print " -> " .
4769                                               $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4770                                                                      file_name=>$norm_target),
4771                                                        -title => $norm_target}, esc_path($link_target));
4772                                 } else {
4773                                         print " -> " . esc_path($link_target);
4774                                 }
4775                         }
4776                 }
4777                 print "</td>\n";
4778                 print "<td class=\"link\">";
4779                 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4780                                              file_name=>"$basedir$t->{'name'}", %base_key)},
4781                               "blob");
4782                 if ($have_blame) {
4783                         print " | " .
4784                               $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4785                                                      file_name=>"$basedir$t->{'name'}", %base_key)},
4786                                       "blame");
4787                 }
4788                 if (defined $hash_base) {
4789                         print " | " .
4790                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4791                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4792                                       "history");
4793                 }
4794                 print " | " .
4795                         $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4796                                                file_name=>"$basedir$t->{'name'}")},
4797                                 "raw");
4798                 print "</td>\n";
4799
4800         } elsif ($t->{'type'} eq "tree") {
4801                 print "<td class=\"list\">";
4802                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4803                                              file_name=>"$basedir$t->{'name'}",
4804                                              %base_key)},
4805                               esc_path($t->{'name'}));
4806                 print "</td>\n";
4807                 print "<td class=\"link\">";
4808                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4809                                              file_name=>"$basedir$t->{'name'}",
4810                                              %base_key)},
4811                               "tree");
4812                 if (defined $hash_base) {
4813                         print " | " .
4814                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4815                                                      file_name=>"$basedir$t->{'name'}")},
4816                                       "history");
4817                 }
4818                 print "</td>\n";
4819         } else {
4820                 # unknown object: we can only present history for it
4821                 # (this includes 'commit' object, i.e. submodule support)
4822                 print "<td class=\"list\">" .
4823                       esc_path($t->{'name'}) .
4824                       "</td>\n";
4825                 print "<td class=\"link\">";
4826                 if (defined $hash_base) {
4827                         print $cgi->a({-href => href(action=>"history",
4828                                                      hash_base=>$hash_base,
4829                                                      file_name=>"$basedir$t->{'name'}")},
4830                                       "history");
4831                 }
4832                 print "</td>\n";
4833         }
4834 }
4835
4836 ## ......................................................................
4837 ## functions printing large fragments of HTML
4838
4839 # get pre-image filenames for merge (combined) diff
4840 sub fill_from_file_info {
4841         my ($diff, @parents) = @_;
4842
4843         $diff->{'from_file'} = [ ];
4844         $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4845         for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4846                 if ($diff->{'status'}[$i] eq 'R' ||
4847                     $diff->{'status'}[$i] eq 'C') {
4848                         $diff->{'from_file'}[$i] =
4849                                 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4850                 }
4851         }
4852
4853         return $diff;
4854 }
4855
4856 # is current raw difftree line of file deletion
4857 sub is_deleted {
4858         my $diffinfo = shift;
4859
4860         return $diffinfo->{'to_id'} eq ('0' x 40) || $diffinfo->{'to_id'} eq ('0' x 64);
4861 }
4862
4863 # does patch correspond to [previous] difftree raw line
4864 # $diffinfo  - hashref of parsed raw diff format
4865 # $patchinfo - hashref of parsed patch diff format
4866 #              (the same keys as in $diffinfo)
4867 sub is_patch_split {
4868         my ($diffinfo, $patchinfo) = @_;
4869
4870         return defined $diffinfo && defined $patchinfo
4871                 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4872 }
4873
4874
4875 sub git_difftree_body {
4876         my ($difftree, $hash, @parents) = @_;
4877         my ($parent) = $parents[0];
4878         my $have_blame = gitweb_check_feature('blame');
4879         print "<div class=\"list_head\">\n";
4880         if ($#{$difftree} > 10) {
4881                 print(($#{$difftree} + 1) . " files changed:\n");
4882         }
4883         print "</div>\n";
4884
4885         print "<table class=\"" .
4886               (@parents > 1 ? "combined " : "") .
4887               "diff_tree\">\n";
4888
4889         # header only for combined diff in 'commitdiff' view
4890         my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4891         if ($has_header) {
4892                 # table header
4893                 print "<thead><tr>\n" .
4894                        "<th></th><th></th>\n"; # filename, patchN link
4895                 for (my $i = 0; $i < @parents; $i++) {
4896                         my $par = $parents[$i];
4897                         print "<th>" .
4898                               $cgi->a({-href => href(action=>"commitdiff",
4899                                                      hash=>$hash, hash_parent=>$par),
4900                                        -title => 'commitdiff to parent number ' .
4901                                                   ($i+1) . ': ' . substr($par,0,7)},
4902                                       $i+1) .
4903                               "&nbsp;</th>\n";
4904                 }
4905                 print "</tr></thead>\n<tbody>\n";
4906         }
4907
4908         my $alternate = 1;
4909         my $patchno = 0;
4910         foreach my $line (@{$difftree}) {
4911                 my $diff = parsed_difftree_line($line);
4912
4913                 if ($alternate) {
4914                         print "<tr class=\"dark\">\n";
4915                 } else {
4916                         print "<tr class=\"light\">\n";
4917                 }
4918                 $alternate ^= 1;
4919
4920                 if (exists $diff->{'nparents'}) { # combined diff
4921
4922                         fill_from_file_info($diff, @parents)
4923                                 unless exists $diff->{'from_file'};
4924
4925                         if (!is_deleted($diff)) {
4926                                 # file exists in the result (child) commit
4927                                 print "<td>" .
4928                                       $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4929                                                              file_name=>$diff->{'to_file'},
4930                                                              hash_base=>$hash),
4931                                               -class => "list"}, esc_path($diff->{'to_file'})) .
4932                                       "</td>\n";
4933                         } else {
4934                                 print "<td>" .
4935                                       esc_path($diff->{'to_file'}) .
4936                                       "</td>\n";
4937                         }
4938
4939                         if ($action eq 'commitdiff') {
4940                                 # link to patch
4941                                 $patchno++;
4942                                 print "<td class=\"link\">" .
4943                                       $cgi->a({-href => href(-anchor=>"patch$patchno")},
4944                                               "patch") .
4945                                       " | " .
4946                                       "</td>\n";
4947                         }
4948
4949                         my $has_history = 0;
4950                         my $not_deleted = 0;
4951                         for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4952                                 my $hash_parent = $parents[$i];
4953                                 my $from_hash = $diff->{'from_id'}[$i];
4954                                 my $from_path = $diff->{'from_file'}[$i];
4955                                 my $status = $diff->{'status'}[$i];
4956
4957                                 $has_history ||= ($status ne 'A');
4958                                 $not_deleted ||= ($status ne 'D');
4959
4960                                 if ($status eq 'A') {
4961                                         print "<td  class=\"link\" align=\"right\"> | </td>\n";
4962                                 } elsif ($status eq 'D') {
4963                                         print "<td class=\"link\">" .
4964                                               $cgi->a({-href => href(action=>"blob",
4965                                                                      hash_base=>$hash,
4966                                                                      hash=>$from_hash,
4967                                                                      file_name=>$from_path)},
4968                                                       "blob" . ($i+1)) .
4969                                               " | </td>\n";
4970                                 } else {
4971                                         if ($diff->{'to_id'} eq $from_hash) {
4972                                                 print "<td class=\"link nochange\">";
4973                                         } else {
4974                                                 print "<td class=\"link\">";
4975                                         }
4976                                         print $cgi->a({-href => href(action=>"blobdiff",
4977                                                                      hash=>$diff->{'to_id'},
4978                                                                      hash_parent=>$from_hash,
4979                                                                      hash_base=>$hash,
4980                                                                      hash_parent_base=>$hash_parent,
4981                                                                      file_name=>$diff->{'to_file'},
4982                                                                      file_parent=>$from_path)},
4983                                                       "diff" . ($i+1)) .
4984                                               " | </td>\n";
4985                                 }
4986                         }
4987
4988                         print "<td class=\"link\">";
4989                         if ($not_deleted) {
4990                                 print $cgi->a({-href => href(action=>"blob",
4991                                                              hash=>$diff->{'to_id'},
4992                                                              file_name=>$diff->{'to_file'},
4993                                                              hash_base=>$hash)},
4994                                               "blob");
4995                                 print " | " if ($has_history);
4996                         }
4997                         if ($has_history) {
4998                                 print $cgi->a({-href => href(action=>"history",
4999                                                              file_name=>$diff->{'to_file'},
5000                                                              hash_base=>$hash)},
5001                                               "history");
5002                         }
5003                         print "</td>\n";
5004
5005                         print "</tr>\n";
5006                         next; # instead of 'else' clause, to avoid extra indent
5007                 }
5008                 # else ordinary diff
5009
5010                 my ($to_mode_oct, $to_mode_str, $to_file_type);
5011                 my ($from_mode_oct, $from_mode_str, $from_file_type);
5012                 if ($diff->{'to_mode'} ne ('0' x 6)) {
5013                         $to_mode_oct = oct $diff->{'to_mode'};
5014                         if (S_ISREG($to_mode_oct)) { # only for regular file
5015                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
5016                         }
5017                         $to_file_type = file_type($diff->{'to_mode'});
5018                 }
5019                 if ($diff->{'from_mode'} ne ('0' x 6)) {
5020                         $from_mode_oct = oct $diff->{'from_mode'};
5021                         if (S_ISREG($from_mode_oct)) { # only for regular file
5022                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
5023                         }
5024                         $from_file_type = file_type($diff->{'from_mode'});
5025                 }
5026
5027                 if ($diff->{'status'} eq "A") { # created
5028                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
5029                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
5030                         $mode_chng   .= "]</span>";
5031                         print "<td>";
5032                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5033                                                      hash_base=>$hash, file_name=>$diff->{'file'}),
5034                                       -class => "list"}, esc_path($diff->{'file'}));
5035                         print "</td>\n";
5036                         print "<td>$mode_chng</td>\n";
5037                         print "<td class=\"link\">";
5038                         if ($action eq 'commitdiff') {
5039                                 # link to patch
5040                                 $patchno++;
5041                                 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5042                                               "patch") .
5043                                       " | ";
5044                         }
5045                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5046                                                      hash_base=>$hash, file_name=>$diff->{'file'})},
5047                                       "blob");
5048                         print "</td>\n";
5049
5050                 } elsif ($diff->{'status'} eq "D") { # deleted
5051                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
5052                         print "<td>";
5053                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5054                                                      hash_base=>$parent, file_name=>$diff->{'file'}),
5055                                        -class => "list"}, esc_path($diff->{'file'}));
5056                         print "</td>\n";
5057                         print "<td>$mode_chng</td>\n";
5058                         print "<td class=\"link\">";
5059                         if ($action eq 'commitdiff') {
5060                                 # link to patch
5061                                 $patchno++;
5062                                 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5063                                               "patch") .
5064                                       " | ";
5065                         }
5066                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5067                                                      hash_base=>$parent, file_name=>$diff->{'file'})},
5068                                       "blob") . " | ";
5069                         if ($have_blame) {
5070                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
5071                                                              file_name=>$diff->{'file'})},
5072                                               "blame") . " | ";
5073                         }
5074                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
5075                                                      file_name=>$diff->{'file'})},
5076                                       "history");
5077                         print "</td>\n";
5078
5079                 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5080                         my $mode_chnge = "";
5081                         if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5082                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5083                                 if ($from_file_type ne $to_file_type) {
5084                                         $mode_chnge .= " from $from_file_type to $to_file_type";
5085                                 }
5086                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5087                                         if ($from_mode_str && $to_mode_str) {
5088                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5089                                         } elsif ($to_mode_str) {
5090                                                 $mode_chnge .= " mode: $to_mode_str";
5091                                         }
5092                                 }
5093                                 $mode_chnge .= "]</span>\n";
5094                         }
5095                         print "<td>";
5096                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5097                                                      hash_base=>$hash, file_name=>$diff->{'file'}),
5098                                       -class => "list"}, esc_path($diff->{'file'}));
5099                         print "</td>\n";
5100                         print "<td>$mode_chnge</td>\n";
5101                         print "<td class=\"link\">";
5102                         if ($action eq 'commitdiff') {
5103                                 # link to patch
5104                                 $patchno++;
5105                                 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5106                                               "patch") .
5107                                       " | ";
5108                         } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5109                                 # "commit" view and modified file (not onlu mode changed)
5110                                 print $cgi->a({-href => href(action=>"blobdiff",
5111                                                              hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5112                                                              hash_base=>$hash, hash_parent_base=>$parent,
5113                                                              file_name=>$diff->{'file'})},
5114                                               "diff") .
5115                                       " | ";
5116                         }
5117                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5118                                                      hash_base=>$hash, file_name=>$diff->{'file'})},
5119                                        "blob") . " | ";
5120                         if ($have_blame) {
5121                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5122                                                              file_name=>$diff->{'file'})},
5123                                               "blame") . " | ";
5124                         }
5125                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5126                                                      file_name=>$diff->{'file'})},
5127                                       "history");
5128                         print "</td>\n";
5129
5130                 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5131                         my %status_name = ('R' => 'moved', 'C' => 'copied');
5132                         my $nstatus = $status_name{$diff->{'status'}};
5133                         my $mode_chng = "";
5134                         if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5135                                 # mode also for directories, so we cannot use $to_mode_str
5136                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5137                         }
5138                         print "<td>" .
5139                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
5140                                                      hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
5141                                       -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
5142                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5143                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
5144                                                      hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
5145                                       -class => "list"}, esc_path($diff->{'from_file'})) .
5146                               " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5147                               "<td class=\"link\">";
5148                         if ($action eq 'commitdiff') {
5149                                 # link to patch
5150                                 $patchno++;
5151                                 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5152                                               "patch") .
5153                                       " | ";
5154                         } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5155                                 # "commit" view and modified file (not only pure rename or copy)
5156                                 print $cgi->a({-href => href(action=>"blobdiff",
5157                                                              hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5158                                                              hash_base=>$hash, hash_parent_base=>$parent,
5159                                                              file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5160                                               "diff") .
5161                                       " | ";
5162                         }
5163                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5164                                                      hash_base=>$parent, file_name=>$diff->{'to_file'})},
5165                                       "blob") . " | ";
5166                         if ($have_blame) {
5167                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5168                                                              file_name=>$diff->{'to_file'})},
5169                                               "blame") . " | ";
5170                         }
5171                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5172                                                     file_name=>$diff->{'to_file'})},
5173                                       "history");
5174                         print "</td>\n";
5175
5176                 } # we should not encounter Unmerged (U) or Unknown (X) status
5177                 print "</tr>\n";
5178         }
5179         print "</tbody>" if $has_header;
5180         print "</table>\n";
5181 }
5182
5183 # Print context lines and then rem/add lines in a side-by-side manner.
5184 sub print_sidebyside_diff_lines {
5185         my ($ctx, $rem, $add) = @_;
5186
5187         # print context block before add/rem block
5188         if (@$ctx) {
5189                 print join '',
5190                         '<div class="chunk_block ctx">',
5191                                 '<div class="old">',
5192                                 @$ctx,
5193                                 '</div>',
5194                                 '<div class="new">',
5195                                 @$ctx,
5196                                 '</div>',
5197                         '</div>';
5198         }
5199
5200         if (!@$add) {
5201                 # pure removal
5202                 print join '',
5203                         '<div class="chunk_block rem">',
5204                                 '<div class="old">',
5205                                 @$rem,
5206                                 '</div>',
5207                         '</div>';
5208         } elsif (!@$rem) {
5209                 # pure addition
5210                 print join '',
5211                         '<div class="chunk_block add">',
5212                                 '<div class="new">',
5213                                 @$add,
5214                                 '</div>',
5215                         '</div>';
5216         } else {
5217                 print join '',
5218                         '<div class="chunk_block chg">',
5219                                 '<div class="old">',
5220                                 @$rem,
5221                                 '</div>',
5222                                 '<div class="new">',
5223                                 @$add,
5224                                 '</div>',
5225                         '</div>';
5226         }
5227 }
5228
5229 # Print context lines and then rem/add lines in inline manner.
5230 sub print_inline_diff_lines {
5231         my ($ctx, $rem, $add) = @_;
5232
5233         print @$ctx, @$rem, @$add;
5234 }
5235
5236 # Format removed and added line, mark changed part and HTML-format them.
5237 # Implementation is based on contrib/diff-highlight
5238 sub format_rem_add_lines_pair {
5239         my ($rem, $add, $num_parents) = @_;
5240
5241         # We need to untabify lines before split()'ing them;
5242         # otherwise offsets would be invalid.
5243         chomp $rem;
5244         chomp $add;
5245         $rem = untabify($rem);
5246         $add = untabify($add);
5247
5248         my @rem = split(//, $rem);
5249         my @add = split(//, $add);
5250         my ($esc_rem, $esc_add);
5251         # Ignore leading +/- characters for each parent.
5252         my ($prefix_len, $suffix_len) = ($num_parents, 0);
5253         my ($prefix_has_nonspace, $suffix_has_nonspace);
5254
5255         my $shorter = (@rem < @add) ? @rem : @add;
5256         while ($prefix_len < $shorter) {
5257                 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5258
5259                 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5260                 $prefix_len++;
5261         }
5262
5263         while ($prefix_len + $suffix_len < $shorter) {
5264                 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5265
5266                 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5267                 $suffix_len++;
5268         }
5269
5270         # Mark lines that are different from each other, but have some common
5271         # part that isn't whitespace.  If lines are completely different, don't
5272         # mark them because that would make output unreadable, especially if
5273         # diff consists of multiple lines.
5274         if ($prefix_has_nonspace || $suffix_has_nonspace) {
5275                 $esc_rem = esc_html_hl_regions($rem, 'marked',
5276                         [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5277                 $esc_add = esc_html_hl_regions($add, 'marked',
5278                         [$prefix_len, @add - $suffix_len], -nbsp=>1);
5279         } else {
5280                 $esc_rem = esc_html($rem, -nbsp=>1);
5281                 $esc_add = esc_html($add, -nbsp=>1);
5282         }
5283
5284         return format_diff_line(\$esc_rem, 'rem'),
5285                format_diff_line(\$esc_add, 'add');
5286 }
5287
5288 # HTML-format diff context, removed and added lines.
5289 sub format_ctx_rem_add_lines {
5290         my ($ctx, $rem, $add, $num_parents) = @_;
5291         my (@new_ctx, @new_rem, @new_add);
5292         my $can_highlight = 0;
5293         my $is_combined = ($num_parents > 1);
5294
5295         # Highlight if every removed line has a corresponding added line.
5296         if (@$add > 0 && @$add == @$rem) {
5297                 $can_highlight = 1;
5298
5299                 # Highlight lines in combined diff only if the chunk contains
5300                 # diff between the same version, e.g.
5301                 #
5302                 #    - a
5303                 #   -  b
5304                 #    + c
5305                 #   +  d
5306                 #
5307                 # Otherwise the highlighting would be confusing.
5308                 if ($is_combined) {
5309                         for (my $i = 0; $i < @$add; $i++) {
5310                                 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5311                                 my $prefix_add = substr($add->[$i], 0, $num_parents);
5312
5313                                 $prefix_rem =~ s/-/+/g;
5314
5315                                 if ($prefix_rem ne $prefix_add) {
5316                                         $can_highlight = 0;
5317                                         last;
5318                                 }
5319                         }
5320                 }
5321         }
5322
5323         if ($can_highlight) {
5324                 for (my $i = 0; $i < @$add; $i++) {
5325                         my ($line_rem, $line_add) = format_rem_add_lines_pair(
5326                                 $rem->[$i], $add->[$i], $num_parents);
5327                         push @new_rem, $line_rem;
5328                         push @new_add, $line_add;
5329                 }
5330         } else {
5331                 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5332                 @new_add = map { format_diff_line($_, 'add') } @$add;
5333         }
5334
5335         @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5336
5337         return (\@new_ctx, \@new_rem, \@new_add);
5338 }
5339
5340 # Print context lines and then rem/add lines.
5341 sub print_diff_lines {
5342         my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5343         my $is_combined = $num_parents > 1;
5344
5345         ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5346                 $num_parents);
5347
5348         if ($diff_style eq 'sidebyside' && !$is_combined) {
5349                 print_sidebyside_diff_lines($ctx, $rem, $add);
5350         } else {
5351                 # default 'inline' style and unknown styles
5352                 print_inline_diff_lines($ctx, $rem, $add);
5353         }
5354 }
5355
5356 sub print_diff_chunk {
5357         my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5358         my (@ctx, @rem, @add);
5359
5360         # The class of the previous line.
5361         my $prev_class = '';
5362
5363         return unless @chunk;
5364
5365         # incomplete last line might be among removed or added lines,
5366         # or both, or among context lines: find which
5367         for (my $i = 1; $i < @chunk; $i++) {
5368                 if ($chunk[$i][0] eq 'incomplete') {
5369                         $chunk[$i][0] = $chunk[$i-1][0];
5370                 }
5371         }
5372
5373         # guardian
5374         push @chunk, ["", ""];
5375
5376         foreach my $line_info (@chunk) {
5377                 my ($class, $line) = @$line_info;
5378
5379                 # print chunk headers
5380                 if ($class && $class eq 'chunk_header') {
5381                         print format_diff_line($line, $class, $from, $to);
5382                         next;
5383                 }
5384
5385                 ## print from accumulator when have some add/rem lines or end
5386                 # of chunk (flush context lines), or when have add and rem
5387                 # lines and new block is reached (otherwise add/rem lines could
5388                 # be reordered)
5389                 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5390                     (@rem && @add && $class ne $prev_class)) {
5391                         print_diff_lines(\@ctx, \@rem, \@add,
5392                                          $diff_style, $num_parents);
5393                         @ctx = @rem = @add = ();
5394                 }
5395
5396                 ## adding lines to accumulator
5397                 # guardian value
5398                 last unless $line;
5399                 # rem, add or change
5400                 if ($class eq 'rem') {
5401                         push @rem, $line;
5402                 } elsif ($class eq 'add') {
5403                         push @add, $line;
5404                 }
5405                 # context line
5406                 if ($class eq 'ctx') {
5407                         push @ctx, $line;
5408                 }
5409
5410                 $prev_class = $class;
5411         }
5412 }
5413
5414 sub git_patchset_body {
5415         my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5416         my ($hash_parent) = $hash_parents[0];
5417
5418         my $is_combined = (@hash_parents > 1);
5419         my $patch_idx = 0;
5420         my $patch_number = 0;
5421         my $patch_line;
5422         my $diffinfo;
5423         my $to_name;
5424         my (%from, %to);
5425         my @chunk; # for side-by-side diff
5426
5427         print "<div class=\"patchset\">\n";
5428
5429         # skip to first patch
5430         while ($patch_line = <$fd>) {
5431                 chomp $patch_line;
5432
5433                 last if ($patch_line =~ m/^diff /);
5434         }
5435
5436  PATCH:
5437         while ($patch_line) {
5438
5439                 # parse "git diff" header line
5440                 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5441                         # $1 is from_name, which we do not use
5442                         $to_name = unquote($2);
5443                         $to_name =~ s!^b/!!;
5444                 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5445                         # $1 is 'cc' or 'combined', which we do not use
5446                         $to_name = unquote($2);
5447                 } else {
5448                         $to_name = undef;
5449                 }
5450
5451                 # check if current patch belong to current raw line
5452                 # and parse raw git-diff line if needed
5453                 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5454                         # this is continuation of a split patch
5455                         print "<div class=\"patch cont\">\n";
5456                 } else {
5457                         # advance raw git-diff output if needed
5458                         $patch_idx++ if defined $diffinfo;
5459
5460                         # read and prepare patch information
5461                         $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5462
5463                         # compact combined diff output can have some patches skipped
5464                         # find which patch (using pathname of result) we are at now;
5465                         if ($is_combined) {
5466                                 while ($to_name ne $diffinfo->{'to_file'}) {
5467                                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5468                                               format_diff_cc_simplified($diffinfo, @hash_parents) .
5469                                               "</div>\n";  # class="patch"
5470
5471                                         $patch_idx++;
5472                                         $patch_number++;
5473
5474                                         last if $patch_idx > $#$difftree;
5475                                         $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5476                                 }
5477                         }
5478
5479                         # modifies %from, %to hashes
5480                         parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5481
5482                         # this is first patch for raw difftree line with $patch_idx index
5483                         # we index @$difftree array from 0, but number patches from 1
5484                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5485                 }
5486
5487                 # git diff header
5488                 #assert($patch_line =~ m/^diff /) if DEBUG;
5489                 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5490                 $patch_number++;
5491                 # print "git diff" header
5492                 print format_git_diff_header_line($patch_line, $diffinfo,
5493                                                   \%from, \%to);
5494
5495                 # print extended diff header
5496                 print "<div class=\"diff extended_header\">\n";
5497         EXTENDED_HEADER:
5498                 while ($patch_line = <$fd>) {
5499                         chomp $patch_line;
5500
5501                         last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5502
5503                         print format_extended_diff_header_line($patch_line, $diffinfo,
5504                                                                \%from, \%to);
5505                 }
5506                 print "</div>\n"; # class="diff extended_header"
5507
5508                 # from-file/to-file diff header
5509                 if (! $patch_line) {
5510                         print "</div>\n"; # class="patch"
5511                         last PATCH;
5512                 }
5513                 next PATCH if ($patch_line =~ m/^diff /);
5514                 #assert($patch_line =~ m/^---/) if DEBUG;
5515
5516                 my $last_patch_line = $patch_line;
5517                 $patch_line = <$fd>;
5518                 chomp $patch_line;
5519                 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5520
5521                 print format_diff_from_to_header($last_patch_line, $patch_line,
5522                                                  $diffinfo, \%from, \%to,
5523                                                  @hash_parents);
5524
5525                 # the patch itself
5526         LINE:
5527                 while ($patch_line = <$fd>) {
5528                         chomp $patch_line;
5529
5530                         next PATCH if ($patch_line =~ m/^diff /);
5531
5532                         my $class = diff_line_class($patch_line, \%from, \%to);
5533
5534                         if ($class eq 'chunk_header') {
5535                                 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5536                                 @chunk = ();
5537                         }
5538
5539                         push @chunk, [ $class, $patch_line ];
5540                 }
5541
5542         } continue {
5543                 if (@chunk) {
5544                         print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5545                         @chunk = ();
5546                 }
5547                 print "</div>\n"; # class="patch"
5548         }
5549
5550         # for compact combined (--cc) format, with chunk and patch simplification
5551         # the patchset might be empty, but there might be unprocessed raw lines
5552         for (++$patch_idx if $patch_number > 0;
5553              $patch_idx < @$difftree;
5554              ++$patch_idx) {
5555                 # read and prepare patch information
5556                 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5557
5558                 # generate anchor for "patch" links in difftree / whatchanged part
5559                 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5560                       format_diff_cc_simplified($diffinfo, @hash_parents) .
5561                       "</div>\n";  # class="patch"
5562
5563                 $patch_number++;
5564         }
5565
5566         if ($patch_number == 0) {
5567                 if (@hash_parents > 1) {
5568                         print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5569                 } else {
5570                         print "<div class=\"diff nodifferences\">No differences found</div>\n";
5571                 }
5572         }
5573
5574         print "</div>\n"; # class="patchset"
5575 }
5576
5577 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5578
5579 sub git_project_search_form {
5580         my ($searchtext, $search_use_regexp) = @_;
5581
5582         my $limit = '';
5583         if ($project_filter) {
5584                 $limit = " in '$project_filter/'";
5585         }
5586
5587         print "<div class=\"projsearch\">\n";
5588         print $cgi->start_form(-method => 'get', -action => $my_uri) .
5589               $cgi->hidden(-name => 'a', -value => 'project_list')  . "\n";
5590         print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5591                 if (defined $project_filter);
5592         print $cgi->textfield(-name => 's', -value => $searchtext,
5593                               -title => "Search project by name and description$limit",
5594                               -size => 60) . "\n" .
5595               "<span title=\"Extended regular expression\">" .
5596               $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5597                              -checked => $search_use_regexp) .
5598               "</span>\n" .
5599               $cgi->submit(-name => 'btnS', -value => 'Search') .
5600               $cgi->end_form() . "\n" .
5601               $cgi->a({-href => href(project => undef, searchtext => undef,
5602                                      project_filter => $project_filter)},
5603                       esc_html("List all projects$limit")) . "<br />\n";
5604         print "</div>\n";
5605 }
5606
5607 # entry for given @keys needs filling if at least one of keys in list
5608 # is not present in %$project_info
5609 sub project_info_needs_filling {
5610         my ($project_info, @keys) = @_;
5611
5612         # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5613         foreach my $key (@keys) {
5614                 if (!exists $project_info->{$key}) {
5615                         return 1;
5616                 }
5617         }
5618         return;
5619 }
5620
5621 # fills project list info (age, description, owner, category, forks, etc.)
5622 # for each project in the list, removing invalid projects from
5623 # returned list, or fill only specified info.
5624 #
5625 # Invalid projects are removed from the returned list if and only if you
5626 # ask 'age' or 'age_string' to be filled, because they are the only fields
5627 # that run unconditionally git command that requires repository, and
5628 # therefore do always check if project repository is invalid.
5629 #
5630 # USAGE:
5631 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5632 #   ensures that 'descr_long' and 'ctags' fields are filled
5633 # * @project_list = fill_project_list_info(\@project_list)
5634 #   ensures that all fields are filled (and invalid projects removed)
5635 #
5636 # NOTE: modifies $projlist, but does not remove entries from it
5637 sub fill_project_list_info {
5638         my ($projlist, @wanted_keys) = @_;
5639         my @projects;
5640         my $filter_set = sub { return @_; };
5641         if (@wanted_keys) {
5642                 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5643                 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5644         }
5645
5646         my $show_ctags = gitweb_check_feature('ctags');
5647  PROJECT:
5648         foreach my $pr (@$projlist) {
5649                 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5650                         my (@activity) = git_get_last_activity($pr->{'path'});
5651                         unless (@activity) {
5652                                 next PROJECT;
5653                         }
5654                         ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5655                 }
5656                 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5657                         my $descr = git_get_project_description($pr->{'path'}) || "";
5658                         $descr = to_utf8($descr);
5659                         $pr->{'descr_long'} = $descr;
5660                         $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5661                 }
5662                 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5663                         $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5664                 }
5665                 if ($show_ctags &&
5666                     project_info_needs_filling($pr, $filter_set->('ctags'))) {
5667                         $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5668                 }
5669                 if ($projects_list_group_categories &&
5670                     project_info_needs_filling($pr, $filter_set->('category'))) {
5671                         my $cat = git_get_project_category($pr->{'path'}) ||
5672                                                            $project_list_default_category;
5673                         $pr->{'category'} = to_utf8($cat);
5674                 }
5675
5676                 push @projects, $pr;
5677         }
5678
5679         return @projects;
5680 }
5681
5682 sub sort_projects_list {
5683         my ($projlist, $order) = @_;
5684
5685         sub order_str {
5686                 my $key = shift;
5687                 return sub { $a->{$key} cmp $b->{$key} };
5688         }
5689
5690         sub order_num_then_undef {
5691                 my $key = shift;
5692                 return sub {
5693                         defined $a->{$key} ?
5694                                 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5695                                 (defined $b->{$key} ? 1 : 0)
5696                 };
5697         }
5698
5699         my %orderings = (
5700                 project => order_str('path'),
5701                 descr => order_str('descr_long'),
5702                 owner => order_str('owner'),
5703                 age => order_num_then_undef('age'),
5704         );
5705
5706         my $ordering = $orderings{$order};
5707         return defined $ordering ? sort $ordering @$projlist : @$projlist;
5708 }
5709
5710 # returns a hash of categories, containing the list of project
5711 # belonging to each category
5712 sub build_projlist_by_category {
5713         my ($projlist, $from, $to) = @_;
5714         my %categories;
5715
5716         $from = 0 unless defined $from;
5717         $to = $#$projlist if (!defined $to || $#$projlist < $to);
5718
5719         for (my $i = $from; $i <= $to; $i++) {
5720                 my $pr = $projlist->[$i];
5721                 push @{$categories{ $pr->{'category'} }}, $pr;
5722         }
5723
5724         return wantarray ? %categories : \%categories;
5725 }
5726
5727 # print 'sort by' <th> element, generating 'sort by $name' replay link
5728 # if that order is not selected
5729 sub print_sort_th {
5730         print format_sort_th(@_);
5731 }
5732
5733 sub format_sort_th {
5734         my ($name, $order, $header) = @_;
5735         my $sort_th = "";
5736         $header ||= ucfirst($name);
5737
5738         if ($order eq $name) {
5739                 $sort_th .= "<th>$header</th>\n";
5740         } else {
5741                 $sort_th .= "<th>" .
5742                             $cgi->a({-href => href(-replay=>1, order=>$name),
5743                                      -class => "header"}, $header) .
5744                             "</th>\n";
5745         }
5746
5747         return $sort_th;
5748 }
5749
5750 sub git_project_list_rows {
5751         my ($projlist, $from, $to, $check_forks) = @_;
5752
5753         $from = 0 unless defined $from;
5754         $to = $#$projlist if (!defined $to || $#$projlist < $to);
5755
5756         my $alternate = 1;
5757         for (my $i = $from; $i <= $to; $i++) {
5758                 my $pr = $projlist->[$i];
5759
5760                 if ($alternate) {
5761                         print "<tr class=\"dark\">\n";
5762                 } else {
5763                         print "<tr class=\"light\">\n";
5764                 }
5765                 $alternate ^= 1;
5766
5767                 if ($check_forks) {
5768                         print "<td>";
5769                         if ($pr->{'forks'}) {
5770                                 my $nforks = scalar @{$pr->{'forks'}};
5771                                 if ($nforks > 0) {
5772                                         print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5773                                                        -title => "$nforks forks"}, "+");
5774                                 } else {
5775                                         print $cgi->span({-title => "$nforks forks"}, "+");
5776                                 }
5777                         }
5778                         print "</td>\n";
5779                 }
5780                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5781                                         -class => "list"},
5782                                        esc_html_match_hl($pr->{'path'}, $search_regexp)) .
5783                       "</td>\n" .
5784                       "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5785                                         -class => "list",
5786                                         -title => $pr->{'descr_long'}},
5787                                         $search_regexp
5788                                         ? esc_html_match_hl_chopped($pr->{'descr_long'},
5789                                                                     $pr->{'descr'}, $search_regexp)
5790                                         : esc_html($pr->{'descr'})) .
5791                       "</td>\n";
5792                 unless ($omit_owner) {
5793                         print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5794                 }
5795                 unless ($omit_age_column) {
5796                         print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5797                             (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
5798                 }
5799                 print"<td class=\"link\">" .
5800                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
5801                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5802                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5803                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5804                       ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5805                       "</td>\n" .
5806                       "</tr>\n";
5807         }
5808 }
5809
5810 sub git_project_list_body {
5811         # actually uses global variable $project
5812         my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5813         my @projects = @$projlist;
5814
5815         my $check_forks = gitweb_check_feature('forks');
5816         my $show_ctags  = gitweb_check_feature('ctags');
5817         my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
5818         $check_forks = undef
5819                 if ($tagfilter || $search_regexp);
5820
5821         # filtering out forks before filling info allows to do less work
5822         @projects = filter_forks_from_projects_list(\@projects)
5823                 if ($check_forks);
5824         # search_projects_list pre-fills required info
5825         @projects = search_projects_list(\@projects,
5826                                          'search_regexp' => $search_regexp,
5827                                          'tagfilter'  => $tagfilter)
5828                 if ($tagfilter || $search_regexp);
5829         # fill the rest
5830         my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
5831         push @all_fields, ('age', 'age_string') unless($omit_age_column);
5832         push @all_fields, 'owner' unless($omit_owner);
5833         @projects = fill_project_list_info(\@projects, @all_fields);
5834
5835         $order ||= $default_projects_order;
5836         $from = 0 unless defined $from;
5837         $to = $#projects if (!defined $to || $#projects < $to);
5838
5839         # short circuit
5840         if ($from > $to) {
5841                 print "<center>\n".
5842                       "<b>No such projects found</b><br />\n".
5843                       "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5844                       "</center>\n<br />\n";
5845                 return;
5846         }
5847
5848         @projects = sort_projects_list(\@projects, $order);
5849
5850         if ($show_ctags) {
5851                 my $ctags = git_gather_all_ctags(\@projects);
5852                 my $cloud = git_populate_project_tagcloud($ctags);
5853                 print git_show_project_tagcloud($cloud, 64);
5854         }
5855
5856         print "<table class=\"project_list\">\n";
5857         unless ($no_header) {
5858                 print "<tr>\n";
5859                 if ($check_forks) {
5860                         print "<th></th>\n";
5861                 }
5862                 print_sort_th('project', $order, 'Project');
5863                 print_sort_th('descr', $order, 'Description');
5864                 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
5865                 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
5866                 print "<th></th>\n" . # for links
5867                       "</tr>\n";
5868         }
5869
5870         if ($projects_list_group_categories) {
5871                 # only display categories with projects in the $from-$to window
5872                 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5873                 my %categories = build_projlist_by_category(\@projects, $from, $to);
5874                 foreach my $cat (sort keys %categories) {
5875                         unless ($cat eq "") {
5876                                 print "<tr>\n";
5877                                 if ($check_forks) {
5878                                         print "<td></td>\n";
5879                                 }
5880                                 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5881                                 print "</tr>\n";
5882                         }
5883
5884                         git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5885                 }
5886         } else {
5887                 git_project_list_rows(\@projects, $from, $to, $check_forks);
5888         }
5889
5890         if (defined $extra) {
5891                 print "<tr>\n";
5892                 if ($check_forks) {
5893                         print "<td></td>\n";
5894                 }
5895                 print "<td colspan=\"5\">$extra</td>\n" .
5896                       "</tr>\n";
5897         }
5898         print "</table>\n";
5899 }
5900
5901 sub git_log_body {
5902         # uses global variable $project
5903         my ($commitlist, $from, $to, $refs, $extra) = @_;
5904
5905         $from = 0 unless defined $from;
5906         $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5907
5908         for (my $i = 0; $i <= $to; $i++) {
5909                 my %co = %{$commitlist->[$i]};
5910                 next if !%co;
5911                 my $commit = $co{'id'};
5912                 my $ref = format_ref_marker($refs, $commit);
5913                 git_print_header_div('commit',
5914                                "<span class=\"age\">$co{'age_string'}</span>" .
5915                                esc_html($co{'title'}) . $ref,
5916                                $commit);
5917                 print "<div class=\"title_text\">\n" .
5918                       "<div class=\"log_link\">\n" .
5919                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5920                       " | " .
5921                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5922                       " | " .
5923                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5924                       "<br/>\n" .
5925                       "</div>\n";
5926                       git_print_authorship(\%co, -tag => 'span');
5927                       print "<br/>\n</div>\n";
5928
5929                 print "<div class=\"log_body\">\n";
5930                 git_print_log($co{'comment'}, -final_empty_line=> 1);
5931                 print "</div>\n";
5932         }
5933         if ($extra) {
5934                 print "<div class=\"page_nav\">\n";
5935                 print "$extra\n";
5936                 print "</div>\n";
5937         }
5938 }
5939
5940 sub git_shortlog_body {
5941         # uses global variable $project
5942         my ($commitlist, $from, $to, $refs, $extra) = @_;
5943
5944         $from = 0 unless defined $from;
5945         $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5946
5947         print "<table class=\"shortlog\">\n";
5948         my $alternate = 1;
5949         for (my $i = $from; $i <= $to; $i++) {
5950                 my %co = %{$commitlist->[$i]};
5951                 my $commit = $co{'id'};
5952                 my $ref = format_ref_marker($refs, $commit);
5953                 if ($alternate) {
5954                         print "<tr class=\"dark\">\n";
5955                 } else {
5956                         print "<tr class=\"light\">\n";
5957                 }
5958                 $alternate ^= 1;
5959                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5960                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5961                       format_author_html('td', \%co, 10) . "<td>";
5962                 print format_subject_html($co{'title'}, $co{'title_short'},
5963                                           href(action=>"commit", hash=>$commit), $ref);
5964                 print "</td>\n" .
5965                       "<td class=\"link\">" .
5966                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5967                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5968                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5969                 my $snapshot_links = format_snapshot_links($commit);
5970                 if (defined $snapshot_links) {
5971                         print " | " . $snapshot_links;
5972                 }
5973                 print "</td>\n" .
5974                       "</tr>\n";
5975         }
5976         if (defined $extra) {
5977                 print "<tr>\n" .
5978                       "<td colspan=\"4\">$extra</td>\n" .
5979                       "</tr>\n";
5980         }
5981         print "</table>\n";
5982 }
5983
5984 sub git_history_body {
5985         # Warning: assumes constant type (blob or tree) during history
5986         my ($commitlist, $from, $to, $refs, $extra,
5987             $file_name, $file_hash, $ftype) = @_;
5988
5989         $from = 0 unless defined $from;
5990         $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5991
5992         print "<table class=\"history\">\n";
5993         my $alternate = 1;
5994         for (my $i = $from; $i <= $to; $i++) {
5995                 my %co = %{$commitlist->[$i]};
5996                 if (!%co) {
5997                         next;
5998                 }
5999                 my $commit = $co{'id'};
6000
6001                 my $ref = format_ref_marker($refs, $commit);
6002
6003                 if ($alternate) {
6004                         print "<tr class=\"dark\">\n";
6005                 } else {
6006                         print "<tr class=\"light\">\n";
6007                 }
6008                 $alternate ^= 1;
6009                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6010         # shortlog:   format_author_html('td', \%co, 10)
6011                       format_author_html('td', \%co, 15, 3) . "<td>";
6012                 # originally git_history used chop_str($co{'title'}, 50)
6013                 print format_subject_html($co{'title'}, $co{'title_short'},
6014                                           href(action=>"commit", hash=>$commit), $ref);
6015                 print "</td>\n" .
6016                       "<td class=\"link\">" .
6017                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
6018                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
6019
6020                 if ($ftype eq 'blob') {
6021                         print " | " .
6022                               $cgi->a({-href => href(action=>"blob_plain", hash_base=>$commit, file_name=>$file_name)}, "raw");
6023
6024                         my $blob_current = $file_hash;
6025                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
6026                         if (defined $blob_current && defined $blob_parent &&
6027                                         $blob_current ne $blob_parent) {
6028                                 print " | " .
6029                                         $cgi->a({-href => href(action=>"blobdiff",
6030                                                                hash=>$blob_current, hash_parent=>$blob_parent,
6031                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
6032                                                                file_name=>$file_name)},
6033                                                 "diff to current");
6034                         }
6035                 }
6036                 print "</td>\n" .
6037                       "</tr>\n";
6038         }
6039         if (defined $extra) {
6040                 print "<tr>\n" .
6041                       "<td colspan=\"4\">$extra</td>\n" .
6042                       "</tr>\n";
6043         }
6044         print "</table>\n";
6045 }
6046
6047 sub git_tags_body {
6048         # uses global variable $project
6049         my ($taglist, $from, $to, $extra) = @_;
6050         $from = 0 unless defined $from;
6051         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6052
6053         print "<table class=\"tags\">\n";
6054         my $alternate = 1;
6055         for (my $i = $from; $i <= $to; $i++) {
6056                 my $entry = $taglist->[$i];
6057                 my %tag = %$entry;
6058                 my $comment = $tag{'subject'};
6059                 my $comment_short;
6060                 if (defined $comment) {
6061                         $comment_short = chop_str($comment, 30, 5);
6062                 }
6063                 if ($alternate) {
6064                         print "<tr class=\"dark\">\n";
6065                 } else {
6066                         print "<tr class=\"light\">\n";
6067                 }
6068                 $alternate ^= 1;
6069                 if (defined $tag{'age'}) {
6070                         print "<td><i>$tag{'age'}</i></td>\n";
6071                 } else {
6072                         print "<td></td>\n";
6073                 }
6074                 print "<td>" .
6075                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
6076                                -class => "list name"}, esc_html($tag{'name'})) .
6077                       "</td>\n" .
6078                       "<td>";
6079                 if (defined $comment) {
6080                         print format_subject_html($comment, $comment_short,
6081                                                   href(action=>"tag", hash=>$tag{'id'}));
6082                 }
6083                 print "</td>\n" .
6084                       "<td class=\"selflink\">";
6085                 if ($tag{'type'} eq "tag") {
6086                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6087                 } else {
6088                         print "&nbsp;";
6089                 }
6090                 print "</td>\n" .
6091                       "<td class=\"link\">" . " | " .
6092                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6093                 if ($tag{'reftype'} eq "commit") {
6094                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6095                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6096                 } elsif ($tag{'reftype'} eq "blob") {
6097                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6098                 }
6099                 print "</td>\n" .
6100                       "</tr>";
6101         }
6102         if (defined $extra) {
6103                 print "<tr>\n" .
6104                       "<td colspan=\"5\">$extra</td>\n" .
6105                       "</tr>\n";
6106         }
6107         print "</table>\n";
6108 }
6109
6110 sub git_heads_body {
6111         # uses global variable $project
6112         my ($headlist, $head_at, $from, $to, $extra) = @_;
6113         $from = 0 unless defined $from;
6114         $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6115
6116         print "<table class=\"heads\">\n";
6117         my $alternate = 1;
6118         for (my $i = $from; $i <= $to; $i++) {
6119                 my $entry = $headlist->[$i];
6120                 my %ref = %$entry;
6121                 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6122                 if ($alternate) {
6123                         print "<tr class=\"dark\">\n";
6124                 } else {
6125                         print "<tr class=\"light\">\n";
6126                 }
6127                 $alternate ^= 1;
6128                 print "<td><i>$ref{'age'}</i></td>\n" .
6129                       ($curr ? "<td class=\"current_head\">" : "<td>") .
6130                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6131                                -class => "list name"},esc_html($ref{'name'})) .
6132                       "</td>\n" .
6133                       "<td class=\"link\">" .
6134                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6135                       $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6136                       $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6137                       "</td>\n" .
6138                       "</tr>";
6139         }
6140         if (defined $extra) {
6141                 print "<tr>\n" .
6142                       "<td colspan=\"3\">$extra</td>\n" .
6143                       "</tr>\n";
6144         }
6145         print "</table>\n";
6146 }
6147
6148 # Display a single remote block
6149 sub git_remote_block {
6150         my ($remote, $rdata, $limit, $head) = @_;
6151
6152         my $heads = $rdata->{'heads'};
6153         my $fetch = $rdata->{'fetch'};
6154         my $push = $rdata->{'push'};
6155
6156         my $urls_table = "<table class=\"projects_list\">\n" ;
6157
6158         if (defined $fetch) {
6159                 if ($fetch eq $push) {
6160                         $urls_table .= format_repo_url("URL", $fetch);
6161                 } else {
6162                         $urls_table .= format_repo_url("Fetch URL", $fetch);
6163                         $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6164                 }
6165         } elsif (defined $push) {
6166                 $urls_table .= format_repo_url("Push URL", $push);
6167         } else {
6168                 $urls_table .= format_repo_url("", "No remote URL");
6169         }
6170
6171         $urls_table .= "</table>\n";
6172
6173         my $dots;
6174         if (defined $limit && $limit < @$heads) {
6175                 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6176         }
6177
6178         print $urls_table;
6179         git_heads_body($heads, $head, 0, $limit, $dots);
6180 }
6181
6182 # Display a list of remote names with the respective fetch and push URLs
6183 sub git_remotes_list {
6184         my ($remotedata, $limit) = @_;
6185         print "<table class=\"heads\">\n";
6186         my $alternate = 1;
6187         my @remotes = sort keys %$remotedata;
6188
6189         my $limited = $limit && $limit < @remotes;
6190
6191         $#remotes = $limit - 1 if $limited;
6192
6193         while (my $remote = shift @remotes) {
6194                 my $rdata = $remotedata->{$remote};
6195                 my $fetch = $rdata->{'fetch'};
6196                 my $push = $rdata->{'push'};
6197                 if ($alternate) {
6198                         print "<tr class=\"dark\">\n";
6199                 } else {
6200                         print "<tr class=\"light\">\n";
6201                 }
6202                 $alternate ^= 1;
6203                 print "<td>" .
6204                       $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6205                                -class=> "list name"},esc_html($remote)) .
6206                       "</td>";
6207                 print "<td class=\"link\">" .
6208                       (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6209                       " | " .
6210                       (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6211                       "</td>";
6212
6213                 print "</tr>\n";
6214         }
6215
6216         if ($limited) {
6217                 print "<tr>\n" .
6218                       "<td colspan=\"3\">" .
6219                       $cgi->a({-href => href(action=>"remotes")}, "...") .
6220                       "</td>\n" . "</tr>\n";
6221         }
6222
6223         print "</table>";
6224 }
6225
6226 # Display remote heads grouped by remote, unless there are too many
6227 # remotes, in which case we only display the remote names
6228 sub git_remotes_body {
6229         my ($remotedata, $limit, $head) = @_;
6230         if ($limit and $limit < keys %$remotedata) {
6231                 git_remotes_list($remotedata, $limit);
6232         } else {
6233                 fill_remote_heads($remotedata);
6234                 while (my ($remote, $rdata) = each %$remotedata) {
6235                         git_print_section({-class=>"remote", -id=>$remote},
6236                                 ["remotes", $remote, $remote], sub {
6237                                         git_remote_block($remote, $rdata, $limit, $head);
6238                                 });
6239                 }
6240         }
6241 }
6242
6243 sub git_search_message {
6244         my %co = @_;
6245
6246         my $greptype;
6247         if ($searchtype eq 'commit') {
6248                 $greptype = "--grep=";
6249         } elsif ($searchtype eq 'author') {
6250                 $greptype = "--author=";
6251         } elsif ($searchtype eq 'committer') {
6252                 $greptype = "--committer=";
6253         }
6254         $greptype .= $searchtext;
6255         my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6256                                        $greptype, '--regexp-ignore-case',
6257                                        $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6258
6259         my $paging_nav = '';
6260         if ($page > 0) {
6261                 $paging_nav .=
6262                         $cgi->a({-href => href(-replay=>1, page=>undef)},
6263                                 "first") .
6264                         " &sdot; " .
6265                         $cgi->a({-href => href(-replay=>1, page=>$page-1),
6266                                  -accesskey => "p", -title => "Alt-p"}, "prev");
6267         } else {
6268                 $paging_nav .= "first &sdot; prev";
6269         }
6270         my $next_link = '';
6271         if ($#commitlist >= 100) {
6272                 $next_link =
6273                         $cgi->a({-href => href(-replay=>1, page=>$page+1),
6274                                  -accesskey => "n", -title => "Alt-n"}, "next");
6275                 $paging_nav .= " &sdot; $next_link";
6276         } else {
6277                 $paging_nav .= " &sdot; next";
6278         }
6279
6280         git_header_html();
6281
6282         git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6283         git_print_header_div('commit', esc_html($co{'title'}), $hash);
6284         if ($page == 0 && !@commitlist) {
6285                 print "<p>No match.</p>\n";
6286         } else {
6287                 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6288         }
6289
6290         git_footer_html();
6291 }
6292
6293 sub git_search_changes {
6294         my %co = @_;
6295
6296         local $/ = "\n";
6297         open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6298                 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6299                 ($search_use_regexp ? '--pickaxe-regex' : ())
6300                         or die_error(500, "Open git-log failed");
6301
6302         git_header_html();
6303
6304         git_print_page_nav('','', $hash,$co{'tree'},$hash);
6305         git_print_header_div('commit', esc_html($co{'title'}), $hash);
6306
6307         print "<table class=\"pickaxe search\">\n";
6308         my $alternate = 1;
6309         undef %co;
6310         my @files;
6311         while (my $line = <$fd>) {
6312                 chomp $line;
6313                 next unless $line;
6314
6315                 my %set = parse_difftree_raw_line($line);
6316                 if (defined $set{'commit'}) {
6317                         # finish previous commit
6318                         if (%co) {
6319                                 print "</td>\n" .
6320                                       "<td class=\"link\">" .
6321                                       $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6322                                               "commit") .
6323                                       " | " .
6324                                       $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6325                                                              hash_base=>$co{'id'})},
6326                                               "tree") .
6327                                       "</td>\n" .
6328                                       "</tr>\n";
6329                         }
6330
6331                         if ($alternate) {
6332                                 print "<tr class=\"dark\">\n";
6333                         } else {
6334                                 print "<tr class=\"light\">\n";
6335                         }
6336                         $alternate ^= 1;
6337                         %co = parse_commit($set{'commit'});
6338                         my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6339                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6340                               "<td><i>$author</i></td>\n" .
6341                               "<td>" .
6342                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6343                                       -class => "list subject"},
6344                                       chop_and_escape_str($co{'title'}, 50) . "<br/>");
6345                 } elsif (defined $set{'to_id'}) {
6346                         next if is_deleted(\%set);
6347
6348                         print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6349                                                      hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6350                                       -class => "list"},
6351                                       "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6352                               "<br/>\n";
6353                 }
6354         }
6355         close $fd;
6356
6357         # finish last commit (warning: repetition!)
6358         if (%co) {
6359                 print "</td>\n" .
6360                       "<td class=\"link\">" .
6361                       $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6362                               "commit") .
6363                       " | " .
6364                       $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6365                                              hash_base=>$co{'id'})},
6366                               "tree") .
6367                       "</td>\n" .
6368                       "</tr>\n";
6369         }
6370
6371         print "</table>\n";
6372
6373         git_footer_html();
6374 }
6375
6376 sub git_search_files {
6377         my %co = @_;
6378
6379         local $/ = "\n";
6380         open my $fd, "-|", git_cmd(), 'grep', '-n', '-z',
6381                 $search_use_regexp ? ('-E', '-i') : '-F',
6382                 $searchtext, $co{'tree'}
6383                         or die_error(500, "Open git-grep failed");
6384
6385         git_header_html();
6386
6387         git_print_page_nav('','', $hash,$co{'tree'},$hash);
6388         git_print_header_div('commit', esc_html($co{'title'}), $hash);
6389
6390         print "<table class=\"grep_search\">\n";
6391         my $alternate = 1;
6392         my $matches = 0;
6393         my $lastfile = '';
6394         my $file_href;
6395         while (my $line = <$fd>) {
6396                 chomp $line;
6397                 my ($file, $lno, $ltext, $binary);
6398                 last if ($matches++ > 1000);
6399                 if ($line =~ /^Binary file (.+) matches$/) {
6400                         $file = $1;
6401                         $binary = 1;
6402                 } else {
6403                         ($file, $lno, $ltext) = split(/\0/, $line, 3);
6404                         $file =~ s/^$co{'tree'}://;
6405                 }
6406                 if ($file ne $lastfile) {
6407                         $lastfile and print "</td></tr>\n";
6408                         if ($alternate++) {
6409                                 print "<tr class=\"dark\">\n";
6410                         } else {
6411                                 print "<tr class=\"light\">\n";
6412                         }
6413                         $file_href = href(action=>"blob", hash_base=>$co{'id'},
6414                                           file_name=>$file);
6415                         print "<td class=\"list\">".
6416                                 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6417                         print "</td><td>\n";
6418                         $lastfile = $file;
6419                 }
6420                 if ($binary) {
6421                         print "<div class=\"binary\">Binary file</div>\n";
6422                 } else {
6423                         $ltext = untabify($ltext);
6424                         if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6425                                 $ltext = esc_html($1, -nbsp=>1);
6426                                 $ltext .= '<span class="match">';
6427                                 $ltext .= esc_html($2, -nbsp=>1);
6428                                 $ltext .= '</span>';
6429                                 $ltext .= esc_html($3, -nbsp=>1);
6430                         } else {
6431                                 $ltext = esc_html($ltext, -nbsp=>1);
6432                         }
6433                         print "<div class=\"pre\">" .
6434                                 $cgi->a({-href => $file_href.'#l'.$lno,
6435                                         -class => "linenr"}, sprintf('%4i', $lno)) .
6436                                 ' ' .  $ltext . "</div>\n";
6437                 }
6438         }
6439         if ($lastfile) {
6440                 print "</td></tr>\n";
6441                 if ($matches > 1000) {
6442                         print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6443                 }
6444         } else {
6445                 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6446         }
6447         close $fd;
6448
6449         print "</table>\n";
6450
6451         git_footer_html();
6452 }
6453
6454 sub git_search_grep_body {
6455         my ($commitlist, $from, $to, $extra) = @_;
6456         $from = 0 unless defined $from;
6457         $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6458
6459         print "<table class=\"commit_search\">\n";
6460         my $alternate = 1;
6461         for (my $i = $from; $i <= $to; $i++) {
6462                 my %co = %{$commitlist->[$i]};
6463                 if (!%co) {
6464                         next;
6465                 }
6466                 my $commit = $co{'id'};
6467                 if ($alternate) {
6468                         print "<tr class=\"dark\">\n";
6469                 } else {
6470                         print "<tr class=\"light\">\n";
6471                 }
6472                 $alternate ^= 1;
6473                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6474                       format_author_html('td', \%co, 15, 5) .
6475                       "<td>" .
6476                       $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6477                                -class => "list subject"},
6478                               chop_and_escape_str($co{'title'}, 50) . "<br/>");
6479                 my $comment = $co{'comment'};
6480                 foreach my $line (@$comment) {
6481                         if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6482                                 my ($lead, $match, $trail) = ($1, $2, $3);
6483                                 $match = chop_str($match, 70, 5, 'center');
6484                                 my $contextlen = int((80 - length($match))/2);
6485                                 $contextlen = 30 if ($contextlen > 30);
6486                                 $lead  = chop_str($lead,  $contextlen, 10, 'left');
6487                                 $trail = chop_str($trail, $contextlen, 10, 'right');
6488
6489                                 $lead  = esc_html($lead);
6490                                 $match = esc_html($match);
6491                                 $trail = esc_html($trail);
6492
6493                                 print "$lead<span class=\"match\">$match</span>$trail<br />";
6494                         }
6495                 }
6496                 print "</td>\n" .
6497                       "<td class=\"link\">" .
6498                       $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6499                       " | " .
6500                       $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6501                       " | " .
6502                       $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6503                 print "</td>\n" .
6504                       "</tr>\n";
6505         }
6506         if (defined $extra) {
6507                 print "<tr>\n" .
6508                       "<td colspan=\"3\">$extra</td>\n" .
6509                       "</tr>\n";
6510         }
6511         print "</table>\n";
6512 }
6513
6514 ## ======================================================================
6515 ## ======================================================================
6516 ## actions
6517
6518 sub git_project_list {
6519         my $order = $input_params{'order'};
6520         if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6521                 die_error(400, "Unknown order parameter");
6522         }
6523
6524         my @list = git_get_projects_list($project_filter, $strict_export);
6525         if (!@list) {
6526                 die_error(404, "No projects found");
6527         }
6528
6529         git_header_html();
6530         if (defined $home_text && -f $home_text) {
6531                 print "<div class=\"index_include\">\n";
6532                 insert_file($home_text);
6533                 print "</div>\n";
6534         }
6535
6536         git_project_search_form($searchtext, $search_use_regexp);
6537         git_project_list_body(\@list, $order);
6538         git_footer_html();
6539 }
6540
6541 sub git_forks {
6542         my $order = $input_params{'order'};
6543         if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6544                 die_error(400, "Unknown order parameter");
6545         }
6546
6547         my $filter = $project;
6548         $filter =~ s/\.git$//;
6549         my @list = git_get_projects_list($filter);
6550         if (!@list) {
6551                 die_error(404, "No forks found");
6552         }
6553
6554         git_header_html();
6555         git_print_page_nav('','');
6556         git_print_header_div('summary', "$project forks");
6557         git_project_list_body(\@list, $order);
6558         git_footer_html();
6559 }
6560
6561 sub git_project_index {
6562         my @projects = git_get_projects_list($project_filter, $strict_export);
6563         if (!@projects) {
6564                 die_error(404, "No projects found");
6565         }
6566
6567         print $cgi->header(
6568                 -type => 'text/plain',
6569                 -charset => 'utf-8',
6570                 -content_disposition => 'inline; filename="index.aux"');
6571
6572         foreach my $pr (@projects) {
6573                 if (!exists $pr->{'owner'}) {
6574                         $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6575                 }
6576
6577                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6578                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6579                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6580                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6581                 $path  =~ s/ /\+/g;
6582                 $owner =~ s/ /\+/g;
6583
6584                 print "$path $owner\n";
6585         }
6586 }
6587
6588 sub git_summary {
6589         my $descr = git_get_project_description($project) || "none";
6590         my %co = parse_commit("HEAD");
6591         my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6592         my $head = $co{'id'};
6593         my $remote_heads = gitweb_check_feature('remote_heads');
6594
6595         my $owner = git_get_project_owner($project);
6596
6597         my $refs = git_get_references();
6598         # These get_*_list functions return one more to allow us to see if
6599         # there are more ...
6600         my @taglist  = git_get_tags_list(16);
6601         my @headlist = git_get_heads_list(16);
6602         my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6603         my @forklist;
6604         my $check_forks = gitweb_check_feature('forks');
6605
6606         if ($check_forks) {
6607                 # find forks of a project
6608                 my $filter = $project;
6609                 $filter =~ s/\.git$//;
6610                 @forklist = git_get_projects_list($filter);
6611                 # filter out forks of forks
6612                 @forklist = filter_forks_from_projects_list(\@forklist)
6613                         if (@forklist);
6614         }
6615
6616         git_header_html();
6617         git_print_page_nav('summary','', $head);
6618
6619         print "<div class=\"title\">&nbsp;</div>\n";
6620         print "<table class=\"projects_list\">\n" .
6621               "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6622         if ($owner and not $omit_owner) {
6623                 print  "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6624         }
6625         if (defined $cd{'rfc2822'}) {
6626                 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6627                       "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6628         }
6629
6630         # use per project git URL list in $projectroot/$project/cloneurl
6631         # or make project git URL from git base URL and project name
6632         my $url_tag = "URL";
6633         my @url_list = git_get_project_url_list($project);
6634         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6635         foreach my $git_url (@url_list) {
6636                 next unless $git_url;
6637                 print format_repo_url($url_tag, $git_url);
6638                 $url_tag = "";
6639         }
6640
6641         # Tag cloud
6642         my $show_ctags = gitweb_check_feature('ctags');
6643         if ($show_ctags) {
6644                 my $ctags = git_get_project_ctags($project);
6645                 if (%$ctags) {
6646                         # without ability to add tags, don't show if there are none
6647                         my $cloud = git_populate_project_tagcloud($ctags);
6648                         print "<tr id=\"metadata_ctags\">" .
6649                               "<td>content tags</td>" .
6650                               "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
6651                               "</tr>\n";
6652                 }
6653         }
6654
6655         print "</table>\n";
6656
6657         # If XSS prevention is on, we don't include README.html.
6658         # TODO: Allow a readme in some safe format.
6659         if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6660                 print "<div class=\"title\">readme</div>\n" .
6661                       "<div class=\"readme\">\n";
6662                 insert_file("$projectroot/$project/README.html");
6663                 print "\n</div>\n"; # class="readme"
6664         }
6665
6666     if (!$prevent_xss) {
6667         $file_name = "README.md";
6668         my $proj_head_hash = git_get_head_hash($project);
6669         my $readme_blob_hash = git_get_hash_by_path($proj_head_hash, "readme.md", "blob");
6670  
6671         if ($readme_blob_hash) { # if README.md exists
6672             print "<div class=\"header\">$file_name</div>\n";
6673             print "<div class=\"readme page_body\">"; # TODO find/create a better CSS class than page_body
6674             print get_markdown($file_name, $readme_blob_hash);
6675             print "</div>";
6676         }
6677     }
6678
6679         # we need to request one more than 16 (0..15) to check if
6680         # those 16 are all
6681         my @commitlist = $head ? parse_commits($head, 17) : ();
6682         if (@commitlist) {
6683                 git_print_header_div('shortlog');
6684                 git_shortlog_body(\@commitlist, 0, 15, $refs,
6685                                   $#commitlist <=  15 ? undef :
6686                                   $cgi->a({-href => href(action=>"shortlog")}, "..."));
6687         }
6688
6689         if (@taglist) {
6690                 git_print_header_div('tags');
6691                 git_tags_body(\@taglist, 0, 15,
6692                               $#taglist <=  15 ? undef :
6693                               $cgi->a({-href => href(action=>"tags")}, "..."));
6694         }
6695
6696         if (@headlist) {
6697                 git_print_header_div('heads');
6698                 git_heads_body(\@headlist, $head, 0, 15,
6699                                $#headlist <= 15 ? undef :
6700                                $cgi->a({-href => href(action=>"heads")}, "..."));
6701         }
6702
6703         if (%remotedata) {
6704                 git_print_header_div('remotes');
6705                 git_remotes_body(\%remotedata, 15, $head);
6706         }
6707
6708         if (@forklist) {
6709                 git_print_header_div('forks');
6710                 git_project_list_body(\@forklist, 'age', 0, 15,
6711                                       $#forklist <= 15 ? undef :
6712                                       $cgi->a({-href => href(action=>"forks")}, "..."),
6713                                       'no_header');
6714         }
6715
6716         git_footer_html();
6717 }
6718
6719 sub git_tag {
6720         my %tag = parse_tag($hash);
6721
6722         if (! %tag) {
6723                 die_error(404, "Unknown tag object");
6724         }
6725
6726         my $head = git_get_head_hash($project);
6727         git_header_html();
6728         git_print_page_nav('','', $head,undef,$head);
6729         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
6730         print "<div class=\"title_text\">\n" .
6731               "<table class=\"object_header\">\n" .
6732               "<tr>\n" .
6733               "<td>object</td>\n" .
6734               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6735                                $tag{'object'}) . "</td>\n" .
6736               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6737                                               $tag{'type'}) . "</td>\n" .
6738               "</tr>\n";
6739         if (defined($tag{'author'})) {
6740                 git_print_authorship_rows(\%tag, 'author');
6741         }
6742         print "</table>\n\n" .
6743               "</div>\n";
6744         print "<div class=\"page_body\">";
6745         my $comment = $tag{'comment'};
6746         foreach my $line (@$comment) {
6747                 chomp $line;
6748                 print esc_html($line, -nbsp=>1) . "<br/>\n";
6749         }
6750         print "</div>\n";
6751         git_footer_html();
6752 }
6753
6754 sub git_blame_common {
6755         my $format = shift || 'porcelain';
6756         if ($format eq 'porcelain' && $input_params{'javascript'}) {
6757                 $format = 'incremental';
6758                 $action = 'blame_incremental'; # for page title etc
6759         }
6760
6761         # permissions
6762         gitweb_check_feature('blame')
6763                 or die_error(403, "Blame view not allowed");
6764
6765         # error checking
6766         die_error(400, "No file name given") unless $file_name;
6767         $hash_base ||= git_get_head_hash($project);
6768         die_error(404, "Couldn't find base commit") unless $hash_base;
6769         my %co = parse_commit($hash_base)
6770                 or die_error(404, "Commit not found");
6771         my $ftype = "blob";
6772         if (!defined $hash) {
6773                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6774                         or die_error(404, "Error looking up file");
6775         } else {
6776                 $ftype = git_get_type($hash);
6777                 if ($ftype !~ "blob") {
6778                         die_error(400, "Object is not a blob");
6779                 }
6780         }
6781
6782         my $fd;
6783         if ($format eq 'incremental') {
6784                 # get file contents (as base)
6785                 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6786                         or die_error(500, "Open git-cat-file failed");
6787         } elsif ($format eq 'data') {
6788                 # run git-blame --incremental
6789                 open $fd, "-|", git_cmd(), "blame", "--incremental",
6790                         $hash_base, "--", $file_name
6791                         or die_error(500, "Open git-blame --incremental failed");
6792         } else {
6793                 # run git-blame --porcelain
6794                 open $fd, "-|", git_cmd(), "blame", '-p',
6795                         $hash_base, '--', $file_name
6796                         or die_error(500, "Open git-blame --porcelain failed");
6797         }
6798         binmode $fd, ':utf8';
6799
6800         # incremental blame data returns early
6801         if ($format eq 'data') {
6802                 print $cgi->header(
6803                         -type=>"text/plain", -charset => "utf-8",
6804                         -status=> "200 OK");
6805                 local $| = 1; # output autoflush
6806                 while (my $line = <$fd>) {
6807                         print to_utf8($line);
6808                 }
6809                 close $fd
6810                         or print "ERROR $!\n";
6811
6812                 print 'END';
6813                 if (defined $t0 && gitweb_check_feature('timed')) {
6814                         print ' '.
6815                               tv_interval($t0, [ gettimeofday() ]).
6816                               ' '.$number_of_git_cmds;
6817                 }
6818                 print "\n";
6819
6820                 return;
6821         }
6822
6823         # page header
6824         git_header_html();
6825         my $formats_nav =
6826                 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6827                         "blob") .
6828                 " | ";
6829         if ($format eq 'incremental') {
6830                 $formats_nav .=
6831                         $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6832                                 "blame") . " (non-incremental)";
6833         } else {
6834                 $formats_nav .=
6835                         $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6836                                 "blame") . " (incremental)";
6837         }
6838         $formats_nav .=
6839                 " | " .
6840                 $cgi->a({-href => href(action=>"history", -replay=>1)},
6841                         "history") .
6842                 " | " .
6843                 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6844                         "HEAD");
6845         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6846         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6847         git_print_page_path($file_name, $ftype, $hash_base);
6848
6849         # page body
6850         if ($format eq 'incremental') {
6851                 print "<noscript>\n<div class=\"error\"><center><b>\n".
6852                       "This page requires JavaScript to run.\n Use ".
6853                       $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6854                               'this page').
6855                       " instead.\n".
6856                       "</b></center></div>\n</noscript>\n";
6857
6858                 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6859         }
6860
6861         print qq!<div class="page_body">\n!;
6862         print qq!<div id="progress_info">... / ...</div>\n!
6863                 if ($format eq 'incremental');
6864         print qq!<table id="blame_table" class="blame" width="100%">\n!.
6865               #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6866               qq!<thead>\n!.
6867               qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6868               qq!</thead>\n!.
6869               qq!<tbody>\n!;
6870
6871         my @rev_color = qw(light dark);
6872         my $num_colors = scalar(@rev_color);
6873         my $current_color = 0;
6874
6875         if ($format eq 'incremental') {
6876                 my $color_class = $rev_color[$current_color];
6877
6878                 #contents of a file
6879                 my $linenr = 0;
6880         LINE:
6881                 while (my $line = <$fd>) {
6882                         chomp $line;
6883                         $linenr++;
6884
6885                         print qq!<tr id="l$linenr" class="$color_class">!.
6886                               qq!<td class="sha1"><a href=""> </a></td>!.
6887                               qq!<td class="linenr">!.
6888                               qq!<a class="linenr" href="">$linenr</a></td>!;
6889                         print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6890                         print qq!</tr>\n!;
6891                 }
6892
6893         } else { # porcelain, i.e. ordinary blame
6894                 my %metainfo = (); # saves information about commits
6895
6896                 # blame data
6897         LINE:
6898                 while (my $line = <$fd>) {
6899                         chomp $line;
6900                         # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6901                         # no <lines in group> for subsequent lines in group of lines
6902                         my ($full_rev, $orig_lineno, $lineno, $group_size) =
6903                            ($line =~ /^($oid_regex) (\d+) (\d+)(?: (\d+))?$/);
6904                         if (!exists $metainfo{$full_rev}) {
6905                                 $metainfo{$full_rev} = { 'nprevious' => 0 };
6906                         }
6907                         my $meta = $metainfo{$full_rev};
6908                         my $data;
6909                         while ($data = <$fd>) {
6910                                 chomp $data;
6911                                 last if ($data =~ s/^\t//); # contents of line
6912                                 if ($data =~ /^(\S+)(?: (.*))?$/) {
6913                                         $meta->{$1} = $2 unless exists $meta->{$1};
6914                                 }
6915                                 if ($data =~ /^previous /) {
6916                                         $meta->{'nprevious'}++;
6917                                 }
6918                         }
6919                         my $short_rev = substr($full_rev, 0, 8);
6920                         my $author = $meta->{'author'};
6921                         my %date =
6922                                 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6923                         my $date = $date{'iso-tz'};
6924                         if ($group_size) {
6925                                 $current_color = ($current_color + 1) % $num_colors;
6926                         }
6927                         my $tr_class = $rev_color[$current_color];
6928                         $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6929                         $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6930                         $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6931                         print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6932                         if ($group_size) {
6933                                 print "<td class=\"sha1\"";
6934                                 print " title=\"". esc_html($author) . ", $date\"";
6935                                 print " rowspan=\"$group_size\"" if ($group_size > 1);
6936                                 print ">";
6937                                 print $cgi->a({-href => href(action=>"commit",
6938                                                              hash=>$full_rev,
6939                                                              file_name=>$file_name)},
6940                                               esc_html($short_rev));
6941                                 if ($group_size >= 2) {
6942                                         my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6943                                         if (@author_initials) {
6944                                                 print "<br />" .
6945                                                       esc_html(join('', @author_initials));
6946                                                 #           or join('.', ...)
6947                                         }
6948                                 }
6949                                 print "</td>\n";
6950                         }
6951                         # 'previous' <sha1 of parent commit> <filename at commit>
6952                         if (exists $meta->{'previous'} &&
6953                             $meta->{'previous'} =~ /^($oid_regex) (.*)$/) {
6954                                 $meta->{'parent'} = $1;
6955                                 $meta->{'file_parent'} = unquote($2);
6956                         }
6957                         my $linenr_commit =
6958                                 exists($meta->{'parent'}) ?
6959                                 $meta->{'parent'} : $full_rev;
6960                         my $linenr_filename =
6961                                 exists($meta->{'file_parent'}) ?
6962                                 $meta->{'file_parent'} : unquote($meta->{'filename'});
6963                         my $blamed = href(action => 'blame',
6964                                           file_name => $linenr_filename,
6965                                           hash_base => $linenr_commit);
6966                         print "<td class=\"linenr\">";
6967                         print $cgi->a({ -href => "$blamed#l$orig_lineno",
6968                                         -class => "linenr" },
6969                                       esc_html($lineno));
6970                         print "</td>";
6971                         print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6972                         print "</tr>\n";
6973                 } # end while
6974
6975         }
6976
6977         # footer
6978         print "</tbody>\n".
6979               "</table>\n"; # class="blame"
6980         print "</div>\n";   # class="blame_body"
6981         close $fd
6982                 or print "Reading blob failed\n";
6983
6984         git_footer_html();
6985 }
6986
6987 sub git_blame {
6988         git_blame_common();
6989 }
6990
6991 sub git_blame_incremental {
6992         git_blame_common('incremental');
6993 }
6994
6995 sub git_blame_data {
6996         git_blame_common('data');
6997 }
6998
6999 sub git_tags {
7000         my $head = git_get_head_hash($project);
7001         git_header_html();
7002         git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
7003         git_print_header_div('summary', $project);
7004
7005         my @tagslist = git_get_tags_list();
7006         if (@tagslist) {
7007                 git_tags_body(\@tagslist);
7008         }
7009         git_footer_html();
7010 }
7011
7012 sub git_heads {
7013         my $head = git_get_head_hash($project);
7014         git_header_html();
7015         git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
7016         git_print_header_div('summary', $project);
7017
7018         my @headslist = git_get_heads_list();
7019         if (@headslist) {
7020                 git_heads_body(\@headslist, $head);
7021         }
7022         git_footer_html();
7023 }
7024
7025 # used both for single remote view and for list of all the remotes
7026 sub git_remotes {
7027         gitweb_check_feature('remote_heads')
7028                 or die_error(403, "Remote heads view is disabled");
7029
7030         my $head = git_get_head_hash($project);
7031         my $remote = $input_params{'hash'};
7032
7033         my $remotedata = git_get_remotes_list($remote);
7034         die_error(500, "Unable to get remote information") unless defined $remotedata;
7035
7036         unless (%$remotedata) {
7037                 die_error(404, defined $remote ?
7038                         "Remote $remote not found" :
7039                         "No remotes found");
7040         }
7041
7042         git_header_html(undef, undef, -action_extra => $remote);
7043         git_print_page_nav('', '',  $head, undef, $head,
7044                 format_ref_views($remote ? '' : 'remotes'));
7045
7046         fill_remote_heads($remotedata);
7047         if (defined $remote) {
7048                 git_print_header_div('remotes', "$remote remote for $project");
7049                 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
7050         } else {
7051                 git_print_header_div('summary', "$project remotes");
7052                 git_remotes_body($remotedata, undef, $head);
7053         }
7054
7055         git_footer_html();
7056 }
7057
7058 sub git_blob_plain {
7059         my $type = shift;
7060         my $expires;
7061
7062         if (!defined $hash) {
7063                 if (defined $file_name) {
7064                         my $base = $hash_base || git_get_head_hash($project);
7065                         $hash = git_get_hash_by_path($base, $file_name, "blob")
7066                                 or die_error(404, "Cannot find file");
7067                 } else {
7068                         die_error(400, "No file name defined");
7069                 }
7070         } elsif ($hash =~ m/^$oid_regex$/) {
7071                 # blobs defined by non-textual hash id's can be cached
7072                 $expires = "+1d";
7073         }
7074
7075         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7076                 or die_error(500, "Open git-cat-file blob '$hash' failed");
7077
7078         # content-type (can include charset)
7079         $type = blob_contenttype($fd, $file_name, $type);
7080
7081         # "save as" filename, even when no $file_name is given
7082         my $save_as = "$hash";
7083         if (defined $file_name) {
7084                 $save_as = $file_name;
7085         } elsif ($type =~ m/^text\//) {
7086                 $save_as .= '.txt';
7087         }
7088
7089         # With XSS prevention on, blobs of all types except a few known safe
7090         # ones are served with "Content-Disposition: attachment" to make sure
7091         # they don't run in our security domain.  For certain image types,
7092         # blob view writes an <img> tag referring to blob_plain view, and we
7093         # want to be sure not to break that by serving the image as an
7094         # attachment (though Firefox 3 doesn't seem to care).
7095         my $sandbox = $prevent_xss &&
7096                 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7097
7098         # serve text/* as text/plain
7099         if ($prevent_xss &&
7100             ($type =~ m!^text/[a-z]+\b(.*)$! ||
7101              ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7102                 my $rest = $1;
7103                 $rest = defined $rest ? $rest : '';
7104                 $type = "text/plain$rest";
7105         }
7106
7107         print $cgi->header(
7108                 -type => $type,
7109                 -expires => $expires,
7110                 -content_disposition =>
7111                         ($sandbox ? 'attachment' : 'inline')
7112                         . '; filename="' . $save_as . '"');
7113         local $/ = undef;
7114         local *FCGI::Stream::PRINT = $FCGI_Stream_PRINT_raw;
7115         binmode STDOUT, ':raw';
7116         print <$fd>;
7117         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7118         close $fd;
7119 }
7120
7121 sub git_blob {
7122         my $expires;
7123
7124         if (!defined $hash) {
7125                 if (defined $file_name) {
7126                         my $base = $hash_base || git_get_head_hash($project);
7127                         $hash = git_get_hash_by_path($base, $file_name, "blob")
7128                                 or die_error(404, "Cannot find file");
7129                 } else {
7130                         die_error(400, "No file name defined");
7131                 }
7132         } elsif ($hash =~ m/^$oid_regex$/) {
7133                 # blobs defined by non-textual hash id's can be cached
7134                 $expires = "+1d";
7135         }
7136
7137         my $have_blame = gitweb_check_feature('blame');
7138         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
7139                 or die_error(500, "Couldn't cat $file_name, $hash");
7140         my $mimetype = blob_mimetype($fd, $file_name);
7141         # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7142         if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7143                 close $fd;
7144                 return git_blob_plain($mimetype);
7145         }
7146         # we can have blame only for text/* mimetype
7147         $have_blame &&= ($mimetype =~ m!^text/!);
7148
7149         my $highlight = gitweb_check_feature('highlight');
7150         my $syntax = guess_file_syntax($highlight, $file_name);
7151         $fd = run_highlighter($fd, $highlight, $syntax);
7152
7153         my $ismarkdown = ($file_name =~ /md$/);
7154
7155         git_header_html(undef, $expires);
7156         my $formats_nav = '';
7157         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7158                 if (defined $file_name) {
7159                         if ($have_blame) {
7160                                 $formats_nav .=
7161                                         $cgi->a({-href => href(action=>"blame", -replay=>1)},
7162                                                 "blame") .
7163                                         " | ";
7164                         }
7165                         $formats_nav .=
7166                                 $cgi->a({-href => href(action=>"history", -replay=>1)},
7167                                         "history") .
7168                                 " | " .
7169                                 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7170                                         "raw") .
7171                                 " | " .
7172                                 $cgi->a({-href => href(action=>"blob",
7173                                                        hash_base=>"HEAD", file_name=>$file_name)},
7174                                         "HEAD");
7175                 } else {
7176                         $formats_nav .=
7177                                 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7178                                         "raw");
7179                 }
7180                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7181                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7182         } else {
7183                 print "<div class=\"page_nav\">\n" .
7184                       "<br/><br/></div>\n" .
7185                       "<div class=\"title\">".esc_html($hash)."</div>\n";
7186         }
7187         git_print_page_path($file_name, "blob", $hash_base);
7188         print "<div class=\"page_body\">\n";
7189         if ($mimetype =~ m!^image/!) {
7190                 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
7191                 if ($file_name) {
7192                         print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7193                 }
7194                 print qq! src="! .
7195                       esc_attr(href(action=>"blob_plain", hash=>$hash,
7196                            hash_base=>$hash_base, file_name=>$file_name)) .
7197                       qq!" />\n!;
7198     } elsif ($ismarkdown) {
7199         print qq!<div class="readme page_body">\n!;
7200         print get_markdown($file_name, $hash);
7201         print qq!</div>\n!; #  $cmd_markdownify
7202     } else {
7203                 my $nr;
7204                 while (my $line = <$fd>) {
7205                         chomp $line;
7206                         $nr++;
7207                         $line = untabify($line);
7208                         printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7209                                $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7210                                $highlight ? sanitize($line) : esc_html($line, -nbsp=>1);
7211                 }
7212         }
7213         close $fd
7214                 or print "Reading blob failed.\n";
7215         print "</div>";
7216         git_footer_html();
7217 }
7218
7219 sub get_norm_rel_path { # http://www.perlmonks.org/bare/?node_id=11907
7220    my $unnormpath = shift;
7221    while ($unnormpath =~ m!/\.!) {
7222        $unnormpath =~ s!/[^\/]+/\.\.!!;
7223        # print "Path is now -+$unnormpath+-\n";
7224    }
7225    return $unnormpath;
7226 }
7227 sub get_markdown {
7228    my $tfilename = shift;
7229    my $thash = shift;
7230    my $rethtmlstr = "";
7231    use open ":encoding(utf8)"; # needed to have utf8 survive through the shell pipe
7232    my $cmd_markdownify = $GIT . " " . git_cmd() . " cat-file blob " . $thash . " | perl -e 'my \$str = do { local \$/; <STDIN> }; \$str =~ s/<!--.*?--\s*>//gs; print \$str;' | markdown |";
7233    open (FOO, $cmd_markdownify) or die_error(500, "Open git-cat-file blob '$thash' failed");
7234    while (<FOO>) {
7235        if ($_ =~ /(<img[^>]src=")(.*?)"/) {
7236            my $origcut = "".$2;
7237            my $testcut = "".$2;
7238            my $is_anchor = ($testcut =~ /^#/);
7239            my $is_absolute = ($testcut =~ /^http/);
7240            my $is_relative_up = ($testcut =~ /^\.\./);
7241            my $is_local_link = ((!$is_anchor) and (!$is_absolute));
7242            my $tdir = dirname($tfilename);
7243            my $is_tdir_proper = (($tdir ne "") and ($tdir ne "."));
7244            #print "XX: $origcut ($is_anchor, $is_absolute - $is_local_link) ($is_relative_up, $is_tdir_proper, $tdir, $tfilename)\n"; # dbg
7245            if ($is_local_link) {
7246                if ($is_relative_up) { # normalize
7247                    if ($is_tdir_proper) {
7248                        # cheat with absolute path here:
7249                        my $resolved = get_norm_rel_path( File::Spec->rel2abs ("$origcut", "/$tdir" ) );
7250                        $resolved = substr $resolved, 1;
7251                        #print "YY: $resolved\n";
7252                        $_ =~ s!(<img[^>]src=")(.*?)"!$1?p=$project;a=blob_plain;f=$resolved"!gi;
7253                    }
7254                } else {
7255                    $_ =~ s!(<img[^>]src=")(.*?)"!$1?p=$project;a=blob_plain;f=$2"!gi;
7256                    #print "ZZ: $_\n";
7257                }
7258            }
7259        }
7260        if ($_ =~ /(<a[^>]href=")(.*?)"/) {
7261            my $origcut = "".$2;
7262            my $testcut = "".$2;
7263            my $is_anchor = ($testcut =~ /^#/);
7264            my $is_absolute = ($testcut =~ /^http/);
7265            my $is_relative_up = ($testcut =~ /^\.\./);
7266            my $is_local_link = ((!$is_anchor) and (!$is_absolute));
7267            my $tdir = dirname($tfilename);
7268            my $is_tdir_proper = (($tdir ne "") and ($tdir ne "."));
7269            #print "XX: $origcut ($is_anchor, $is_absolute - $is_local_link) ($is_relative_up, $is_tdir_proper, $tdir, $tfilename)\n"; # dbg
7270            if ($is_local_link) {
7271                if ($is_relative_up) { # normalize
7272                    if ($is_tdir_proper) {
7273                        # cheat with absolute path here:
7274                        my $resolved = get_norm_rel_path( File::Spec->rel2abs ("$origcut", "/$tdir" ) );
7275                        $resolved = substr $resolved, 1;
7276                        #print "YY: $resolved\n";
7277                        $_ =~ s!(<a[^>]href=")(.*?)"!$1?p=$project;a=blob;f=$resolved"!gi;
7278                    }
7279                } else {
7280                    $_ =~ s!(<a[^>]href=")(.*?)"!$1?p=$project;a=blob;f=$2"!gi;
7281                    #print "ZZ: $_\n";
7282                }
7283            }
7284        }
7285        $rethtmlstr .= $_;
7286    }
7287    close(FOO);
7288    return $rethtmlstr;
7289 }
7290
7291 sub git_tree {
7292         if (!defined $hash_base) {
7293                 $hash_base = "HEAD";
7294         }
7295         if (!defined $hash) {
7296                 if (defined $file_name) {
7297                         $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7298                 } else {
7299                         $hash = $hash_base;
7300                 }
7301         }
7302         die_error(404, "No such tree") unless defined($hash);
7303
7304         my $show_sizes = gitweb_check_feature('show-sizes');
7305         my $have_blame = gitweb_check_feature('blame');
7306
7307         my @entries = ();
7308         {
7309                 local $/ = "\0";
7310                 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
7311                         ($show_sizes ? '-l' : ()), @extra_options, $hash
7312                         or die_error(500, "Open git-ls-tree failed");
7313                 @entries = map { chomp; $_ } <$fd>;
7314                 close $fd
7315                         or die_error(404, "Reading tree failed");
7316         }
7317
7318         my $refs = git_get_references();
7319         my $ref = format_ref_marker($refs, $hash_base);
7320         git_header_html();
7321         my $basedir = '';
7322         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7323                 my @views_nav = ();
7324                 if (defined $file_name) {
7325                         push @views_nav,
7326                                 $cgi->a({-href => href(action=>"history", -replay=>1)},
7327                                         "history"),
7328                                 $cgi->a({-href => href(action=>"tree",
7329                                                        hash_base=>"HEAD", file_name=>$file_name)},
7330                                         "HEAD"),
7331                 }
7332                 my $snapshot_links = format_snapshot_links($hash);
7333                 if (defined $snapshot_links) {
7334                         # FIXME: Should be available when we have no hash base as well.
7335                         push @views_nav, $snapshot_links;
7336                 }
7337                 git_print_page_nav('tree','', $hash_base, undef, undef,
7338                                    join(' | ', @views_nav));
7339                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7340         } else {
7341                 undef $hash_base;
7342                 print "<div class=\"page_nav\">\n";
7343                 print "<br/><br/></div>\n";
7344                 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7345         }
7346         if (defined $file_name) {
7347                 $basedir = $file_name;
7348                 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7349                         $basedir .= '/';
7350                 }
7351                 git_print_page_path($file_name, 'tree', $hash_base);
7352         }
7353         print "<div class=\"page_body\">\n";
7354         print "<table class=\"tree\">\n";
7355         my $alternate = 1;
7356         # '..' (top directory) link if possible
7357         if (defined $hash_base &&
7358             defined $file_name && $file_name =~ m![^/]+$!) {
7359                 if ($alternate) {
7360                         print "<tr class=\"dark\">\n";
7361                 } else {
7362                         print "<tr class=\"light\">\n";
7363                 }
7364                 $alternate ^= 1;
7365
7366                 my $up = $file_name;
7367                 $up =~ s!/?[^/]+$!!;
7368                 undef $up unless $up;
7369                 # based on git_print_tree_entry
7370                 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7371                 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7372                 print '<td class="list">';
7373                 print $cgi->a({-href => href(action=>"tree",
7374                                              hash_base=>$hash_base,
7375                                              file_name=>$up)},
7376                               "..");
7377                 print "</td>\n";
7378                 print "<td class=\"link\"></td>\n";
7379
7380                 print "</tr>\n";
7381         }
7382         foreach my $line (@entries) {
7383                 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7384
7385                 if ($alternate) {
7386                         print "<tr class=\"dark\">\n";
7387                 } else {
7388                         print "<tr class=\"light\">\n";
7389                 }
7390                 $alternate ^= 1;
7391
7392                 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7393
7394                 print "</tr>\n";
7395         }
7396         print "</table>\n" .
7397               "</div>";
7398         git_footer_html();
7399 }
7400
7401 sub sanitize_for_filename {
7402     my $name = shift;
7403
7404     $name =~ s!/!-!g;
7405     $name =~ s/[^[:alnum:]_.-]//g;
7406
7407     return $name;
7408 }
7409
7410 sub snapshot_name {
7411         my ($project, $hash) = @_;
7412
7413         # path/to/project.git  -> project
7414         # path/to/project/.git -> project
7415         my $name = to_utf8($project);
7416         $name =~ s,([^/])/*\.git$,$1,;
7417         $name = sanitize_for_filename(basename($name));
7418
7419         my $ver = $hash;
7420         if ($hash =~ /^[0-9a-fA-F]+$/) {
7421                 # shorten SHA-1 hash
7422                 my $full_hash = git_get_full_hash($project, $hash);
7423                 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7424                         $ver = git_get_short_hash($project, $hash);
7425                 }
7426         } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7427                 # tags don't need shortened SHA-1 hash
7428                 $ver = $1;
7429         } else {
7430                 # branches and other need shortened SHA-1 hash
7431                 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
7432                 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7433                         my $ref_dir = (defined $1) ? $1 : '';
7434                         $ver = $2;
7435
7436                         $ref_dir = sanitize_for_filename($ref_dir);
7437                         # for refs neither in heads nor remotes we want to
7438                         # add a ref dir to archive name
7439                         if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7440                                 $ver = $ref_dir . '-' . $ver;
7441                         }
7442                 }
7443                 $ver .= '-' . git_get_short_hash($project, $hash);
7444         }
7445         # special case of sanitization for filename - we change
7446         # slashes to dots instead of dashes
7447         # in case of hierarchical branch names
7448         $ver =~ s!/!.!g;
7449         $ver =~ s/[^[:alnum:]_.-]//g;
7450
7451         # name = project-version_string
7452         $name = "$name-$ver";
7453
7454         return wantarray ? ($name, $name) : $name;
7455 }
7456
7457 sub exit_if_unmodified_since {
7458         my ($latest_epoch) = @_;
7459         our $cgi;
7460
7461         my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7462         if (defined $if_modified) {
7463                 my $since;
7464                 if (eval { require HTTP::Date; 1; }) {
7465                         $since = HTTP::Date::str2time($if_modified);
7466                 } elsif (eval { require Time::ParseDate; 1; }) {
7467                         $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7468                 }
7469                 if (defined $since && $latest_epoch <= $since) {
7470                         my %latest_date = parse_date($latest_epoch);
7471                         print $cgi->header(
7472                                 -last_modified => $latest_date{'rfc2822'},
7473                                 -status => '304 Not Modified');
7474                         goto DONE_GITWEB;
7475                 }
7476         }
7477 }
7478
7479 sub git_snapshot {
7480         my $format = $input_params{'snapshot_format'};
7481         if (!@snapshot_fmts) {
7482                 die_error(403, "Snapshots not allowed");
7483         }
7484         # default to first supported snapshot format
7485         $format ||= $snapshot_fmts[0];
7486         if ($format !~ m/^[a-z0-9]+$/) {
7487                 die_error(400, "Invalid snapshot format parameter");
7488         } elsif (!exists($known_snapshot_formats{$format})) {
7489                 die_error(400, "Unknown snapshot format");
7490         } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7491                 die_error(403, "Snapshot format not allowed");
7492         } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7493                 die_error(403, "Unsupported snapshot format");
7494         }
7495
7496         my $type = git_get_type("$hash^{}");
7497         if (!$type) {
7498                 die_error(404, 'Object does not exist');
7499         }  elsif ($type eq 'blob') {
7500                 die_error(400, 'Object is not a tree-ish');
7501         }
7502
7503         my ($name, $prefix) = snapshot_name($project, $hash);
7504         my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7505
7506         my %co = parse_commit($hash);
7507         exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7508
7509         my $cmd = quote_command(
7510                 git_cmd(), 'archive',
7511                 "--format=$known_snapshot_formats{$format}{'format'}",
7512                 "--prefix=$prefix/", $hash);
7513         if (exists $known_snapshot_formats{$format}{'compressor'}) {
7514                 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
7515         }
7516
7517         $filename =~ s/(["\\])/\\$1/g;
7518         my %latest_date;
7519         if (%co) {
7520                 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7521         }
7522
7523         print $cgi->header(
7524                 -type => $known_snapshot_formats{$format}{'type'},
7525                 -content_disposition => 'inline; filename="' . $filename . '"',
7526                 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7527                 -status => '200 OK');
7528
7529         open my $fd, "-|", $cmd
7530                 or die_error(500, "Execute git-archive failed");
7531         local *FCGI::Stream::PRINT = $FCGI_Stream_PRINT_raw;
7532         binmode STDOUT, ':raw';
7533         print <$fd>;
7534         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7535         close $fd;
7536 }
7537
7538 sub git_log_generic {
7539         my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7540
7541         my $head = git_get_head_hash($project);
7542         if (!defined $base) {
7543                 $base = $head;
7544         }
7545         if (!defined $page) {
7546                 $page = 0;
7547         }
7548         my $refs = git_get_references();
7549
7550         my $commit_hash = $base;
7551         if (defined $parent) {
7552                 $commit_hash = "$parent..$base";
7553         }
7554         my @commitlist =
7555                 parse_commits($commit_hash, 101, (100 * $page),
7556                               defined $file_name ? ($file_name, "--full-history") : ());
7557
7558         my $ftype;
7559         if (!defined $file_hash && defined $file_name) {
7560                 # some commits could have deleted file in question,
7561                 # and not have it in tree, but one of them has to have it
7562                 for (my $i = 0; $i < @commitlist; $i++) {
7563                         $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7564                         last if defined $file_hash;
7565                 }
7566         }
7567         if (defined $file_hash) {
7568                 $ftype = git_get_type($file_hash);
7569         }
7570         if (defined $file_name && !defined $ftype) {
7571                 die_error(500, "Unknown type of object");
7572         }
7573         my %co;
7574         if (defined $file_name) {
7575                 %co = parse_commit($base)
7576                         or die_error(404, "Unknown commit object");
7577         }
7578
7579
7580         my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7581         my $next_link = '';
7582         if ($#commitlist >= 100) {
7583                 $next_link =
7584                         $cgi->a({-href => href(-replay=>1, page=>$page+1),
7585                                  -accesskey => "n", -title => "Alt-n"}, "next");
7586         }
7587         my $patch_max = gitweb_get_feature('patches');
7588         if ($patch_max && !defined $file_name &&
7589                 !gitweb_check_feature('email-privacy')) {
7590                 if ($patch_max < 0 || @commitlist <= $patch_max) {
7591                         $paging_nav .= " &sdot; " .
7592                                 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7593                                         "patches");
7594                 }
7595         }
7596
7597         git_header_html();
7598         git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7599         if (defined $file_name) {
7600                 git_print_header_div('commit', esc_html($co{'title'}), $base);
7601         } else {
7602                 git_print_header_div('summary', $project)
7603         }
7604         git_print_page_path($file_name, $ftype, $hash_base)
7605                 if (defined $file_name);
7606
7607         $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7608                      $file_name, $file_hash, $ftype);
7609
7610         git_footer_html();
7611 }
7612
7613 sub git_log {
7614         git_log_generic('log', \&git_log_body,
7615                         $hash, $hash_parent);
7616 }
7617
7618 sub git_commit {
7619         $hash ||= $hash_base || "HEAD";
7620         my %co = parse_commit($hash)
7621             or die_error(404, "Unknown commit object");
7622
7623         my $parent  = $co{'parent'};
7624         my $parents = $co{'parents'}; # listref
7625
7626         # we need to prepare $formats_nav before any parameter munging
7627         my $formats_nav;
7628         if (!defined $parent) {
7629                 # --root commitdiff
7630                 $formats_nav .= '(initial)';
7631         } elsif (@$parents == 1) {
7632                 # single parent commit
7633                 $formats_nav .=
7634                         '(parent: ' .
7635                         $cgi->a({-href => href(action=>"commit",
7636                                                hash=>$parent)},
7637                                 esc_html(substr($parent, 0, 7))) .
7638                         ')';
7639         } else {
7640                 # merge commit
7641                 $formats_nav .=
7642                         '(merge: ' .
7643                         join(' ', map {
7644                                 $cgi->a({-href => href(action=>"commit",
7645                                                        hash=>$_)},
7646                                         esc_html(substr($_, 0, 7)));
7647                         } @$parents ) .
7648                         ')';
7649         }
7650         if (gitweb_check_feature('patches') && @$parents <= 1 &&
7651                 !gitweb_check_feature('email-privacy')) {
7652                 $formats_nav .= " | " .
7653                         $cgi->a({-href => href(action=>"patch", -replay=>1)},
7654                                 "patch");
7655         }
7656
7657         if (!defined $parent) {
7658                 $parent = "--root";
7659         }
7660         my @difftree;
7661         open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
7662                 @diff_opts,
7663                 (@$parents <= 1 ? $parent : '-c'),
7664                 $hash, "--"
7665                 or die_error(500, "Open git-diff-tree failed");
7666         @difftree = map { chomp; $_ } <$fd>;
7667         close $fd or die_error(404, "Reading git-diff-tree failed");
7668
7669         # non-textual hash id's can be cached
7670         my $expires;
7671         if ($hash =~ m/^$oid_regex$/) {
7672                 $expires = "+1d";
7673         }
7674         my $refs = git_get_references();
7675         my $ref = format_ref_marker($refs, $co{'id'});
7676
7677         git_header_html(undef, $expires);
7678         git_print_page_nav('commit', '',
7679                            $hash, $co{'tree'}, $hash,
7680                            $formats_nav);
7681
7682         if (defined $co{'parent'}) {
7683                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7684         } else {
7685                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7686         }
7687         print "<div class=\"title_text\">\n" .
7688               "<table class=\"object_header\">\n";
7689         git_print_authorship_rows(\%co);
7690         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7691         print "<tr>" .
7692               "<td>tree</td>" .
7693               "<td class=\"sha1\">" .
7694               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7695                        class => "list"}, $co{'tree'}) .
7696               "</td>" .
7697               "<td class=\"link\">" .
7698               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7699                       "tree");
7700         my $snapshot_links = format_snapshot_links($hash);
7701         if (defined $snapshot_links) {
7702                 print " | " . $snapshot_links;
7703         }
7704         print "</td>" .
7705               "</tr>\n";
7706
7707         foreach my $par (@$parents) {
7708                 print "<tr>" .
7709                       "<td>parent</td>" .
7710                       "<td class=\"sha1\">" .
7711                       $cgi->a({-href => href(action=>"commit", hash=>$par),
7712                                class => "list"}, $par) .
7713                       "</td>" .
7714                       "<td class=\"link\">" .
7715                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7716                       " | " .
7717                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7718                       "</td>" .
7719                       "</tr>\n";
7720         }
7721         print "</table>".
7722               "</div>\n";
7723
7724         print "<div class=\"page_body\">\n";
7725         git_print_log($co{'comment'});
7726         print "</div>\n";
7727
7728         git_difftree_body(\@difftree, $hash, @$parents);
7729
7730         git_footer_html();
7731 }
7732
7733 sub git_object {
7734         # object is defined by:
7735         # - hash or hash_base alone
7736         # - hash_base and file_name
7737         my $type;
7738
7739         # - hash or hash_base alone
7740         if ($hash || ($hash_base && !defined $file_name)) {
7741                 my $object_id = $hash || $hash_base;
7742
7743                 open my $fd, "-|", quote_command(
7744                         git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
7745                         or die_error(404, "Object does not exist");
7746                 $type = <$fd>;
7747                 defined $type && chomp $type;
7748                 close $fd
7749                         or die_error(404, "Object does not exist");
7750
7751         # - hash_base and file_name
7752         } elsif ($hash_base && defined $file_name) {
7753                 $file_name =~ s,/+$,,;
7754
7755                 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7756                         or die_error(404, "Base object does not exist");
7757
7758                 # here errors should not happen
7759                 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
7760                         or die_error(500, "Open git-ls-tree failed");
7761                 my $line = <$fd>;
7762                 close $fd;
7763
7764                 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
7765                 unless ($line && $line =~ m/^([0-9]+) (.+) ($oid_regex)\t/) {
7766                         die_error(404, "File or directory for given base does not exist");
7767                 }
7768                 $type = $2;
7769                 $hash = $3;
7770         } else {
7771                 die_error(400, "Not enough information to find object");
7772         }
7773
7774         print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7775                                           hash=>$hash, hash_base=>$hash_base,
7776                                           file_name=>$file_name),
7777                              -status => '302 Found');
7778 }
7779
7780 sub git_blobdiff {
7781         my $format = shift || 'html';
7782         my $diff_style = $input_params{'diff_style'} || 'inline';
7783
7784         my $fd;
7785         my @difftree;
7786         my %diffinfo;
7787         my $expires;
7788
7789         # preparing $fd and %diffinfo for git_patchset_body
7790         # new style URI
7791         if (defined $hash_base && defined $hash_parent_base) {
7792                 if (defined $file_name) {
7793                         # read raw output
7794                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7795                                 $hash_parent_base, $hash_base,
7796                                 "--", (defined $file_parent ? $file_parent : ()), $file_name
7797                                 or die_error(500, "Open git-diff-tree failed");
7798                         @difftree = map { chomp; $_ } <$fd>;
7799                         close $fd
7800                                 or die_error(404, "Reading git-diff-tree failed");
7801                         @difftree
7802                                 or die_error(404, "Blob diff not found");
7803
7804                 } elsif (defined $hash &&
7805                          $hash =~ $oid_regex) {
7806                         # try to find filename from $hash
7807
7808                         # read filtered raw output
7809                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7810                                 $hash_parent_base, $hash_base, "--"
7811                                 or die_error(500, "Open git-diff-tree failed");
7812                         @difftree =
7813                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
7814                                 # $hash == to_id
7815                                 grep { /^:[0-7]{6} [0-7]{6} $oid_regex $hash/ }
7816                                 map { chomp; $_ } <$fd>;
7817                         close $fd
7818                                 or die_error(404, "Reading git-diff-tree failed");
7819                         @difftree
7820                                 or die_error(404, "Blob diff not found");
7821
7822                 } else {
7823                         die_error(400, "Missing one of the blob diff parameters");
7824                 }
7825
7826                 if (@difftree > 1) {
7827                         die_error(400, "Ambiguous blob diff specification");
7828                 }
7829
7830                 %diffinfo = parse_difftree_raw_line($difftree[0]);
7831                 $file_parent ||= $diffinfo{'from_file'} || $file_name;
7832                 $file_name   ||= $diffinfo{'to_file'};
7833
7834                 $hash_parent ||= $diffinfo{'from_id'};
7835                 $hash        ||= $diffinfo{'to_id'};
7836
7837                 # non-textual hash id's can be cached
7838                 if ($hash_base =~ m/^$oid_regex$/ &&
7839                     $hash_parent_base =~ m/^$oid_regex$/) {
7840                         $expires = '+1d';
7841                 }
7842
7843                 # open patch output
7844                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7845                         '-p', ($format eq 'html' ? "--full-index" : ()),
7846                         $hash_parent_base, $hash_base,
7847                         "--", (defined $file_parent ? $file_parent : ()), $file_name
7848                         or die_error(500, "Open git-diff-tree failed");
7849         }
7850
7851         # old/legacy style URI -- not generated anymore since 1.4.3.
7852         if (!%diffinfo) {
7853                 die_error('404 Not Found', "Missing one of the blob diff parameters")
7854         }
7855
7856         # header
7857         if ($format eq 'html') {
7858                 my $formats_nav =
7859                         $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
7860                                 "raw");
7861                 $formats_nav .= diff_style_nav($diff_style);
7862                 git_header_html(undef, $expires);
7863                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7864                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7865                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7866                 } else {
7867                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
7868                         print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7869                 }
7870                 if (defined $file_name) {
7871                         git_print_page_path($file_name, "blob", $hash_base);
7872                 } else {
7873                         print "<div class=\"page_path\"></div>\n";
7874                 }
7875
7876         } elsif ($format eq 'plain') {
7877                 print $cgi->header(
7878                         -type => 'text/plain',
7879                         -charset => 'utf-8',
7880                         -expires => $expires,
7881                         -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7882
7883                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7884
7885         } else {
7886                 die_error(400, "Unknown blobdiff format");
7887         }
7888
7889         # patch
7890         if ($format eq 'html') {
7891                 print "<div class=\"page_body\">\n";
7892
7893                 git_patchset_body($fd, $diff_style,
7894                                   [ \%diffinfo ], $hash_base, $hash_parent_base);
7895                 close $fd;
7896
7897                 print "</div>\n"; # class="page_body"
7898                 git_footer_html();
7899
7900         } else {
7901                 while (my $line = <$fd>) {
7902                         $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7903                         $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7904
7905                         print $line;
7906
7907                         last if $line =~ m!^\+\+\+!;
7908                 }
7909                 local $/ = undef;
7910                 print <$fd>;
7911                 close $fd;
7912         }
7913 }
7914
7915 sub git_blobdiff_plain {
7916         git_blobdiff('plain');
7917 }
7918
7919 # assumes that it is added as later part of already existing navigation,
7920 # so it returns "| foo | bar" rather than just "foo | bar"
7921 sub diff_style_nav {
7922         my ($diff_style, $is_combined) = @_;
7923         $diff_style ||= 'inline';
7924
7925         return "" if ($is_combined);
7926
7927         my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
7928         my %styles = @styles;
7929         @styles =
7930                 @styles[ map { $_ * 2 } 0..$#styles/2 ];
7931
7932         return join '',
7933                 map { " | ".$_ }
7934                 map {
7935                         $_ eq $diff_style ? $styles{$_} :
7936                         $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
7937                 } @styles;
7938 }
7939
7940 sub git_commitdiff {
7941         my %params = @_;
7942         my $format = $params{-format} || 'html';
7943         my $diff_style = $input_params{'diff_style'} || 'inline';
7944
7945         my ($patch_max) = gitweb_get_feature('patches');
7946         if ($format eq 'patch') {
7947                 die_error(403, "Patch view not allowed") unless $patch_max;
7948         }
7949
7950         $hash ||= $hash_base || "HEAD";
7951         my %co = parse_commit($hash)
7952             or die_error(404, "Unknown commit object");
7953
7954         # choose format for commitdiff for merge
7955         if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7956                 $hash_parent = '--cc';
7957         }
7958         # we need to prepare $formats_nav before almost any parameter munging
7959         my $formats_nav;
7960         if ($format eq 'html') {
7961                 $formats_nav =
7962                         $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7963                                 "raw");
7964                 if ($patch_max && @{$co{'parents'}} <= 1 &&
7965                         !gitweb_check_feature('email-privacy')) {
7966                         $formats_nav .= " | " .
7967                                 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7968                                         "patch");
7969                 }
7970                 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
7971
7972                 if (defined $hash_parent &&
7973                     $hash_parent ne '-c' && $hash_parent ne '--cc') {
7974                         # commitdiff with two commits given
7975                         my $hash_parent_short = $hash_parent;
7976                         if ($hash_parent =~ m/^$oid_regex$/) {
7977                                 $hash_parent_short = substr($hash_parent, 0, 7);
7978                         }
7979                         $formats_nav .=
7980                                 ' (from';
7981                         for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7982                                 if ($co{'parents'}[$i] eq $hash_parent) {
7983                                         $formats_nav .= ' parent ' . ($i+1);
7984                                         last;
7985                                 }
7986                         }
7987                         $formats_nav .= ': ' .
7988                                 $cgi->a({-href => href(-replay=>1,
7989                                                        hash=>$hash_parent, hash_base=>undef)},
7990                                         esc_html($hash_parent_short)) .
7991                                 ')';
7992                 } elsif (!$co{'parent'}) {
7993                         # --root commitdiff
7994                         $formats_nav .= ' (initial)';
7995                 } elsif (scalar @{$co{'parents'}} == 1) {
7996                         # single parent commit
7997                         $formats_nav .=
7998                                 ' (parent: ' .
7999                                 $cgi->a({-href => href(-replay=>1,
8000                                                        hash=>$co{'parent'}, hash_base=>undef)},
8001                                         esc_html(substr($co{'parent'}, 0, 7))) .
8002                                 ')';
8003                 } else {
8004                         # merge commit
8005                         if ($hash_parent eq '--cc') {
8006                                 $formats_nav .= ' | ' .
8007                                         $cgi->a({-href => href(-replay=>1,
8008                                                                hash=>$hash, hash_parent=>'-c')},
8009                                                 'combined');
8010                         } else { # $hash_parent eq '-c'
8011                                 $formats_nav .= ' | ' .
8012                                         $cgi->a({-href => href(-replay=>1,
8013                                                                hash=>$hash, hash_parent=>'--cc')},
8014                                                 'compact');
8015                         }
8016                         $formats_nav .=
8017                                 ' (merge: ' .
8018                                 join(' ', map {
8019                                         $cgi->a({-href => href(-replay=>1,
8020                                                                hash=>$_, hash_base=>undef)},
8021                                                 esc_html(substr($_, 0, 7)));
8022                                 } @{$co{'parents'}} ) .
8023                                 ')';
8024                 }
8025         }
8026
8027         my $hash_parent_param = $hash_parent;
8028         if (!defined $hash_parent_param) {
8029                 # --cc for multiple parents, --root for parentless
8030                 $hash_parent_param =
8031                         @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
8032         }
8033
8034         # read commitdiff
8035         my $fd;
8036         my @difftree;
8037         if ($format eq 'html') {
8038                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8039                         "--no-commit-id", "--patch-with-raw", "--full-index",
8040                         $hash_parent_param, $hash, "--"
8041                         or die_error(500, "Open git-diff-tree failed");
8042
8043                 while (my $line = <$fd>) {
8044                         chomp $line;
8045                         # empty line ends raw part of diff-tree output
8046                         last unless $line;
8047                         push @difftree, scalar parse_difftree_raw_line($line);
8048                 }
8049
8050         } elsif ($format eq 'plain') {
8051                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8052                         '-p', $hash_parent_param, $hash, "--"
8053                         or die_error(500, "Open git-diff-tree failed");
8054         } elsif ($format eq 'patch') {
8055                 # For commit ranges, we limit the output to the number of
8056                 # patches specified in the 'patches' feature.
8057                 # For single commits, we limit the output to a single patch,
8058                 # diverging from the git-format-patch default.
8059                 my @commit_spec = ();
8060                 if ($hash_parent) {
8061                         if ($patch_max > 0) {
8062                                 push @commit_spec, "-$patch_max";
8063                         }
8064                         push @commit_spec, '-n', "$hash_parent..$hash";
8065                 } else {
8066                         if ($params{-single}) {
8067                                 push @commit_spec, '-1';
8068                         } else {
8069                                 if ($patch_max > 0) {
8070                                         push @commit_spec, "-$patch_max";
8071                                 }
8072                                 push @commit_spec, "-n";
8073                         }
8074                         push @commit_spec, '--root', $hash;
8075                 }
8076                 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
8077                         '--encoding=utf8', '--stdout', @commit_spec
8078                         or die_error(500, "Open git-format-patch failed");
8079         } else {
8080                 die_error(400, "Unknown commitdiff format");
8081         }
8082
8083         # non-textual hash id's can be cached
8084         my $expires;
8085         if ($hash =~ m/^$oid_regex$/) {
8086                 $expires = "+1d";
8087         }
8088
8089         # write commit message
8090         if ($format eq 'html') {
8091                 my $refs = git_get_references();
8092                 my $ref = format_ref_marker($refs, $co{'id'});
8093
8094                 git_header_html(undef, $expires);
8095                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
8096                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
8097                 print "<div class=\"title_text\">\n" .
8098                       "<table class=\"object_header\">\n";
8099                 git_print_authorship_rows(\%co);
8100                 print "</table>".
8101                       "</div>\n";
8102                 print "<div class=\"page_body\">\n";
8103                 if (@{$co{'comment'}} > 1) {
8104                         print "<div class=\"log\">\n";
8105                         git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
8106                         print "</div>\n"; # class="log"
8107                 }
8108
8109         } elsif ($format eq 'plain') {
8110                 my $refs = git_get_references("tags");
8111                 my $tagname = git_get_rev_name_tags($hash);
8112                 my $filename = basename($project) . "-$hash.patch";
8113
8114                 print $cgi->header(
8115                         -type => 'text/plain',
8116                         -charset => 'utf-8',
8117                         -expires => $expires,
8118                         -content_disposition => 'inline; filename="' . "$filename" . '"');
8119                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
8120                 print "From: " . to_utf8($co{'author'}) . "\n";
8121                 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
8122                 print "Subject: " . to_utf8($co{'title'}) . "\n";
8123
8124                 print "X-Git-Tag: $tagname\n" if $tagname;
8125                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
8126
8127                 foreach my $line (@{$co{'comment'}}) {
8128                         print to_utf8($line) . "\n";
8129                 }
8130                 print "---\n\n";
8131         } elsif ($format eq 'patch') {
8132                 my $filename = basename($project) . "-$hash.patch";
8133
8134                 print $cgi->header(
8135                         -type => 'text/plain',
8136                         -charset => 'utf-8',
8137                         -expires => $expires,
8138                         -content_disposition => 'inline; filename="' . "$filename" . '"');
8139         }
8140
8141         # write patch
8142         if ($format eq 'html') {
8143                 my $use_parents = !defined $hash_parent ||
8144                         $hash_parent eq '-c' || $hash_parent eq '--cc';
8145                 git_difftree_body(\@difftree, $hash,
8146                                   $use_parents ? @{$co{'parents'}} : $hash_parent);
8147                 print "<br/>\n";
8148
8149                 git_patchset_body($fd, $diff_style,
8150                                   \@difftree, $hash,
8151                                   $use_parents ? @{$co{'parents'}} : $hash_parent);
8152                 close $fd;
8153                 print "</div>\n"; # class="page_body"
8154                 git_footer_html();
8155
8156         } elsif ($format eq 'plain') {
8157                 local $/ = undef;
8158                 print <$fd>;
8159                 close $fd
8160                         or print "Reading git-diff-tree failed\n";
8161         } elsif ($format eq 'patch') {
8162                 local $/ = undef;
8163                 print <$fd>;
8164                 close $fd
8165                         or print "Reading git-format-patch failed\n";
8166         }
8167 }
8168
8169 sub git_commitdiff_plain {
8170         git_commitdiff(-format => 'plain');
8171 }
8172
8173 # format-patch-style patches
8174 sub git_patch {
8175         git_commitdiff(-format => 'patch', -single => 1);
8176 }
8177
8178 sub git_patches {
8179         git_commitdiff(-format => 'patch');
8180 }
8181
8182 sub git_history {
8183         git_log_generic('history', \&git_history_body,
8184                         $hash_base, $hash_parent_base,
8185                         $file_name, $hash);
8186 }
8187
8188 sub git_search {
8189         $searchtype ||= 'commit';
8190
8191         # check if appropriate features are enabled
8192         gitweb_check_feature('search')
8193                 or die_error(403, "Search is disabled");
8194         if ($searchtype eq 'pickaxe') {
8195                 # pickaxe may take all resources of your box and run for several minutes
8196                 # with every query - so decide by yourself how public you make this feature
8197                 gitweb_check_feature('pickaxe')
8198                         or die_error(403, "Pickaxe search is disabled");
8199         }
8200         if ($searchtype eq 'grep') {
8201                 # grep search might be potentially CPU-intensive, too
8202                 gitweb_check_feature('grep')
8203                         or die_error(403, "Grep search is disabled");
8204         }
8205
8206         if (!defined $searchtext) {
8207                 die_error(400, "Text field is empty");
8208         }
8209         if (!defined $hash) {
8210                 $hash = git_get_head_hash($project);
8211         }
8212         my %co = parse_commit($hash);
8213         if (!%co) {
8214                 die_error(404, "Unknown commit object");
8215         }
8216         if (!defined $page) {
8217                 $page = 0;
8218         }
8219
8220         if ($searchtype eq 'commit' ||
8221             $searchtype eq 'author' ||
8222             $searchtype eq 'committer') {
8223                 git_search_message(%co);
8224         } elsif ($searchtype eq 'pickaxe') {
8225                 git_search_changes(%co);
8226         } elsif ($searchtype eq 'grep') {
8227                 git_search_files(%co);
8228         } else {
8229                 die_error(400, "Unknown search type");
8230         }
8231 }
8232
8233 sub git_search_help {
8234         git_header_html();
8235         git_print_page_nav('','', $hash,$hash,$hash);
8236         print <<EOT;
8237 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8238 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8239 the pattern entered is recognized as the POSIX extended
8240 <a href="https://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8241 insensitive).</p>
8242 <dl>
8243 <dt><b>commit</b></dt>
8244 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8245 EOT
8246         my $have_grep = gitweb_check_feature('grep');
8247         if ($have_grep) {
8248                 print <<EOT;
8249 <dt><b>grep</b></dt>
8250 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8251     a different one) are searched for the given pattern. On large trees, this search can take
8252 a while and put some strain on the server, so please use it with some consideration. Note that
8253 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8254 case-sensitive.</dd>
8255 EOT
8256         }
8257         print <<EOT;
8258 <dt><b>author</b></dt>
8259 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8260 <dt><b>committer</b></dt>
8261 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8262 EOT
8263         my $have_pickaxe = gitweb_check_feature('pickaxe');
8264         if ($have_pickaxe) {
8265                 print <<EOT;
8266 <dt><b>pickaxe</b></dt>
8267 <dd>All commits that caused the string to appear or disappear from any file (changes that
8268 added, removed or "modified" the string) will be listed. This search can take a while and
8269 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8270 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8271 EOT
8272         }
8273         print "</dl>\n";
8274         git_footer_html();
8275 }
8276
8277 sub git_shortlog {
8278         git_log_generic('shortlog', \&git_shortlog_body,
8279                         $hash, $hash_parent);
8280 }
8281
8282 ## ......................................................................
8283 ## feeds (RSS, Atom; OPML)
8284
8285 sub git_feed {
8286         my $format = shift || 'atom';
8287         my $have_blame = gitweb_check_feature('blame');
8288
8289         # Atom: http://www.atomenabled.org/developers/syndication/
8290         # RSS:  https://web.archive.org/web/20030729001534/http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8291         if ($format ne 'rss' && $format ne 'atom') {
8292                 die_error(400, "Unknown web feed format");
8293         }
8294
8295         # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8296         my $head = $hash || 'HEAD';
8297         my @commitlist = parse_commits($head, 150, 0, $file_name);
8298
8299         my %latest_commit;
8300         my %latest_date;
8301         my $content_type = "application/$format+xml";
8302         if (defined $cgi->http('HTTP_ACCEPT') &&
8303                  $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8304                 # browser (feed reader) prefers text/xml
8305                 $content_type = 'text/xml';
8306         }
8307         if (defined($commitlist[0])) {
8308                 %latest_commit = %{$commitlist[0]};
8309                 my $latest_epoch = $latest_commit{'committer_epoch'};
8310                 exit_if_unmodified_since($latest_epoch);
8311                 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8312         }
8313         print $cgi->header(
8314                 -type => $content_type,
8315                 -charset => 'utf-8',
8316                 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8317                 -status => '200 OK');
8318
8319         # Optimization: skip generating the body if client asks only
8320         # for Last-Modified date.
8321         return if ($cgi->request_method() eq 'HEAD');
8322
8323         # header variables
8324         my $title = "$site_name - $project/$action";
8325         my $feed_type = 'log';
8326         if (defined $hash) {
8327                 $title .= " - '$hash'";
8328                 $feed_type = 'branch log';
8329                 if (defined $file_name) {
8330                         $title .= " :: $file_name";
8331                         $feed_type = 'history';
8332                 }
8333         } elsif (defined $file_name) {
8334                 $title .= " - $file_name";
8335                 $feed_type = 'history';
8336         }
8337         $title .= " $feed_type";
8338         $title = esc_html($title);
8339         my $descr = git_get_project_description($project);
8340         if (defined $descr) {
8341                 $descr = esc_html($descr);
8342         } else {
8343                 $descr = "$project " .
8344                          ($format eq 'rss' ? 'RSS' : 'Atom') .
8345                          " feed";
8346         }
8347         my $owner = git_get_project_owner($project);
8348         $owner = esc_html($owner);
8349
8350         #header
8351         my $alt_url;
8352         if (defined $file_name) {
8353                 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8354         } elsif (defined $hash) {
8355                 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8356         } else {
8357                 $alt_url = href(-full=>1, action=>"summary");
8358         }
8359         $alt_url = esc_attr($alt_url);
8360         print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8361         if ($format eq 'rss') {
8362                 print <<XML;
8363 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8364 <channel>
8365 XML
8366                 print "<title>$title</title>\n" .
8367                       "<link>$alt_url</link>\n" .
8368                       "<description>$descr</description>\n" .
8369                       "<language>en</language>\n" .
8370                       # project owner is responsible for 'editorial' content
8371                       "<managingEditor>$owner</managingEditor>\n";
8372                 if (defined $logo || defined $favicon) {
8373                         # prefer the logo to the favicon, since RSS
8374                         # doesn't allow both
8375                         my $img = esc_url($logo || $favicon);
8376                         print "<image>\n" .
8377                               "<url>$img</url>\n" .
8378                               "<title>$title</title>\n" .
8379                               "<link>$alt_url</link>\n" .
8380                               "</image>\n";
8381                 }
8382                 if (%latest_date) {
8383                         print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8384                         print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8385                 }
8386                 print "<generator>gitweb v.$version/$git_version</generator>\n";
8387         } elsif ($format eq 'atom') {
8388                 print <<XML;
8389 <feed xmlns="http://www.w3.org/2005/Atom">
8390 XML
8391                 print "<title>$title</title>\n" .
8392                       "<subtitle>$descr</subtitle>\n" .
8393                       '<link rel="alternate" type="text/html" href="' .
8394                       $alt_url . '" />' . "\n" .
8395                       '<link rel="self" type="' . $content_type . '" href="' .
8396                       $cgi->self_url() . '" />' . "\n" .
8397                       "<id>" . esc_url(href(-full=>1)) . "</id>\n" .
8398                       # use project owner for feed author
8399                       "<author><name>$owner</name></author>\n";
8400                 if (defined $favicon) {
8401                         print "<icon>" . esc_url($favicon) . "</icon>\n";
8402                 }
8403                 if (defined $logo) {
8404                         # not twice as wide as tall: 72 x 27 pixels
8405                         print "<logo>" . esc_url($logo) . "</logo>\n";
8406                 }
8407                 if (! %latest_date) {
8408                         # dummy date to keep the feed valid until commits trickle in:
8409                         print "<updated>1970-01-01T00:00:00Z</updated>\n";
8410                 } else {
8411                         print "<updated>$latest_date{'iso-8601'}</updated>\n";
8412                 }
8413                 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8414         }
8415
8416         # contents
8417         for (my $i = 0; $i <= $#commitlist; $i++) {
8418                 my %co = %{$commitlist[$i]};
8419                 my $commit = $co{'id'};
8420                 # we read 150, we always show 30 and the ones more recent than 48 hours
8421                 if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
8422                         last;
8423                 }
8424                 my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
8425
8426                 # get list of changed files
8427                 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
8428                         $co{'parent'} || "--root",
8429                         $co{'id'}, "--", (defined $file_name ? $file_name : ())
8430                         or next;
8431                 my @difftree = map { chomp; $_ } <$fd>;
8432                 close $fd
8433                         or next;
8434
8435                 # print element (entry, item)
8436                 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8437                 if ($format eq 'rss') {
8438                         print "<item>\n" .
8439                               "<title>" . esc_html($co{'title'}) . "</title>\n" .
8440                               "<author>" . esc_html($co{'author'}) . "</author>\n" .
8441                               "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8442                               "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8443                               "<link>" . esc_html($co_url) . "</link>\n" .
8444                               "<description>" . esc_html($co{'title'}) . "</description>\n" .
8445                               "<content:encoded>" .
8446                               "<![CDATA[\n";
8447                 } elsif ($format eq 'atom') {
8448                         print "<entry>\n" .
8449                               "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8450                               "<updated>$cd{'iso-8601'}</updated>\n" .
8451                               "<author>\n" .
8452                               "  <name>" . esc_html($co{'author_name'}) . "</name>\n";
8453                         if ($co{'author_email'}) {
8454                                 print "  <email>" . esc_html($co{'author_email'}) . "</email>\n";
8455                         }
8456                         print "</author>\n" .
8457                               # use committer for contributor
8458                               "<contributor>\n" .
8459                               "  <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8460                         if ($co{'committer_email'}) {
8461                                 print "  <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8462                         }
8463                         print "</contributor>\n" .
8464                               "<published>$cd{'iso-8601'}</published>\n" .
8465                               "<link rel=\"alternate\" type=\"text/html\" href=\"" . esc_attr($co_url) . "\" />\n" .
8466                               "<id>" . esc_html($co_url) . "</id>\n" .
8467                               "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8468                               "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8469                 }
8470                 my $comment = $co{'comment'};
8471                 print "<pre>\n";
8472                 foreach my $line (@$comment) {
8473                         $line = esc_html($line);
8474                         print "$line\n";
8475                 }
8476                 print "</pre><ul>\n";
8477                 foreach my $difftree_line (@difftree) {
8478                         my %difftree = parse_difftree_raw_line($difftree_line);
8479                         next if !$difftree{'from_id'};
8480
8481                         my $file = $difftree{'file'} || $difftree{'to_file'};
8482
8483                         print "<li>" .
8484                               "[" .
8485                               $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8486                                                      hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8487                                                      hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8488                                                      file_name=>$file, file_parent=>$difftree{'from_file'}),
8489                                       -title => "diff"}, 'D');
8490                         if ($have_blame) {
8491                                 print $cgi->a({-href => href(-full=>1, action=>"blame",
8492                                                              file_name=>$file, hash_base=>$commit),
8493                                               -title => "blame"}, 'B');
8494                         }
8495                         # if this is not a feed of a file history
8496                         if (!defined $file_name || $file_name ne $file) {
8497                                 print $cgi->a({-href => href(-full=>1, action=>"history",
8498                                                              file_name=>$file, hash=>$commit),
8499                                               -title => "history"}, 'H');
8500                         }
8501                         $file = esc_path($file);
8502                         print "] ".
8503                               "$file</li>\n";
8504                 }
8505                 if ($format eq 'rss') {
8506                         print "</ul>]]>\n" .
8507                               "</content:encoded>\n" .
8508                               "</item>\n";
8509                 } elsif ($format eq 'atom') {
8510                         print "</ul>\n</div>\n" .
8511                               "</content>\n" .
8512                               "</entry>\n";
8513                 }
8514         }
8515
8516         # end of feed
8517         if ($format eq 'rss') {
8518                 print "</channel>\n</rss>\n";
8519         } elsif ($format eq 'atom') {
8520                 print "</feed>\n";
8521         }
8522 }
8523
8524 sub git_rss {
8525         git_feed('rss');
8526 }
8527
8528 sub git_atom {
8529         git_feed('atom');
8530 }
8531
8532 sub git_opml {
8533         my @list = git_get_projects_list($project_filter, $strict_export);
8534         if (!@list) {
8535                 die_error(404, "No projects found");
8536         }
8537
8538         print $cgi->header(
8539                 -type => 'text/xml',
8540                 -charset => 'utf-8',
8541                 -content_disposition => 'inline; filename="opml.xml"');
8542
8543         my $title = esc_html($site_name);
8544         my $filter = " within subdirectory ";
8545         if (defined $project_filter) {
8546                 $filter .= esc_html($project_filter);
8547         } else {
8548                 $filter = "";
8549         }
8550         print <<XML;
8551 <?xml version="1.0" encoding="utf-8"?>
8552 <opml version="1.0">
8553 <head>
8554   <title>$title OPML Export$filter</title>
8555 </head>
8556 <body>
8557 <outline text="git RSS feeds">
8558 XML
8559
8560         foreach my $pr (@list) {
8561                 my %proj = %$pr;
8562                 my $head = git_get_head_hash($proj{'path'});
8563                 if (!defined $head) {
8564                         next;
8565                 }
8566                 $git_dir = "$projectroot/$proj{'path'}";
8567                 my %co = parse_commit($head);
8568                 if (!%co) {
8569                         next;
8570                 }
8571
8572                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8573                 my $rss  = esc_attr(href('project' => $proj{'path'}, 'action' => 'rss', -full => 1));
8574                 my $html = esc_attr(href('project' => $proj{'path'}, 'action' => 'summary', -full => 1));
8575                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8576         }
8577         print <<XML;
8578 </outline>
8579 </body>
8580 </opml>
8581 XML
8582 }