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