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