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