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