summaryrefslogtreecommitdiff
path: root/gitweb/gitweb.cgi
blob: 072042586432fb8d84e267b4c47754417b2ba0f1 (plain)
    1 #!/usr/bin/perl
    2 
    3 # gitweb - simple web interface to track changes in git repositories
    4 #
    5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
    6 # (C) 2005, Christian Gierke
    7 #
    8 # This program is licensed under the GPLv2
    9 
   10 use strict;
   11 use warnings;
   12 use CGI qw(:standard :escapeHTML -nosticky);
   13 use CGI::Util qw(unescape);
   14 use CGI::Carp qw(fatalsToBrowser);
   15 use Encode;
   16 use Fcntl ':mode';
   17 use File::Find qw();
   18 use File::Basename qw(basename);
   19 binmode STDOUT, ':utf8';
   20 
   21 our $cgi = new CGI;
   22 our $version = "1.4.4.2";
   23 our $my_url = $cgi->url();
   24 our $my_uri = $cgi->url(-absolute => 1);
   25 
   26 # core git executable to use
   27 # this can just be "git" if your webserver has a sensible PATH
   28 our $GIT = "/usr/bin/git";
   29 
   30 # absolute fs-path which will be prepended to the project path
   31 #our $projectroot = "/pub/scm";
   32 our $projectroot = "/home/crux/scm";
   33 
   34 # target of the home link on top of all pages
   35 our $home_link = $my_uri || "/";
   36 
   37 # string of the home link on top of all pages
   38 our $home_link_str = "projects";
   39 
   40 # name of your site or organization to appear in page titles
   41 # replace this with something more descriptive for clearer bookmarks
   42 our $site_name = ""
   43                  || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
   44 
   45 # filename of html text to include at top of each page
   46 our $site_header = "header.html";
   47 # html text to include at home page
   48 our $home_text = "indextext.html";
   49 # filename of html text to include at bottom of each page
   50 our $site_footer = "";
   51 
   52 # URI of stylesheets
   53 our @stylesheets = ("gitweb.css");
   54 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
   55 our $stylesheet = undef;
   56 # URI of GIT logo (72x27 size)
   57 our $logo = "git-logo.png";
   58 # URI of GIT favicon, assumed to be image/png type
   59 our $favicon = "git-favicon.png";
   60 
   61 # URI and label (title) of GIT logo link
   62 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
   63 #our $logo_label = "git documentation";
   64 our $logo_url = "http://git.or.cz/";
   65 our $logo_label = "git homepage";
   66 
   67 # source of projects list
   68 our $projects_list = "index.aux";
   69 
   70 # show repository only if this file exists
   71 # (only effective if this variable evaluates to true)
   72 our $export_ok = "";
   73 
   74 # only allow viewing of repositories also shown on the overview page
   75 our $strict_export = "";
   76 
   77 # list of git base URLs used for URL to where fetch project from,
   78 # i.e. full URL is "$git_base_url/$project"
   79 our @git_base_url_list = ("git://crux.nu", "ssh://crux.nu/home/crux/scm");
   80 
   81 # default blob_plain mimetype and default charset for text/plain blob
   82 our $default_blob_plain_mimetype = 'text/plain';
   83 our $default_text_plain_charset  = undef;
   84 
   85 # file to use for guessing MIME types before trying /etc/mime.types
   86 # (relative to the current git repository)
   87 our $mimetypes_file = undef;
   88 
   89 # You define site-wide feature defaults here; override them with
   90 # $GITWEB_CONFIG as necessary.
   91 our %feature = (
   92 	# feature => {
   93 	# 	'sub' => feature-sub (subroutine),
   94 	# 	'override' => allow-override (boolean),
   95 	# 	'default' => [ default options...] (array reference)}
   96 	#
   97 	# if feature is overridable (it means that allow-override has true value,
   98 	# then feature-sub will be called with default options as parameters;
   99 	# return value of feature-sub indicates if to enable specified feature
  100 	#
  101 	# use gitweb_check_feature(<feature>) to check if <feature> is enabled
  102 
  103 	# Enable the 'blame' blob view, showing the last commit that modified
  104 	# each line in the file. This can be very CPU-intensive.
  105 
  106 	# To enable system wide have in $GITWEB_CONFIG
  107 	# $feature{'blame'}{'default'} = [1];
  108 	# To have project specific config enable override in $GITWEB_CONFIG
  109 	# $feature{'blame'}{'override'} = 1;
  110 	# and in project config gitweb.blame = 0|1;
  111 	'blame' => {
  112 		'sub' => \&feature_blame,
  113 		'override' => 0,
  114 		'default' => [0]},
  115 
  116 	# Enable the 'snapshot' link, providing a compressed tarball of any
  117 	# tree. This can potentially generate high traffic if you have large
  118 	# project.
  119 
  120 	# To disable system wide have in $GITWEB_CONFIG
  121 	# $feature{'snapshot'}{'default'} = [undef];
  122 	# To have project specific config enable override in $GITWEB_CONFIG
  123 	# $feature{'blame'}{'override'} = 1;
  124 	# and in project config gitweb.snapshot = none|gzip|bzip2;
  125 	'snapshot' => {
  126 		'sub' => \&feature_snapshot,
  127 		'override' => 0,
  128 		#         => [content-encoding, suffix, program]
  129 		'default' => ['x-gzip', 'gz', 'gzip']},
  130 
  131 	# Enable the pickaxe search, which will list the commits that modified
  132 	# a given string in a file. This can be practical and quite faster
  133 	# alternative to 'blame', but still potentially CPU-intensive.
  134 
  135 	# To enable system wide have in $GITWEB_CONFIG
  136 	# $feature{'pickaxe'}{'default'} = [1];
  137 	# To have project specific config enable override in $GITWEB_CONFIG
  138 	# $feature{'pickaxe'}{'override'} = 1;
  139 	# and in project config gitweb.pickaxe = 0|1;
  140 	'pickaxe' => {
  141 		'sub' => \&feature_pickaxe,
  142 		'override' => 0,
  143 		'default' => [1]},
  144 
  145 	# Make gitweb use an alternative format of the URLs which can be
  146 	# more readable and natural-looking: project name is embedded
  147 	# directly in the path and the query string contains other
  148 	# auxiliary information. All gitweb installations recognize
  149 	# URL in either format; this configures in which formats gitweb
  150 	# generates links.
  151 
  152 	# To enable system wide have in $GITWEB_CONFIG
  153 	# $feature{'pathinfo'}{'default'} = [1];
  154 	# Project specific override is not supported.
  155 
  156 	# Note that you will need to change the default location of CSS,
  157 	# favicon, logo and possibly other files to an absolute URL. Also,
  158 	# if gitweb.cgi serves as your indexfile, you will need to force
  159 	# $my_uri to contain the script name in your $GITWEB_CONFIG.
  160 	'pathinfo' => {
  161 		'override' => 0,
  162 		'default' => [0]},
  163 
  164 	# Make gitweb consider projects in project root subdirectories
  165 	# to be forks of existing projects. Given project $projname.git,
  166 	# projects matching $projname/*.git will not be shown in the main
  167 	# projects list, instead a '+' mark will be added to $projname
  168 	# there and a 'forks' view will be enabled for the project, listing
  169 	# all the forks. This feature is supported only if project list
  170 	# is taken from a directory, not file.
  171 
  172 	# To enable system wide have in $GITWEB_CONFIG
  173 	# $feature{'forks'}{'default'} = [1];
  174 	# Project specific override is not supported.
  175 	'forks' => {
  176 		'override' => 0,
  177 		'default' => [0]},
  178 );
  179 
  180 # CRUX: allow custom default HEAD for each project
  181 our %default_heads = (
  182     "ports/core.git" => "2.4",
  183     "ports/opt.git" => "2.4",
  184     "ports/contrib.git" => "2.4",
  185     "ports/xfce.git" => "2.4",
  186     "ports/xorg.git" => "2.4",
  187     "ports/sip.git" => "2.4",
  188     "ports/kde.git" => "2.2",
  189     "system/iso.git" => "2.4",
  190 );
  191 
  192 sub gitweb_get_default_head {
  193     my $project = shift;
  194     exists $default_heads{$project} && return $default_heads{$project};
  195     return "HEAD";
  196 }
  197 
  198 sub nospam {
  199     my $committer = shift;
  200     $committer =~ s/\./ dot /g;
  201     $committer =~ s/\@/ at /g;
  202     return $committer;
  203 }
  204 
  205 sub gitweb_check_feature {
  206 	my ($name) = @_;
  207 	return unless exists $feature{$name};
  208 	my ($sub, $override, @defaults) = (
  209 		$feature{$name}{'sub'},
  210 		$feature{$name}{'override'},
  211 		@{$feature{$name}{'default'}});
  212 	if (!$override) { return @defaults; }
  213 	if (!defined $sub) {
  214 		warn "feature $name is not overrideable";
  215 		return @defaults;
  216 	}
  217 	return $sub->(@defaults);
  218 }
  219 
  220 sub feature_blame {
  221 	my ($val) = git_get_project_config('blame', '--bool');
  222 
  223 	if ($val eq 'true') {
  224 		return 1;
  225 	} elsif ($val eq 'false') {
  226 		return 0;
  227 	}
  228 
  229 	return $_[0];
  230 }
  231 
  232 sub feature_snapshot {
  233 	my ($ctype, $suffix, $command) = @_;
  234 
  235 	my ($val) = git_get_project_config('snapshot');
  236 
  237 	if ($val eq 'gzip') {
  238 		return ('x-gzip', 'gz', 'gzip');
  239 	} elsif ($val eq 'bzip2') {
  240 		return ('x-bzip2', 'bz2', 'bzip2');
  241 	} elsif ($val eq 'none') {
  242 		return ();
  243 	}
  244 
  245 	return ($ctype, $suffix, $command);
  246 }
  247 
  248 sub gitweb_have_snapshot {
  249 	my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
  250 	my $have_snapshot = (defined $ctype && defined $suffix);
  251 
  252 	return $have_snapshot;
  253 }
  254 
  255 sub feature_pickaxe {
  256 	my ($val) = git_get_project_config('pickaxe', '--bool');
  257 
  258 	if ($val eq 'true') {
  259 		return (1);
  260 	} elsif ($val eq 'false') {
  261 		return (0);
  262 	}
  263 
  264 	return ($_[0]);
  265 }
  266 
  267 # checking HEAD file with -e is fragile if the repository was
  268 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
  269 # and then pruned.
  270 sub check_head_link {
  271 	my ($dir) = @_;
  272 	my $headfile = "$dir/HEAD";
  273 	return ((-e $headfile) ||
  274 		(-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
  275 }
  276 
  277 sub check_export_ok {
  278 	my ($dir) = @_;
  279 	return (check_head_link($dir) &&
  280 		(!$export_ok || -e "$dir/$export_ok"));
  281 }
  282 
  283 # rename detection options for git-diff and git-diff-tree
  284 # - default is '-M', with the cost proportional to
  285 #   (number of removed files) * (number of new files).
  286 # - more costly is '-C' (or '-C', '-M'), with the cost proportional to
  287 #   (number of changed files + number of removed files) * (number of new files)
  288 # - even more costly is '-C', '--find-copies-harder' with cost
  289 #   (number of files in the original tree) * (number of new files)
  290 # - one might want to include '-B' option, e.g. '-B', '-M'
  291 our @diff_opts = ('-M'); # taken from git_commit
  292 
  293 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "gitweb_config.perl";
  294 do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
  295 
  296 # version of the core git binary
  297 our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
  298 
  299 $projects_list ||= $projectroot;
  300 
  301 # ======================================================================
  302 # input validation and dispatch
  303 our $action = $cgi->param('a');
  304 if (defined $action) {
  305 	if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
  306 		die_error(undef, "Invalid action parameter");
  307 	}
  308 }
  309 
  310 # parameters which are pathnames
  311 our $project = $cgi->param('p');
  312 if (defined $project) {
  313 	if (!validate_pathname($project) ||
  314 	    !(-d "$projectroot/$project") ||
  315 	    !check_head_link("$projectroot/$project") ||
  316 	    ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
  317 	    ($strict_export && !project_in_list($project))) {
  318 		undef $project;
  319 		die_error(undef, "No such project");
  320 	}
  321 }
  322 
  323 our $file_name = $cgi->param('f');
  324 if (defined $file_name) {
  325 	if (!validate_pathname($file_name)) {
  326 		die_error(undef, "Invalid file parameter");
  327 	}
  328 }
  329 
  330 our $file_parent = $cgi->param('fp');
  331 if (defined $file_parent) {
  332 	if (!validate_pathname($file_parent)) {
  333 		die_error(undef, "Invalid file parent parameter");
  334 	}
  335 }
  336 
  337 # parameters which are refnames
  338 our $hash = $cgi->param('h');
  339 if (defined $hash) {
  340 	if (!validate_refname($hash)) {
  341 		die_error(undef, "Invalid hash parameter");
  342 	}
  343 }
  344 
  345 our $hash_parent = $cgi->param('hp');
  346 if (defined $hash_parent) {
  347 	if (!validate_refname($hash_parent)) {
  348 		die_error(undef, "Invalid hash parent parameter");
  349 	}
  350 }
  351 
  352 our $hash_base = $cgi->param('hb');
  353 if (defined $hash_base) {
  354 	if (!validate_refname($hash_base)) {
  355 		die_error(undef, "Invalid hash base parameter");
  356 	}
  357 }
  358 
  359 our $hash_parent_base = $cgi->param('hpb');
  360 if (defined $hash_parent_base) {
  361 	if (!validate_refname($hash_parent_base)) {
  362 		die_error(undef, "Invalid hash parent base parameter");
  363 	}
  364 }
  365 
  366 # other parameters
  367 our $page = $cgi->param('pg');
  368 if (defined $page) {
  369 	if ($page =~ m/[^0-9]/) {
  370 		die_error(undef, "Invalid page parameter");
  371 	}
  372 }
  373 
  374 our $searchtext = $cgi->param('s');
  375 if (defined $searchtext) {
  376 	if ($searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
  377 		die_error(undef, "Invalid search parameter");
  378 	}
  379 	$searchtext = quotemeta $searchtext;
  380 }
  381 
  382 our $searchtype = $cgi->param('st');
  383 if (defined $searchtype) {
  384 	if ($searchtype =~ m/[^a-z]/) {
  385 		die_error(undef, "Invalid searchtype parameter");
  386 	}
  387 }
  388 
  389 # now read PATH_INFO and use it as alternative to parameters
  390 sub evaluate_path_info {
  391 	return if defined $project;
  392 	my $path_info = $ENV{"PATH_INFO"};
  393 	return if !$path_info;
  394 	$path_info =~ s,^/+,,;
  395 	return if !$path_info;
  396 	# find which part of PATH_INFO is project
  397 	$project = $path_info;
  398 	$project =~ s,/+$,,;
  399 	while ($project && !check_head_link("$projectroot/$project")) {
  400 		$project =~ s,/*[^/]*$,,;
  401 	}
  402 	# validate project
  403 	$project = validate_pathname($project);
  404 	if (!$project ||
  405 	    ($export_ok && !-e "$projectroot/$project/$export_ok") ||
  406 	    ($strict_export && !project_in_list($project))) {
  407 		undef $project;
  408 		return;
  409 	}
  410 	# do not change any parameters if an action is given using the query string
  411 	return if $action;
  412 	$path_info =~ s,^$project/*,,;
  413 	my ($refname, $pathname) = split(/:/, $path_info, 2);
  414 	if (defined $pathname) {
  415 		# we got "project.git/branch:filename" or "project.git/branch:dir/"
  416 		# we could use git_get_type(branch:pathname), but it needs $git_dir
  417 		$pathname =~ s,^/+,,;
  418 		if (!$pathname || substr($pathname, -1) eq "/") {
  419 			$action  ||= "tree";
  420 			$pathname =~ s,/$,,;
  421 		} else {
  422 			$action  ||= "blob_plain";
  423 		}
  424 		$hash_base ||= validate_refname($refname);
  425 		$file_name ||= validate_pathname($pathname);
  426 	} elsif (defined $refname) {
  427 		# we got "project.git/branch"
  428 		$action ||= "shortlog";
  429 		$hash   ||= validate_refname($refname);
  430 	}
  431 }
  432 evaluate_path_info();
  433 
  434 # path to the current git repository
  435 our $git_dir;
  436 $git_dir = "$projectroot/$project" if $project;
  437 
  438 # dispatch
  439 my %actions = (
  440 	"blame" => \&git_blame2,
  441 	"blobdiff" => \&git_blobdiff,
  442 	"blobdiff_plain" => \&git_blobdiff_plain,
  443 	"blob" => \&git_blob,
  444 	"blob_plain" => \&git_blob_plain,
  445 	"commitdiff" => \&git_commitdiff,
  446 	"commitdiff_plain" => \&git_commitdiff_plain,
  447 	"commit" => \&git_commit,
  448 	"forks" => \&git_forks,
  449 	"heads" => \&git_heads,
  450 	"history" => \&git_history,
  451 	"log" => \&git_log,
  452 	"rss" => \&git_rss,
  453 	"search" => \&git_search,
  454 	"search_help" => \&git_search_help,
  455 	"shortlog" => \&git_shortlog,
  456 	"summary" => \&git_summary,
  457 	"tag" => \&git_tag,
  458 	"tags" => \&git_tags,
  459 	"tree" => \&git_tree,
  460 	"snapshot" => \&git_snapshot,
  461 	# those below don't need $project
  462 	"opml" => \&git_opml,
  463 	"project_list" => \&git_project_list,
  464 	"project_index" => \&git_project_index,
  465 );
  466 
  467 if (defined $project) {
  468 	$action ||= 'summary';
  469 } else {
  470 	$action ||= 'project_list';
  471 }
  472 if (!defined($actions{$action})) {
  473 	die_error(undef, "Unknown action");
  474 }
  475 if ($action !~ m/^(opml|project_list|project_index)$/ &&
  476     !$project) {
  477 	die_error(undef, "Project needed");
  478 }
  479 $actions{$action}->();
  480 exit;
  481 
  482 ## ======================================================================
  483 ## action links
  484 
  485 sub href(%) {
  486 	my %params = @_;
  487 	my $href = $my_uri;
  488 
  489 	# XXX: Warning: If you touch this, check the search form for updating,
  490 	# too.
  491 
  492 	my @mapping = (
  493 		project => "p",
  494 		action => "a",
  495 		file_name => "f",
  496 		file_parent => "fp",
  497 		hash => "h",
  498 		hash_parent => "hp",
  499 		hash_base => "hb",
  500 		hash_parent_base => "hpb",
  501 		page => "pg",
  502 		order => "o",
  503 		searchtext => "s",
  504 		searchtype => "st",
  505 	);
  506 	my %mapping = @mapping;
  507 
  508 	$params{'project'} = $project unless exists $params{'project'};
  509 
  510 	my ($use_pathinfo) = gitweb_check_feature('pathinfo');
  511 	if ($use_pathinfo) {
  512 		# use PATH_INFO for project name
  513 		$href .= "/$params{'project'}" if defined $params{'project'};
  514 		delete $params{'project'};
  515 
  516 		# Summary just uses the project path URL
  517 		if (defined $params{'action'} && $params{'action'} eq 'summary') {
  518 			delete $params{'action'};
  519 		}
  520 	}
  521 
  522 	# now encode the parameters explicitly
  523 	my @result = ();
  524 	for (my $i = 0; $i < @mapping; $i += 2) {
  525 		my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
  526 		if (defined $params{$name}) {
  527 			push @result, $symbol . "=" . esc_param($params{$name});
  528 		}
  529 	}
  530 	$href .= "?" . join(';', @result) if scalar @result;
  531 
  532 	return $href;
  533 }
  534 
  535 
  536 ## ======================================================================
  537 ## validation, quoting/unquoting and escaping
  538 
  539 sub validate_pathname {
  540 	my $input = shift || return undef;
  541 
  542 	# no '.' or '..' as elements of path, i.e. no '.' nor '..'
  543 	# at the beginning, at the end, and between slashes.
  544 	# also this catches doubled slashes
  545 	if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
  546 		return undef;
  547 	}
  548 	# no null characters
  549 	if ($input =~ m!\0!) {
  550 		return undef;
  551 	}
  552 	return $input;
  553 }
  554 
  555 sub validate_refname {
  556 	my $input = shift || return undef;
  557 
  558 	# textual hashes are O.K.
  559 	if ($input =~ m/^[0-9a-fA-F]{40}$/) {
  560 		return $input;
  561 	}
  562 	# it must be correct pathname
  563 	$input = validate_pathname($input)
  564 		or return undef;
  565 	# restrictions on ref name according to git-check-ref-format
  566 	if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
  567 		return undef;
  568 	}
  569 	return $input;
  570 }
  571 
  572 # very thin wrapper for decode("utf8", $str, Encode::FB_DEFAULT);
  573 sub to_utf8 {
  574 	my $str = shift;
  575 	return decode("utf8", $str, Encode::FB_DEFAULT);
  576 }
  577 
  578 # quote unsafe chars, but keep the slash, even when it's not
  579 # correct, but quoted slashes look too horrible in bookmarks
  580 sub esc_param {
  581 	my $str = shift;
  582 	$str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
  583 	$str =~ s/\+/%2B/g;
  584 	$str =~ s/ /\+/g;
  585 	return $str;
  586 }
  587 
  588 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
  589 sub esc_url {
  590 	my $str = shift;
  591 	$str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
  592 	$str =~ s/\+/%2B/g;
  593 	$str =~ s/ /\+/g;
  594 	return $str;
  595 }
  596 
  597 # replace invalid utf8 character with SUBSTITUTION sequence
  598 sub esc_html ($;%) {
  599 	my $str = shift;
  600 	my %opts = @_;
  601 
  602 	$str = to_utf8($str);
  603 	$str = escapeHTML($str);
  604 	if ($opts{'-nbsp'}) {
  605 		$str =~ s/ /&nbsp;/g;
  606 	}
  607 	$str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
  608 	return $str;
  609 }
  610 
  611 # Make control characterss "printable".
  612 sub quot_cec {
  613 	my $cntrl = shift;
  614 	my %es = ( # character escape codes, aka escape sequences
  615 		   "\t" => '\t',   # tab            (HT)
  616 		   "\n" => '\n',   # line feed      (LF)
  617 		   "\r" => '\r',   # carrige return (CR)
  618 		   "\f" => '\f',   # form feed      (FF)
  619 		   "\b" => '\b',   # backspace      (BS)
  620 		   "\a" => '\a',   # alarm (bell)   (BEL)
  621 		   "\e" => '\e',   # escape         (ESC)
  622 		   "\013" => '\v', # vertical tab   (VT)
  623 		   "\000" => '\0', # nul character  (NUL)
  624 		   );
  625 	my $chr = ( (exists $es{$cntrl})
  626 		    ? $es{$cntrl}
  627 		    : sprintf('\%03o', ord($cntrl)) );
  628 	return "<span class=\"cntrl\">$chr</span>";
  629 }
  630 
  631 # Alternatively use unicode control pictures codepoints.
  632 sub quot_upr {
  633 	my $cntrl = shift;
  634 	my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
  635 	return "<span class=\"cntrl\">$chr</span>";
  636 }
  637 
  638 # quote control characters and escape filename to HTML
  639 sub esc_path {
  640 	my $str = shift;
  641 
  642 	$str = esc_html($str);
  643 	$str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
  644 	return $str;
  645 }
  646 
  647 # git may return quoted and escaped filenames
  648 sub unquote {
  649 	my $str = shift;
  650 
  651 	sub unq {
  652 		my $seq = shift;
  653 		my %es = ( # character escape codes, aka escape sequences
  654 			't' => "\t",   # tab            (HT, TAB)
  655 			'n' => "\n",   # newline        (NL)
  656 			'r' => "\r",   # return         (CR)
  657 			'f' => "\f",   # form feed      (FF)
  658 			'b' => "\b",   # backspace      (BS)
  659 			'a' => "\a",   # alarm (bell)   (BEL)
  660 			'e' => "\e",   # escape         (ESC)
  661 			'v' => "\013", # vertical tab   (VT)
  662 		);
  663 
  664 		if ($seq =~ m/^[0-7]{1,3}$/) {
  665 			# octal char sequence
  666 			return chr(oct($seq));
  667 		} elsif (exists $es{$seq}) {
  668 			# C escape sequence, aka character escape code
  669 			return $es{$seq}
  670 		}
  671 		# quoted ordinary character
  672 		return $seq;
  673 	}
  674 
  675 	if ($str =~ m/^"(.*)"$/) {
  676 		# needs unquoting
  677 		$str = $1;
  678 		$str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
  679 	}
  680 	return $str;
  681 }
  682 
  683 # escape tabs (convert tabs to spaces)
  684 sub untabify {
  685 	my $line = shift;
  686 
  687 	while ((my $pos = index($line, "\t")) != -1) {
  688 		if (my $count = (8 - ($pos % 8))) {
  689 			my $spaces = ' ' x $count;
  690 			$line =~ s/\t/$spaces/;
  691 		}
  692 	}
  693 
  694 	return $line;
  695 }
  696 
  697 sub project_in_list {
  698 	my $project = shift;
  699 	my @list = git_get_projects_list();
  700 	return @list && scalar(grep { $_->{'path'} eq $project } @list);
  701 }
  702 
  703 ## ----------------------------------------------------------------------
  704 ## HTML aware string manipulation
  705 
  706 sub chop_str {
  707 	my $str = shift;
  708 	my $len = shift;
  709 	my $add_len = shift || 10;
  710 
  711 	# allow only $len chars, but don't cut a word if it would fit in $add_len
  712 	# if it doesn't fit, cut it if it's still longer than the dots we would add
  713 	$str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
  714 	my $body = $1;
  715 	my $tail = $2;
  716 	if (length($tail) > 4) {
  717 		$tail = " ...";
  718 		$body =~ s/&[^;]*$//; # remove chopped character entities
  719 	}
  720 	return "$body$tail";
  721 }
  722 
  723 ## ----------------------------------------------------------------------
  724 ## functions returning short strings
  725 
  726 # CSS class for given age value (in seconds)
  727 sub age_class {
  728 	my $age = shift;
  729 
  730 	if ($age < 60*60*2) {
  731 		return "age0";
  732 	} elsif ($age < 60*60*24*2) {
  733 		return "age1";
  734 	} else {
  735 		return "age2";
  736 	}
  737 }
  738 
  739 # convert age in seconds to "nn units ago" string
  740 sub age_string {
  741 	my $age = shift;
  742 	my $age_str;
  743 
  744 	if ($age > 60*60*24*365*2) {
  745 		$age_str = (int $age/60/60/24/365);
  746 		$age_str .= " years ago";
  747 	} elsif ($age > 60*60*24*(365/12)*2) {
  748 		$age_str = int $age/60/60/24/(365/12);
  749 		$age_str .= " months ago";
  750 	} elsif ($age > 60*60*24*7*2) {
  751 		$age_str = int $age/60/60/24/7;
  752 		$age_str .= " weeks ago";
  753 	} elsif ($age > 60*60*24*2) {
  754 		$age_str = int $age/60/60/24;
  755 		$age_str .= " days ago";
  756 	} elsif ($age > 60*60*2) {
  757 		$age_str = int $age/60/60;
  758 		$age_str .= " hours ago";
  759 	} elsif ($age > 60*2) {
  760 		$age_str = int $age/60;
  761 		$age_str .= " min ago";
  762 	} elsif ($age > 2) {
  763 		$age_str = int $age;
  764 		$age_str .= " sec ago";
  765 	} else {
  766 		$age_str .= " right now";
  767 	}
  768 	return $age_str;
  769 }
  770 
  771 # convert file mode in octal to symbolic file mode string
  772 sub mode_str {
  773 	my $mode = oct shift;
  774 
  775 	if (S_ISDIR($mode & S_IFMT)) {
  776 		return 'drwxr-xr-x';
  777 	} elsif (S_ISLNK($mode)) {
  778 		return 'lrwxrwxrwx';
  779 	} elsif (S_ISREG($mode)) {
  780 		# git cares only about the executable bit
  781 		if ($mode & S_IXUSR) {
  782 			return '-rwxr-xr-x';
  783 		} else {
  784 			return '-rw-r--r--';
  785 		};
  786 	} else {
  787 		return '----------';
  788 	}
  789 }
  790 
  791 # convert file mode in octal to file type string
  792 sub file_type {
  793 	my $mode = shift;
  794 
  795 	if ($mode !~ m/^[0-7]+$/) {
  796 		return $mode;
  797 	} else {
  798 		$mode = oct $mode;
  799 	}
  800 
  801 	if (S_ISDIR($mode & S_IFMT)) {
  802 		return "directory";
  803 	} elsif (S_ISLNK($mode)) {
  804 		return "symlink";
  805 	} elsif (S_ISREG($mode)) {
  806 		return "file";
  807 	} else {
  808 		return "unknown";
  809 	}
  810 }
  811 
  812 # convert file mode in octal to file type description string
  813 sub file_type_long {
  814 	my $mode = shift;
  815 
  816 	if ($mode !~ m/^[0-7]+$/) {
  817 		return $mode;
  818 	} else {
  819 		$mode = oct $mode;
  820 	}
  821 
  822 	if (S_ISDIR($mode & S_IFMT)) {
  823 		return "directory";
  824 	} elsif (S_ISLNK($mode)) {
  825 		return "symlink";
  826 	} elsif (S_ISREG($mode)) {
  827 		if ($mode & S_IXUSR) {
  828 			return "executable";
  829 		} else {
  830 			return "file";
  831 		};
  832 	} else {
  833 		return "unknown";
  834 	}
  835 }
  836 
  837 
  838 ## ----------------------------------------------------------------------
  839 ## functions returning short HTML fragments, or transforming HTML fragments
  840 ## which don't beling to other sections
  841 
  842 # format line of commit message.
  843 sub format_log_line_html {
  844 	my $line = shift;
  845 
  846 	$line = esc_html($line, -nbsp=>1);
  847 	if ($line =~ m/([0-9a-fA-F]{40})/) {
  848 		my $hash_text = $1;
  849 		if (git_get_type($hash_text) eq "commit") {
  850 			my $link =
  851 				$cgi->a({-href => href(action=>"commit", hash=>$hash_text),
  852 				        -class => "text"}, $hash_text);
  853 			$line =~ s/$hash_text/$link/;
  854 		}
  855 	}
  856 	return $line;
  857 }
  858 
  859 # format marker of refs pointing to given object
  860 sub format_ref_marker {
  861 	my ($refs, $id) = @_;
  862 	my $markers = '';
  863 
  864 	if (defined $refs->{$id}) {
  865 		foreach my $ref (@{$refs->{$id}}) {
  866 			my ($type, $name) = qw();
  867 			# e.g. tags/v2.6.11 or heads/next
  868 			if ($ref =~ m!^(.*?)s?/(.*)$!) {
  869 				$type = $1;
  870 				$name = $2;
  871 			} else {
  872 				$type = "ref";
  873 				$name = $ref;
  874 			}
  875 
  876 			$markers .= " <span class=\"$type\">" . esc_html($name) . "</span>";
  877 		}
  878 	}
  879 
  880 	if ($markers) {
  881 		return ' <span class="refs">'. $markers . '</span>';
  882 	} else {
  883 		return "";
  884 	}
  885 }
  886 
  887 # format, perhaps shortened and with markers, title line
  888 sub format_subject_html {
  889 	my ($long, $short, $href, $extra) = @_;
  890 	$extra = '' unless defined($extra);
  891 
  892 	if (length($short) < length($long)) {
  893 		return $cgi->a({-href => $href, -class => "list subject",
  894 		                -title => to_utf8($long)},
  895 		       esc_html($short) . $extra);
  896 	} else {
  897 		return $cgi->a({-href => $href, -class => "list subject"},
  898 		       esc_html($long)  . $extra);
  899 	}
  900 }
  901 
  902 sub format_diff_line {
  903 	my $line = shift;
  904 	my $char = substr($line, 0, 1);
  905 	my $diff_class = "";
  906 
  907 	chomp $line;
  908 
  909 	if ($char eq '+') {
  910 		$diff_class = " add";
  911 	} elsif ($char eq "-") {
  912 		$diff_class = " rem";
  913 	} elsif ($char eq "@") {
  914 		$diff_class = " chunk_header";
  915 	} elsif ($char eq "\\") {
  916 		$diff_class = " incomplete";
  917 	}
  918 	$line = untabify($line);
  919 	return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
  920 }
  921 
  922 ## ----------------------------------------------------------------------
  923 ## git utility subroutines, invoking git commands
  924 
  925 # returns path to the core git executable and the --git-dir parameter as list
  926 sub git_cmd {
  927 	return $GIT, '--git-dir='.$git_dir;
  928 }
  929 
  930 # returns path to the core git executable and the --git-dir parameter as string
  931 sub git_cmd_str {
  932 	return join(' ', git_cmd());
  933 }
  934 
  935 # get HEAD ref of given project as hash
  936 sub git_get_head_hash {
  937 	my $project = shift;
  938 	my $head = gitweb_get_default_head($project);
  939 	my $o_git_dir = $git_dir;
  940 	my $retval = undef;
  941 	$git_dir = "$projectroot/$project";
  942 	if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", $head) {
  943 		my $head = <$fd>;
  944 		close $fd;
  945 		if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
  946 			$retval = $1;
  947 		}
  948 	}
  949 	if (defined $o_git_dir) {
  950 		$git_dir = $o_git_dir;
  951 	}
  952 	return $retval;
  953 }
  954 
  955 # get type of given object
  956 sub git_get_type {
  957 	my $hash = shift;
  958 
  959 	open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
  960 	my $type = <$fd>;
  961 	close $fd or return;
  962 	chomp $type;
  963 	return $type;
  964 }
  965 
  966 sub git_get_project_config {
  967 	my ($key, $type) = @_;
  968 
  969 	return unless ($key);
  970 	$key =~ s/^gitweb\.//;
  971 	return if ($key =~ m/\W/);
  972 
  973 	my @x = (git_cmd(), 'repo-config');
  974 	if (defined $type) { push @x, $type; }
  975 	push @x, "--get";
  976 	push @x, "gitweb.$key";
  977 	my $val = qx(@x);
  978 	chomp $val;
  979 	return ($val);
  980 }
  981 
  982 # get hash of given path at given ref
  983 sub git_get_hash_by_path {
  984 	my $base = shift;
  985 	my $path = shift || return undef;
  986 	my $type = shift;
  987 
  988 	$path =~ s,/+$,,;
  989 
  990 	open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
  991 		or die_error(undef, "Open git-ls-tree failed");
  992 	my $line = <$fd>;
  993 	close $fd or return undef;
  994 
  995 	#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa	panic.c'
  996 	$line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
  997 	if (defined $type && $type ne $2) {
  998 		# type doesn't match
  999 		return undef;
 1000 	}
 1001 	return $3;
 1002 }
 1003 
 1004 ## ......................................................................
 1005 ## git utility functions, directly accessing git repository
 1006 
 1007 sub git_get_project_description {
 1008 	my $path = shift;
 1009 
 1010 	open my $fd, "$projectroot/$path/description" or return undef;
 1011 	my $descr = <$fd>;
 1012 	close $fd;
 1013 	chomp $descr;
 1014 	return $descr;
 1015 }
 1016 
 1017 sub git_get_project_url_list {
 1018 	my $path = shift;
 1019 
 1020 	open my $fd, "$projectroot/$path/cloneurl" or return;
 1021 	my @git_project_url_list = map { chomp; $_ } <$fd>;
 1022 	close $fd;
 1023 
 1024 	return wantarray ? @git_project_url_list : \@git_project_url_list;
 1025 }
 1026 
 1027 sub git_get_projects_list {
 1028 	my ($filter) = @_;
 1029 	my @list;
 1030 
 1031 	$filter ||= '';
 1032 	$filter =~ s/\.git$//;
 1033 
 1034 	if (-d $projects_list) {
 1035 		# search in directory
 1036 		my $dir = $projects_list . ($filter ? "/$filter" : '');
 1037 		# remove the trailing "/"
 1038 		$dir =~ s!/+$!!;
 1039 		my $pfxlen = length("$dir");
 1040 
 1041 		my ($check_forks) = gitweb_check_feature('forks');
 1042 
 1043 		File::Find::find({
 1044 			follow_fast => 1, # follow symbolic links
 1045 			dangling_symlinks => 0, # ignore dangling symlinks, silently
 1046 			wanted => sub {
 1047 				# skip project-list toplevel, if we get it.
 1048 				return if (m!^[/.]$!);
 1049 				# only directories can be git repositories
 1050 				return unless (-d $_);
 1051 
 1052 				my $subdir = substr($File::Find::name, $pfxlen + 1);
 1053 				# we check related file in $projectroot
 1054 				if ($check_forks and $subdir =~ m#/.#) {
 1055 					$File::Find::prune = 1;
 1056 				} elsif (check_export_ok("$projectroot/$filter/$subdir")) {
 1057 					push @list, { path => ($filter ? "$filter/" : '') . $subdir };
 1058 					$File::Find::prune = 1;
 1059 				}
 1060 			},
 1061 		}, "$dir");
 1062 
 1063 	} elsif (-f $projects_list) {
 1064 		# read from file(url-encoded):
 1065 		# 'git%2Fgit.git Linus+Torvalds'
 1066 		# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
 1067 		# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
 1068 		open my ($fd), $projects_list or return;
 1069 		while (my $line = <$fd>) {
 1070 			chomp $line;
 1071 			my ($path, $owner) = split ' ', $line;
 1072 			$path = unescape($path);
 1073 			$owner = unescape($owner);
 1074 			if (!defined $path) {
 1075 				next;
 1076 			}
 1077 			if ($filter ne '') {
 1078 				# looking for forks;
 1079 				my $pfx = substr($path, 0, length($filter));
 1080 				if ($pfx ne $filter) {
 1081 					next;
 1082 				}
 1083 				my $sfx = substr($path, length($filter));
 1084 				if ($sfx !~ /^\/.*\.git$/) {
 1085 					next;
 1086 				}
 1087 			}
 1088 			if (check_export_ok("$projectroot/$path")) {
 1089 				my $pr = {
 1090 					path => $path,
 1091 					owner => to_utf8($owner),
 1092 				};
 1093 				push @list, $pr
 1094 			}
 1095 		}
 1096 		close $fd;
 1097 	}
 1098 	@list = sort {$a->{'path'} cmp $b->{'path'}} @list;
 1099 	return @list;
 1100 }
 1101 
 1102 sub git_get_project_owner {
 1103 	my $project = shift;
 1104 	my $owner;
 1105 
 1106 	return undef unless $project;
 1107 
 1108 	# read from file (url-encoded):
 1109 	# 'git%2Fgit.git Linus+Torvalds'
 1110 	# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
 1111 	# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
 1112 	if (-f $projects_list) {
 1113 		open (my $fd , $projects_list);
 1114 		while (my $line = <$fd>) {
 1115 			chomp $line;
 1116 			my ($pr, $ow) = split ' ', $line;
 1117 			$pr = unescape($pr);
 1118 			$ow = unescape($ow);
 1119 			if ($pr eq $project) {
 1120 				$owner = to_utf8($ow);
 1121 				last;
 1122 			}
 1123 		}
 1124 		close $fd;
 1125 	}
 1126 	if (!defined $owner) {
 1127 		$owner = get_file_owner("$projectroot/$project");
 1128 	}
 1129 
 1130 	return $owner;
 1131 }
 1132 
 1133 sub git_get_last_activity {
 1134 	my ($path) = @_;
 1135 	my $fd;
 1136 
 1137 	$git_dir = "$projectroot/$path";
 1138 	open($fd, "-|", git_cmd(), 'for-each-ref',
 1139 	     '--format=%(refname) %(committer)',
 1140 	     '--sort=-committerdate',
 1141 	     'refs/heads') or return;
 1142 	my $most_recent = <$fd>;
 1143 	close $fd or return;
 1144 	if ($most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
 1145 		my $timestamp = $1;
 1146 		my $age = time - $timestamp;
 1147 		return ($age, age_string($age));
 1148 	}
 1149 }
 1150 
 1151 sub git_get_references {
 1152 	my $type = shift || "";
 1153 	my %refs;
 1154 	# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c	refs/tags/v2.6.11
 1155 	# c39ae07f393806ccf406ef966e9a15afc43cc36a	refs/tags/v2.6.11^{}
 1156 	open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
 1157 		or return;
 1158 
 1159 	while (my $line = <$fd>) {
 1160 		chomp $line;
 1161 		if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?[^\^]+)/) {
 1162 			if (defined $refs{$1}) {
 1163 				push @{$refs{$1}}, $2;
 1164 			} else {
 1165 				$refs{$1} = [ $2 ];
 1166 			}
 1167 		}
 1168 	}
 1169 	close $fd or return;
 1170 	return \%refs;
 1171 }
 1172 
 1173 sub git_get_rev_name_tags {
 1174 	my $hash = shift || return undef;
 1175 
 1176 	open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
 1177 		or return;
 1178 	my $name_rev = <$fd>;
 1179 	close $fd;
 1180 
 1181 	if ($name_rev =~ m|^$hash tags/(.*)$|) {
 1182 		return $1;
 1183 	} else {
 1184 		# catches also '$hash undefined' output
 1185 		return undef;
 1186 	}
 1187 }
 1188 
 1189 ## ----------------------------------------------------------------------
 1190 ## parse to hash functions
 1191 
 1192 sub parse_date {
 1193 	my $epoch = shift;
 1194 	my $tz = shift || "-0000";
 1195 
 1196 	my %date;
 1197 	my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
 1198 	my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
 1199 	my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
 1200 	$date{'hour'} = $hour;
 1201 	$date{'minute'} = $min;
 1202 	$date{'mday'} = $mday;
 1203 	$date{'day'} = $days[$wday];
 1204 	$date{'month'} = $months[$mon];
 1205 	$date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
 1206 	                   $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
 1207 	$date{'mday-time'} = sprintf "%d %s %02d:%02d",
 1208 	                     $mday, $months[$mon], $hour ,$min;
 1209 
 1210 	$tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
 1211 	my $local = $epoch + ((int $1 + ($2/60)) * 3600);
 1212 	($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
 1213 	$date{'hour_local'} = $hour;
 1214 	$date{'minute_local'} = $min;
 1215 	$date{'tz_local'} = $tz;
 1216 	$date{'iso-tz'} = sprintf ("%04d-%02d-%02d %02d:%02d:%02d %s",
 1217 				   1900+$year, $mon+1, $mday,
 1218 				   $hour, $min, $sec, $tz);
 1219 	return %date;
 1220 }
 1221 
 1222 sub parse_tag {
 1223 	my $tag_id = shift;
 1224 	my %tag;
 1225 	my @comment;
 1226 
 1227 	open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
 1228 	$tag{'id'} = $tag_id;
 1229 	while (my $line = <$fd>) {
 1230 		chomp $line;
 1231 		if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
 1232 			$tag{'object'} = $1;
 1233 		} elsif ($line =~ m/^type (.+)$/) {
 1234 			$tag{'type'} = $1;
 1235 		} elsif ($line =~ m/^tag (.+)$/) {
 1236 			$tag{'name'} = $1;
 1237 		} elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
 1238 			$tag{'author'} = $1;
 1239 			$tag{'epoch'} = $2;
 1240 			$tag{'tz'} = $3;
 1241 		} elsif ($line =~ m/--BEGIN/) {
 1242 			push @comment, $line;
 1243 			last;
 1244 		} elsif ($line eq "") {
 1245 			last;
 1246 		}
 1247 	}
 1248 	push @comment, <$fd>;
 1249 	$tag{'comment'} = \@comment;
 1250 	close $fd or return;
 1251 	if (!defined $tag{'name'}) {
 1252 		return
 1253 	};
 1254 	return %tag
 1255 }
 1256 
 1257 sub parse_commit {
 1258 	my $commit_id = shift;
 1259 	my $commit_text = shift;
 1260 
 1261 	my @commit_lines;
 1262 	my %co;
 1263 
 1264 	if (defined $commit_text) {
 1265 		@commit_lines = @$commit_text;
 1266 	} else {
 1267 		local $/ = "\0";
 1268 		open my $fd, "-|", git_cmd(), "rev-list",
 1269 			"--header", "--parents", "--max-count=1",
 1270 			$commit_id, "--"
 1271 			or return;
 1272 		@commit_lines = split '\n', <$fd>;
 1273 		close $fd or return;
 1274 		pop @commit_lines;
 1275 	}
 1276 	my $header = shift @commit_lines;
 1277 	if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
 1278 		return;
 1279 	}
 1280 	($co{'id'}, my @parents) = split ' ', $header;
 1281 	$co{'parents'} = \@parents;
 1282 	$co{'parent'} = $parents[0];
 1283 	while (my $line = shift @commit_lines) {
 1284 		last if $line eq "\n";
 1285 		if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
 1286 			$co{'tree'} = $1;
 1287 		} elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
 1288 			$co{'author'} = $1;
 1289 			$co{'author_epoch'} = $2;
 1290 			$co{'author_tz'} = $3;
 1291 			if ($co{'author'} =~ m/^([^<]+) </) {
 1292 				$co{'author_name'} = $1;
 1293 			} else {
 1294 				$co{'author_name'} = $co{'author'};
 1295 			}
 1296 		} elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
 1297 			$co{'committer'} = $1;
 1298 			$co{'committer_epoch'} = $2;
 1299 			$co{'committer_tz'} = $3;
 1300 			$co{'committer_name'} = $co{'committer'};
 1301 			$co{'committer_name'} =~ s/ <.*//;
 1302 		}
 1303 	}
 1304 	if (!defined $co{'tree'}) {
 1305 		return;
 1306 	};
 1307 
 1308 	foreach my $title (@commit_lines) {
 1309 		$title =~ s/^    //;
 1310 		if ($title ne "") {
 1311 			$co{'title'} = chop_str($title, 80, 5);
 1312 			# remove leading stuff of merges to make the interesting part visible
 1313 			if (length($title) > 50) {
 1314 				$title =~ s/^Automatic //;
 1315 				$title =~ s/^merge (of|with) /Merge ... /i;
 1316 				if (length($title) > 50) {
 1317 					$title =~ s/(http|rsync):\/\///;
 1318 				}
 1319 				if (length($title) > 50) {
 1320 					$title =~ s/(master|www|rsync)\.//;
 1321 				}
 1322 				if (length($title) > 50) {
 1323 					$title =~ s/kernel.org:?//;
 1324 				}
 1325 				if (length($title) > 50) {
 1326 					$title =~ s/\/pub\/scm//;
 1327 				}
 1328 			}
 1329 			$co{'title_short'} = chop_str($title, 50, 5);
 1330 			last;
 1331 		}
 1332 	}
 1333 	if ($co{'title'} eq "") {
 1334 		$co{'title'} = $co{'title_short'} = '(no commit message)';
 1335 	}
 1336 	# remove added spaces
 1337 	foreach my $line (@commit_lines) {
 1338 		$line =~ s/^    //;
 1339 	}
 1340 	$co{'comment'} = \@commit_lines;
 1341 
 1342 	my $age = time - $co{'committer_epoch'};
 1343 	$co{'age'} = $age;
 1344 	$co{'age_string'} = age_string($age);
 1345 	my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
 1346 	if ($age > 60*60*24*7*2) {
 1347 		$co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
 1348 		$co{'age_string_age'} = $co{'age_string'};
 1349 	} else {
 1350 		$co{'age_string_date'} = $co{'age_string'};
 1351 		$co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
 1352 	}
 1353 	return %co;
 1354 }
 1355 
 1356 # parse ref from ref_file, given by ref_id, with given type
 1357 sub parse_ref {
 1358 	my $ref_file = shift;
 1359 	my $ref_id = shift;
 1360 	my $type = shift || git_get_type($ref_id);
 1361 	my %ref_item;
 1362 
 1363 	$ref_item{'type'} = $type;
 1364 	$ref_item{'id'} = $ref_id;
 1365 	$ref_item{'epoch'} = 0;
 1366 	$ref_item{'age'} = "unknown";
 1367 	if ($type eq "tag") {
 1368 		my %tag = parse_tag($ref_id);
 1369 		$ref_item{'comment'} = $tag{'comment'};
 1370 		if ($tag{'type'} eq "commit") {
 1371 			my %co = parse_commit($tag{'object'});
 1372 			$ref_item{'epoch'} = $co{'committer_epoch'};
 1373 			$ref_item{'age'} = $co{'age_string'};
 1374 		} elsif (defined($tag{'epoch'})) {
 1375 			my $age = time - $tag{'epoch'};
 1376 			$ref_item{'epoch'} = $tag{'epoch'};
 1377 			$ref_item{'age'} = age_string($age);
 1378 		}
 1379 		$ref_item{'reftype'} = $tag{'type'};
 1380 		$ref_item{'name'} = $tag{'name'};
 1381 		$ref_item{'refid'} = $tag{'object'};
 1382 	} elsif ($type eq "commit"){
 1383 		my %co = parse_commit($ref_id);
 1384 		$ref_item{'reftype'} = "commit";
 1385 		$ref_item{'name'} = $ref_file;
 1386 		$ref_item{'title'} = $co{'title'};
 1387 		$ref_item{'refid'} = $ref_id;
 1388 		$ref_item{'epoch'} = $co{'committer_epoch'};
 1389 		$ref_item{'age'} = $co{'age_string'};
 1390 	} else {
 1391 		$ref_item{'reftype'} = $type;
 1392 		$ref_item{'name'} = $ref_file;
 1393 		$ref_item{'refid'} = $ref_id;
 1394 	}
 1395 
 1396 	return %ref_item;
 1397 }
 1398 
 1399 # parse line of git-diff-tree "raw" output
 1400 sub parse_difftree_raw_line {
 1401 	my $line = shift;
 1402 	my %res;
 1403 
 1404 	# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M	ls-files.c'
 1405 	# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M	rev-tree.c'
 1406 	if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
 1407 		$res{'from_mode'} = $1;
 1408 		$res{'to_mode'} = $2;
 1409 		$res{'from_id'} = $3;
 1410 		$res{'to_id'} = $4;
 1411 		$res{'status'} = $5;
 1412 		$res{'similarity'} = $6;
 1413 		if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
 1414 			($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
 1415 		} else {
 1416 			$res{'file'} = unquote($7);
 1417 		}
 1418 	}
 1419 	# 'c512b523472485aef4fff9e57b229d9d243c967f'
 1420 	elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
 1421 		$res{'commit'} = $1;
 1422 	}
 1423 
 1424 	return wantarray ? %res : \%res;
 1425 }
 1426 
 1427 # parse line of git-ls-tree output
 1428 sub parse_ls_tree_line ($;%) {
 1429 	my $line = shift;
 1430 	my %opts = @_;
 1431 	my %res;
 1432 
 1433 	#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa	panic.c'
 1434 	$line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
 1435 
 1436 	$res{'mode'} = $1;
 1437 	$res{'type'} = $2;
 1438 	$res{'hash'} = $3;
 1439 	if ($opts{'-z'}) {
 1440 		$res{'name'} = $4;
 1441 	} else {
 1442 		$res{'name'} = unquote($4);
 1443 	}
 1444 
 1445 	return wantarray ? %res : \%res;
 1446 }
 1447 
 1448 ## ......................................................................
 1449 ## parse to array of hashes functions
 1450 
 1451 sub git_get_heads_list {
 1452 	my $limit = shift;
 1453 	my @headslist;
 1454 
 1455 	open my $fd, '-|', git_cmd(), 'for-each-ref',
 1456 		($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
 1457 		'--format=%(objectname) %(refname) %(subject)%00%(committer)',
 1458 		'refs/heads'
 1459 		or return;
 1460 	while (my $line = <$fd>) {
 1461 		my %ref_item;
 1462 
 1463 		chomp $line;
 1464 		my ($refinfo, $committerinfo) = split(/\0/, $line);
 1465 		my ($hash, $name, $title) = split(' ', $refinfo, 3);
 1466 		my ($committer, $epoch, $tz) =
 1467 			($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
 1468 		$name =~ s!^refs/heads/!!;
 1469 
 1470 		$ref_item{'name'}  = $name;
 1471 		$ref_item{'id'}    = $hash;
 1472 		$ref_item{'title'} = $title || '(no commit message)';
 1473 		$ref_item{'epoch'} = $epoch;
 1474 		if ($epoch) {
 1475 			$ref_item{'age'} = age_string(time - $ref_item{'epoch'});
 1476 		} else {
 1477 			$ref_item{'age'} = "unknown";
 1478 		}
 1479 
 1480 		push @headslist, \%ref_item;
 1481 	}
 1482 	close $fd;
 1483 
 1484 	return wantarray ? @headslist : \@headslist;
 1485 }
 1486 
 1487 sub git_get_tags_list {
 1488 	my $limit = shift;
 1489 	my @tagslist;
 1490 
 1491 	open my $fd, '-|', git_cmd(), 'for-each-ref',
 1492 		($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
 1493 		'--format=%(objectname) %(objecttype) %(refname) '.
 1494 		'%(*objectname) %(*objecttype) %(subject)%00%(creator)',
 1495 		'refs/tags'
 1496 		or return;
 1497 	while (my $line = <$fd>) {
 1498 		my %ref_item;
 1499 
 1500 		chomp $line;
 1501 		my ($refinfo, $creatorinfo) = split(/\0/, $line);
 1502 		my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
 1503 		my ($creator, $epoch, $tz) =
 1504 			($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
 1505 		$name =~ s!^refs/tags/!!;
 1506 
 1507 		$ref_item{'type'} = $type;
 1508 		$ref_item{'id'} = $id;
 1509 		$ref_item{'name'} = $name;
 1510 		if ($type eq "tag") {
 1511 			$ref_item{'subject'} = $title;
 1512 			$ref_item{'reftype'} = $reftype;
 1513 			$ref_item{'refid'}   = $refid;
 1514 		} else {
 1515 			$ref_item{'reftype'} = $type;
 1516 			$ref_item{'refid'}   = $id;
 1517 		}
 1518 
 1519 		if ($type eq "tag" || $type eq "commit") {
 1520 			$ref_item{'epoch'} = $epoch;
 1521 			if ($epoch) {
 1522 				$ref_item{'age'} = age_string(time - $ref_item{'epoch'});
 1523 			} else {
 1524 				$ref_item{'age'} = "unknown";
 1525 			}
 1526 		}
 1527 
 1528 		push @tagslist, \%ref_item;
 1529 	}
 1530 	close $fd;
 1531 
 1532 	return wantarray ? @tagslist : \@tagslist;
 1533 }
 1534 
 1535 ## ----------------------------------------------------------------------
 1536 ## filesystem-related functions
 1537 
 1538 sub get_file_owner {
 1539 	my $path = shift;
 1540 
 1541 	my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
 1542 	my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
 1543 	if (!defined $gcos) {
 1544 		return undef;
 1545 	}
 1546 	my $owner = $gcos;
 1547 	$owner =~ s/[,;].*$//;
 1548 	return to_utf8($owner);
 1549 }
 1550 
 1551 ## ......................................................................
 1552 ## mimetype related functions
 1553 
 1554 sub mimetype_guess_file {
 1555 	my $filename = shift;
 1556 	my $mimemap = shift;
 1557 	-r $mimemap or return undef;
 1558 
 1559 	my %mimemap;
 1560 	open(MIME, $mimemap) or return undef;
 1561 	while (<MIME>) {
 1562 		next if m/^#/; # skip comments
 1563 		my ($mime, $exts) = split(/\t+/);
 1564 		if (defined $exts) {
 1565 			my @exts = split(/\s+/, $exts);
 1566 			foreach my $ext (@exts) {
 1567 				$mimemap{$ext} = $mime;
 1568 			}
 1569 		}
 1570 	}
 1571 	close(MIME);
 1572 
 1573 	$filename =~ /\.([^.]*)$/;
 1574 	return $mimemap{$1};
 1575 }
 1576 
 1577 sub mimetype_guess {
 1578 	my $filename = shift;
 1579 	my $mime;
 1580 	$filename =~ /\./ or return undef;
 1581 
 1582 	if ($mimetypes_file) {
 1583 		my $file = $mimetypes_file;
 1584 		if ($file !~ m!^/!) { # if it is relative path
 1585 			# it is relative to project
 1586 			$file = "$projectroot/$project/$file";
 1587 		}
 1588 		$mime = mimetype_guess_file($filename, $file);
 1589 	}
 1590 	$mime ||= mimetype_guess_file($filename, '/etc/mime.types');
 1591 	return $mime;
 1592 }
 1593 
 1594 sub blob_mimetype {
 1595 	my $fd = shift;
 1596 	my $filename = shift;
 1597 
 1598 	if ($filename) {
 1599 		my $mime = mimetype_guess($filename);
 1600 		$mime and return $mime;
 1601 	}
 1602 
 1603 	# just in case
 1604 	return $default_blob_plain_mimetype unless $fd;
 1605 
 1606 	if (-T $fd) {
 1607 		return 'text/plain' .
 1608 		       ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
 1609 	} elsif (! $filename) {
 1610 		return 'application/octet-stream';
 1611 	} elsif ($filename =~ m/\.png$/i) {
 1612 		return 'image/png';
 1613 	} elsif ($filename =~ m/\.gif$/i) {
 1614 		return 'image/gif';
 1615 	} elsif ($filename =~ m/\.jpe?g$/i) {
 1616 		return 'image/jpeg';
 1617 	} else {
 1618 		return 'application/octet-stream';
 1619 	}
 1620 }
 1621 
 1622 ## ======================================================================
 1623 ## functions printing HTML: header, footer, error page
 1624 
 1625 sub git_header_html {
 1626 	my $status = shift || "200 OK";
 1627 	my $expires = shift;
 1628 
 1629 	my $title = "$site_name";
 1630 	if (defined $project) {
 1631 		$title .= " - $project";
 1632 		if (defined $action) {
 1633 			$title .= "/$action";
 1634 			if (defined $file_name) {
 1635 				$title .= " - " . esc_path($file_name);
 1636 				if ($action eq "tree" && $file_name !~ m|/$|) {
 1637 					$title .= "/";
 1638 				}
 1639 			}
 1640 		}
 1641 	}
 1642 	my $content_type;
 1643 	# require explicit support from the UA if we are to send the page as
 1644 	# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
 1645 	# we have to do this because MSIE sometimes globs '*/*', pretending to
 1646 	# support xhtml+xml but choking when it gets what it asked for.
 1647 	if (defined $cgi->http('HTTP_ACCEPT') &&
 1648 	    $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
 1649 	    $cgi->Accept('application/xhtml+xml') != 0) {
 1650 		$content_type = 'application/xhtml+xml';
 1651 	} else {
 1652 		$content_type = 'text/html';
 1653 	}
 1654 	$content_type = 'text/html';
 1655 	print $cgi->header(-type=>$content_type, -charset => 'utf-8',
 1656 	                   -status=> $status, -expires => $expires);
 1657 	print <<EOF;
 1658 <?xml version="1.0" encoding="utf-8"?>
 1659 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 1660 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
 1661 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
 1662 <!-- git core binaries version $git_version -->
 1663 <head>
 1664 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
 1665 <meta name="generator" content="gitweb/$version git/$git_version"/>
 1666 <meta name="robots" content="index, nofollow"/>
 1667 <title>$title</title>
 1668 EOF
 1669 # print out each stylesheet that exist
 1670 	if (defined $stylesheet) {
 1671 #provides backwards capability for those people who define style sheet in a config file
 1672 		print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
 1673 	} else {
 1674 		foreach my $stylesheet (@stylesheets) {
 1675 			next unless $stylesheet;
 1676 			print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
 1677 		}
 1678 	}
 1679 	if (defined $project) {
 1680 		printf('<link rel="alternate" title="%s log" '.
 1681 		       'href="%s" type="application/rss+xml"/>'."\n",
 1682 		       esc_param($project), href(action=>"rss"));
 1683 	} else {
 1684 		printf('<link rel="alternate" title="%s projects list" '.
 1685 		       'href="%s" type="text/plain; charset=utf-8"/>'."\n",
 1686 		       $site_name, href(project=>undef, action=>"project_index"));
 1687 		printf('<link rel="alternate" title="%s projects logs" '.
 1688 		       'href="%s" type="text/x-opml"/>'."\n",
 1689 		       $site_name, href(project=>undef, action=>"opml"));
 1690 	}
 1691 	if (defined $favicon) {
 1692 		print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
 1693 	}
 1694 
 1695 	print "</head>\n" .
 1696 	      "<body>\n";
 1697 
 1698 	if (-f $site_header) {
 1699 		open (my $fd, $site_header);
 1700 		print <$fd>;
 1701 		close $fd;
 1702 	}
 1703 
 1704 	print "<div class=\"page_header\">\n" .
 1705 	      $cgi->a({-href => esc_url($logo_url),
 1706 	               -title => $logo_label},
 1707 	              qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
 1708 	print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
 1709 	if (defined $project) {
 1710 		print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
 1711 		if (defined $action) {
 1712 			print " / $action";
 1713 		}
 1714 		print "\n";
 1715 		if (!defined $searchtext) {
 1716 			$searchtext = "";
 1717 		}
 1718 		my $search_hash;
 1719 		if (defined $hash_base) {
 1720 			$search_hash = $hash_base;
 1721 		} elsif (defined $hash) {
 1722 			$search_hash = $hash;
 1723 		} else {
 1724 			$search_hash = "HEAD";
 1725 		}
 1726 		$cgi->param("a", "search");
 1727 		$cgi->param("h", $search_hash);
 1728 		$cgi->param("p", $project);
 1729 		print $cgi->startform(-method => "get", -action => $my_uri) .
 1730 		      "<div class=\"search\">\n" .
 1731 		      $cgi->hidden(-name => "p") . "\n" .
 1732 		      $cgi->hidden(-name => "a") . "\n" .
 1733 		      $cgi->hidden(-name => gitweb_get_default_head($project)) . "\n" .
 1734 		      $cgi->popup_menu(-name => 'st', -default => 'commit',
 1735 				       -values => ['commit', 'author', 'committer', 'pickaxe']) .
 1736 		      $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
 1737 		      " search:\n",
 1738 		      $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
 1739 		      "</div>" .
 1740 		      $cgi->end_form() . "\n";
 1741 	}
 1742 	print "</div><div class=\"content\">\n";
 1743 }
 1744 
 1745 sub git_footer_html {
 1746 	print "</div><div class=\"page_footer\">\n";
 1747 	if (defined $project) {
 1748 		my $descr = git_get_project_description($project);
 1749 		if (defined $descr) {
 1750 			print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
 1751 		}
 1752 		print $cgi->a({-href => href(action=>"rss"),
 1753 		              -class => "rss_logo"}, "RSS") . "\n";
 1754 	} else {
 1755 		print $cgi->a({-href => href(project=>undef, action=>"opml"),
 1756 		              -class => "rss_logo"}, "OPML") . " ";
 1757 		print $cgi->a({-href => href(project=>undef, action=>"project_index"),
 1758 		              -class => "rss_logo"}, "TXT") . "\n";
 1759 	}
 1760 	print "</div>\n" ;
 1761 
 1762 	if (-f $site_footer) {
 1763 		open (my $fd, $site_footer);
 1764 		print <$fd>;
 1765 		close $fd;
 1766 	}
 1767 
 1768 	print "</body>\n" .
 1769 	      "</html>";
 1770 }
 1771 
 1772 sub die_error {
 1773 	my $status = shift || "403 Forbidden";
 1774 	my $error = shift || "Malformed query, file missing or permission denied";
 1775 
 1776 	git_header_html($status);
 1777 	print <<EOF;
 1778 <div class="page_body">
 1779 <br /><br />
 1780 $status - $error
 1781 <br />
 1782 </div>
 1783 EOF
 1784 	git_footer_html();
 1785 	exit;
 1786 }
 1787 
 1788 ## ----------------------------------------------------------------------
 1789 ## functions printing or outputting HTML: navigation
 1790 
 1791 sub git_print_page_nav {
 1792 	my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
 1793 	$extra = '' if !defined $extra; # pager or formats
 1794 
 1795 	my @navs = qw(summary shortlog log commit commitdiff tree);
 1796 	if ($suppress) {
 1797 		@navs = grep { $_ ne $suppress } @navs;
 1798 	}
 1799 
 1800 	my %arg = map { $_ => {action=>$_} } @navs;
 1801 	if (defined $head) {
 1802 		for (qw(commit commitdiff)) {
 1803 			$arg{$_}{hash} = $head;
 1804 		}
 1805 		if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
 1806 			for (qw(shortlog log)) {
 1807 				$arg{$_}{hash} = $head;
 1808 			}
 1809 		}
 1810 	}
 1811 	$arg{tree}{hash} = $treehead if defined $treehead;
 1812 	$arg{tree}{hash_base} = $treebase if defined $treebase;
 1813 
 1814 	print "<div class=\"page_nav\">\n" .
 1815 		(join " | ",
 1816 		 map { $_ eq $current ?
 1817 		       $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
 1818 		 } @navs);
 1819 	print "<br/>\n$extra<br/>\n" .
 1820 	      "</div>\n";
 1821 }
 1822 
 1823 sub format_paging_nav {
 1824 	my ($action, $hash, $head, $page, $nrevs) = @_;
 1825 	my $paging_nav;
 1826 
 1827 
 1828 	if ($hash ne $head || $page) {
 1829 		$paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
 1830 	} else {
 1831 		$paging_nav .= "HEAD";
 1832 	}
 1833 
 1834 	if ($page > 0) {
 1835 		$paging_nav .= " &sdot; " .
 1836 			$cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
 1837 			         -accesskey => "p", -title => "Alt-p"}, "prev");
 1838 	} else {
 1839 		$paging_nav .= " &sdot; prev";
 1840 	}
 1841 
 1842 	if ($nrevs >= (100 * ($page+1)-1)) {
 1843 		$paging_nav .= " &sdot; " .
 1844 			$cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
 1845 			         -accesskey => "n", -title => "Alt-n"}, "next");
 1846 	} else {
 1847 		$paging_nav .= " &sdot; next";
 1848 	}
 1849 
 1850 	return $paging_nav;
 1851 }
 1852 
 1853 ## ......................................................................
 1854 ## functions printing or outputting HTML: div
 1855 
 1856 sub git_print_header_div {
 1857 	my ($action, $title, $hash, $hash_base) = @_;
 1858 	my %args = ();
 1859 
 1860 	$args{action} = $action;
 1861 	$args{hash} = $hash if $hash;
 1862 	$args{hash_base} = $hash_base if $hash_base;
 1863 
 1864 	print "<div class=\"header\">\n" .
 1865 	      $cgi->a({-href => href(%args), -class => "title"},
 1866 	      $title ? $title : $action) .
 1867 	      "\n</div>\n";
 1868 }
 1869 
 1870 #sub git_print_authorship (\%) {
 1871 sub git_print_authorship {
 1872 	my $co = shift;
 1873 
 1874 	my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
 1875 	print "<div class=\"author_date\">" .
 1876 	      esc_html($co->{'author_name'}) .
 1877 	      " [$ad{'rfc2822'}";
 1878 	if ($ad{'hour_local'} < 6) {
 1879 		printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
 1880 		       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
 1881 	} else {
 1882 		printf(" (%02d:%02d %s)",
 1883 		       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
 1884 	}
 1885 	print "]</div>\n";
 1886 }
 1887 
 1888 sub git_print_page_path {
 1889 	my $name = shift;
 1890 	my $type = shift;
 1891 	my $hb = shift;
 1892 
 1893 
 1894 	print "<div class=\"page_path\">";
 1895 	print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
 1896 	              -title => 'tree root'}, "[$project]");
 1897 	print " / ";
 1898 	if (defined $name) {
 1899 		my @dirname = split '/', $name;
 1900 		my $basename = pop @dirname;
 1901 		my $fullname = '';
 1902 
 1903 		foreach my $dir (@dirname) {
 1904 			$fullname .= ($fullname ? '/' : '') . $dir;
 1905 			print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
 1906 			                             hash_base=>$hb),
 1907 			              -title => esc_html($fullname)}, esc_path($dir));
 1908 			print " / ";
 1909 		}
 1910 		if (defined $type && $type eq 'blob') {
 1911 			print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
 1912 			                             hash_base=>$hb),
 1913 			              -title => esc_html($name)}, esc_path($basename));
 1914 		} elsif (defined $type && $type eq 'tree') {
 1915 			print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
 1916 			                             hash_base=>$hb),
 1917 			              -title => esc_html($name)}, esc_path($basename));
 1918 			print " / ";
 1919 		} else {
 1920 			print esc_path($basename);
 1921 		}
 1922 	}
 1923 	print "<br/></div>\n";
 1924 }
 1925 
 1926 # sub git_print_log (\@;%) {
 1927 sub git_print_log ($;%) {
 1928 	my $log = shift;
 1929 	my %opts = @_;
 1930 
 1931 	if ($opts{'-remove_title'}) {
 1932 		# remove title, i.e. first line of log
 1933 		shift @$log;
 1934 	}
 1935 	# remove leading empty lines
 1936 	while (defined $log->[0] && $log->[0] eq "") {
 1937 		shift @$log;
 1938 	}
 1939 
 1940 	# print log
 1941 	my $signoff = 0;
 1942 	my $empty = 0;
 1943 	foreach my $line (@$log) {
 1944 		if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
 1945 			$signoff = 1;
 1946 			$empty = 0;
 1947 			if (! $opts{'-remove_signoff'}) {
 1948 				print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
 1949 				next;
 1950 			} else {
 1951 				# remove signoff lines
 1952 				next;
 1953 			}
 1954 		} else {
 1955 			$signoff = 0;
 1956 		}
 1957 
 1958 		# print only one empty line
 1959 		# do not print empty line after signoff
 1960 		if ($line eq "") {
 1961 			next if ($empty || $signoff);
 1962 			$empty = 1;
 1963 		} else {
 1964 			$empty = 0;
 1965 		}
 1966 
 1967 		print format_log_line_html($line) . "<br/>\n";
 1968 	}
 1969 
 1970 	if ($opts{'-final_empty_line'}) {
 1971 		# end with single empty line
 1972 		print "<br/>\n" unless $empty;
 1973 	}
 1974 }
 1975 
 1976 # print tree entry (row of git_tree), but without encompassing <tr> element
 1977 sub git_print_tree_entry {
 1978 	my ($t, $basedir, $hash_base, $have_blame) = @_;
 1979 
 1980 	my %base_key = ();
 1981 	$base_key{hash_base} = $hash_base if defined $hash_base;
 1982 
 1983 	# The format of a table row is: mode list link.  Where mode is
 1984 	# the mode of the entry, list is the name of the entry, an href,
 1985 	# and link is the action links of the entry.
 1986 
 1987 	print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
 1988 	if ($t->{'type'} eq "blob") {
 1989 		print "<td class=\"list\">" .
 1990 			$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
 1991 			                       file_name=>"$basedir$t->{'name'}", %base_key),
 1992 			        -class => "list"}, esc_path($t->{'name'})) . "</td>\n";
 1993 		print "<td class=\"link\">";
 1994 		print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
 1995 					     file_name=>"$basedir$t->{'name'}", %base_key)},
 1996 			      "blob");
 1997 		if ($have_blame) {
 1998 			print " | " .
 1999 			      $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
 2000 				                           file_name=>"$basedir$t->{'name'}", %base_key)},
 2001 				            "blame");
 2002 		}
 2003 		if (defined $hash_base) {
 2004 			print " | " .
 2005 			      $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
 2006 			                             hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
 2007 			              "history");
 2008 		}
 2009 		print " | " .
 2010 			$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
 2011 			                       file_name=>"$basedir$t->{'name'}")},
 2012 			        "raw");
 2013 		print "</td>\n";
 2014 
 2015 	} elsif ($t->{'type'} eq "tree") {
 2016 		print "<td class=\"list\">";
 2017 		print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
 2018 		                             file_name=>"$basedir$t->{'name'}", %base_key)},
 2019 		              esc_path($t->{'name'}));
 2020 		print "</td>\n";
 2021 		print "<td class=\"link\">";
 2022 		print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
 2023 					     file_name=>"$basedir$t->{'name'}", %base_key)},
 2024 			      "tree");
 2025 		if (defined $hash_base) {
 2026 			print " | " .
 2027 			      $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
 2028 			                             file_name=>"$basedir$t->{'name'}")},
 2029 			              "history");
 2030 		}
 2031 		print "</td>\n";
 2032 	}
 2033 }
 2034 
 2035 ## ......................................................................
 2036 ## functions printing large fragments of HTML
 2037 
 2038 sub git_difftree_body {
 2039 	my ($difftree, $hash, $parent) = @_;
 2040 	my ($have_blame) = gitweb_check_feature('blame');
 2041 	print "<div class=\"list_head\">\n";
 2042 	if ($#{$difftree} > 10) {
 2043 		print(($#{$difftree} + 1) . " files changed:\n");
 2044 	}
 2045 	print "</div>\n";
 2046 
 2047 	print "<table class=\"diff_tree\">\n";
 2048 	my $alternate = 1;
 2049 	my $patchno = 0;
 2050 	foreach my $line (@{$difftree}) {
 2051 		my %diff = parse_difftree_raw_line($line);
 2052 
 2053 		if ($alternate) {
 2054 			print "<tr class=\"dark\">\n";
 2055 		} else {
 2056 			print "<tr class=\"light\">\n";
 2057 		}
 2058 		$alternate ^= 1;
 2059 
 2060 		my ($to_mode_oct, $to_mode_str, $to_file_type);
 2061 		my ($from_mode_oct, $from_mode_str, $from_file_type);
 2062 		if ($diff{'to_mode'} ne ('0' x 6)) {
 2063 			$to_mode_oct = oct $diff{'to_mode'};
 2064 			if (S_ISREG($to_mode_oct)) { # only for regular file
 2065 				$to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
 2066 			}
 2067 			$to_file_type = file_type($diff{'to_mode'});
 2068 		}
 2069 		if ($diff{'from_mode'} ne ('0' x 6)) {
 2070 			$from_mode_oct = oct $diff{'from_mode'};
 2071 			if (S_ISREG($to_mode_oct)) { # only for regular file
 2072 				$from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
 2073 			}
 2074 			$from_file_type = file_type($diff{'from_mode'});
 2075 		}
 2076 
 2077 		if ($diff{'status'} eq "A") { # created
 2078 			my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
 2079 			$mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
 2080 			$mode_chng   .= "]</span>";
 2081 			print "<td>";
 2082 			print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
 2083 			                             hash_base=>$hash, file_name=>$diff{'file'}),
 2084 			              -class => "list"}, esc_path($diff{'file'}));
 2085 			print "</td>\n";
 2086 			print "<td>$mode_chng</td>\n";
 2087 			print "<td class=\"link\">";
 2088 			if ($action eq 'commitdiff') {
 2089 				# link to patch
 2090 				$patchno++;
 2091 				print $cgi->a({-href => "#patch$patchno"}, "patch");
 2092 			}
 2093 			print "</td>\n";
 2094 
 2095 		} elsif ($diff{'status'} eq "D") { # deleted
 2096 			my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
 2097 			print "<td>";
 2098 			print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
 2099 			                             hash_base=>$parent, file_name=>$diff{'file'}),
 2100 			               -class => "list"}, esc_path($diff{'file'}));
 2101 			print "</td>\n";
 2102 			print "<td>$mode_chng</td>\n";
 2103 			print "<td class=\"link\">";
 2104 			if ($action eq 'commitdiff') {
 2105 				# link to patch
 2106 				$patchno++;
 2107 				print $cgi->a({-href => "#patch$patchno"}, "patch");
 2108 				print " | ";
 2109 			}
 2110 			print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
 2111 			                             hash_base=>$parent, file_name=>$diff{'file'})},
 2112 				      "blob") . " | ";
 2113 			if ($have_blame) {
 2114 				print $cgi->a({-href =>
 2115 						   href(action=>"blame",
 2116 							hash_base=>$parent,
 2117 							file_name=>$diff{'file'})},
 2118 					      "blame") . " | ";
 2119 			}
 2120 			print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
 2121 			                             file_name=>$diff{'file'})},
 2122 			              "history");
 2123 			print "</td>\n";
 2124 
 2125 		} elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
 2126 			my $mode_chnge = "";
 2127 			if ($diff{'from_mode'} != $diff{'to_mode'}) {
 2128 				$mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
 2129 				if ($from_file_type != $to_file_type) {
 2130 					$mode_chnge .= " from $from_file_type to $to_file_type";
 2131 				}
 2132 				if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
 2133 					if ($from_mode_str && $to_mode_str) {
 2134 						$mode_chnge .= " mode: $from_mode_str->$to_mode_str";
 2135 					} elsif ($to_mode_str) {
 2136 						$mode_chnge .= " mode: $to_mode_str";
 2137 					}
 2138 				}
 2139 				$mode_chnge .= "]</span>\n";
 2140 			}
 2141 			print "<td>";
 2142 			print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
 2143 			                             hash_base=>$hash, file_name=>$diff{'file'}),
 2144 			              -class => "list"}, esc_path($diff{'file'}));
 2145 			print "</td>\n";
 2146 			print "<td>$mode_chnge</td>\n";
 2147 			print "<td class=\"link\">";
 2148 			if ($action eq 'commitdiff') {
 2149 				# link to patch
 2150 				$patchno++;
 2151 				print $cgi->a({-href => "#patch$patchno"}, "patch") .
 2152 				      " | ";
 2153 			} elsif ($diff{'to_id'} ne $diff{'from_id'}) {
 2154 				# "commit" view and modified file (not onlu mode changed)
 2155 				print $cgi->a({-href => href(action=>"blobdiff",
 2156 				                             hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
 2157 				                             hash_base=>$hash, hash_parent_base=>$parent,
 2158 				                             file_name=>$diff{'file'})},
 2159 				              "diff") .
 2160 				      " | ";
 2161 			}
 2162 			print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
 2163 						     hash_base=>$hash, file_name=>$diff{'file'})},
 2164 				      "blob") . " | ";
 2165 			if ($have_blame) {
 2166 				print $cgi->a({-href => href(action=>"blame",
 2167 							     hash_base=>$hash,
 2168 							     file_name=>$diff{'file'})},
 2169 					      "blame") . " | ";
 2170 			}
 2171 			print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
 2172 			                             file_name=>$diff{'file'})},
 2173 			              "history");
 2174 			print "</td>\n";
 2175 
 2176 		} elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
 2177 			my %status_name = ('R' => 'moved', 'C' => 'copied');
 2178 			my $nstatus = $status_name{$diff{'status'}};
 2179 			my $mode_chng = "";
 2180 			if ($diff{'from_mode'} != $diff{'to_mode'}) {
 2181 				# mode also for directories, so we cannot use $to_mode_str
 2182 				$mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
 2183 			}
 2184 			print "<td>" .
 2185 			      $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
 2186 			                             hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
 2187 			              -class => "list"}, esc_path($diff{'to_file'})) . "</td>\n" .
 2188 			      "<td><span class=\"file_status $nstatus\">[$nstatus from " .
 2189 			      $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
 2190 			                             hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
 2191 			              -class => "list"}, esc_path($diff{'from_file'})) .
 2192 			      " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
 2193 			      "<td class=\"link\">";
 2194 			if ($action eq 'commitdiff') {
 2195 				# link to patch
 2196 				$patchno++;
 2197 				print $cgi->a({-href => "#patch$patchno"}, "patch") .
 2198 				      " | ";
 2199 			} elsif ($diff{'to_id'} ne $diff{'from_id'}) {
 2200 				# "commit" view and modified file (not only pure rename or copy)
 2201 				print $cgi->a({-href => href(action=>"blobdiff",
 2202 				                             hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
 2203 				                             hash_base=>$hash, hash_parent_base=>$parent,
 2204 				                             file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
 2205 				              "diff") .
 2206 				      " | ";
 2207 			}
 2208 			print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
 2209 						     hash_base=>$parent, file_name=>$diff{'from_file'})},
 2210 				      "blob") . " | ";
 2211 			if ($have_blame) {
 2212 				print $cgi->a({-href => href(action=>"blame",
 2213 							     hash_base=>$hash,
 2214 							     file_name=>$diff{'to_file'})},
 2215 					      "blame") . " | ";
 2216 			}
 2217 			print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
 2218 			                            file_name=>$diff{'from_file'})},
 2219 			              "history");
 2220 			print "</td>\n";
 2221 
 2222 		} # we should not encounter Unmerged (U) or Unknown (X) status
 2223 		print "</tr>\n";
 2224 	}
 2225 	print "</table>\n";
 2226 }
 2227 
 2228 sub git_patchset_body {
 2229 	my ($fd, $difftree, $hash, $hash_parent) = @_;
 2230 
 2231 	my $patch_idx = 0;
 2232 	my $in_header = 0;
 2233 	my $patch_found = 0;
 2234 	my $diffinfo;
 2235 	my (%from, %to);
 2236 
 2237 	print "<div class=\"patchset\">\n";
 2238 
 2239 	LINE:
 2240 	while (my $patch_line = <$fd>) {
 2241 		chomp $patch_line;
 2242 
 2243 		if ($patch_line =~ m/^diff /) { # "git diff" header
 2244 			# beginning of patch (in patchset)
 2245 			if ($patch_found) {
 2246 				# close extended header for previous empty patch
 2247 				if ($in_header) {
 2248 					print "</div>\n" # class="diff extended_header"
 2249 				}
 2250 				# close previous patch
 2251 				print "</div>\n"; # class="patch"
 2252 			} else {
 2253 				# first patch in patchset
 2254 				$patch_found = 1;
 2255 			}
 2256 			print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
 2257 
 2258 			# read and prepare patch information
 2259 			if (ref($difftree->[$patch_idx]) eq "HASH") {
 2260 				# pre-parsed (or generated by hand)
 2261 				$diffinfo = $difftree->[$patch_idx];
 2262 			} else {
 2263 				$diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
 2264 			}
 2265 			$from{'file'} = $diffinfo->{'from_file'} || $diffinfo->{'file'};
 2266 			$to{'file'}   = $diffinfo->{'to_file'}   || $diffinfo->{'file'};
 2267 			if ($diffinfo->{'status'} ne "A") { # not new (added) file
 2268 				$from{'href'} = href(action=>"blob", hash_base=>$hash_parent,
 2269 				                     hash=>$diffinfo->{'from_id'},
 2270 				                     file_name=>$from{'file'});
 2271 			}
 2272 			if ($diffinfo->{'status'} ne "D") { # not deleted file
 2273 				$to{'href'} = href(action=>"blob", hash_base=>$hash,
 2274 				                   hash=>$diffinfo->{'to_id'},
 2275 				                   file_name=>$to{'file'});
 2276 			}
 2277 			$patch_idx++;
 2278 
 2279 			# print "git diff" header
 2280 			$patch_line =~ s!^(diff (.*?) )"?a/.*$!$1!;
 2281 			if ($from{'href'}) {
 2282 				$patch_line .= $cgi->a({-href => $from{'href'}, -class => "path"},
 2283 				                       'a/' . esc_path($from{'file'}));
 2284 			} else { # file was added
 2285 				$patch_line .= 'a/' . esc_path($from{'file'});
 2286 			}
 2287 			$patch_line .= ' ';
 2288 			if ($to{'href'}) {
 2289 				$patch_line .= $cgi->a({-href => $to{'href'}, -class => "path"},
 2290 				                       'b/' . esc_path($to{'file'}));
 2291 			} else { # file was deleted
 2292 				$patch_line .= 'b/' . esc_path($to{'file'});
 2293 			}
 2294 
 2295 			print "<div class=\"diff header\">$patch_line</div>\n";
 2296 			print "<div class=\"diff extended_header\">\n";
 2297 			$in_header = 1;
 2298 			next LINE;
 2299 		}
 2300 
 2301 		if ($in_header) {
 2302 			if ($patch_line !~ m/^---/) {
 2303 				# match <path>
 2304 				if ($patch_line =~ s!^((copy|rename) from ).*$!$1! && $from{'href'}) {
 2305 					$patch_line .= $cgi->a({-href=>$from{'href'}, -class=>"path"},
 2306 					                        esc_path($from{'file'}));
 2307 				}
 2308 				if ($patch_line =~ s!^((copy|rename) to ).*$!$1! && $to{'href'}) {
 2309 					$patch_line = $cgi->a({-href=>$to{'href'}, -class=>"path"},
 2310 					                      esc_path($to{'file'}));
 2311 				}
 2312 				# match <mode>
 2313 				if ($patch_line =~ m/\s(\d{6})$/) {
 2314 					$patch_line .= '<span class="info"> (' .
 2315 					               file_type_long($1) .
 2316 					               ')</span>';
 2317 				}
 2318 				# match <hash>
 2319 				if ($patch_line =~ m/^index/) {
 2320 					my ($from_link, $to_link);
 2321 					if ($from{'href'}) {
 2322 						$from_link = $cgi->a({-href=>$from{'href'}, -class=>"hash"},
 2323 						                     substr($diffinfo->{'from_id'},0,7));
 2324 					} else {
 2325 						$from_link = '0' x 7;
 2326 					}
 2327 					if ($to{'href'}) {
 2328 						$to_link = $cgi->a({-href=>$to{'href'}, -class=>"hash"},
 2329 						                   substr($diffinfo->{'to_id'},0,7));
 2330 					} else {
 2331 						$to_link = '0' x 7;
 2332 					}
 2333 					my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
 2334 					$patch_line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
 2335 				}
 2336 				print $patch_line . "<br/>\n";
 2337 
 2338 			} else {
 2339 				#$in_header && $patch_line =~ m/^---/;
 2340 				print "</div>\n"; # class="diff extended_header"
 2341 				$in_header = 0;
 2342 
 2343 				if ($from{'href'}) {
 2344 					$patch_line = '--- a/' .
 2345 					              $cgi->a({-href=>$from{'href'}, -class=>"path"},
 2346 					                      esc_path($from{'file'}));
 2347 				}
 2348 				print "<div class=\"diff from_file\">$patch_line</div>\n";
 2349 
 2350 				$patch_line = <$fd>;
 2351 				chomp $patch_line;
 2352 
 2353 				#$patch_line =~ m/^+++/;
 2354 				if ($to{'href'}) {
 2355 					$patch_line = '+++ b/' .
 2356 					              $cgi->a({-href=>$to{'href'}, -class=>"path"},
 2357 					                      esc_path($to{'file'}));
 2358 				}
 2359 				print "<div class=\"diff to_file\">$patch_line</div>\n";
 2360 
 2361 			}
 2362 
 2363 			next LINE;
 2364 		}
 2365 
 2366 		print format_diff_line($patch_line);
 2367 	}
 2368 	print "</div>\n" if $in_header; # extended header
 2369 
 2370 	print "</div>\n" if $patch_found; # class="patch"
 2371 
 2372 	print "</div>\n"; # class="patchset"
 2373 }
 2374 
 2375 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 2376 
 2377 sub git_project_list_body {
 2378 	my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
 2379 
 2380 	my ($check_forks) = gitweb_check_feature('forks');
 2381 
 2382 	my @projects;
 2383 	foreach my $pr (@$projlist) {
 2384 		my (@aa) = git_get_last_activity($pr->{'path'});
 2385 		unless (@aa) {
 2386 			next;
 2387 		}
 2388 		($pr->{'age'}, $pr->{'age_string'}) = @aa;
 2389 		if (!defined $pr->{'descr'}) {
 2390 			my $descr = git_get_project_description($pr->{'path'}) || "";
 2391 			$pr->{'descr'} = chop_str($descr, 25, 5);
 2392 		}
 2393 		if (!defined $pr->{'owner'}) {
 2394 			$pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
 2395 		}
 2396 		if ($check_forks) {
 2397 			my $pname = $pr->{'path'};
 2398 			if (($pname =~ s/\.git$//) &&
 2399 			    ($pname !~ /\/$/) &&
 2400 			    (-d "$projectroot/$pname")) {
 2401 				$pr->{'forks'} = "-d $projectroot/$pname";
 2402 			}
 2403 			else {
 2404 				$pr->{'forks'} = 0;
 2405 			}
 2406 		}
 2407 		push @projects, $pr;
 2408 	}
 2409 
 2410 	$order ||= "project";
 2411 	$from = 0 unless defined $from;
 2412 	$to = $#projects if (!defined $to || $#projects < $to);
 2413 
 2414 	print "<table class=\"project_list\">\n";
 2415 	unless ($no_header) {
 2416 		print "<tr>\n";
 2417 		if ($check_forks) {
 2418 			print "<th></th>\n";
 2419 		}
 2420 		if ($order eq "project") {
 2421 			@projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
 2422 			print "<th>Project</th>\n";
 2423 		} else {
 2424 			print "<th>" .
 2425 			      $cgi->a({-href => href(project=>undef, order=>'project'),
 2426 				       -class => "header"}, "Project") .
 2427 			      "</th>\n";
 2428 		}
 2429 		if ($order eq "descr") {
 2430 			@projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
 2431 			print "<th>Description</th>\n";
 2432 		} else {
 2433 			print "<th>" .
 2434 			      $cgi->a({-href => href(project=>undef, order=>'descr'),
 2435 				       -class => "header"}, "Description") .
 2436 			      "</th>\n";
 2437 		}
 2438 		if ($order eq "owner") {
 2439 			@projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
 2440 			print "<th>Owner</th>\n";
 2441 		} else {
 2442 			print "<th>" .
 2443 			      $cgi->a({-href => href(project=>undef, order=>'owner'),
 2444 				       -class => "header"}, "Owner") .
 2445 			      "</th>\n";
 2446 		}
 2447 		if ($order eq "age") {
 2448 			@projects = sort {$a->{'age'} <=> $b->{'age'}} @projects;
 2449 			print "<th>Last Change</th>\n";
 2450 		} else {
 2451 			print "<th>" .
 2452 			      $cgi->a({-href => href(project=>undef, order=>'age'),
 2453 				       -class => "header"}, "Last Change") .
 2454 			      "</th>\n";
 2455 		}
 2456 		print "<th></th>\n" .
 2457 		      "</tr>\n";
 2458 	}
 2459 	my $alternate = 1;
 2460 	for (my $i = $from; $i <= $to; $i++) {
 2461 		my $pr = $projects[$i];
 2462 		if ($alternate) {
 2463 			print "<tr class=\"dark\">\n";
 2464 		} else {
 2465 			print "<tr class=\"light\">\n";
 2466 		}
 2467 		$alternate ^= 1;
 2468 		if ($check_forks) {
 2469 			print "<td>";
 2470 			if ($pr->{'forks'}) {
 2471 				print "<!-- $pr->{'forks'} -->\n";
 2472 				print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
 2473 			}
 2474 			print "</td>\n";
 2475 		}
 2476 		print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
 2477 		                        -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
 2478 		      "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
 2479 		      "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
 2480 		print "<td class=\"". age_class($pr->{'age'}) . "\">" .
 2481 		      $pr->{'age_string'} . "</td>\n" .
 2482 		      "<td class=\"link\">" .
 2483 		      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
 2484 		      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
 2485 		      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
 2486 		      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
 2487 		      ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
 2488 		      "</td>\n" .
 2489 		      "</tr>\n";
 2490 	}
 2491 	if (defined $extra) {
 2492 		print "<tr>\n";
 2493 		if ($check_forks) {
 2494 			print "<td></td>\n";
 2495 		}
 2496 		print "<td colspan=\"5\">$extra</td>\n" .
 2497 		      "</tr>\n";
 2498 	}
 2499 	print "</table>\n";
 2500 }
 2501 
 2502 sub git_shortlog_body {
 2503 	# uses global variable $project
 2504 	my ($revlist, $from, $to, $refs, $extra) = @_;
 2505 
 2506 	$from = 0 unless defined $from;
 2507 	$to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
 2508 
 2509 	print "<table class=\"shortlog\" cellspacing=\"0\">\n";
 2510 	my $alternate = 1;
 2511 	for (my $i = $from; $i <= $to; $i++) {
 2512 		my $commit = $revlist->[$i];
 2513 		#my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
 2514 		my $ref = format_ref_marker($refs, $commit);
 2515 		my %co = parse_commit($commit);
 2516 		if ($alternate) {
 2517 			print "<tr class=\"dark\">\n";
 2518 		} else {
 2519 			print "<tr class=\"light\">\n";
 2520 		}
 2521 		$alternate ^= 1;
 2522 		# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
 2523 		print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
 2524 		      "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
 2525 		      "<td>";
 2526 		print format_subject_html($co{'title'}, $co{'title_short'},
 2527 		                          href(action=>"commit", hash=>$commit), $ref);
 2528 		print "</td>\n" .
 2529 		      "<td class=\"link\">" .
 2530 		      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
 2531 		      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
 2532 		      $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
 2533 		if (gitweb_have_snapshot()) {
 2534 			print " | " . $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
 2535 		}
 2536 		print "</td>\n" .
 2537 		      "</tr>\n";
 2538 	}
 2539 	if (defined $extra) {
 2540 		print "<tr>\n" .
 2541 		      "<td colspan=\"4\">$extra</td>\n" .
 2542 		      "</tr>\n";
 2543 	}
 2544 	print "</table>\n";
 2545 }
 2546 
 2547 sub git_history_body {
 2548 	# Warning: assumes constant type (blob or tree) during history
 2549 	my ($revlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
 2550 
 2551 	$from = 0 unless defined $from;
 2552 	$to = $#{$revlist} unless (defined $to && $to <= $#{$revlist});
 2553 
 2554 	print "<table class=\"history\" cellspacing=\"0\">\n";
 2555 	my $alternate = 1;
 2556 	for (my $i = $from; $i <= $to; $i++) {
 2557 		if ($revlist->[$i] !~ m/^([0-9a-fA-F]{40})/) {
 2558 			next;
 2559 		}
 2560 
 2561 		my $commit = $1;
 2562 		my %co = parse_commit($commit);
 2563 		if (!%co) {
 2564 			next;
 2565 		}
 2566 
 2567 		my $ref = format_ref_marker($refs, $commit);
 2568 
 2569 		if ($alternate) {
 2570 			print "<tr class=\"dark\">\n";
 2571 		} else {
 2572 			print "<tr class=\"light\">\n";
 2573 		}
 2574 		$alternate ^= 1;
 2575 		print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
 2576 		      # shortlog uses      chop_str($co{'author_name'}, 10)
 2577 		      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
 2578 		      "<td>";
 2579 		# originally git_history used chop_str($co{'title'}, 50)
 2580 		print format_subject_html($co{'title'}, $co{'title_short'},
 2581 		                          href(action=>"commit", hash=>$commit), $ref);
 2582 		print "</td>\n" .
 2583 		      "<td class=\"link\">" .
 2584 		      $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
 2585 		      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
 2586 
 2587 		if ($ftype eq 'blob') {
 2588 			my $blob_current = git_get_hash_by_path($hash_base, $file_name);
 2589 			my $blob_parent  = git_get_hash_by_path($commit, $file_name);
 2590 			if (defined $blob_current && defined $blob_parent &&
 2591 					$blob_current ne $blob_parent) {
 2592 				print " | " .
 2593 					$cgi->a({-href => href(action=>"blobdiff",
 2594 					                       hash=>$blob_current, hash_parent=>$blob_parent,
 2595 					                       hash_base=>$hash_base, hash_parent_base=>$commit,
 2596 					                       file_name=>$file_name)},
 2597 					        "diff to current");
 2598 			}
 2599 		}
 2600 		print "</td>\n" .
 2601 		      "</tr>\n";
 2602 	}
 2603 	if (defined $extra) {
 2604 		print "<tr>\n" .
 2605 		      "<td colspan=\"4\">$extra</td>\n" .
 2606 		      "</tr>\n";
 2607 	}
 2608 	print "</table>\n";
 2609 }
 2610 
 2611 sub git_tags_body {
 2612 	# uses global variable $project
 2613 	my ($taglist, $from, $to, $extra) = @_;
 2614 	$from = 0 unless defined $from;
 2615 	$to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
 2616 
 2617 	print "<table class=\"tags\" cellspacing=\"0\">\n";
 2618 	my $alternate = 1;
 2619 	for (my $i = $from; $i <= $to; $i++) {
 2620 		my $entry = $taglist->[$i];
 2621 		my %tag = %$entry;
 2622 		my $comment = $tag{'subject'};
 2623 		my $comment_short;
 2624 		if (defined $comment) {
 2625 			$comment_short = chop_str($comment, 30, 5);
 2626 		}
 2627 		if ($alternate) {
 2628 			print "<tr class=\"dark\">\n";
 2629 		} else {
 2630 			print "<tr class=\"light\">\n";
 2631 		}
 2632 		$alternate ^= 1;
 2633 		print "<td><i>$tag{'age'}</i></td>\n" .
 2634 		      "<td>" .
 2635 		      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
 2636 		               -class => "list name"}, esc_html($tag{'name'})) .
 2637 		      "</td>\n" .
 2638 		      "<td>";
 2639 		if (defined $comment) {
 2640 			print format_subject_html($comment, $comment_short,
 2641 			                          href(action=>"tag", hash=>$tag{'id'}));
 2642 		}
 2643 		print "</td>\n" .
 2644 		      "<td class=\"selflink\">";
 2645 		if ($tag{'type'} eq "tag") {
 2646 			print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
 2647 		} else {
 2648 			print "&nbsp;";
 2649 		}
 2650 		print "</td>\n" .
 2651 		      "<td class=\"link\">" . " | " .
 2652 		      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
 2653 		if ($tag{'reftype'} eq "commit") {
 2654 			print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
 2655 			      " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log");
 2656 		} elsif ($tag{'reftype'} eq "blob") {
 2657 			print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
 2658 		}
 2659 		print "</td>\n" .
 2660 		      "</tr>";
 2661 	}
 2662 	if (defined $extra) {
 2663 		print "<tr>\n" .
 2664 		      "<td colspan=\"5\">$extra</td>\n" .
 2665 		      "</tr>\n";
 2666 	}
 2667 	print "</table>\n";
 2668 }
 2669 
 2670 sub git_heads_body {
 2671 	# uses global variable $project
 2672 	my ($headlist, $head, $from, $to, $extra) = @_;
 2673 	$from = 0 unless defined $from;
 2674 	$to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
 2675 
 2676 	print "<table class=\"heads\" cellspacing=\"0\">\n";
 2677 	my $alternate = 1;
 2678 	for (my $i = $from; $i <= $to; $i++) {
 2679 		my $entry = $headlist->[$i];
 2680 		my %ref = %$entry;
 2681 		my $curr = $ref{'id'} eq $head;
 2682 		if ($alternate) {
 2683 			print "<tr class=\"dark\">\n";
 2684 		} else {
 2685 			print "<tr class=\"light\">\n";
 2686 		}
 2687 		$alternate ^= 1;
 2688 		print "<td><i>$ref{'age'}</i></td>\n" .
 2689 		      ($curr ? "<td class=\"current_head\">" : "<td>") .
 2690 		      $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'}),
 2691 		               -class => "list name"},esc_html($ref{'name'})) .
 2692 		      "</td>\n" .
 2693 		      "<td class=\"link\">" .
 2694 		      $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'})}, "shortlog") . " | " .
 2695 		      $cgi->a({-href => href(action=>"log", hash=>$ref{'name'})}, "log") . " | " .
 2696 		      $cgi->a({-href => href(action=>"tree", hash=>$ref{'name'}, hash_base=>$ref{'name'})}, "tree") .
 2697 		      "</td>\n" .
 2698 		      "</tr>";
 2699 	}
 2700 	if (defined $extra) {
 2701 		print "<tr>\n" .
 2702 		      "<td colspan=\"3\">$extra</td>\n" .
 2703 		      "</tr>\n";
 2704 	}
 2705 	print "</table>\n";
 2706 }
 2707 
 2708 ## ======================================================================
 2709 ## ======================================================================
 2710 ## actions
 2711 
 2712 sub git_project_list {
 2713 	my $order = $cgi->param('o');
 2714 	if (defined $order && $order !~ m/project|descr|owner|age/) {
 2715 		die_error(undef, "Unknown order parameter");
 2716 	}
 2717 
 2718 	my @list = git_get_projects_list();
 2719 	if (!@list) {
 2720 		die_error(undef, "No projects found");
 2721 	}
 2722 
 2723 	git_header_html();
 2724 	if (-f $home_text) {
 2725 		print "<div class=\"index_include\">\n";
 2726 		open (my $fd, $home_text);
 2727 		print <$fd>;
 2728 		close $fd;
 2729 		print "</div>\n";
 2730 	}
 2731 	git_project_list_body(\@list, $order);
 2732 	git_footer_html();
 2733 }
 2734 
 2735 sub git_forks {
 2736 	my $order = $cgi->param('o');
 2737 	if (defined $order && $order !~ m/project|descr|owner|age/) {
 2738 		die_error(undef, "Unknown order parameter");
 2739 	}
 2740 
 2741 	my @list = git_get_projects_list($project);
 2742 	if (!@list) {
 2743 		die_error(undef, "No forks found");
 2744 	}
 2745 
 2746 	git_header_html();
 2747 	git_print_page_nav('','');
 2748 	git_print_header_div('summary', "$project forks");
 2749 	git_project_list_body(\@list, $order);
 2750 	git_footer_html();
 2751 }
 2752 
 2753 sub git_project_index {
 2754 	my @projects = git_get_projects_list($project);
 2755 
 2756 	print $cgi->header(
 2757 		-type => 'text/plain',
 2758 		-charset => 'utf-8',
 2759 		-content_disposition => 'inline; filename="index.aux"');
 2760 
 2761 	foreach my $pr (@projects) {
 2762 		if (!exists $pr->{'owner'}) {
 2763 			$pr->{'owner'} = get_file_owner("$projectroot/$project");
 2764 		}
 2765 
 2766 		my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
 2767 		# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
 2768 		$path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
 2769 		$owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
 2770 		$path  =~ s/ /\+/g;
 2771 		$owner =~ s/ /\+/g;
 2772 
 2773 		print "$path $owner\n";
 2774 	}
 2775 }
 2776 
 2777 sub git_summary {
 2778 	my $descr = git_get_project_description($project) || "none";
 2779 	my $head = git_get_head_hash($project);
 2780 	my %co = parse_commit($head);
 2781 	my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
 2782 
 2783 	my $owner = git_get_project_owner($project);
 2784 
 2785 	my $refs = git_get_references();
 2786 	my @taglist  = git_get_tags_list(15);
 2787 	my @headlist = git_get_heads_list(15);
 2788 	my @forklist;
 2789 	my ($check_forks) = gitweb_check_feature('forks');
 2790 
 2791 	if ($check_forks) {
 2792 		@forklist = git_get_projects_list($project);
 2793 	}
 2794 
 2795 	git_header_html();
 2796 	git_print_page_nav('summary','', $head);
 2797 
 2798 	print "<div class=\"title\">&nbsp;</div>\n";
 2799 	print "<table cellspacing=\"0\">\n" .
 2800 	      "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
 2801 	      "<tr><td>owner</td><td>$owner</td></tr>\n" .
 2802 	      "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
 2803 	# use per project git URL list in $projectroot/$project/cloneurl
 2804 	# or make project git URL from git base URL and project name
 2805 	my $url_tag = "URL";
 2806 	my @url_list = git_get_project_url_list($project);
 2807 	@url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
 2808 	foreach my $git_url (@url_list) {
 2809 		next unless $git_url;
 2810 		print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
 2811 		$url_tag = "";
 2812 	}
 2813 	print "</table>\n";
 2814 
 2815 	if (-s "$projectroot/$project/README.html") {
 2816 		if (open my $fd, "$projectroot/$project/README.html") {
 2817 			print "<div class=\"title\">readme</div>\n";
 2818 			print $_ while (<$fd>);
 2819 			close $fd;
 2820 		}
 2821 	}
 2822 
 2823 	open my $fd, "-|", git_cmd(), "rev-list", "--max-count=17",
 2824 		git_get_head_hash($project), "--"
 2825 		or die_error(undef, "Open git-rev-list failed");
 2826 	my @revlist = map { chomp; $_ } <$fd>;
 2827 	close $fd;
 2828 	git_print_header_div('shortlog');
 2829 	git_shortlog_body(\@revlist, 0, 15, $refs,
 2830 	                  $cgi->a({-href => href(action=>"shortlog")}, "..."));
 2831 
 2832 	if (@taglist) {
 2833 		git_print_header_div('tags');
 2834 		git_tags_body(\@taglist, 0, 15,
 2835 		              $cgi->a({-href => href(action=>"tags")}, "..."));
 2836 	}
 2837 
 2838 	if (@headlist) {
 2839 		git_print_header_div('heads');
 2840 		git_heads_body(\@headlist, $head, 0, 15,
 2841 		               $cgi->a({-href => href(action=>"heads")}, "..."));
 2842 	}
 2843 
 2844 	if (@forklist) {
 2845 		git_print_header_div('forks');
 2846 		git_project_list_body(\@forklist, undef, 0, 15,
 2847 		                      $cgi->a({-href => href(action=>"forks")}, "..."),
 2848 				      'noheader');
 2849 	}
 2850 
 2851 	git_footer_html();
 2852 }
 2853 
 2854 sub git_tag {
 2855 	my $head = git_get_head_hash($project);
 2856 	git_header_html();
 2857 	git_print_page_nav('','', $head,undef,$head);
 2858 	my %tag = parse_tag($hash);
 2859 	git_print_header_div('commit', esc_html($tag{'name'}), $hash);
 2860 	print "<div class=\"title_text\">\n" .
 2861 	      "<table cellspacing=\"0\">\n" .
 2862 	      "<tr>\n" .
 2863 	      "<td>object</td>\n" .
 2864 	      "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
 2865 	                       $tag{'object'}) . "</td>\n" .
 2866 	      "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
 2867 	                                      $tag{'type'}) . "</td>\n" .
 2868 	      "</tr>\n";
 2869 	if (defined($tag{'author'})) {
 2870 		my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
 2871 		print "<tr><td>author</td><td>" . esc_html(nospam($tag{'author'})) . "</td></tr>\n";
 2872 		print "<tr><td></td><td>" . $ad{'rfc2822'} .
 2873 			sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
 2874 			"</td></tr>\n";
 2875 	}
 2876 	print "</table>\n\n" .
 2877 	      "</div>\n";
 2878 	print "<div class=\"page_body\">";
 2879 	my $comment = $tag{'comment'};
 2880 	foreach my $line (@$comment) {
 2881 		chomp($line);
 2882 		print esc_html($line) . "<br/>\n";
 2883 	}
 2884 	print "</div>\n";
 2885 	git_footer_html();
 2886 }
 2887 
 2888 sub git_blame2 {
 2889 	my $fd;
 2890 	my $ftype;
 2891 
 2892 	my ($have_blame) = gitweb_check_feature('blame');
 2893 	if (!$have_blame) {
 2894 		die_error('403 Permission denied', "Permission denied");
 2895 	}
 2896 	die_error('404 Not Found', "File name not defined") if (!$file_name);
 2897 	$hash_base ||= git_get_head_hash($project);
 2898 	die_error(undef, "Couldn't find base commit") unless ($hash_base);
 2899 	my %co = parse_commit($hash_base)
 2900 		or die_error(undef, "Reading commit failed");
 2901 	if (!defined $hash) {
 2902 		$hash = git_get_hash_by_path($hash_base, $file_name, "blob")
 2903 			or die_error(undef, "Error looking up file");
 2904 	}
 2905 	$ftype = git_get_type($hash);
 2906 	if ($ftype !~ "blob") {
 2907 		die_error("400 Bad Request", "Object is not a blob");
 2908 	}
 2909 	open ($fd, "-|", git_cmd(), "blame", '-p', '--',
 2910 	      $file_name, $hash_base)
 2911 		or die_error(undef, "Open git-blame failed");
 2912 	git_header_html();
 2913 	my $formats_nav =
 2914 		$cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
 2915 		        "blob") .
 2916 		" | " .
 2917 		$cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
 2918 			"history") .
 2919 		" | " .
 2920 		$cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
 2921 		        "HEAD");
 2922 	git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
 2923 	git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
 2924 	git_print_page_path($file_name, $ftype, $hash_base);
 2925 	my @rev_color = (qw(light2 dark2));
 2926 	my $num_colors = scalar(@rev_color);
 2927 	my $current_color = 0;
 2928 	my $last_rev;
 2929 	print <<HTML;
 2930 <div class="page_body">
 2931 <table class="blame">
 2932 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
 2933 HTML
 2934 	my %metainfo = ();
 2935 	while (1) {
 2936 		$_ = <$fd>;
 2937 		last unless defined $_;
 2938 		my ($full_rev, $orig_lineno, $lineno, $group_size) =
 2939 		    /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
 2940 		if (!exists $metainfo{$full_rev}) {
 2941 			$metainfo{$full_rev} = {};
 2942 		}
 2943 		my $meta = $metainfo{$full_rev};
 2944 		while (<$fd>) {
 2945 			last if (s/^\t//);
 2946 			if (/^(\S+) (.*)$/) {
 2947 				$meta->{$1} = $2;
 2948 			}
 2949 		}
 2950 		my $data = $_;
 2951 		chomp($data);
 2952 		my $rev = substr($full_rev, 0, 8);
 2953 		my $author = $meta->{'author'};
 2954 		my %date = parse_date($meta->{'author-time'},
 2955 				      $meta->{'author-tz'});
 2956 		my $date = $date{'iso-tz'};
 2957 		if ($group_size) {
 2958 			$current_color = ++$current_color % $num_colors;
 2959 		}
 2960 		print "<tr class=\"$rev_color[$current_color]\">\n";
 2961 		if ($group_size) {
 2962 			print "<td class=\"sha1\"";
 2963 			print " title=\"". esc_html($author) . ", $date\"";
 2964 			print " rowspan=\"$group_size\"" if ($group_size > 1);
 2965 			print ">";
 2966 			print $cgi->a({-href => href(action=>"commit",
 2967 						     hash=>$full_rev,
 2968 						     file_name=>$file_name)},
 2969 				      esc_html($rev));
 2970 			print "</td>\n";
 2971 		}
 2972 		my $blamed = href(action => 'blame',
 2973 				  file_name => $meta->{'filename'},
 2974 				  hash_base => $full_rev);
 2975 		print "<td class=\"linenr\">";
 2976 		print $cgi->a({ -href => "$blamed#l$orig_lineno",
 2977 				-id => "l$lineno",
 2978 				-class => "linenr" },
 2979 			      esc_html($lineno));
 2980 		print "</td>";
 2981 		print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
 2982 		print "</tr>\n";
 2983 	}
 2984 	print "</table>\n";
 2985 	print "</div>";
 2986 	close $fd
 2987 		or print "Reading blob failed\n";
 2988 	git_footer_html();
 2989 }
 2990 
 2991 sub git_blame {
 2992 	my $fd;
 2993 
 2994 	my ($have_blame) = gitweb_check_feature('blame');
 2995 	if (!$have_blame) {
 2996 		die_error('403 Permission denied', "Permission denied");
 2997 	}
 2998 	die_error('404 Not Found', "File name not defined") if (!$file_name);
 2999 	$hash_base ||= git_get_head_hash($project);
 3000 	die_error(undef, "Couldn't find base commit") unless ($hash_base);
 3001 	my %co = parse_commit($hash_base)
 3002 		or die_error(undef, "Reading commit failed");
 3003 	if (!defined $hash) {
 3004 		$hash = git_get_hash_by_path($hash_base, $file_name, "blob")
 3005 			or die_error(undef, "Error lookup file");
 3006 	}
 3007 	open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
 3008 		or die_error(undef, "Open git-annotate failed");
 3009 	git_header_html();
 3010 	my $formats_nav =
 3011 		$cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
 3012 		        "blob") .
 3013 		" | " .
 3014 		$cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
 3015 			"history") .
 3016 		" | " .
 3017 		$cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
 3018 		        "HEAD");
 3019 	git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
 3020 	git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
 3021 	git_print_page_path($file_name, 'blob', $hash_base);
 3022 	print "<div class=\"page_body\">\n";
 3023 	print <<HTML;
 3024 <table class="blame">
 3025   <tr>
 3026     <th>Commit</th>
 3027     <th>Age</th>
 3028     <th>Author</th>
 3029     <th>Line</th>
 3030     <th>Data</th>
 3031   </tr>
 3032 HTML
 3033 	my @line_class = (qw(light dark));
 3034 	my $line_class_len = scalar (@line_class);
 3035 	my $line_class_num = $#line_class;
 3036 	while (my $line = <$fd>) {
 3037 		my $long_rev;
 3038 		my $short_rev;
 3039 		my $author;
 3040 		my $time;
 3041 		my $lineno;
 3042 		my $data;
 3043 		my $age;
 3044 		my $age_str;
 3045 		my $age_class;
 3046 
 3047 		chomp $line;
 3048 		$line_class_num = ($line_class_num + 1) % $line_class_len;
 3049 
 3050 		if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
 3051 			$long_rev = $1;
 3052 			$author   = $2;
 3053 			$time     = $3;
 3054 			$lineno   = $4;
 3055 			$data     = $5;
 3056 		} else {
 3057 			print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
 3058 			next;
 3059 		}
 3060 		$short_rev  = substr ($long_rev, 0, 8);
 3061 		$age        = time () - $time;
 3062 		$age_str    = age_string ($age);
 3063 		$age_str    =~ s/ /&nbsp;/g;
 3064 		$age_class  = age_class($age);
 3065 		$author     = esc_html ($author);
 3066 		$author     =~ s/ /&nbsp;/g;
 3067 
 3068 		$data = untabify($data);
 3069 		$data = esc_html ($data);
 3070 
 3071 		print <<HTML;
 3072   <tr class="$line_class[$line_class_num]">
 3073     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
 3074     <td class="$age_class">$age_str</td>
 3075     <td>$author</td>
 3076     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
 3077     <td class="pre">$data</td>
 3078   </tr>
 3079 HTML
 3080 	} # while (my $line = <$fd>)
 3081 	print "</table>\n\n";
 3082 	close $fd
 3083 		or print "Reading blob failed.\n";
 3084 	print "</div>";
 3085 	git_footer_html();
 3086 }
 3087 
 3088 sub git_tags {
 3089 	my $head = git_get_head_hash($project);
 3090 	git_header_html();
 3091 	git_print_page_nav('','', $head,undef,$head);
 3092 	git_print_header_div('summary', $project);
 3093 
 3094 	my @tagslist = git_get_tags_list();
 3095 	if (@tagslist) {
 3096 		git_tags_body(\@tagslist);
 3097 	}
 3098 	git_footer_html();
 3099 }
 3100 
 3101 sub git_heads {
 3102 	my $head = git_get_head_hash($project);
 3103 	git_header_html();
 3104 	git_print_page_nav('','', $head,undef,$head);
 3105 	git_print_header_div('summary', $project);
 3106 
 3107 	my @headslist = git_get_heads_list();
 3108 	if (@headslist) {
 3109 		git_heads_body(\@headslist, $head);
 3110 	}
 3111 	git_footer_html();
 3112 }
 3113 
 3114 sub git_blob_plain {
 3115 	my $expires;
 3116 
 3117 	if (!defined $hash) {
 3118 		if (defined $file_name) {
 3119 			my $base = $hash_base || git_get_head_hash($project);
 3120 			$hash = git_get_hash_by_path($base, $file_name, "blob")
 3121 				or die_error(undef, "Error lookup file");
 3122 		} else {
 3123 			die_error(undef, "No file name defined");
 3124 		}
 3125 	} elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
 3126 		# blobs defined by non-textual hash id's can be cached
 3127 		$expires = "+1d";
 3128 	}
 3129 
 3130 	my $type = shift;
 3131 	open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
 3132 		or die_error(undef, "Couldn't cat $file_name, $hash");
 3133 
 3134 	$type ||= blob_mimetype($fd, $file_name);
 3135 
 3136 	# save as filename, even when no $file_name is given
 3137 	my $save_as = "$hash";
 3138 	if (defined $file_name) {
 3139 		$save_as = $file_name;
 3140 	} elsif ($type =~ m/^text\//) {
 3141 		$save_as .= '.txt';
 3142 	}
 3143 
 3144 	print $cgi->header(
 3145 		-type => "$type",
 3146 		-expires=>$expires,
 3147 		-content_disposition => 'inline; filename="' . "$save_as" . '"');
 3148 	undef $/;
 3149 	binmode STDOUT, ':raw';
 3150 	print <$fd>;
 3151 	binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
 3152 	$/ = "\n";
 3153 	close $fd;
 3154 }
 3155 
 3156 sub git_blob {
 3157 	my $expires;
 3158 
 3159 	if (!defined $hash) {
 3160 		if (defined $file_name) {
 3161 			my $base = $hash_base || git_get_head_hash($project);
 3162 			$hash = git_get_hash_by_path($base, $file_name, "blob")
 3163 				or die_error(undef, "Error lookup file");
 3164 		} else {
 3165 			die_error(undef, "No file name defined");
 3166 		}
 3167 	} elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
 3168 		# blobs defined by non-textual hash id's can be cached
 3169 		$expires = "+1d";
 3170 	}
 3171 
 3172 	my ($have_blame) = gitweb_check_feature('blame');
 3173 	open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
 3174 		or die_error(undef, "Couldn't cat $file_name, $hash");
 3175 	my $mimetype = blob_mimetype($fd, $file_name);
 3176 	if ($mimetype !~ m/^text\//) {
 3177 		close $fd;
 3178 		return git_blob_plain($mimetype);
 3179 	}
 3180 	git_header_html(undef, $expires);
 3181 	my $formats_nav = '';
 3182 	if (defined $hash_base && (my %co = parse_commit($hash_base))) {
 3183 		if (defined $file_name) {
 3184 			if ($have_blame) {
 3185 				$formats_nav .=
 3186 					$cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
 3187 					                       hash=>$hash, file_name=>$file_name)},
 3188 					        "blame") .
 3189 					" | ";
 3190 			}
 3191 			$formats_nav .=
 3192 				$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
 3193 				                       hash=>$hash, file_name=>$file_name)},
 3194 				        "history") .
 3195 				" | " .
 3196 				$cgi->a({-href => href(action=>"blob_plain",
 3197 				                       hash=>$hash, file_name=>$file_name)},
 3198 				        "raw") .
 3199 				" | " .
 3200 				$cgi->a({-href => href(action=>"blob",
 3201 				                       hash_base=>"HEAD", file_name=>$file_name)},
 3202 				        "HEAD");
 3203 		} else {
 3204 			$formats_nav .=
 3205 				$cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
 3206 		}
 3207 		git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
 3208 		git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
 3209 	} else {
 3210 		print "<div class=\"page_nav\">\n" .
 3211 		      "<br/><br/></div>\n" .
 3212 		      "<div class=\"title\">$hash</div>\n";
 3213 	}
 3214 	git_print_page_path($file_name, "blob", $hash_base);
 3215 	print "<div class=\"page_body\">\n";
 3216 	my $nr;
 3217 	while (my $line = <$fd>) {
 3218 		chomp $line;
 3219 		$nr++;
 3220 		$line = untabify($line);
 3221 		printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
 3222 		       $nr, $nr, $nr, esc_html($line, -nbsp=>1);
 3223 	}
 3224 	close $fd
 3225 		or print "Reading blob failed.\n";
 3226 	print "</div>";
 3227 	git_footer_html();
 3228 }
 3229 
 3230 sub git_tree {
 3231 	my $have_snapshot = gitweb_have_snapshot();
 3232 
 3233 	if (!defined $hash_base) {
 3234 		$hash_base = gitweb_get_default_head($project);
 3235 	}
 3236 	if (!defined $hash) {
 3237 		if (defined $file_name) {
 3238 			$hash = git_get_hash_by_path($hash_base, $file_name, "tree");
 3239 		} else {
 3240 			$hash = $hash_base;
 3241 		}
 3242 	}
 3243 	$/ = "\0";
 3244 	open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
 3245 		or die_error(undef, "Open git-ls-tree failed");
 3246 	my @entries = map { chomp; $_ } <$fd>;
 3247 	close $fd or die_error(undef, "Reading tree failed");
 3248 	$/ = "\n";
 3249 
 3250 	my $refs = git_get_references();
 3251 	my $ref = format_ref_marker($refs, $hash_base);
 3252 	git_header_html();
 3253 	my $basedir = '';
 3254 	my ($have_blame) = gitweb_check_feature('blame');
 3255 	if (defined $hash_base && (my %co = parse_commit($hash_base))) {
 3256 		my @views_nav = ();
 3257 		if (defined $file_name) {
 3258 			push @views_nav,
 3259 				$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
 3260 				                       hash=>$hash, file_name=>$file_name)},
 3261 				        "history"),
 3262 				$cgi->a({-href => href(action=>"tree",
 3263 				                       hash_base=>"HEAD", file_name=>$file_name)},
 3264 				        "HEAD"),
 3265 		}
 3266 		if ($have_snapshot) {
 3267 			# FIXME: Should be available when we have no hash base as well.
 3268 			push @views_nav,
 3269 				$cgi->a({-href => href(action=>"snapshot", hash=>$hash)},
 3270 				        "snapshot");
 3271 		}
 3272 		git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
 3273 		git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
 3274 	} else {
 3275 		undef $hash_base;
 3276 		print "<div class=\"page_nav\">\n";
 3277 		print "<br/><br/></div>\n";
 3278 		print "<div class=\"title\">$hash</div>\n";
 3279 	}
 3280 	if (defined $file_name) {
 3281 		$basedir = $file_name;
 3282 		if ($basedir ne '' && substr($basedir, -1) ne '/') {
 3283 			$basedir .= '/';
 3284 		}
 3285 	}
 3286 	git_print_page_path($file_name, 'tree', $hash_base);
 3287 	print "<div class=\"page_body\">\n";
 3288 	print "<table cellspacing=\"0\">\n";
 3289 	my $alternate = 1;
 3290 	# '..' (top directory) link if possible
 3291 	if (defined $hash_base &&
 3292 	    defined $file_name && $file_name =~ m![^/]+$!) {
 3293 		if ($alternate) {
 3294 			print "<tr class=\"dark\">\n";
 3295 		} else {
 3296 			print "<tr class=\"light\">\n";
 3297 		}
 3298 		$alternate ^= 1;
 3299 
 3300 		my $up = $file_name;
 3301 		$up =~ s!/?[^/]+$!!;
 3302 		undef $up unless $up;
 3303 		# based on git_print_tree_entry
 3304 		print '<td class="mode">' . mode_str('040000') . "</td>\n";
 3305 		print '<td class="list">';
 3306 		print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
 3307 		                             file_name=>$up)},
 3308 		              "..");
 3309 		print "</td>\n";
 3310 		print "<td class=\"link\"></td>\n";
 3311 
 3312 		print "</tr>\n";
 3313 	}
 3314 	foreach my $line (@entries) {
 3315 		my %t = parse_ls_tree_line($line, -z => 1);
 3316 
 3317 		if ($alternate) {
 3318 			print "<tr class=\"dark\">\n";
 3319 		} else {
 3320 			print "<tr class=\"light\">\n";
 3321 		}
 3322 		$alternate ^= 1;
 3323 
 3324 		git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
 3325 
 3326 		print "</tr>\n";
 3327 	}
 3328 	print "</table>\n" .
 3329 	      "</div>";
 3330 	git_footer_html();
 3331 }
 3332 
 3333 sub git_snapshot {
 3334 	my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
 3335 	my $have_snapshot = (defined $ctype && defined $suffix);
 3336 	if (!$have_snapshot) {
 3337 		die_error('403 Permission denied', "Permission denied");
 3338 	}
 3339 
 3340 	if (!defined $hash) {
 3341 		$hash = git_get_head_hash($project);
 3342 	}
 3343 
 3344 	my $filename = basename($project) . "-$hash.tar.$suffix";
 3345 
 3346 	print $cgi->header(
 3347 		-type => 'application/x-tar',
 3348 		-content_encoding => $ctype,
 3349 		-content_disposition => 'inline; filename="' . "$filename" . '"',
 3350 		-status => '200 OK');
 3351 
 3352 	my $git = git_cmd_str();
 3353 	my $name = $project;
 3354 	$name =~ s/\047/\047\\\047\047/g;
 3355 	open my $fd, "-|",
 3356 	"$git archive --format=tar --prefix=\'$name\'/ $hash | $command"
 3357 		or die_error(undef, "Execute git-tar-tree failed.");
 3358 	binmode STDOUT, ':raw';
 3359 	print <$fd>;
 3360 	binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
 3361 	close $fd;
 3362 
 3363 }
 3364 
 3365 sub git_log {
 3366 	my $head = git_get_head_hash($project);
 3367 	if (!defined $hash) {
 3368 		$hash = $head;
 3369 	}
 3370 	if (!defined $page) {
 3371 		$page = 0;
 3372 	}
 3373 	my $refs = git_get_references();
 3374 
 3375 	my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
 3376 	open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash, "--"
 3377 		or die_error(undef, "Open git-rev-list failed");
 3378 	my @revlist = map { chomp; $_ } <$fd>;
 3379 	close $fd;
 3380 
 3381 	my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
 3382 
 3383 	git_header_html();
 3384 	git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
 3385 
 3386 	if (!@revlist) {
 3387 		my %co = parse_commit($hash);
 3388 
 3389 		git_print_header_div('summary', $project);
 3390 		print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
 3391 	}
 3392 	for (my $i = ($page * 100); $i <= $#revlist; $i++) {
 3393 		my $commit = $revlist[$i];
 3394 		my $ref = format_ref_marker($refs, $commit);
 3395 		my %co = parse_commit($commit);
 3396 		next if !%co;
 3397 		my %ad = parse_date($co{'author_epoch'});
 3398 		git_print_header_div('commit',
 3399 		               "<span class=\"age\">$co{'age_string'}</span>" .
 3400 		               esc_html($co{'title'}) . $ref,
 3401 		               $commit);
 3402 		print "<div class=\"title_text\">\n" .
 3403 		      "<div class=\"log_link\">\n" .
 3404 		      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
 3405 		      " | " .
 3406 		      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
 3407 		      " | " .
 3408 		      $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
 3409 		      "<br/>\n" .
 3410 		      "</div>\n" .
 3411 		      "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
 3412 		      "</div>\n";
 3413 
 3414 		print "<div class=\"log_body\">\n";
 3415 		git_print_log($co{'comment'}, -final_empty_line=> 1);
 3416 		print "</div>\n";
 3417 	}
 3418 	git_footer_html();
 3419 }
 3420 
 3421 sub git_commit {
 3422 	my %co = parse_commit($hash);
 3423 	if (!%co) {
 3424 		die_error(undef, "Unknown commit object");
 3425 	}
 3426 	my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
 3427 	my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
 3428 
 3429 	my $parent = $co{'parent'};
 3430 	if (!defined $parent) {
 3431 		$parent = "--root";
 3432 	}
 3433 	open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
 3434 		@diff_opts, $parent, $hash, "--"
 3435 		or die_error(undef, "Open git-diff-tree failed");
 3436 	my @difftree = map { chomp; $_ } <$fd>;
 3437 	close $fd or die_error(undef, "Reading git-diff-tree failed");
 3438 
 3439 	# non-textual hash id's can be cached
 3440 	my $expires;
 3441 	if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
 3442 		$expires = "+1d";
 3443 	}
 3444 	my $refs = git_get_references();
 3445 	my $ref = format_ref_marker($refs, $co{'id'});
 3446 
 3447 	my $have_snapshot = gitweb_have_snapshot();
 3448 
 3449 	my @views_nav = ();
 3450 	if (defined $file_name && defined $co{'parent'}) {
 3451 		push @views_nav,
 3452 			$cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)},
 3453 			        "blame");
 3454 	}
 3455 	git_header_html(undef, $expires);
 3456 	git_print_page_nav('commit', '',
 3457 	                   $hash, $co{'tree'}, $hash,
 3458 	                   join (' | ', @views_nav));
 3459 
 3460 	if (defined $co{'parent'}) {
 3461 		git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
 3462 	} else {
 3463 		git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
 3464 	}
 3465 	print "<div class=\"title_text\">\n" .
 3466 	      "<table cellspacing=\"0\">\n";
 3467 	print "<tr><td>author</td><td>" . esc_html(nospam($co{'author'})) . "</td></tr>\n".
 3468 	      "<tr>" .
 3469 	      "<td></td><td> $ad{'rfc2822'}";
 3470 	if ($ad{'hour_local'} < 6) {
 3471 		printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
 3472 		       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
 3473 	} else {
 3474 		printf(" (%02d:%02d %s)",
 3475 		       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
 3476 	}
 3477 	print "</td>" .
 3478 	      "</tr>\n";
 3479 	print "<tr><td>committer</td><td>" . esc_html(nospam($co{'committer'})) . "</td></tr>\n";
 3480 	print "<tr><td></td><td> $cd{'rfc2822'}" .
 3481 	      sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
 3482 	      "</td></tr>\n";
 3483 	print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
 3484 	print "<tr>" .
 3485 	      "<td>tree</td>" .
 3486 	      "<td class=\"sha1\">" .
 3487 	      $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
 3488 	               class => "list"}, $co{'tree'}) .
 3489 	      "</td>" .
 3490 	      "<td class=\"link\">" .
 3491 	      $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
 3492 	              "tree");
 3493 	if ($have_snapshot) {
 3494 		print " | " .
 3495 		      $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
 3496 	}
 3497 	print "</td>" .
 3498 	      "</tr>\n";
 3499 	my $parents = $co{'parents'};
 3500 	foreach my $par (@$parents) {
 3501 		print "<tr>" .
 3502 		      "<td>parent</td>" .
 3503 		      "<td class=\"sha1\">" .
 3504 		      $cgi->a({-href => href(action=>"commit", hash=>$par),
 3505 		               class => "list"}, $par) .
 3506 		      "</td>" .
 3507 		      "<td class=\"link\">" .
 3508 		      $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
 3509 		      " | " .
 3510 		      $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
 3511 		      "</td>" .
 3512 		      "</tr>\n";
 3513 	}
 3514 	print "</table>".
 3515 	      "</div>\n";
 3516 
 3517 	print "<div class=\"page_body\">\n";
 3518 	git_print_log($co{'comment'});
 3519 	print "</div>\n";
 3520 
 3521 	git_difftree_body(\@difftree, $hash, $parent);
 3522 
 3523 	git_footer_html();
 3524 }
 3525 
 3526 sub git_blobdiff {
 3527 	my $format = shift || 'html';
 3528 
 3529 	my $fd;
 3530 	my @difftree;
 3531 	my %diffinfo;
 3532 	my $expires;
 3533 
 3534 	# preparing $fd and %diffinfo for git_patchset_body
 3535 	# new style URI
 3536 	if (defined $hash_base && defined $hash_parent_base) {
 3537 		if (defined $file_name) {
 3538 			# read raw output
 3539 			open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
 3540 				$hash_parent_base, $hash_base,
 3541 				"--", $file_name
 3542 				or die_error(undef, "Open git-diff-tree failed");
 3543 			@difftree = map { chomp; $_ } <$fd>;
 3544 			close $fd
 3545 				or die_error(undef, "Reading git-diff-tree failed");
 3546 			@difftree
 3547 				or die_error('404 Not Found', "Blob diff not found");
 3548 
 3549 		} elsif (defined $hash &&
 3550 		         $hash =~ /[0-9a-fA-F]{40}/) {
 3551 			# try to find filename from $hash
 3552 
 3553 			# read filtered raw output
 3554 			open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
 3555 				$hash_parent_base, $hash_base, "--"
 3556 				or die_error(undef, "Open git-diff-tree failed");
 3557 			@difftree =
 3558 				# ':100644 100644 03b21826... 3b93d5e7... M	ls-files.c'
 3559 				# $hash == to_id
 3560 				grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
 3561 				map { chomp; $_ } <$fd>;
 3562 			close $fd
 3563 				or die_error(undef, "Reading git-diff-tree failed");
 3564 			@difftree
 3565 				or die_error('404 Not Found', "Blob diff not found");
 3566 
 3567 		} else {
 3568 			die_error('404 Not Found', "Missing one of the blob diff parameters");
 3569 		}
 3570 
 3571 		if (@difftree > 1) {
 3572 			die_error('404 Not Found', "Ambiguous blob diff specification");
 3573 		}
 3574 
 3575 		%diffinfo = parse_difftree_raw_line($difftree[0]);
 3576 		$file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
 3577 		$file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
 3578 
 3579 		$hash_parent ||= $diffinfo{'from_id'};
 3580 		$hash        ||= $diffinfo{'to_id'};
 3581 
 3582 		# non-textual hash id's can be cached
 3583 		if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
 3584 		    $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
 3585 			$expires = '+1d';
 3586 		}
 3587 
 3588 		# open patch output
 3589 		open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
 3590 			'-p', $hash_parent_base, $hash_base,
 3591 			"--", $file_name
 3592 			or die_error(undef, "Open git-diff-tree failed");
 3593 	}
 3594 
 3595 	# old/legacy style URI
 3596 	if (!%diffinfo && # if new style URI failed
 3597 	    defined $hash && defined $hash_parent) {
 3598 		# fake git-diff-tree raw output
 3599 		$diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
 3600 		$diffinfo{'from_id'} = $hash_parent;
 3601 		$diffinfo{'to_id'}   = $hash;
 3602 		if (defined $file_name) {
 3603 			if (defined $file_parent) {
 3604 				$diffinfo{'status'} = '2';
 3605 				$diffinfo{'from_file'} = $file_parent;
 3606 				$diffinfo{'to_file'}   = $file_name;
 3607 			} else { # assume not renamed
 3608 				$diffinfo{'status'} = '1';
 3609 				$diffinfo{'from_file'} = $file_name;
 3610 				$diffinfo{'to_file'}   = $file_name;
 3611 			}
 3612 		} else { # no filename given
 3613 			$diffinfo{'status'} = '2';
 3614 			$diffinfo{'from_file'} = $hash_parent;
 3615 			$diffinfo{'to_file'}   = $hash;
 3616 		}
 3617 
 3618 		# non-textual hash id's can be cached
 3619 		if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
 3620 		    $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
 3621 			$expires = '+1d';
 3622 		}
 3623 
 3624 		# open patch output
 3625 		open $fd, "-|", git_cmd(), "diff", '-p', @diff_opts,
 3626 			$hash_parent, $hash, "--"
 3627 			or die_error(undef, "Open git-diff failed");
 3628 	} else  {
 3629 		die_error('404 Not Found', "Missing one of the blob diff parameters")
 3630 			unless %diffinfo;
 3631 	}
 3632 
 3633 	# header
 3634 	if ($format eq 'html') {
 3635 		my $formats_nav =
 3636 			$cgi->a({-href => href(action=>"blobdiff_plain",
 3637 			                       hash=>$hash, hash_parent=>$hash_parent,
 3638 			                       hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
 3639 			                       file_name=>$file_name, file_parent=>$file_parent)},
 3640 			        "raw");
 3641 		git_header_html(undef, $expires);
 3642 		if (defined $hash_base && (my %co = parse_commit($hash_base))) {
 3643 			git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
 3644 			git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
 3645 		} else {
 3646 			print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
 3647 			print "<div class=\"title\">$hash vs $hash_parent</div>\n";
 3648 		}
 3649 		if (defined $file_name) {
 3650 			git_print_page_path($file_name, "blob", $hash_base);
 3651 		} else {
 3652 			print "<div class=\"page_path\"></div>\n";
 3653 		}
 3654 
 3655 	} elsif ($format eq 'plain') {
 3656 		print $cgi->header(
 3657 			-type => 'text/plain',
 3658 			-charset => 'utf-8',
 3659 			-expires => $expires,
 3660 			-content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
 3661 
 3662 		print "X-Git-Url: " . $cgi->self_url() . "\n\n";
 3663 
 3664 	} else {
 3665 		die_error(undef, "Unknown blobdiff format");
 3666 	}
 3667 
 3668 	# patch
 3669 	if ($format eq 'html') {
 3670 		print "<div class=\"page_body\">\n";
 3671 
 3672 		git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
 3673 		close $fd;
 3674 
 3675 		print "</div>\n"; # class="page_body"
 3676 		git_footer_html();
 3677 
 3678 	} else {
 3679 		while (my $line = <$fd>) {
 3680 			$line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
 3681 			$line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
 3682 
 3683 			print $line;
 3684 
 3685 			last if $line =~ m!^\+\+\+!;
 3686 		}
 3687 		local $/ = undef;
 3688 		print <$fd>;
 3689 		close $fd;
 3690 	}
 3691 }
 3692 
 3693 sub git_blobdiff_plain {
 3694 	git_blobdiff('plain');
 3695 }
 3696 
 3697 sub git_commitdiff {
 3698 	my $format = shift || 'html';
 3699 	my %co = parse_commit($hash);
 3700 	if (!%co) {
 3701 		die_error(undef, "Unknown commit object");
 3702 	}
 3703 
 3704 	# we need to prepare $formats_nav before any parameter munging
 3705 	my $formats_nav;
 3706 	if ($format eq 'html') {
 3707 		$formats_nav =
 3708 			$cgi->a({-href => href(action=>"commitdiff_plain",
 3709 			                       hash=>$hash, hash_parent=>$hash_parent)},
 3710 			        "raw");
 3711 
 3712 		if (defined $hash_parent) {
 3713 			# commitdiff with two commits given
 3714 			my $hash_parent_short = $hash_parent;
 3715 			if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
 3716 				$hash_parent_short = substr($hash_parent, 0, 7);
 3717 			}
 3718 			$formats_nav .=
 3719 				' (from: ' .
 3720 				$cgi->a({-href => href(action=>"commitdiff",
 3721 				                       hash=>$hash_parent)},
 3722 				        esc_html($hash_parent_short)) .
 3723 				')';
 3724 		} elsif (!$co{'parent'}) {
 3725 			# --root commitdiff
 3726 			$formats_nav .= ' (initial)';
 3727 		} elsif (scalar @{$co{'parents'}} == 1) {
 3728 			# single parent commit
 3729 			$formats_nav .=
 3730 				' (parent: ' .
 3731 				$cgi->a({-href => href(action=>"commitdiff",
 3732 				                       hash=>$co{'parent'})},
 3733 				        esc_html(substr($co{'parent'}, 0, 7))) .
 3734 				')';
 3735 		} else {
 3736 			# merge commit
 3737 			$formats_nav .=
 3738 				' (merge: ' .
 3739 				join(' ', map {
 3740 					$cgi->a({-href => href(action=>"commitdiff",
 3741 					                       hash=>$_)},
 3742 					        esc_html(substr($_, 0, 7)));
 3743 				} @{$co{'parents'}} ) .
 3744 				')';
 3745 		}
 3746 	}
 3747 
 3748 	if (!defined $hash_parent) {
 3749 		$hash_parent = $co{'parent'} || '--root';
 3750 	}
 3751 
 3752 	# read commitdiff
 3753 	my $fd;
 3754 	my @difftree;
 3755 	if ($format eq 'html') {
 3756 		open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
 3757 			"--no-commit-id", "--patch-with-raw", "--full-index",
 3758 			$hash_parent, $hash, "--"
 3759 			or die_error(undef, "Open git-diff-tree failed");
 3760 
 3761 		while (chomp(my $line = <$fd>)) {
 3762 			# empty line ends raw part of diff-tree output
 3763 			last unless $line;
 3764 			push @difftree, $line;
 3765 		}
 3766 
 3767 	} elsif ($format eq 'plain') {
 3768 		open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
 3769 			'-p', $hash_parent, $hash, "--"
 3770 			or die_error(undef, "Open git-diff-tree failed");
 3771 
 3772 	} else {
 3773 		die_error(undef, "Unknown commitdiff format");
 3774 	}
 3775 
 3776 	# non-textual hash id's can be cached
 3777 	my $expires;
 3778 	if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
 3779 		$expires = "+1d";
 3780 	}
 3781 
 3782 	# write commit message
 3783 	if ($format eq 'html') {
 3784 		my $refs = git_get_references();
 3785 		my $ref = format_ref_marker($refs, $co{'id'});
 3786 
 3787 		git_header_html(undef, $expires);
 3788 		git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
 3789 		git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
 3790 		git_print_authorship(\%co);
 3791 		print "<div class=\"page_body\">\n";
 3792 		if (@{$co{'comment'}} > 1) {
 3793 			print "<div class=\"log\">\n";
 3794 			git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
 3795 			print "</div>\n"; # class="log"
 3796 		}
 3797 
 3798 	} elsif ($format eq 'plain') {
 3799 		my $refs = git_get_references("tags");
 3800 		my $tagname = git_get_rev_name_tags($hash);
 3801 		my $filename = basename($project) . "-$hash.patch";
 3802 
 3803 		print $cgi->header(
 3804 			-type => 'text/plain',
 3805 			-charset => 'utf-8',
 3806 			-expires => $expires,
 3807 			-content_disposition => 'inline; filename="' . "$filename" . '"');
 3808 		my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
 3809 		print <<TEXT;
 3810 From: $co{'author'}
 3811 Date: $ad{'rfc2822'} ($ad{'tz_local'})
 3812 Subject: $co{'title'}
 3813 TEXT
 3814 		print "X-Git-Tag: $tagname\n" if $tagname;
 3815 		print "X-Git-Url: " . $cgi->self_url() . "\n\n";
 3816 
 3817 		foreach my $line (@{$co{'comment'}}) {
 3818 			print "$line\n";
 3819 		}
 3820 		print "---\n\n";
 3821 	}
 3822 
 3823 	# write patch
 3824 	if ($format eq 'html') {
 3825 		git_difftree_body(\@difftree, $hash, $hash_parent);
 3826 		print "<br/>\n";
 3827 
 3828 		git_patchset_body($fd, \@difftree, $hash, $hash_parent);
 3829 		close $fd;
 3830 		print "</div>\n"; # class="page_body"
 3831 		git_footer_html();
 3832 
 3833 	} elsif ($format eq 'plain') {
 3834 		local $/ = undef;
 3835 		print <$fd>;
 3836 		close $fd
 3837 			or print "Reading git-diff-tree failed\n";
 3838 	}
 3839 }
 3840 
 3841 sub git_commitdiff_plain {
 3842 	git_commitdiff('plain');
 3843 }
 3844 
 3845 sub git_history {
 3846 	if (!defined $hash_base) {
 3847 		$hash_base = git_get_head_hash($project);
 3848 	}
 3849 	if (!defined $page) {
 3850 		$page = 0;
 3851 	}
 3852 	my $ftype;
 3853 	my %co = parse_commit($hash_base);
 3854 	if (!%co) {
 3855 		die_error(undef, "Unknown commit object");
 3856 	}
 3857 
 3858 	my $refs = git_get_references();
 3859 	my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
 3860 
 3861 	if (!defined $hash && defined $file_name) {
 3862 		$hash = git_get_hash_by_path($hash_base, $file_name);
 3863 	}
 3864 	if (defined $hash) {
 3865 		$ftype = git_get_type($hash);
 3866 	}
 3867 
 3868 	open my $fd, "-|",
 3869 		git_cmd(), "rev-list", $limit, "--full-history", $hash_base, "--", $file_name
 3870 			or die_error(undef, "Open git-rev-list-failed");
 3871 	my @revlist = map { chomp; $_ } <$fd>;
 3872 	close $fd
 3873 		or die_error(undef, "Reading git-rev-list failed");
 3874 
 3875 	my $paging_nav = '';
 3876 	if ($page > 0) {
 3877 		$paging_nav .=
 3878 			$cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
 3879 			                       file_name=>$file_name)},
 3880 			        "first");
 3881 		$paging_nav .= " &sdot; " .
 3882 			$cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
 3883 			                       file_name=>$file_name, page=>$page-1),
 3884 			         -accesskey => "p", -title => "Alt-p"}, "prev");
 3885 	} else {
 3886 		$paging_nav .= "first";
 3887 		$paging_nav .= " &sdot; prev";
 3888 	}
 3889 	if ($#revlist >= (100 * ($page+1)-1)) {
 3890 		$paging_nav .= " &sdot; " .
 3891 			$cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
 3892 			                       file_name=>$file_name, page=>$page+1),
 3893 			         -accesskey => "n", -title => "Alt-n"}, "next");
 3894 	} else {
 3895 		$paging_nav .= " &sdot; next";
 3896 	}
 3897 	my $next_link = '';
 3898 	if ($#revlist >= (100 * ($page+1)-1)) {
 3899 		$next_link =
 3900 			$cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
 3901 			                       file_name=>$file_name, page=>$page+1),
 3902 			         -title => "Alt-n"}, "next");
 3903 	}
 3904 
 3905 	git_header_html();
 3906 	git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
 3907 	git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
 3908 	git_print_page_path($file_name, $ftype, $hash_base);
 3909 
 3910 	git_history_body(\@revlist, ($page * 100), $#revlist,
 3911 	                 $refs, $hash_base, $ftype, $next_link);
 3912 
 3913 	git_footer_html();
 3914 }
 3915 
 3916 sub git_search {
 3917 	if (!defined $searchtext) {
 3918 		die_error(undef, "Text field empty");
 3919 	}
 3920 	if (!defined $hash) {
 3921 		$hash = git_get_head_hash($project);
 3922 	}
 3923 	my %co = parse_commit($hash);
 3924 	if (!%co) {
 3925 		die_error(undef, "Unknown commit object");
 3926 	}
 3927 
 3928 	$searchtype ||= 'commit';
 3929 	if ($searchtype eq 'pickaxe') {
 3930 		# pickaxe may take all resources of your box and run for several minutes
 3931 		# with every query - so decide by yourself how public you make this feature
 3932 		my ($have_pickaxe) = gitweb_check_feature('pickaxe');
 3933 		if (!$have_pickaxe) {
 3934 			die_error('403 Permission denied', "Permission denied");
 3935 		}
 3936 	}
 3937 
 3938 	git_header_html();
 3939 	git_print_page_nav('','', $hash,$co{'tree'},$hash);
 3940 	git_print_header_div('commit', esc_html($co{'title'}), $hash);
 3941 
 3942 	print "<table cellspacing=\"0\">\n";
 3943 	my $alternate = 1;
 3944 	if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
 3945 		$/ = "\0";
 3946 		open my $fd, "-|", git_cmd(), "rev-list",
 3947 			"--header", "--parents", $hash, "--"
 3948 			or next;
 3949 		while (my $commit_text = <$fd>) {
 3950 			if (!grep m/$searchtext/i, $commit_text) {
 3951 				next;
 3952 			}
 3953 			if ($searchtype eq 'author' && !grep m/\nauthor .*$searchtext/i, $commit_text) {
 3954 				next;
 3955 			}
 3956 			if ($searchtype eq 'committer' && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
 3957 				next;
 3958 			}
 3959 			my @commit_lines = split "\n", $commit_text;
 3960 			my %co = parse_commit(undef, \@commit_lines);
 3961 			if (!%co) {
 3962 				next;
 3963 			}
 3964 			if ($alternate) {
 3965 				print "<tr class=\"dark\">\n";
 3966 			} else {
 3967 				print "<tr class=\"light\">\n";
 3968 			}
 3969 			$alternate ^= 1;
 3970 			print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
 3971 			      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
 3972 			      "<td>" .
 3973 			      $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
 3974 			               esc_html(chop_str($co{'title'}, 50)) . "<br/>");
 3975 			my $comment = $co{'comment'};
 3976 			foreach my $line (@$comment) {
 3977 				if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
 3978 					my $lead = esc_html($1) || "";
 3979 					$lead = chop_str($lead, 30, 10);
 3980 					my $match = esc_html($2) || "";
 3981 					my $trail = esc_html($3) || "";
 3982 					$trail = chop_str($trail, 30, 10);
 3983 					my $text = "$lead<span class=\"match\">$match</span>$trail";
 3984 					print chop_str($text, 80, 5) . "<br/>\n";
 3985 				}
 3986 			}
 3987 			print "</td>\n" .
 3988 			      "<td class=\"link\">" .
 3989 			      $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
 3990 			      " | " .
 3991 			      $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
 3992 			print "</td>\n" .
 3993 			      "</tr>\n";
 3994 		}
 3995 		close $fd;
 3996 	}
 3997 
 3998 	if ($searchtype eq 'pickaxe') {
 3999 		$/ = "\n";
 4000 		my $git_command = git_cmd_str();
 4001 		open my $fd, "-|", "$git_command rev-list $hash | " .
 4002 			"$git_command diff-tree -r --stdin -S\'$searchtext\'";
 4003 		undef %co;
 4004 		my @files;
 4005 		while (my $line = <$fd>) {
 4006 			if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
 4007 				my %set;
 4008 				$set{'file'} = $6;
 4009 				$set{'from_id'} = $3;
 4010 				$set{'to_id'} = $4;
 4011 				$set{'id'} = $set{'to_id'};
 4012 				if ($set{'id'} =~ m/0{40}/) {
 4013 					$set{'id'} = $set{'from_id'};
 4014 				}
 4015 				if ($set{'id'} =~ m/0{40}/) {
 4016 					next;
 4017 				}
 4018 				push @files, \%set;
 4019 			} elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
 4020 				if (%co) {
 4021 					if ($alternate) {
 4022 						print "<tr class=\"dark\">\n";
 4023 					} else {
 4024 						print "<tr class=\"light\">\n";
 4025 					}
 4026 					$alternate ^= 1;
 4027 					print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
 4028 					      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
 4029 					      "<td>" .
 4030 					      $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
 4031 					              -class => "list subject"},
 4032 					              esc_html(chop_str($co{'title'}, 50)) . "<br/>");
 4033 					while (my $setref = shift @files) {
 4034 						my %set = %$setref;
 4035 						print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
 4036 						                             hash=>$set{'id'}, file_name=>$set{'file'}),
 4037 						              -class => "list"},
 4038 						              "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
 4039 						      "<br/>\n";
 4040 					}
 4041 					print "</td>\n" .
 4042 					      "<td class=\"link\">" .
 4043 					      $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
 4044 					      " | " .
 4045 					      $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
 4046 					print "</td>\n" .
 4047 					      "</tr>\n";
 4048 				}
 4049 				%co = parse_commit($1);
 4050 			}
 4051 		}
 4052 		close $fd;
 4053 	}
 4054 	print "</table>\n";
 4055 	git_footer_html();
 4056 }
 4057 
 4058 sub git_search_help {
 4059 	git_header_html();
 4060 	git_print_page_nav('','', $hash,$hash,$hash);
 4061 	print <<EOT;
 4062 <dl>
 4063 <dt><b>commit</b></dt>
 4064 <dd>The commit messages and authorship information will be scanned for the given string.</dd>
 4065 <dt><b>author</b></dt>
 4066 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given string.</dd>
 4067 <dt><b>committer</b></dt>
 4068 <dd>Name and e-mail of the committer and date of commit will be scanned for the given string.</dd>
 4069 EOT
 4070 	my ($have_pickaxe) = gitweb_check_feature('pickaxe');
 4071 	if ($have_pickaxe) {
 4072 		print <<EOT;
 4073 <dt><b>pickaxe</b></dt>
 4074 <dd>All commits that caused the string to appear or disappear from any file (changes that
 4075 added, removed or "modified" the string) will be listed. This search can take a while and
 4076 takes a lot of strain on the server, so please use it wisely.</dd>
 4077 EOT
 4078 	}
 4079 	print "</dl>\n";
 4080 	git_footer_html();
 4081 }
 4082 
 4083 sub git_shortlog {
 4084 	my $head = git_get_head_hash($project);
 4085 	if (!defined $hash) {
 4086 		$hash = $head;
 4087 	}
 4088 	if (!defined $page) {
 4089 		$page = 0;
 4090 	}
 4091 	my $refs = git_get_references();
 4092 
 4093 	my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
 4094 	open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash, "--"
 4095 		or die_error(undef, "Open git-rev-list failed");
 4096 	my @revlist = map { chomp; $_ } <$fd>;
 4097 	close $fd;
 4098 
 4099 	my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
 4100 	my $next_link = '';
 4101 	if ($#revlist >= (100 * ($page+1)-1)) {
 4102 		$next_link =
 4103 			$cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
 4104 			         -title => "Alt-n"}, "next");
 4105 	}
 4106 
 4107 
 4108 	git_header_html();
 4109 	git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
 4110 	git_print_header_div('summary', $project);
 4111 
 4112 	git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
 4113 
 4114 	git_footer_html();
 4115 }
 4116 
 4117 ## ......................................................................
 4118 ## feeds (RSS, OPML)
 4119 
 4120 sub git_rss {
 4121 	# http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
 4122 	open my $fd, "-|", git_cmd(), "rev-list", "--max-count=150",
 4123 		git_get_head_hash($project), "--"
 4124 		or die_error(undef, "Open git-rev-list failed");
 4125 	my @revlist = map { chomp; $_ } <$fd>;
 4126 	close $fd or die_error(undef, "Reading git-rev-list failed");
 4127 	print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
 4128 	print <<XML;
 4129 <?xml version="1.0" encoding="utf-8"?>
 4130 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
 4131 <channel>
 4132 <title>$project $my_uri $my_url</title>
 4133 <link>${\esc_html("$my_url?p=$project;a=summary")}</link>
 4134 <description>$project log</description>
 4135 <language>en</language>
 4136 XML
 4137 
 4138 	for (my $i = 0; $i <= $#revlist; $i++) {
 4139 		my $commit = $revlist[$i];
 4140 		my %co = parse_commit($commit);
 4141 		# we read 150, we always show 30 and the ones more recent than 48 hours
 4142 		if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
 4143 			last;
 4144 		}
 4145 		my %cd = parse_date($co{'committer_epoch'});
 4146 		open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
 4147 			$co{'parent'}, $co{'id'}, "--"
 4148 			or next;
 4149 		my @difftree = map { chomp; $_ } <$fd>;
 4150 		close $fd
 4151 			or next;
 4152 		print "<item>\n" .
 4153 		      "<title>" .
 4154 		      sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
 4155 		      "</title>\n" .
 4156 		      "<author>" . esc_html($co{'author'}) . "</author>\n" .
 4157 		      "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
 4158 		      "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
 4159 		      "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
 4160 		      "<description>" . esc_html($co{'title'}) . "</description>\n" .
 4161 		      "<content:encoded>" .
 4162 		      "<![CDATA[\n";
 4163 		my $comment = $co{'comment'};
 4164 		foreach my $line (@$comment) {
 4165 			$line = to_utf8($line);
 4166 			print "$line<br/>\n";
 4167 		}
 4168 		print "<br/>\n";
 4169 		foreach my $line (@difftree) {
 4170 			if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
 4171 				next;
 4172 			}
 4173 			my $file = esc_path(unquote($7));
 4174 			$file = to_utf8($file);
 4175 			print "$file<br/>\n";
 4176 		}
 4177 		print "]]>\n" .
 4178 		      "</content:encoded>\n" .
 4179 		      "</item>\n";
 4180 	}
 4181 	print "</channel></rss>";
 4182 }
 4183 
 4184 sub git_opml {
 4185 	my @list = git_get_projects_list();
 4186 
 4187 	print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
 4188 	print <<XML;
 4189 <?xml version="1.0" encoding="utf-8"?>
 4190 <opml version="1.0">
 4191 <head>
 4192   <title>$site_name OPML Export</title>
 4193 </head>
 4194 <body>
 4195 <outline text="git RSS feeds">
 4196 XML
 4197 
 4198 	foreach my $pr (@list) {
 4199 		my %proj = %$pr;
 4200 		my $head = git_get_head_hash($proj{'path'});
 4201 		if (!defined $head) {
 4202 			next;
 4203 		}
 4204 		$git_dir = "$projectroot/$proj{'path'}";
 4205 		my %co = parse_commit($head);
 4206 		if (!%co) {
 4207 			next;
 4208 		}
 4209 
 4210 		my $path = esc_html(chop_str($proj{'path'}, 25, 5));
 4211 		my $rss  = "$my_url?p=$proj{'path'};a=rss";
 4212 		my $html = "$my_url?p=$proj{'path'};a=summary";
 4213 		print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
 4214 	}
 4215 	print <<XML;
 4216 </outline>
 4217 </body>
 4218 </opml>
 4219 XML
 4220 }

Generated by cgit