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