6bd57a4e3246e981805ac2ddbf3b33ec5dcbc189
   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'}, my @parents) = split ' ', $header;
1285        $co{'parents'} = \@parents;
1286        $co{'parent'} = $parents[0];
1287        while (my $line = shift @commit_lines) {
1288                last if $line eq "\n";
1289                if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1290                        $co{'tree'} = $1;
1291                } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1292                        $co{'author'} = $1;
1293                        $co{'author_epoch'} = $2;
1294                        $co{'author_tz'} = $3;
1295                        if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
1296                                $co{'author_name'}  = $1;
1297                                $co{'author_email'} = $2;
1298                        } else {
1299                                $co{'author_name'} = $co{'author'};
1300                        }
1301                } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1302                        $co{'committer'} = $1;
1303                        $co{'committer_epoch'} = $2;
1304                        $co{'committer_tz'} = $3;
1305                        $co{'committer_name'} = $co{'committer'};
1306                        if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
1307                                $co{'committer_name'}  = $1;
1308                                $co{'committer_email'} = $2;
1309                        } else {
1310                                $co{'committer_name'} = $co{'committer'};
1311                        }
1312                }
1313        }
1314        if (!defined $co{'tree'}) {
1315                return;
1316        };
1317
1318        foreach my $title (@commit_lines) {
1319                $title =~ s/^    //;
1320                if ($title ne "") {
1321                        $co{'title'} = chop_str($title, 80, 5);
1322                        # remove leading stuff of merges to make the interesting part visible
1323                        if (length($title) > 50) {
1324                                $title =~ s/^Automatic //;
1325                                $title =~ s/^merge (of|with) /Merge ... /i;
1326                                if (length($title) > 50) {
1327                                        $title =~ s/(http|rsync):\/\///;
1328                                }
1329                                if (length($title) > 50) {
1330                                        $title =~ s/(master|www|rsync)\.//;
1331                                }
1332                                if (length($title) > 50) {
1333                                        $title =~ s/kernel.org:?//;
1334                                }
1335                                if (length($title) > 50) {
1336                                        $title =~ s/\/pub\/scm//;
1337                                }
1338                        }
1339                        $co{'title_short'} = chop_str($title, 50, 5);
1340                        last;
1341                }
1342        }
1343        if ($co{'title'} eq "") {
1344                $co{'title'} = $co{'title_short'} = '(no commit message)';
1345        }
1346        # remove added spaces
1347        foreach my $line (@commit_lines) {
1348                $line =~ s/^    //;
1349        }
1350        $co{'comment'} = \@commit_lines;
1351
1352        my $age = time - $co{'committer_epoch'};
1353        $co{'age'} = $age;
1354        $co{'age_string'} = age_string($age);
1355        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1356        if ($age > 60*60*24*7*2) {
1357                $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1358                $co{'age_string_age'} = $co{'age_string'};
1359        } else {
1360                $co{'age_string_date'} = $co{'age_string'};
1361                $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1362        }
1363        return %co;
1364}
1365
1366sub parse_commit {
1367        my ($commit_id) = @_;
1368        my %co;
1369
1370        local $/ = "\0";
1371
1372        open my $fd, "-|", git_cmd(), "rev-list",
1373                "--header",
1374                "--parents",
1375                "--max-count=1",
1376                $commit_id,
1377                "--",
1378                or die_error(undef, "Open git-rev-list failed");
1379        %co = parse_commit_text(<$fd>);
1380        close $fd;
1381
1382        return %co;
1383}
1384
1385sub parse_commits {
1386        my ($commit_id, $maxcount, $skip, $arg, $filename) = @_;
1387        my @cos;
1388
1389        $maxcount ||= 1;
1390        $skip ||= 0;
1391
1392        # Delete once rev-list supports the --skip option
1393        if ($skip > 0) {
1394                open my $fd, "-|", git_cmd(), "rev-list",
1395                        ($arg ? ($arg) : ()),
1396                        ("--max-count=" . ($maxcount + $skip)),
1397                        $commit_id,
1398                        "--",
1399                        ($filename ? ($filename) : ())
1400                        or die_error(undef, "Open git-rev-list failed");
1401                while (my $line = <$fd>) {
1402                        if ($skip-- <= 0) {
1403                                chomp $line;
1404                                my %co = parse_commit($line);
1405                                push @cos, \%co;
1406                        }
1407                }
1408                close $fd;
1409
1410                return wantarray ? @cos : \@cos;
1411        }
1412
1413        local $/ = "\0";
1414
1415        open my $fd, "-|", git_cmd(), "rev-list",
1416                "--header",
1417                "--parents",
1418                ($arg ? ($arg) : ()),
1419                ("--max-count=" . $maxcount),
1420                # Add once rev-list supports the --skip option
1421                # ("--skip=" . $skip),
1422                $commit_id,
1423                "--",
1424                ($filename ? ($filename) : ())
1425                or die_error(undef, "Open git-rev-list failed");
1426        while (my $line = <$fd>) {
1427                my %co = parse_commit_text($line);
1428                push @cos, \%co;
1429        }
1430        close $fd;
1431
1432        return wantarray ? @cos : \@cos;
1433}
1434
1435# parse ref from ref_file, given by ref_id, with given type
1436sub parse_ref {
1437        my $ref_file = shift;
1438        my $ref_id = shift;
1439        my $type = shift || git_get_type($ref_id);
1440        my %ref_item;
1441
1442        $ref_item{'type'} = $type;
1443        $ref_item{'id'} = $ref_id;
1444        $ref_item{'epoch'} = 0;
1445        $ref_item{'age'} = "unknown";
1446        if ($type eq "tag") {
1447                my %tag = parse_tag($ref_id);
1448                $ref_item{'comment'} = $tag{'comment'};
1449                if ($tag{'type'} eq "commit") {
1450                        my %co = parse_commit($tag{'object'});
1451                        $ref_item{'epoch'} = $co{'committer_epoch'};
1452                        $ref_item{'age'} = $co{'age_string'};
1453                } elsif (defined($tag{'epoch'})) {
1454                        my $age = time - $tag{'epoch'};
1455                        $ref_item{'epoch'} = $tag{'epoch'};
1456                        $ref_item{'age'} = age_string($age);
1457                }
1458                $ref_item{'reftype'} = $tag{'type'};
1459                $ref_item{'name'} = $tag{'name'};
1460                $ref_item{'refid'} = $tag{'object'};
1461        } elsif ($type eq "commit"){
1462                my %co = parse_commit($ref_id);
1463                $ref_item{'reftype'} = "commit";
1464                $ref_item{'name'} = $ref_file;
1465                $ref_item{'title'} = $co{'title'};
1466                $ref_item{'refid'} = $ref_id;
1467                $ref_item{'epoch'} = $co{'committer_epoch'};
1468                $ref_item{'age'} = $co{'age_string'};
1469        } else {
1470                $ref_item{'reftype'} = $type;
1471                $ref_item{'name'} = $ref_file;
1472                $ref_item{'refid'} = $ref_id;
1473        }
1474
1475        return %ref_item;
1476}
1477
1478# parse line of git-diff-tree "raw" output
1479sub parse_difftree_raw_line {
1480        my $line = shift;
1481        my %res;
1482
1483        # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1484        # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1485        if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1486                $res{'from_mode'} = $1;
1487                $res{'to_mode'} = $2;
1488                $res{'from_id'} = $3;
1489                $res{'to_id'} = $4;
1490                $res{'status'} = $5;
1491                $res{'similarity'} = $6;
1492                if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1493                        ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1494                } else {
1495                        $res{'file'} = unquote($7);
1496                }
1497        }
1498        # 'c512b523472485aef4fff9e57b229d9d243c967f'
1499        elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1500                $res{'commit'} = $1;
1501        }
1502
1503        return wantarray ? %res : \%res;
1504}
1505
1506# parse line of git-ls-tree output
1507sub parse_ls_tree_line ($;%) {
1508        my $line = shift;
1509        my %opts = @_;
1510        my %res;
1511
1512        #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1513        $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
1514
1515        $res{'mode'} = $1;
1516        $res{'type'} = $2;
1517        $res{'hash'} = $3;
1518        if ($opts{'-z'}) {
1519                $res{'name'} = $4;
1520        } else {
1521                $res{'name'} = unquote($4);
1522        }
1523
1524        return wantarray ? %res : \%res;
1525}
1526
1527## ......................................................................
1528## parse to array of hashes functions
1529
1530sub git_get_heads_list {
1531        my $limit = shift;
1532        my @headslist;
1533
1534        open my $fd, '-|', git_cmd(), 'for-each-ref',
1535                ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
1536                '--format=%(objectname) %(refname) %(subject)%00%(committer)',
1537                'refs/heads'
1538                or return;
1539        while (my $line = <$fd>) {
1540                my %ref_item;
1541
1542                chomp $line;
1543                my ($refinfo, $committerinfo) = split(/\0/, $line);
1544                my ($hash, $name, $title) = split(' ', $refinfo, 3);
1545                my ($committer, $epoch, $tz) =
1546                        ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
1547                $name =~ s!^refs/heads/!!;
1548
1549                $ref_item{'name'}  = $name;
1550                $ref_item{'id'}    = $hash;
1551                $ref_item{'title'} = $title || '(no commit message)';
1552                $ref_item{'epoch'} = $epoch;
1553                if ($epoch) {
1554                        $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
1555                } else {
1556                        $ref_item{'age'} = "unknown";
1557                }
1558
1559                push @headslist, \%ref_item;
1560        }
1561        close $fd;
1562
1563        return wantarray ? @headslist : \@headslist;
1564}
1565
1566sub git_get_tags_list {
1567        my $limit = shift;
1568        my @tagslist;
1569
1570        open my $fd, '-|', git_cmd(), 'for-each-ref',
1571                ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
1572                '--format=%(objectname) %(objecttype) %(refname) '.
1573                '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
1574                'refs/tags'
1575                or return;
1576        while (my $line = <$fd>) {
1577                my %ref_item;
1578
1579                chomp $line;
1580                my ($refinfo, $creatorinfo) = split(/\0/, $line);
1581                my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
1582                my ($creator, $epoch, $tz) =
1583                        ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
1584                $name =~ s!^refs/tags/!!;
1585
1586                $ref_item{'type'} = $type;
1587                $ref_item{'id'} = $id;
1588                $ref_item{'name'} = $name;
1589                if ($type eq "tag") {
1590                        $ref_item{'subject'} = $title;
1591                        $ref_item{'reftype'} = $reftype;
1592                        $ref_item{'refid'}   = $refid;
1593                } else {
1594                        $ref_item{'reftype'} = $type;
1595                        $ref_item{'refid'}   = $id;
1596                }
1597
1598                if ($type eq "tag" || $type eq "commit") {
1599                        $ref_item{'epoch'} = $epoch;
1600                        if ($epoch) {
1601                                $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
1602                        } else {
1603                                $ref_item{'age'} = "unknown";
1604                        }
1605                }
1606
1607                push @tagslist, \%ref_item;
1608        }
1609        close $fd;
1610
1611        return wantarray ? @tagslist : \@tagslist;
1612}
1613
1614## ----------------------------------------------------------------------
1615## filesystem-related functions
1616
1617sub get_file_owner {
1618        my $path = shift;
1619
1620        my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1621        my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1622        if (!defined $gcos) {
1623                return undef;
1624        }
1625        my $owner = $gcos;
1626        $owner =~ s/[,;].*$//;
1627        return to_utf8($owner);
1628}
1629
1630## ......................................................................
1631## mimetype related functions
1632
1633sub mimetype_guess_file {
1634        my $filename = shift;
1635        my $mimemap = shift;
1636        -r $mimemap or return undef;
1637
1638        my %mimemap;
1639        open(MIME, $mimemap) or return undef;
1640        while (<MIME>) {
1641                next if m/^#/; # skip comments
1642                my ($mime, $exts) = split(/\t+/);
1643                if (defined $exts) {
1644                        my @exts = split(/\s+/, $exts);
1645                        foreach my $ext (@exts) {
1646                                $mimemap{$ext} = $mime;
1647                        }
1648                }
1649        }
1650        close(MIME);
1651
1652        $filename =~ /\.([^.]*)$/;
1653        return $mimemap{$1};
1654}
1655
1656sub mimetype_guess {
1657        my $filename = shift;
1658        my $mime;
1659        $filename =~ /\./ or return undef;
1660
1661        if ($mimetypes_file) {
1662                my $file = $mimetypes_file;
1663                if ($file !~ m!^/!) { # if it is relative path
1664                        # it is relative to project
1665                        $file = "$projectroot/$project/$file";
1666                }
1667                $mime = mimetype_guess_file($filename, $file);
1668        }
1669        $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1670        return $mime;
1671}
1672
1673sub blob_mimetype {
1674        my $fd = shift;
1675        my $filename = shift;
1676
1677        if ($filename) {
1678                my $mime = mimetype_guess($filename);
1679                $mime and return $mime;
1680        }
1681
1682        # just in case
1683        return $default_blob_plain_mimetype unless $fd;
1684
1685        if (-T $fd) {
1686                return 'text/plain' .
1687                       ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1688        } elsif (! $filename) {
1689                return 'application/octet-stream';
1690        } elsif ($filename =~ m/\.png$/i) {
1691                return 'image/png';
1692        } elsif ($filename =~ m/\.gif$/i) {
1693                return 'image/gif';
1694        } elsif ($filename =~ m/\.jpe?g$/i) {
1695                return 'image/jpeg';
1696        } else {
1697                return 'application/octet-stream';
1698        }
1699}
1700
1701## ======================================================================
1702## functions printing HTML: header, footer, error page
1703
1704sub git_header_html {
1705        my $status = shift || "200 OK";
1706        my $expires = shift;
1707
1708        my $title = "$site_name";
1709        if (defined $project) {
1710                $title .= " - $project";
1711                if (defined $action) {
1712                        $title .= "/$action";
1713                        if (defined $file_name) {
1714                                $title .= " - " . esc_path($file_name);
1715                                if ($action eq "tree" && $file_name !~ m|/$|) {
1716                                        $title .= "/";
1717                                }
1718                        }
1719                }
1720        }
1721        my $content_type;
1722        # require explicit support from the UA if we are to send the page as
1723        # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1724        # we have to do this because MSIE sometimes globs '*/*', pretending to
1725        # support xhtml+xml but choking when it gets what it asked for.
1726        if (defined $cgi->http('HTTP_ACCEPT') &&
1727            $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1728            $cgi->Accept('application/xhtml+xml') != 0) {
1729                $content_type = 'application/xhtml+xml';
1730        } else {
1731                $content_type = 'text/html';
1732        }
1733        print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1734                           -status=> $status, -expires => $expires);
1735        print <<EOF;
1736<?xml version="1.0" encoding="utf-8"?>
1737<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1738<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1739<!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1740<!-- git core binaries version $git_version -->
1741<head>
1742<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1743<meta name="generator" content="gitweb/$version git/$git_version"/>
1744<meta name="robots" content="index, nofollow"/>
1745<title>$title</title>
1746EOF
1747# print out each stylesheet that exist
1748        if (defined $stylesheet) {
1749#provides backwards capability for those people who define style sheet in a config file
1750                print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
1751        } else {
1752                foreach my $stylesheet (@stylesheets) {
1753                        next unless $stylesheet;
1754                        print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
1755                }
1756        }
1757        if (defined $project) {
1758                printf('<link rel="alternate" title="%s log RSS feed" '.
1759                       'href="%s" type="application/rss+xml" />'."\n",
1760                       esc_param($project), href(action=>"rss"));
1761                printf('<link rel="alternate" title="%s log Atom feed" '.
1762                       'href="%s" type="application/atom+xml" />'."\n",
1763                       esc_param($project), href(action=>"atom"));
1764        } else {
1765                printf('<link rel="alternate" title="%s projects list" '.
1766                       'href="%s" type="text/plain; charset=utf-8"/>'."\n",
1767                       $site_name, href(project=>undef, action=>"project_index"));
1768                printf('<link rel="alternate" title="%s projects feeds" '.
1769                       'href="%s" type="text/x-opml"/>'."\n",
1770                       $site_name, href(project=>undef, action=>"opml"));
1771        }
1772        if (defined $favicon) {
1773                print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
1774        }
1775
1776        print "</head>\n" .
1777              "<body>\n";
1778
1779        if (-f $site_header) {
1780                open (my $fd, $site_header);
1781                print <$fd>;
1782                close $fd;
1783        }
1784
1785        print "<div class=\"page_header\">\n" .
1786              $cgi->a({-href => esc_url($logo_url),
1787                       -title => $logo_label},
1788                      qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
1789        print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
1790        if (defined $project) {
1791                print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1792                if (defined $action) {
1793                        print " / $action";
1794                }
1795                print "\n";
1796        }
1797        my ($have_search) = gitweb_check_feature('search');
1798        if ((defined $project) && ($have_search)) {
1799                if (!defined $searchtext) {
1800                        $searchtext = "";
1801                }
1802                my $search_hash;
1803                if (defined $hash_base) {
1804                        $search_hash = $hash_base;
1805                } elsif (defined $hash) {
1806                        $search_hash = $hash;
1807                } else {
1808                        $search_hash = "HEAD";
1809                }
1810                $cgi->param("a", "search");
1811                $cgi->param("h", $search_hash);
1812                $cgi->param("p", $project);
1813                print $cgi->startform(-method => "get", -action => $my_uri) .
1814                      "<div class=\"search\">\n" .
1815                      $cgi->hidden(-name => "p") . "\n" .
1816                      $cgi->hidden(-name => "a") . "\n" .
1817                      $cgi->hidden(-name => "h") . "\n" .
1818                      $cgi->popup_menu(-name => 'st', -default => 'commit',
1819                                       -values => ['commit', 'author', 'committer', 'pickaxe']) .
1820                      $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
1821                      " search:\n",
1822                      $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1823                      "</div>" .
1824                      $cgi->end_form() . "\n";
1825        }
1826        print "</div>\n";
1827}
1828
1829sub git_footer_html {
1830        print "<div class=\"page_footer\">\n";
1831        if (defined $project) {
1832                my $descr = git_get_project_description($project);
1833                if (defined $descr) {
1834                        print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1835                }
1836                print $cgi->a({-href => href(action=>"rss"),
1837                              -class => "rss_logo"}, "RSS") . " ";
1838                print $cgi->a({-href => href(action=>"atom"),
1839                              -class => "rss_logo"}, "Atom") . "\n";
1840        } else {
1841                print $cgi->a({-href => href(project=>undef, action=>"opml"),
1842                              -class => "rss_logo"}, "OPML") . " ";
1843                print $cgi->a({-href => href(project=>undef, action=>"project_index"),
1844                              -class => "rss_logo"}, "TXT") . "\n";
1845        }
1846        print "</div>\n" ;
1847
1848        if (-f $site_footer) {
1849                open (my $fd, $site_footer);
1850                print <$fd>;
1851                close $fd;
1852        }
1853
1854        print "</body>\n" .
1855              "</html>";
1856}
1857
1858sub die_error {
1859        my $status = shift || "403 Forbidden";
1860        my $error = shift || "Malformed query, file missing or permission denied";
1861
1862        git_header_html($status);
1863        print <<EOF;
1864<div class="page_body">
1865<br /><br />
1866$status - $error
1867<br />
1868</div>
1869EOF
1870        git_footer_html();
1871        exit;
1872}
1873
1874## ----------------------------------------------------------------------
1875## functions printing or outputting HTML: navigation
1876
1877sub git_print_page_nav {
1878        my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1879        $extra = '' if !defined $extra; # pager or formats
1880
1881        my @navs = qw(summary shortlog log commit commitdiff tree);
1882        if ($suppress) {
1883                @navs = grep { $_ ne $suppress } @navs;
1884        }
1885
1886        my %arg = map { $_ => {action=>$_} } @navs;
1887        if (defined $head) {
1888                for (qw(commit commitdiff)) {
1889                        $arg{$_}{hash} = $head;
1890                }
1891                if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1892                        for (qw(shortlog log)) {
1893                                $arg{$_}{hash} = $head;
1894                        }
1895                }
1896        }
1897        $arg{tree}{hash} = $treehead if defined $treehead;
1898        $arg{tree}{hash_base} = $treebase if defined $treebase;
1899
1900        print "<div class=\"page_nav\">\n" .
1901                (join " | ",
1902                 map { $_ eq $current ?
1903                       $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1904                 } @navs);
1905        print "<br/>\n$extra<br/>\n" .
1906              "</div>\n";
1907}
1908
1909sub format_paging_nav {
1910        my ($action, $hash, $head, $page, $nrevs) = @_;
1911        my $paging_nav;
1912
1913
1914        if ($hash ne $head || $page) {
1915                $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1916        } else {
1917                $paging_nav .= "HEAD";
1918        }
1919
1920        if ($page > 0) {
1921                $paging_nav .= " &sdot; " .
1922                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1923                                 -accesskey => "p", -title => "Alt-p"}, "prev");
1924        } else {
1925                $paging_nav .= " &sdot; prev";
1926        }
1927
1928        if ($nrevs >= (100 * ($page+1)-1)) {
1929                $paging_nav .= " &sdot; " .
1930                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1931                                 -accesskey => "n", -title => "Alt-n"}, "next");
1932        } else {
1933                $paging_nav .= " &sdot; next";
1934        }
1935
1936        return $paging_nav;
1937}
1938
1939## ......................................................................
1940## functions printing or outputting HTML: div
1941
1942sub git_print_header_div {
1943        my ($action, $title, $hash, $hash_base) = @_;
1944        my %args = ();
1945
1946        $args{action} = $action;
1947        $args{hash} = $hash if $hash;
1948        $args{hash_base} = $hash_base if $hash_base;
1949
1950        print "<div class=\"header\">\n" .
1951              $cgi->a({-href => href(%args), -class => "title"},
1952              $title ? $title : $action) .
1953              "\n</div>\n";
1954}
1955
1956#sub git_print_authorship (\%) {
1957sub git_print_authorship {
1958        my $co = shift;
1959
1960        my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
1961        print "<div class=\"author_date\">" .
1962              esc_html($co->{'author_name'}) .
1963              " [$ad{'rfc2822'}";
1964        if ($ad{'hour_local'} < 6) {
1965                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
1966                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1967        } else {
1968                printf(" (%02d:%02d %s)",
1969                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1970        }
1971        print "]</div>\n";
1972}
1973
1974sub git_print_page_path {
1975        my $name = shift;
1976        my $type = shift;
1977        my $hb = shift;
1978
1979
1980        print "<div class=\"page_path\">";
1981        print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
1982                      -title => 'tree root'}, "[$project]");
1983        print " / ";
1984        if (defined $name) {
1985                my @dirname = split '/', $name;
1986                my $basename = pop @dirname;
1987                my $fullname = '';
1988
1989                foreach my $dir (@dirname) {
1990                        $fullname .= ($fullname ? '/' : '') . $dir;
1991                        print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
1992                                                     hash_base=>$hb),
1993                                      -title => esc_html($fullname)}, esc_path($dir));
1994                        print " / ";
1995                }
1996                if (defined $type && $type eq 'blob') {
1997                        print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
1998                                                     hash_base=>$hb),
1999                                      -title => esc_html($name)}, esc_path($basename));
2000                } elsif (defined $type && $type eq 'tree') {
2001                        print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
2002                                                     hash_base=>$hb),
2003                                      -title => esc_html($name)}, esc_path($basename));
2004                        print " / ";
2005                } else {
2006                        print esc_path($basename);
2007                }
2008        }
2009        print "<br/></div>\n";
2010}
2011
2012# sub git_print_log (\@;%) {
2013sub git_print_log ($;%) {
2014        my $log = shift;
2015        my %opts = @_;
2016
2017        if ($opts{'-remove_title'}) {
2018                # remove title, i.e. first line of log
2019                shift @$log;
2020        }
2021        # remove leading empty lines
2022        while (defined $log->[0] && $log->[0] eq "") {
2023                shift @$log;
2024        }
2025
2026        # print log
2027        my $signoff = 0;
2028        my $empty = 0;
2029        foreach my $line (@$log) {
2030                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
2031                        $signoff = 1;
2032                        $empty = 0;
2033                        if (! $opts{'-remove_signoff'}) {
2034                                print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
2035                                next;
2036                        } else {
2037                                # remove signoff lines
2038                                next;
2039                        }
2040                } else {
2041                        $signoff = 0;
2042                }
2043
2044                # print only one empty line
2045                # do not print empty line after signoff
2046                if ($line eq "") {
2047                        next if ($empty || $signoff);
2048                        $empty = 1;
2049                } else {
2050                        $empty = 0;
2051                }
2052
2053                print format_log_line_html($line) . "<br/>\n";
2054        }
2055
2056        if ($opts{'-final_empty_line'}) {
2057                # end with single empty line
2058                print "<br/>\n" unless $empty;
2059        }
2060}
2061
2062# return link target (what link points to)
2063sub git_get_link_target {
2064        my $hash = shift;
2065        my $link_target;
2066
2067        # read link
2068        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2069                or return;
2070        {
2071                local $/;
2072                $link_target = <$fd>;
2073        }
2074        close $fd
2075                or return;
2076
2077        return $link_target;
2078}
2079
2080# given link target, and the directory (basedir) the link is in,
2081# return target of link relative to top directory (top tree);
2082# return undef if it is not possible (including absolute links).
2083sub normalize_link_target {
2084        my ($link_target, $basedir, $hash_base) = @_;
2085
2086        # we can normalize symlink target only if $hash_base is provided
2087        return unless $hash_base;
2088
2089        # absolute symlinks (beginning with '/') cannot be normalized
2090        return if (substr($link_target, 0, 1) eq '/');
2091
2092        # normalize link target to path from top (root) tree (dir)
2093        my $path;
2094        if ($basedir) {
2095                $path = $basedir . '/' . $link_target;
2096        } else {
2097                # we are in top (root) tree (dir)
2098                $path = $link_target;
2099        }
2100
2101        # remove //, /./, and /../
2102        my @path_parts;
2103        foreach my $part (split('/', $path)) {
2104                # discard '.' and ''
2105                next if (!$part || $part eq '.');
2106                # handle '..'
2107                if ($part eq '..') {
2108                        if (@path_parts) {
2109                                pop @path_parts;
2110                        } else {
2111                                # link leads outside repository (outside top dir)
2112                                return;
2113                        }
2114                } else {
2115                        push @path_parts, $part;
2116                }
2117        }
2118        $path = join('/', @path_parts);
2119
2120        return $path;
2121}
2122
2123# print tree entry (row of git_tree), but without encompassing <tr> element
2124sub git_print_tree_entry {
2125        my ($t, $basedir, $hash_base, $have_blame) = @_;
2126
2127        my %base_key = ();
2128        $base_key{'hash_base'} = $hash_base if defined $hash_base;
2129
2130        # The format of a table row is: mode list link.  Where mode is
2131        # the mode of the entry, list is the name of the entry, an href,
2132        # and link is the action links of the entry.
2133
2134        print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
2135        if ($t->{'type'} eq "blob") {
2136                print "<td class=\"list\">" .
2137                        $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2138                                               file_name=>"$basedir$t->{'name'}", %base_key),
2139                                -class => "list"}, esc_path($t->{'name'}));
2140                if (S_ISLNK(oct $t->{'mode'})) {
2141                        my $link_target = git_get_link_target($t->{'hash'});
2142                        if ($link_target) {
2143                                my $norm_target = normalize_link_target($link_target, $basedir, $hash_base);
2144                                if (defined $norm_target) {
2145                                        print " -> " .
2146                                              $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
2147                                                                     file_name=>$norm_target),
2148                                                       -title => $norm_target}, esc_path($link_target));
2149                                } else {
2150                                        print " -> " . esc_path($link_target);
2151                                }
2152                        }
2153                }
2154                print "</td>\n";
2155                print "<td class=\"link\">";
2156                print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2157                                             file_name=>"$basedir$t->{'name'}", %base_key)},
2158                              "blob");
2159                if ($have_blame) {
2160                        print " | " .
2161                              $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
2162                                                     file_name=>"$basedir$t->{'name'}", %base_key)},
2163                                      "blame");
2164                }
2165                if (defined $hash_base) {
2166                        print " | " .
2167                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2168                                                     hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
2169                                      "history");
2170                }
2171                print " | " .
2172                        $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
2173                                               file_name=>"$basedir$t->{'name'}")},
2174                                "raw");
2175                print "</td>\n";
2176
2177        } elsif ($t->{'type'} eq "tree") {
2178                print "<td class=\"list\">";
2179                print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2180                                             file_name=>"$basedir$t->{'name'}", %base_key)},
2181                              esc_path($t->{'name'}));
2182                print "</td>\n";
2183                print "<td class=\"link\">";
2184                print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2185                                             file_name=>"$basedir$t->{'name'}", %base_key)},
2186                              "tree");
2187                if (defined $hash_base) {
2188                        print " | " .
2189                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2190                                                     file_name=>"$basedir$t->{'name'}")},
2191                                      "history");
2192                }
2193                print "</td>\n";
2194        }
2195}
2196
2197## ......................................................................
2198## functions printing large fragments of HTML
2199
2200sub git_difftree_body {
2201        my ($difftree, $hash, $parent) = @_;
2202        my ($have_blame) = gitweb_check_feature('blame');
2203        print "<div class=\"list_head\">\n";
2204        if ($#{$difftree} > 10) {
2205                print(($#{$difftree} + 1) . " files changed:\n");
2206        }
2207        print "</div>\n";
2208
2209        print "<table class=\"diff_tree\">\n";
2210        my $alternate = 1;
2211        my $patchno = 0;
2212        foreach my $line (@{$difftree}) {
2213                my %diff = parse_difftree_raw_line($line);
2214
2215                if ($alternate) {
2216                        print "<tr class=\"dark\">\n";
2217                } else {
2218                        print "<tr class=\"light\">\n";
2219                }
2220                $alternate ^= 1;
2221
2222                my ($to_mode_oct, $to_mode_str, $to_file_type);
2223                my ($from_mode_oct, $from_mode_str, $from_file_type);
2224                if ($diff{'to_mode'} ne ('0' x 6)) {
2225                        $to_mode_oct = oct $diff{'to_mode'};
2226                        if (S_ISREG($to_mode_oct)) { # only for regular file
2227                                $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
2228                        }
2229                        $to_file_type = file_type($diff{'to_mode'});
2230                }
2231                if ($diff{'from_mode'} ne ('0' x 6)) {
2232                        $from_mode_oct = oct $diff{'from_mode'};
2233                        if (S_ISREG($to_mode_oct)) { # only for regular file
2234                                $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
2235                        }
2236                        $from_file_type = file_type($diff{'from_mode'});
2237                }
2238
2239                if ($diff{'status'} eq "A") { # created
2240                        my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
2241                        $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
2242                        $mode_chng   .= "]</span>";
2243                        print "<td>";
2244                        print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2245                                                     hash_base=>$hash, file_name=>$diff{'file'}),
2246                                      -class => "list"}, esc_path($diff{'file'}));
2247                        print "</td>\n";
2248                        print "<td>$mode_chng</td>\n";
2249                        print "<td class=\"link\">";
2250                        if ($action eq 'commitdiff') {
2251                                # link to patch
2252                                $patchno++;
2253                                print $cgi->a({-href => "#patch$patchno"}, "patch");
2254                                print " | ";
2255                        }
2256                        print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2257                                                     hash_base=>$hash, file_name=>$diff{'file'})},
2258                                      "blob") . " | ";
2259                        print "</td>\n";
2260
2261                } elsif ($diff{'status'} eq "D") { # deleted
2262                        my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
2263                        print "<td>";
2264                        print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
2265                                                     hash_base=>$parent, file_name=>$diff{'file'}),
2266                                       -class => "list"}, esc_path($diff{'file'}));
2267                        print "</td>\n";
2268                        print "<td>$mode_chng</td>\n";
2269                        print "<td class=\"link\">";
2270                        if ($action eq 'commitdiff') {
2271                                # link to patch
2272                                $patchno++;
2273                                print $cgi->a({-href => "#patch$patchno"}, "patch");
2274                                print " | ";
2275                        }
2276                        print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
2277                                                     hash_base=>$parent, file_name=>$diff{'file'})},
2278                                      "blob") . " | ";
2279                        if ($have_blame) {
2280                                print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
2281                                                             file_name=>$diff{'file'})},
2282                                              "blame") . " | ";
2283                        }
2284                        print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
2285                                                     file_name=>$diff{'file'})},
2286                                      "history");
2287                        print "</td>\n";
2288
2289                } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
2290                        my $mode_chnge = "";
2291                        if ($diff{'from_mode'} != $diff{'to_mode'}) {
2292                                $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
2293                                if ($from_file_type != $to_file_type) {
2294                                        $mode_chnge .= " from $from_file_type to $to_file_type";
2295                                }
2296                                if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
2297                                        if ($from_mode_str && $to_mode_str) {
2298                                                $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
2299                                        } elsif ($to_mode_str) {
2300                                                $mode_chnge .= " mode: $to_mode_str";
2301                                        }
2302                                }
2303                                $mode_chnge .= "]</span>\n";
2304                        }
2305                        print "<td>";
2306                        print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2307                                                     hash_base=>$hash, file_name=>$diff{'file'}),
2308                                      -class => "list"}, esc_path($diff{'file'}));
2309                        print "</td>\n";
2310                        print "<td>$mode_chnge</td>\n";
2311                        print "<td class=\"link\">";
2312                        if ($action eq 'commitdiff') {
2313                                # link to patch
2314                                $patchno++;
2315                                print $cgi->a({-href => "#patch$patchno"}, "patch") .
2316                                      " | ";
2317                        } elsif ($diff{'to_id'} ne $diff{'from_id'}) {
2318                                # "commit" view and modified file (not onlu mode changed)
2319                                print $cgi->a({-href => href(action=>"blobdiff",
2320                                                             hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
2321                                                             hash_base=>$hash, hash_parent_base=>$parent,
2322                                                             file_name=>$diff{'file'})},
2323                                              "diff") .
2324                                      " | ";
2325                        }
2326                        print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2327                                                     hash_base=>$hash, file_name=>$diff{'file'})},
2328                                       "blob") . " | ";
2329                        if ($have_blame) {
2330                                print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
2331                                                             file_name=>$diff{'file'})},
2332                                              "blame") . " | ";
2333                        }
2334                        print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
2335                                                     file_name=>$diff{'file'})},
2336                                      "history");
2337                        print "</td>\n";
2338
2339                } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
2340                        my %status_name = ('R' => 'moved', 'C' => 'copied');
2341                        my $nstatus = $status_name{$diff{'status'}};
2342                        my $mode_chng = "";
2343                        if ($diff{'from_mode'} != $diff{'to_mode'}) {
2344                                # mode also for directories, so we cannot use $to_mode_str
2345                                $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
2346                        }
2347                        print "<td>" .
2348                              $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2349                                                     hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
2350                                      -class => "list"}, esc_path($diff{'to_file'})) . "</td>\n" .
2351                              "<td><span class=\"file_status $nstatus\">[$nstatus from " .
2352                              $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
2353                                                     hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
2354                                      -class => "list"}, esc_path($diff{'from_file'})) .
2355                              " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
2356                              "<td class=\"link\">";
2357                        if ($action eq 'commitdiff') {
2358                                # link to patch
2359                                $patchno++;
2360                                print $cgi->a({-href => "#patch$patchno"}, "patch") .
2361                                      " | ";
2362                        } elsif ($diff{'to_id'} ne $diff{'from_id'}) {
2363                                # "commit" view and modified file (not only pure rename or copy)
2364                                print $cgi->a({-href => href(action=>"blobdiff",
2365                                                             hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
2366                                                             hash_base=>$hash, hash_parent_base=>$parent,
2367                                                             file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
2368                                              "diff") .
2369                                      " | ";
2370                        }
2371                        print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2372                                                     hash_base=>$parent, file_name=>$diff{'to_file'})},
2373                                      "blob") . " | ";
2374                        if ($have_blame) {
2375                                print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
2376                                                             file_name=>$diff{'to_file'})},
2377                                              "blame") . " | ";
2378                        }
2379                        print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
2380                                                    file_name=>$diff{'to_file'})},
2381                                      "history");
2382                        print "</td>\n";
2383
2384                } # we should not encounter Unmerged (U) or Unknown (X) status
2385                print "</tr>\n";
2386        }
2387        print "</table>\n";
2388}
2389
2390sub git_patchset_body {
2391        my ($fd, $difftree, $hash, $hash_parent) = @_;
2392
2393        my $patch_idx = 0;
2394        my $patch_line;
2395        my $diffinfo;
2396        my (%from, %to);
2397        my ($from_id, $to_id);
2398
2399        print "<div class=\"patchset\">\n";
2400
2401        # skip to first patch
2402        while ($patch_line = <$fd>) {
2403                chomp $patch_line;
2404
2405                last if ($patch_line =~ m/^diff /);
2406        }
2407
2408 PATCH:
2409        while ($patch_line) {
2410                my @diff_header;
2411
2412                # git diff header
2413                #assert($patch_line =~ m/^diff /) if DEBUG;
2414                #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
2415                push @diff_header, $patch_line;
2416
2417                # extended diff header
2418        EXTENDED_HEADER:
2419                while ($patch_line = <$fd>) {
2420                        chomp $patch_line;
2421
2422                        last EXTENDED_HEADER if ($patch_line =~ m/^--- /);
2423
2424                        if ($patch_line =~ m/^index ([0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
2425                                $from_id = $1;
2426                                $to_id   = $2;
2427                        }
2428
2429                        push @diff_header, $patch_line;
2430                }
2431                #last PATCH unless $patch_line;
2432                my $last_patch_line = $patch_line;
2433
2434                # check if current patch belong to current raw line
2435                # and parse raw git-diff line if needed
2436                if (defined $diffinfo &&
2437                    $diffinfo->{'from_id'} eq $from_id &&
2438                    $diffinfo->{'to_id'}   eq $to_id) {
2439                        # this is split patch
2440                        print "<div class=\"patch cont\">\n";
2441                } else {
2442                        # advance raw git-diff output if needed
2443                        $patch_idx++ if defined $diffinfo;
2444
2445                        # read and prepare patch information
2446                        if (ref($difftree->[$patch_idx]) eq "HASH") {
2447                                # pre-parsed (or generated by hand)
2448                                $diffinfo = $difftree->[$patch_idx];
2449                        } else {
2450                                $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
2451                        }
2452                        $from{'file'} = $diffinfo->{'from_file'} || $diffinfo->{'file'};
2453                        $to{'file'}   = $diffinfo->{'to_file'}   || $diffinfo->{'file'};
2454                        if ($diffinfo->{'status'} ne "A") { # not new (added) file
2455                                $from{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2456                                                     hash=>$diffinfo->{'from_id'},
2457                                                     file_name=>$from{'file'});
2458                        }
2459                        if ($diffinfo->{'status'} ne "D") { # not deleted file
2460                                $to{'href'} = href(action=>"blob", hash_base=>$hash,
2461                                                   hash=>$diffinfo->{'to_id'},
2462                                                   file_name=>$to{'file'});
2463                        }
2464                        # this is first patch for raw difftree line with $patch_idx index
2465                        # we index @$difftree array from 0, but number patches from 1
2466                        print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
2467                }
2468
2469                # print "git diff" header
2470                $patch_line = shift @diff_header;
2471                $patch_line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2472                if ($from{'href'}) {
2473                        $patch_line .= $cgi->a({-href => $from{'href'}, -class => "path"},
2474                                               'a/' . esc_path($from{'file'}));
2475                } else { # file was added
2476                        $patch_line .= 'a/' . esc_path($from{'file'});
2477                }
2478                $patch_line .= ' ';
2479                if ($to{'href'}) {
2480                        $patch_line .= $cgi->a({-href => $to{'href'}, -class => "path"},
2481                                               'b/' . esc_path($to{'file'}));
2482                } else { # file was deleted
2483                        $patch_line .= 'b/' . esc_path($to{'file'});
2484                }
2485                print "<div class=\"diff header\">$patch_line</div>\n";
2486
2487                # print extended diff header
2488                print "<div class=\"diff extended_header\">\n" if (@diff_header > 0);
2489        EXTENDED_HEADER:
2490                foreach $patch_line (@diff_header) {
2491                        # match <path>
2492                        if ($patch_line =~ s!^((copy|rename) from ).*$!$1! && $from{'href'}) {
2493                                $patch_line .= $cgi->a({-href=>$from{'href'}, -class=>"path"},
2494                                                        esc_path($from{'file'}));
2495                        }
2496                        if ($patch_line =~ s!^((copy|rename) to ).*$!$1! && $to{'href'}) {
2497                                $patch_line = $cgi->a({-href=>$to{'href'}, -class=>"path"},
2498                                                      esc_path($to{'file'}));
2499                        }
2500                        # match <mode>
2501                        if ($patch_line =~ m/\s(\d{6})$/) {
2502                                $patch_line .= '<span class="info"> (' .
2503                                               file_type_long($1) .
2504                                               ')</span>';
2505                        }
2506                        # match <hash>
2507                        if ($patch_line =~ m/^index/) {
2508                                my ($from_link, $to_link);
2509                                if ($from{'href'}) {
2510                                        $from_link = $cgi->a({-href=>$from{'href'}, -class=>"hash"},
2511                                                             substr($diffinfo->{'from_id'},0,7));
2512                                } else {
2513                                        $from_link = '0' x 7;
2514                                }
2515                                if ($to{'href'}) {
2516                                        $to_link = $cgi->a({-href=>$to{'href'}, -class=>"hash"},
2517                                                           substr($diffinfo->{'to_id'},0,7));
2518                                } else {
2519                                        $to_link = '0' x 7;
2520                                }
2521                                #affirm {
2522                                #       my ($from_hash, $to_hash) =
2523                                #               ($patch_line =~ m/^index ([0-9a-fA-F]{40})..([0-9a-fA-F]{40})/);
2524                                #       my ($from_id, $to_id) =
2525                                #               ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2526                                #       ($from_hash eq $from_id) && ($to_hash eq $to_id);
2527                                #} if DEBUG;
2528                                my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2529                                $patch_line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2530                        }
2531                        print $patch_line . "<br/>\n";
2532                }
2533                print "</div>\n"  if (@diff_header > 0); # class="diff extended_header"
2534
2535                # from-file/to-file diff header
2536                $patch_line = $last_patch_line;
2537                #assert($patch_line =~ m/^---/) if DEBUG;
2538                if ($from{'href'}) {
2539                        $patch_line = '--- a/' .
2540                                      $cgi->a({-href=>$from{'href'}, -class=>"path"},
2541                                              esc_path($from{'file'}));
2542                }
2543                print "<div class=\"diff from_file\">$patch_line</div>\n";
2544
2545                $patch_line = <$fd>;
2546                #last PATCH unless $patch_line;
2547                chomp $patch_line;
2548
2549                #assert($patch_line =~ m/^+++/) if DEBUG;
2550                if ($to{'href'}) {
2551                        $patch_line = '+++ b/' .
2552                                      $cgi->a({-href=>$to{'href'}, -class=>"path"},
2553                                              esc_path($to{'file'}));
2554                }
2555                print "<div class=\"diff to_file\">$patch_line</div>\n";
2556
2557                # the patch itself
2558        LINE:
2559                while ($patch_line = <$fd>) {
2560                        chomp $patch_line;
2561
2562                        next PATCH if ($patch_line =~ m/^diff /);
2563
2564                        print format_diff_line($patch_line, \%from, \%to);
2565                }
2566
2567        } continue {
2568                print "</div>\n"; # class="patch"
2569        }
2570
2571        print "</div>\n"; # class="patchset"
2572}
2573
2574# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2575
2576sub git_project_list_body {
2577        my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
2578
2579        my ($check_forks) = gitweb_check_feature('forks');
2580
2581        my @projects;
2582        foreach my $pr (@$projlist) {
2583                my (@aa) = git_get_last_activity($pr->{'path'});
2584                unless (@aa) {
2585                        next;
2586                }
2587                ($pr->{'age'}, $pr->{'age_string'}) = @aa;
2588                if (!defined $pr->{'descr'}) {
2589                        my $descr = git_get_project_description($pr->{'path'}) || "";
2590                        $pr->{'descr_long'} = to_utf8($descr);
2591                        $pr->{'descr'} = chop_str($descr, 25, 5);
2592                }
2593                if (!defined $pr->{'owner'}) {
2594                        $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2595                }
2596                if ($check_forks) {
2597                        my $pname = $pr->{'path'};
2598                        if (($pname =~ s/\.git$//) &&
2599                            ($pname !~ /\/$/) &&
2600                            (-d "$projectroot/$pname")) {
2601                                $pr->{'forks'} = "-d $projectroot/$pname";
2602                        }
2603                        else {
2604                                $pr->{'forks'} = 0;
2605                        }
2606                }
2607                push @projects, $pr;
2608        }
2609
2610        $order ||= "project";
2611        $from = 0 unless defined $from;
2612        $to = $#projects if (!defined $to || $#projects < $to);
2613
2614        print "<table class=\"project_list\">\n";
2615        unless ($no_header) {
2616                print "<tr>\n";
2617                if ($check_forks) {
2618                        print "<th></th>\n";
2619                }
2620                if ($order eq "project") {
2621                        @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2622                        print "<th>Project</th>\n";
2623                } else {
2624                        print "<th>" .
2625                              $cgi->a({-href => href(project=>undef, order=>'project'),
2626                                       -class => "header"}, "Project") .
2627                              "</th>\n";
2628                }
2629                if ($order eq "descr") {
2630                        @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2631                        print "<th>Description</th>\n";
2632                } else {
2633                        print "<th>" .
2634                              $cgi->a({-href => href(project=>undef, order=>'descr'),
2635                                       -class => "header"}, "Description") .
2636                              "</th>\n";
2637                }
2638                if ($order eq "owner") {
2639                        @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2640                        print "<th>Owner</th>\n";
2641                } else {
2642                        print "<th>" .
2643                              $cgi->a({-href => href(project=>undef, order=>'owner'),
2644                                       -class => "header"}, "Owner") .
2645                              "</th>\n";
2646                }
2647                if ($order eq "age") {
2648                        @projects = sort {$a->{'age'} <=> $b->{'age'}} @projects;
2649                        print "<th>Last Change</th>\n";
2650                } else {
2651                        print "<th>" .
2652                              $cgi->a({-href => href(project=>undef, order=>'age'),
2653                                       -class => "header"}, "Last Change") .
2654                              "</th>\n";
2655                }
2656                print "<th></th>\n" .
2657                      "</tr>\n";
2658        }
2659        my $alternate = 1;
2660        for (my $i = $from; $i <= $to; $i++) {
2661                my $pr = $projects[$i];
2662                if ($alternate) {
2663                        print "<tr class=\"dark\">\n";
2664                } else {
2665                        print "<tr class=\"light\">\n";
2666                }
2667                $alternate ^= 1;
2668                if ($check_forks) {
2669                        print "<td>";
2670                        if ($pr->{'forks'}) {
2671                                print "<!-- $pr->{'forks'} -->\n";
2672                                print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
2673                        }
2674                        print "</td>\n";
2675                }
2676                print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2677                                        -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2678                      "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2679                                        -class => "list", -title => $pr->{'descr_long'}},
2680                                        esc_html($pr->{'descr'})) . "</td>\n" .
2681                      "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2682                print "<td class=\"". age_class($pr->{'age'}) . "\">" .
2683                      $pr->{'age_string'} . "</td>\n" .
2684                      "<td class=\"link\">" .
2685                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2686                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
2687                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
2688                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
2689                      ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
2690                      "</td>\n" .
2691                      "</tr>\n";
2692        }
2693        if (defined $extra) {
2694                print "<tr>\n";
2695                if ($check_forks) {
2696                        print "<td></td>\n";
2697                }
2698                print "<td colspan=\"5\">$extra</td>\n" .
2699                      "</tr>\n";
2700        }
2701        print "</table>\n";
2702}
2703
2704sub git_shortlog_body {
2705        # uses global variable $project
2706        my ($revlist, $from, $to, $refs, $extra) = @_;
2707
2708        my $have_snapshot = gitweb_have_snapshot();
2709
2710        $from = 0 unless defined $from;
2711        $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
2712
2713        print "<table class=\"shortlog\" cellspacing=\"0\">\n";
2714        my $alternate = 1;
2715        for (my $i = $from; $i <= $to; $i++) {
2716                my $commit = $revlist->[$i];
2717                #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
2718                my $ref = format_ref_marker($refs, $commit);
2719                my %co = parse_commit($commit);
2720                if ($alternate) {
2721                        print "<tr class=\"dark\">\n";
2722                } else {
2723                        print "<tr class=\"light\">\n";
2724                }
2725                $alternate ^= 1;
2726                # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
2727                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2728                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
2729                      "<td>";
2730                print format_subject_html($co{'title'}, $co{'title_short'},
2731                                          href(action=>"commit", hash=>$commit), $ref);
2732                print "</td>\n" .
2733                      "<td class=\"link\">" .
2734                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
2735                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
2736                      $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
2737                if ($have_snapshot) {
2738                        print " | " . $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
2739                }
2740                print "</td>\n" .
2741                      "</tr>\n";
2742        }
2743        if (defined $extra) {
2744                print "<tr>\n" .
2745                      "<td colspan=\"4\">$extra</td>\n" .
2746                      "</tr>\n";
2747        }
2748        print "</table>\n";
2749}
2750
2751sub git_history_body {
2752        # Warning: assumes constant type (blob or tree) during history
2753        my ($revlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
2754
2755        $from = 0 unless defined $from;
2756        $to = $#{$revlist} unless (defined $to && $to <= $#{$revlist});
2757
2758        print "<table class=\"history\" cellspacing=\"0\">\n";
2759        my $alternate = 1;
2760        for (my $i = $from; $i <= $to; $i++) {
2761                if ($revlist->[$i] !~ m/^([0-9a-fA-F]{40})/) {
2762                        next;
2763                }
2764
2765                my $commit = $1;
2766                my %co = parse_commit($commit);
2767                if (!%co) {
2768                        next;
2769                }
2770
2771                my $ref = format_ref_marker($refs, $commit);
2772
2773                if ($alternate) {
2774                        print "<tr class=\"dark\">\n";
2775                } else {
2776                        print "<tr class=\"light\">\n";
2777                }
2778                $alternate ^= 1;
2779                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2780                      # shortlog uses      chop_str($co{'author_name'}, 10)
2781                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
2782                      "<td>";
2783                # originally git_history used chop_str($co{'title'}, 50)
2784                print format_subject_html($co{'title'}, $co{'title_short'},
2785                                          href(action=>"commit", hash=>$commit), $ref);
2786                print "</td>\n" .
2787                      "<td class=\"link\">" .
2788                      $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
2789                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
2790
2791                if ($ftype eq 'blob') {
2792                        my $blob_current = git_get_hash_by_path($hash_base, $file_name);
2793                        my $blob_parent  = git_get_hash_by_path($commit, $file_name);
2794                        if (defined $blob_current && defined $blob_parent &&
2795                                        $blob_current ne $blob_parent) {
2796                                print " | " .
2797                                        $cgi->a({-href => href(action=>"blobdiff",
2798                                                               hash=>$blob_current, hash_parent=>$blob_parent,
2799                                                               hash_base=>$hash_base, hash_parent_base=>$commit,
2800                                                               file_name=>$file_name)},
2801                                                "diff to current");
2802                        }
2803                }
2804                print "</td>\n" .
2805                      "</tr>\n";
2806        }
2807        if (defined $extra) {
2808                print "<tr>\n" .
2809                      "<td colspan=\"4\">$extra</td>\n" .
2810                      "</tr>\n";
2811        }
2812        print "</table>\n";
2813}
2814
2815sub git_tags_body {
2816        # uses global variable $project
2817        my ($taglist, $from, $to, $extra) = @_;
2818        $from = 0 unless defined $from;
2819        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2820
2821        print "<table class=\"tags\" cellspacing=\"0\">\n";
2822        my $alternate = 1;
2823        for (my $i = $from; $i <= $to; $i++) {
2824                my $entry = $taglist->[$i];
2825                my %tag = %$entry;
2826                my $comment = $tag{'subject'};
2827                my $comment_short;
2828                if (defined $comment) {
2829                        $comment_short = chop_str($comment, 30, 5);
2830                }
2831                if ($alternate) {
2832                        print "<tr class=\"dark\">\n";
2833                } else {
2834                        print "<tr class=\"light\">\n";
2835                }
2836                $alternate ^= 1;
2837                print "<td><i>$tag{'age'}</i></td>\n" .
2838                      "<td>" .
2839                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
2840                               -class => "list name"}, esc_html($tag{'name'})) .
2841                      "</td>\n" .
2842                      "<td>";
2843                if (defined $comment) {
2844                        print format_subject_html($comment, $comment_short,
2845                                                  href(action=>"tag", hash=>$tag{'id'}));
2846                }
2847                print "</td>\n" .
2848                      "<td class=\"selflink\">";
2849                if ($tag{'type'} eq "tag") {
2850                        print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
2851                } else {
2852                        print "&nbsp;";
2853                }
2854                print "</td>\n" .
2855                      "<td class=\"link\">" . " | " .
2856                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
2857                if ($tag{'reftype'} eq "commit") {
2858                        print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
2859                              " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log");
2860                } elsif ($tag{'reftype'} eq "blob") {
2861                        print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
2862                }
2863                print "</td>\n" .
2864                      "</tr>";
2865        }
2866        if (defined $extra) {
2867                print "<tr>\n" .
2868                      "<td colspan=\"5\">$extra</td>\n" .
2869                      "</tr>\n";
2870        }
2871        print "</table>\n";
2872}
2873
2874sub git_heads_body {
2875        # uses global variable $project
2876        my ($headlist, $head, $from, $to, $extra) = @_;
2877        $from = 0 unless defined $from;
2878        $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
2879
2880        print "<table class=\"heads\" cellspacing=\"0\">\n";
2881        my $alternate = 1;
2882        for (my $i = $from; $i <= $to; $i++) {
2883                my $entry = $headlist->[$i];
2884                my %ref = %$entry;
2885                my $curr = $ref{'id'} eq $head;
2886                if ($alternate) {
2887                        print "<tr class=\"dark\">\n";
2888                } else {
2889                        print "<tr class=\"light\">\n";
2890                }
2891                $alternate ^= 1;
2892                print "<td><i>$ref{'age'}</i></td>\n" .
2893                      ($curr ? "<td class=\"current_head\">" : "<td>") .
2894                      $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'}),
2895                               -class => "list name"},esc_html($ref{'name'})) .
2896                      "</td>\n" .
2897                      "<td class=\"link\">" .
2898                      $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'})}, "shortlog") . " | " .
2899                      $cgi->a({-href => href(action=>"log", hash=>$ref{'name'})}, "log") . " | " .
2900                      $cgi->a({-href => href(action=>"tree", hash=>$ref{'name'}, hash_base=>$ref{'name'})}, "tree") .
2901                      "</td>\n" .
2902                      "</tr>";
2903        }
2904        if (defined $extra) {
2905                print "<tr>\n" .
2906                      "<td colspan=\"3\">$extra</td>\n" .
2907                      "</tr>\n";
2908        }
2909        print "</table>\n";
2910}
2911
2912sub git_search_grep_body {
2913        my ($greplist, $from, $to, $extra) = @_;
2914        $from = 0 unless defined $from;
2915        $to = $#{$greplist} if (!defined $to || $#{$greplist} < $to);
2916
2917        print "<table class=\"grep\" cellspacing=\"0\">\n";
2918        my $alternate = 1;
2919        for (my $i = $from; $i <= $to; $i++) {
2920                my $commit = $greplist->[$i];
2921                my %co = parse_commit($commit);
2922                if (!%co) {
2923                        next;
2924                }
2925                if ($alternate) {
2926                        print "<tr class=\"dark\">\n";
2927                } else {
2928                        print "<tr class=\"light\">\n";
2929                }
2930                $alternate ^= 1;
2931                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2932                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
2933                      "<td>" .
2934                      $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
2935                               esc_html(chop_str($co{'title'}, 50)) . "<br/>");
2936                my $comment = $co{'comment'};
2937                foreach my $line (@$comment) {
2938                        if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
2939                                my $lead = esc_html($1) || "";
2940                                $lead = chop_str($lead, 30, 10);
2941                                my $match = esc_html($2) || "";
2942                                my $trail = esc_html($3) || "";
2943                                $trail = chop_str($trail, 30, 10);
2944                                my $text = "$lead<span class=\"match\">$match</span>$trail";
2945                                print chop_str($text, 80, 5) . "<br/>\n";
2946                        }
2947                }
2948                print "</td>\n" .
2949                      "<td class=\"link\">" .
2950                      $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
2951                      " | " .
2952                      $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
2953                print "</td>\n" .
2954                      "</tr>\n";
2955        }
2956        if (defined $extra) {
2957                print "<tr>\n" .
2958                      "<td colspan=\"3\">$extra</td>\n" .
2959                      "</tr>\n";
2960        }
2961        print "</table>\n";
2962}
2963
2964## ======================================================================
2965## ======================================================================
2966## actions
2967
2968sub git_project_list {
2969        my $order = $cgi->param('o');
2970        if (defined $order && $order !~ m/project|descr|owner|age/) {
2971                die_error(undef, "Unknown order parameter");
2972        }
2973
2974        my @list = git_get_projects_list();
2975        if (!@list) {
2976                die_error(undef, "No projects found");
2977        }
2978
2979        git_header_html();
2980        if (-f $home_text) {
2981                print "<div class=\"index_include\">\n";
2982                open (my $fd, $home_text);
2983                print <$fd>;
2984                close $fd;
2985                print "</div>\n";
2986        }
2987        git_project_list_body(\@list, $order);
2988        git_footer_html();
2989}
2990
2991sub git_forks {
2992        my $order = $cgi->param('o');
2993        if (defined $order && $order !~ m/project|descr|owner|age/) {
2994                die_error(undef, "Unknown order parameter");
2995        }
2996
2997        my @list = git_get_projects_list($project);
2998        if (!@list) {
2999                die_error(undef, "No forks found");
3000        }
3001
3002        git_header_html();
3003        git_print_page_nav('','');
3004        git_print_header_div('summary', "$project forks");
3005        git_project_list_body(\@list, $order);
3006        git_footer_html();
3007}
3008
3009sub git_project_index {
3010        my @projects = git_get_projects_list($project);
3011
3012        print $cgi->header(
3013                -type => 'text/plain',
3014                -charset => 'utf-8',
3015                -content_disposition => 'inline; filename="index.aux"');
3016
3017        foreach my $pr (@projects) {
3018                if (!exists $pr->{'owner'}) {
3019                        $pr->{'owner'} = get_file_owner("$projectroot/$project");
3020                }
3021
3022                my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
3023                # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
3024                $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3025                $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3026                $path  =~ s/ /\+/g;
3027                $owner =~ s/ /\+/g;
3028
3029                print "$path $owner\n";
3030        }
3031}
3032
3033sub git_summary {
3034        my $descr = git_get_project_description($project) || "none";
3035        my %co = parse_commit("HEAD");
3036        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
3037        my $head = $co{'id'};
3038
3039        my $owner = git_get_project_owner($project);
3040
3041        my $refs = git_get_references();
3042        # These get_*_list functions return one more to allow us to see if
3043        # there are more ...
3044        my @taglist  = git_get_tags_list(16);
3045        my @headlist = git_get_heads_list(16);
3046        my @forklist;
3047        my ($check_forks) = gitweb_check_feature('forks');
3048
3049        if ($check_forks) {
3050                @forklist = git_get_projects_list($project);
3051        }
3052
3053        git_header_html();
3054        git_print_page_nav('summary','', $head);
3055
3056        print "<div class=\"title\">&nbsp;</div>\n";
3057        print "<table cellspacing=\"0\">\n" .
3058              "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
3059              "<tr><td>owner</td><td>$owner</td></tr>\n" .
3060              "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
3061        # use per project git URL list in $projectroot/$project/cloneurl
3062        # or make project git URL from git base URL and project name
3063        my $url_tag = "URL";
3064        my @url_list = git_get_project_url_list($project);
3065        @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
3066        foreach my $git_url (@url_list) {
3067                next unless $git_url;
3068                print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
3069                $url_tag = "";
3070        }
3071        print "</table>\n";
3072
3073        if (-s "$projectroot/$project/README.html") {
3074                if (open my $fd, "$projectroot/$project/README.html") {
3075                        print "<div class=\"title\">readme</div>\n";
3076                        print $_ while (<$fd>);
3077                        close $fd;
3078                }
3079        }
3080
3081        # we need to request one more than 16 (0..15) to check if
3082        # those 16 are all
3083        open my $fd, "-|", git_cmd(), "rev-list", "--max-count=17",
3084                $head, "--"
3085                or die_error(undef, "Open git-rev-list failed");
3086        my @revlist = map { chomp; $_ } <$fd>;
3087        close $fd;
3088        git_print_header_div('shortlog');
3089        git_shortlog_body(\@revlist, 0, 15, $refs,
3090                          $#revlist <=  15 ? undef :
3091                          $cgi->a({-href => href(action=>"shortlog")}, "..."));
3092
3093        if (@taglist) {
3094                git_print_header_div('tags');
3095                git_tags_body(\@taglist, 0, 15,
3096                              $#taglist <=  15 ? undef :
3097                              $cgi->a({-href => href(action=>"tags")}, "..."));
3098        }
3099
3100        if (@headlist) {
3101                git_print_header_div('heads');
3102                git_heads_body(\@headlist, $head, 0, 15,
3103                               $#headlist <= 15 ? undef :
3104                               $cgi->a({-href => href(action=>"heads")}, "..."));
3105        }
3106
3107        if (@forklist) {
3108                git_print_header_div('forks');
3109                git_project_list_body(\@forklist, undef, 0, 15,
3110                                      $#forklist <= 15 ? undef :
3111                                      $cgi->a({-href => href(action=>"forks")}, "..."),
3112                                      'noheader');
3113        }
3114
3115        git_footer_html();
3116}
3117
3118sub git_tag {
3119        my $head = git_get_head_hash($project);
3120        git_header_html();
3121        git_print_page_nav('','', $head,undef,$head);
3122        my %tag = parse_tag($hash);
3123        git_print_header_div('commit', esc_html($tag{'name'}), $hash);
3124        print "<div class=\"title_text\">\n" .
3125              "<table cellspacing=\"0\">\n" .
3126              "<tr>\n" .
3127              "<td>object</td>\n" .
3128              "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3129                               $tag{'object'}) . "</td>\n" .
3130              "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3131                                              $tag{'type'}) . "</td>\n" .
3132              "</tr>\n";
3133        if (defined($tag{'author'})) {
3134                my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
3135                print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
3136                print "<tr><td></td><td>" . $ad{'rfc2822'} .
3137                        sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
3138                        "</td></tr>\n";
3139        }
3140        print "</table>\n\n" .
3141              "</div>\n";
3142        print "<div class=\"page_body\">";
3143        my $comment = $tag{'comment'};
3144        foreach my $line (@$comment) {
3145                chomp $line;
3146                print esc_html($line, -nbsp=>1) . "<br/>\n";
3147        }
3148        print "</div>\n";
3149        git_footer_html();
3150}
3151
3152sub git_blame2 {
3153        my $fd;
3154        my $ftype;
3155
3156        my ($have_blame) = gitweb_check_feature('blame');
3157        if (!$have_blame) {
3158                die_error('403 Permission denied', "Permission denied");
3159        }
3160        die_error('404 Not Found', "File name not defined") if (!$file_name);
3161        $hash_base ||= git_get_head_hash($project);
3162        die_error(undef, "Couldn't find base commit") unless ($hash_base);
3163        my %co = parse_commit($hash_base)
3164                or die_error(undef, "Reading commit failed");
3165        if (!defined $hash) {
3166                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3167                        or die_error(undef, "Error looking up file");
3168        }
3169        $ftype = git_get_type($hash);
3170        if ($ftype !~ "blob") {
3171                die_error("400 Bad Request", "Object is not a blob");
3172        }
3173        open ($fd, "-|", git_cmd(), "blame", '-p', '--',
3174              $file_name, $hash_base)
3175                or die_error(undef, "Open git-blame failed");
3176        git_header_html();
3177        my $formats_nav =
3178                $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3179                        "blob") .
3180                " | " .
3181                $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3182                        "history") .
3183                " | " .
3184                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3185                        "HEAD");
3186        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3187        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3188        git_print_page_path($file_name, $ftype, $hash_base);
3189        my @rev_color = (qw(light2 dark2));
3190        my $num_colors = scalar(@rev_color);
3191        my $current_color = 0;
3192        my $last_rev;
3193        print <<HTML;
3194<div class="page_body">
3195<table class="blame">
3196<tr><th>Commit</th><th>Line</th><th>Data</th></tr>
3197HTML
3198        my %metainfo = ();
3199        while (1) {
3200                $_ = <$fd>;
3201                last unless defined $_;
3202                my ($full_rev, $orig_lineno, $lineno, $group_size) =
3203                    /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
3204                if (!exists $metainfo{$full_rev}) {
3205                        $metainfo{$full_rev} = {};
3206                }
3207                my $meta = $metainfo{$full_rev};
3208                while (<$fd>) {
3209                        last if (s/^\t//);
3210                        if (/^(\S+) (.*)$/) {
3211                                $meta->{$1} = $2;
3212                        }
3213                }
3214                my $data = $_;
3215                chomp $data;
3216                my $rev = substr($full_rev, 0, 8);
3217                my $author = $meta->{'author'};
3218                my %date = parse_date($meta->{'author-time'},
3219                                      $meta->{'author-tz'});
3220                my $date = $date{'iso-tz'};
3221                if ($group_size) {
3222                        $current_color = ++$current_color % $num_colors;
3223                }
3224                print "<tr class=\"$rev_color[$current_color]\">\n";
3225                if ($group_size) {
3226                        print "<td class=\"sha1\"";
3227                        print " title=\"". esc_html($author) . ", $date\"";
3228                        print " rowspan=\"$group_size\"" if ($group_size > 1);
3229                        print ">";
3230                        print $cgi->a({-href => href(action=>"commit",
3231                                                     hash=>$full_rev,
3232                                                     file_name=>$file_name)},
3233                                      esc_html($rev));
3234                        print "</td>\n";
3235                }
3236                my $blamed = href(action => 'blame',
3237                                  file_name => $meta->{'filename'},
3238                                  hash_base => $full_rev);
3239                print "<td class=\"linenr\">";
3240                print $cgi->a({ -href => "$blamed#l$orig_lineno",
3241                                -id => "l$lineno",
3242                                -class => "linenr" },
3243                              esc_html($lineno));
3244                print "</td>";
3245                print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
3246                print "</tr>\n";
3247        }
3248        print "</table>\n";
3249        print "</div>";
3250        close $fd
3251                or print "Reading blob failed\n";
3252        git_footer_html();
3253}
3254
3255sub git_blame {
3256        my $fd;
3257
3258        my ($have_blame) = gitweb_check_feature('blame');
3259        if (!$have_blame) {
3260                die_error('403 Permission denied', "Permission denied");
3261        }
3262        die_error('404 Not Found', "File name not defined") if (!$file_name);
3263        $hash_base ||= git_get_head_hash($project);
3264        die_error(undef, "Couldn't find base commit") unless ($hash_base);
3265        my %co = parse_commit($hash_base)
3266                or die_error(undef, "Reading commit failed");
3267        if (!defined $hash) {
3268                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3269                        or die_error(undef, "Error lookup file");
3270        }
3271        open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
3272                or die_error(undef, "Open git-annotate failed");
3273        git_header_html();
3274        my $formats_nav =
3275                $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3276                        "blob") .
3277                " | " .
3278                $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3279                        "history") .
3280                " | " .
3281                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3282                        "HEAD");
3283        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3284        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3285        git_print_page_path($file_name, 'blob', $hash_base);
3286        print "<div class=\"page_body\">\n";
3287        print <<HTML;
3288<table class="blame">
3289  <tr>
3290    <th>Commit</th>
3291    <th>Age</th>
3292    <th>Author</th>
3293    <th>Line</th>
3294    <th>Data</th>
3295  </tr>
3296HTML
3297        my @line_class = (qw(light dark));
3298        my $line_class_len = scalar (@line_class);
3299        my $line_class_num = $#line_class;
3300        while (my $line = <$fd>) {
3301                my $long_rev;
3302                my $short_rev;
3303                my $author;
3304                my $time;
3305                my $lineno;
3306                my $data;
3307                my $age;
3308                my $age_str;
3309                my $age_class;
3310
3311                chomp $line;
3312                $line_class_num = ($line_class_num + 1) % $line_class_len;
3313
3314                if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
3315                        $long_rev = $1;
3316                        $author   = $2;
3317                        $time     = $3;
3318                        $lineno   = $4;
3319                        $data     = $5;
3320                } else {
3321                        print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
3322                        next;
3323                }
3324                $short_rev  = substr ($long_rev, 0, 8);
3325                $age        = time () - $time;
3326                $age_str    = age_string ($age);
3327                $age_str    =~ s/ /&nbsp;/g;
3328                $age_class  = age_class($age);
3329                $author     = esc_html ($author);
3330                $author     =~ s/ /&nbsp;/g;
3331
3332                $data = untabify($data);
3333                $data = esc_html ($data);
3334
3335                print <<HTML;
3336  <tr class="$line_class[$line_class_num]">
3337    <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
3338    <td class="$age_class">$age_str</td>
3339    <td>$author</td>
3340    <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
3341    <td class="pre">$data</td>
3342  </tr>
3343HTML
3344        } # while (my $line = <$fd>)
3345        print "</table>\n\n";
3346        close $fd
3347                or print "Reading blob failed.\n";
3348        print "</div>";
3349        git_footer_html();
3350}
3351
3352sub git_tags {
3353        my $head = git_get_head_hash($project);
3354        git_header_html();
3355        git_print_page_nav('','', $head,undef,$head);
3356        git_print_header_div('summary', $project);
3357
3358        my @tagslist = git_get_tags_list();
3359        if (@tagslist) {
3360                git_tags_body(\@tagslist);
3361        }
3362        git_footer_html();
3363}
3364
3365sub git_heads {
3366        my $head = git_get_head_hash($project);
3367        git_header_html();
3368        git_print_page_nav('','', $head,undef,$head);
3369        git_print_header_div('summary', $project);
3370
3371        my @headslist = git_get_heads_list();
3372        if (@headslist) {
3373                git_heads_body(\@headslist, $head);
3374        }
3375        git_footer_html();
3376}
3377
3378sub git_blob_plain {
3379        my $expires;
3380
3381        if (!defined $hash) {
3382                if (defined $file_name) {
3383                        my $base = $hash_base || git_get_head_hash($project);
3384                        $hash = git_get_hash_by_path($base, $file_name, "blob")
3385                                or die_error(undef, "Error lookup file");
3386                } else {
3387                        die_error(undef, "No file name defined");
3388                }
3389        } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3390                # blobs defined by non-textual hash id's can be cached
3391                $expires = "+1d";
3392        }
3393
3394        my $type = shift;
3395        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3396                or die_error(undef, "Couldn't cat $file_name, $hash");
3397
3398        $type ||= blob_mimetype($fd, $file_name);
3399
3400        # save as filename, even when no $file_name is given
3401        my $save_as = "$hash";
3402        if (defined $file_name) {
3403                $save_as = $file_name;
3404        } elsif ($type =~ m/^text\//) {
3405                $save_as .= '.txt';
3406        }
3407
3408        print $cgi->header(
3409                -type => "$type",
3410                -expires=>$expires,
3411                -content_disposition => 'inline; filename="' . "$save_as" . '"');
3412        undef $/;
3413        binmode STDOUT, ':raw';
3414        print <$fd>;
3415        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
3416        $/ = "\n";
3417        close $fd;
3418}
3419
3420sub git_blob {
3421        my $expires;
3422
3423        if (!defined $hash) {
3424                if (defined $file_name) {
3425                        my $base = $hash_base || git_get_head_hash($project);
3426                        $hash = git_get_hash_by_path($base, $file_name, "blob")
3427                                or die_error(undef, "Error lookup file");
3428                } else {
3429                        die_error(undef, "No file name defined");
3430                }
3431        } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3432                # blobs defined by non-textual hash id's can be cached
3433                $expires = "+1d";
3434        }
3435
3436        my ($have_blame) = gitweb_check_feature('blame');
3437        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3438                or die_error(undef, "Couldn't cat $file_name, $hash");
3439        my $mimetype = blob_mimetype($fd, $file_name);
3440        if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)!) {
3441                close $fd;
3442                return git_blob_plain($mimetype);
3443        }
3444        # we can have blame only for text/* mimetype
3445        $have_blame &&= ($mimetype =~ m!^text/!);
3446
3447        git_header_html(undef, $expires);
3448        my $formats_nav = '';
3449        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3450                if (defined $file_name) {
3451                        if ($have_blame) {
3452                                $formats_nav .=
3453                                        $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
3454                                                               hash=>$hash, file_name=>$file_name)},
3455                                                "blame") .
3456                                        " | ";
3457                        }
3458                        $formats_nav .=
3459                                $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3460                                                       hash=>$hash, file_name=>$file_name)},
3461                                        "history") .
3462                                " | " .
3463                                $cgi->a({-href => href(action=>"blob_plain",
3464                                                       hash=>$hash, file_name=>$file_name)},
3465                                        "raw") .
3466                                " | " .
3467                                $cgi->a({-href => href(action=>"blob",
3468                                                       hash_base=>"HEAD", file_name=>$file_name)},
3469                                        "HEAD");
3470                } else {
3471                        $formats_nav .=
3472                                $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
3473                }
3474                git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3475                git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3476        } else {
3477                print "<div class=\"page_nav\">\n" .
3478                      "<br/><br/></div>\n" .
3479                      "<div class=\"title\">$hash</div>\n";
3480        }
3481        git_print_page_path($file_name, "blob", $hash_base);
3482        print "<div class=\"page_body\">\n";
3483        if ($mimetype =~ m!^text/!) {
3484                my $nr;
3485                while (my $line = <$fd>) {
3486                        chomp $line;
3487                        $nr++;
3488                        $line = untabify($line);
3489                        printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
3490                               $nr, $nr, $nr, esc_html($line, -nbsp=>1);
3491                }
3492        } elsif ($mimetype =~ m!^image/!) {
3493                print qq!<img type="$mimetype"!;
3494                if ($file_name) {
3495                        print qq! alt="$file_name" title="$file_name"!;
3496                }
3497                print qq! src="! .
3498                      href(action=>"blob_plain", hash=>$hash,
3499                           hash_base=>$hash_base, file_name=>$file_name) .
3500                      qq!" />\n!;
3501        }
3502        close $fd
3503                or print "Reading blob failed.\n";
3504        print "</div>";
3505        git_footer_html();
3506}
3507
3508sub git_tree {
3509        my $have_snapshot = gitweb_have_snapshot();
3510
3511        if (!defined $hash_base) {
3512                $hash_base = "HEAD";
3513        }
3514        if (!defined $hash) {
3515                if (defined $file_name) {
3516                        $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
3517                } else {
3518                        $hash = $hash_base;
3519                }
3520        }
3521        $/ = "\0";
3522        open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
3523                or die_error(undef, "Open git-ls-tree failed");
3524        my @entries = map { chomp; $_ } <$fd>;
3525        close $fd or die_error(undef, "Reading tree failed");
3526        $/ = "\n";
3527
3528        my $refs = git_get_references();
3529        my $ref = format_ref_marker($refs, $hash_base);
3530        git_header_html();
3531        my $basedir = '';
3532        my ($have_blame) = gitweb_check_feature('blame');
3533        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3534                my @views_nav = ();
3535                if (defined $file_name) {
3536                        push @views_nav,
3537                                $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3538                                                       hash=>$hash, file_name=>$file_name)},
3539                                        "history"),
3540                                $cgi->a({-href => href(action=>"tree",
3541                                                       hash_base=>"HEAD", file_name=>$file_name)},
3542                                        "HEAD"),
3543                }
3544                if ($have_snapshot) {
3545                        # FIXME: Should be available when we have no hash base as well.
3546                        push @views_nav,
3547                                $cgi->a({-href => href(action=>"snapshot", hash=>$hash)},
3548                                        "snapshot");
3549                }
3550                git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
3551                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
3552        } else {
3553                undef $hash_base;
3554                print "<div class=\"page_nav\">\n";
3555                print "<br/><br/></div>\n";
3556                print "<div class=\"title\">$hash</div>\n";
3557        }
3558        if (defined $file_name) {
3559                $basedir = $file_name;
3560                if ($basedir ne '' && substr($basedir, -1) ne '/') {
3561                        $basedir .= '/';
3562                }
3563        }
3564        git_print_page_path($file_name, 'tree', $hash_base);
3565        print "<div class=\"page_body\">\n";
3566        print "<table cellspacing=\"0\">\n";
3567        my $alternate = 1;
3568        # '..' (top directory) link if possible
3569        if (defined $hash_base &&
3570            defined $file_name && $file_name =~ m![^/]+$!) {
3571                if ($alternate) {
3572                        print "<tr class=\"dark\">\n";
3573                } else {
3574                        print "<tr class=\"light\">\n";
3575                }
3576                $alternate ^= 1;
3577
3578                my $up = $file_name;
3579                $up =~ s!/?[^/]+$!!;
3580                undef $up unless $up;
3581                # based on git_print_tree_entry
3582                print '<td class="mode">' . mode_str('040000') . "</td>\n";
3583                print '<td class="list">';
3584                print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
3585                                             file_name=>$up)},
3586                              "..");
3587                print "</td>\n";
3588                print "<td class=\"link\"></td>\n";
3589
3590                print "</tr>\n";
3591        }
3592        foreach my $line (@entries) {
3593                my %t = parse_ls_tree_line($line, -z => 1);
3594
3595                if ($alternate) {
3596                        print "<tr class=\"dark\">\n";
3597                } else {
3598                        print "<tr class=\"light\">\n";
3599                }
3600                $alternate ^= 1;
3601
3602                git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
3603
3604                print "</tr>\n";
3605        }
3606        print "</table>\n" .
3607              "</div>";
3608        git_footer_html();
3609}
3610
3611sub git_snapshot {
3612        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
3613        my $have_snapshot = (defined $ctype && defined $suffix);
3614        if (!$have_snapshot) {
3615                die_error('403 Permission denied', "Permission denied");
3616        }
3617
3618        if (!defined $hash) {
3619                $hash = git_get_head_hash($project);
3620        }
3621
3622        my $filename = basename($project) . "-$hash.tar.$suffix";
3623
3624        print $cgi->header(
3625                -type => "application/$ctype",
3626                -content_disposition => 'inline; filename="' . "$filename" . '"',
3627                -status => '200 OK');
3628
3629        my $git = git_cmd_str();
3630        my $name = $project;
3631        $name =~ s/\047/\047\\\047\047/g;
3632        open my $fd, "-|",
3633        "$git archive --format=tar --prefix=\'$name\'/ $hash | $command"
3634                or die_error(undef, "Execute git-tar-tree failed.");
3635        binmode STDOUT, ':raw';
3636        print <$fd>;
3637        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
3638        close $fd;
3639
3640}
3641
3642sub git_log {
3643        my $head = git_get_head_hash($project);
3644        if (!defined $hash) {
3645                $hash = $head;
3646        }
3647        if (!defined $page) {
3648                $page = 0;
3649        }
3650        my $refs = git_get_references();
3651
3652        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3653        open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash, "--"
3654                or die_error(undef, "Open git-rev-list failed");
3655        my @revlist = map { chomp; $_ } <$fd>;
3656        close $fd;
3657
3658        my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
3659
3660        git_header_html();
3661        git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
3662
3663        if (!@revlist) {
3664                my %co = parse_commit($hash);
3665
3666                git_print_header_div('summary', $project);
3667                print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
3668        }
3669        for (my $i = ($page * 100); $i <= $#revlist; $i++) {
3670                my $commit = $revlist[$i];
3671                my $ref = format_ref_marker($refs, $commit);
3672                my %co = parse_commit($commit);
3673                next if !%co;
3674                my %ad = parse_date($co{'author_epoch'});
3675                git_print_header_div('commit',
3676                               "<span class=\"age\">$co{'age_string'}</span>" .
3677                               esc_html($co{'title'}) . $ref,
3678                               $commit);
3679                print "<div class=\"title_text\">\n" .
3680                      "<div class=\"log_link\">\n" .
3681                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
3682                      " | " .
3683                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
3684                      " | " .
3685                      $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
3686                      "<br/>\n" .
3687                      "</div>\n" .
3688                      "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
3689                      "</div>\n";
3690
3691                print "<div class=\"log_body\">\n";
3692                git_print_log($co{'comment'}, -final_empty_line=> 1);
3693                print "</div>\n";
3694        }
3695        git_footer_html();
3696}
3697
3698sub git_commit {
3699        $hash ||= $hash_base || "HEAD";
3700        my %co = parse_commit($hash);
3701        if (!%co) {
3702                die_error(undef, "Unknown commit object");
3703        }
3704        my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3705        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
3706
3707        my $parent  = $co{'parent'};
3708        my $parents = $co{'parents'}; # listref
3709
3710        # we need to prepare $formats_nav before any parameter munging
3711        my $formats_nav;
3712        if (!defined $parent) {
3713                # --root commitdiff
3714                $formats_nav .= '(initial)';
3715        } elsif (@$parents == 1) {
3716                # single parent commit
3717                $formats_nav .=
3718                        '(parent: ' .
3719                        $cgi->a({-href => href(action=>"commit",
3720                                               hash=>$parent)},
3721                                esc_html(substr($parent, 0, 7))) .
3722                        ')';
3723        } else {
3724                # merge commit
3725                $formats_nav .=
3726                        '(merge: ' .
3727                        join(' ', map {
3728                                $cgi->a({-href => href(action=>"commitdiff",
3729                                                       hash=>$_)},
3730                                        esc_html(substr($_, 0, 7)));
3731                        } @$parents ) .
3732                        ')';
3733        }
3734
3735        if (!defined $parent) {
3736                $parent = "--root";
3737        }
3738        my @difftree;
3739        if (@$parents <= 1) {
3740                # difftree output is not printed for merges
3741                open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
3742                        @diff_opts, $parent, $hash, "--"
3743                                or die_error(undef, "Open git-diff-tree failed");
3744                @difftree = map { chomp; $_ } <$fd>;
3745                close $fd or die_error(undef, "Reading git-diff-tree failed");
3746        }
3747
3748        # non-textual hash id's can be cached
3749        my $expires;
3750        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3751                $expires = "+1d";
3752        }
3753        my $refs = git_get_references();
3754        my $ref = format_ref_marker($refs, $co{'id'});
3755
3756        my $have_snapshot = gitweb_have_snapshot();
3757
3758        git_header_html(undef, $expires);
3759        git_print_page_nav('commit', '',
3760                           $hash, $co{'tree'}, $hash,
3761                           $formats_nav);
3762
3763        if (defined $co{'parent'}) {
3764                git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
3765        } else {
3766                git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
3767        }
3768        print "<div class=\"title_text\">\n" .
3769              "<table cellspacing=\"0\">\n";
3770        print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
3771              "<tr>" .
3772              "<td></td><td> $ad{'rfc2822'}";
3773        if ($ad{'hour_local'} < 6) {
3774                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3775                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3776        } else {
3777                printf(" (%02d:%02d %s)",
3778                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3779        }
3780        print "</td>" .
3781              "</tr>\n";
3782        print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
3783        print "<tr><td></td><td> $cd{'rfc2822'}" .
3784              sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
3785              "</td></tr>\n";
3786        print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
3787        print "<tr>" .
3788              "<td>tree</td>" .
3789              "<td class=\"sha1\">" .
3790              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
3791                       class => "list"}, $co{'tree'}) .
3792              "</td>" .
3793              "<td class=\"link\">" .
3794              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
3795                      "tree");
3796        if ($have_snapshot) {
3797                print " | " .
3798                      $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
3799        }
3800        print "</td>" .
3801              "</tr>\n";
3802
3803        foreach my $par (@$parents) {
3804                print "<tr>" .
3805                      "<td>parent</td>" .
3806                      "<td class=\"sha1\">" .
3807                      $cgi->a({-href => href(action=>"commit", hash=>$par),
3808                               class => "list"}, $par) .
3809                      "</td>" .
3810                      "<td class=\"link\">" .
3811                      $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
3812                      " | " .
3813                      $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
3814                      "</td>" .
3815                      "</tr>\n";
3816        }
3817        print "</table>".
3818              "</div>\n";
3819
3820        print "<div class=\"page_body\">\n";
3821        git_print_log($co{'comment'});
3822        print "</div>\n";
3823
3824        if (@$parents <= 1) {
3825                # do not output difftree/whatchanged for merges
3826                git_difftree_body(\@difftree, $hash, $parent);
3827        }
3828
3829        git_footer_html();
3830}
3831
3832sub git_object {
3833        # object is defined by:
3834        # - hash or hash_base alone
3835        # - hash_base and file_name
3836        my $type;
3837
3838        # - hash or hash_base alone
3839        if ($hash || ($hash_base && !defined $file_name)) {
3840                my $object_id = $hash || $hash_base;
3841
3842                my $git_command = git_cmd_str();
3843                open my $fd, "-|", "$git_command cat-file -t $object_id 2>/dev/null"
3844                        or die_error('404 Not Found', "Object does not exist");
3845                $type = <$fd>;
3846                chomp $type;
3847                close $fd
3848                        or die_error('404 Not Found', "Object does not exist");
3849
3850        # - hash_base and file_name
3851        } elsif ($hash_base && defined $file_name) {
3852                $file_name =~ s,/+$,,;
3853
3854                system(git_cmd(), "cat-file", '-e', $hash_base) == 0
3855                        or die_error('404 Not Found', "Base object does not exist");
3856
3857                # here errors should not hapen
3858                open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
3859                        or die_error(undef, "Open git-ls-tree failed");
3860                my $line = <$fd>;
3861                close $fd;
3862
3863                #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
3864                unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
3865                        die_error('404 Not Found', "File or directory for given base does not exist");
3866                }
3867                $type = $2;
3868                $hash = $3;
3869        } else {
3870                die_error('404 Not Found', "Not enough information to find object");
3871        }
3872
3873        print $cgi->redirect(-uri => href(action=>$type, -full=>1,
3874                                          hash=>$hash, hash_base=>$hash_base,
3875                                          file_name=>$file_name),
3876                             -status => '302 Found');
3877}
3878
3879sub git_blobdiff {
3880        my $format = shift || 'html';
3881
3882        my $fd;
3883        my @difftree;
3884        my %diffinfo;
3885        my $expires;
3886
3887        # preparing $fd and %diffinfo for git_patchset_body
3888        # new style URI
3889        if (defined $hash_base && defined $hash_parent_base) {
3890                if (defined $file_name) {
3891                        # read raw output
3892                        open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3893                                $hash_parent_base, $hash_base,
3894                                "--", $file_name
3895                                or die_error(undef, "Open git-diff-tree failed");
3896                        @difftree = map { chomp; $_ } <$fd>;
3897                        close $fd
3898                                or die_error(undef, "Reading git-diff-tree failed");
3899                        @difftree
3900                                or die_error('404 Not Found', "Blob diff not found");
3901
3902                } elsif (defined $hash &&
3903                         $hash =~ /[0-9a-fA-F]{40}/) {
3904                        # try to find filename from $hash
3905
3906                        # read filtered raw output
3907                        open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3908                                $hash_parent_base, $hash_base, "--"
3909                                or die_error(undef, "Open git-diff-tree failed");
3910                        @difftree =
3911                                # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
3912                                # $hash == to_id
3913                                grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
3914                                map { chomp; $_ } <$fd>;
3915                        close $fd
3916                                or die_error(undef, "Reading git-diff-tree failed");
3917                        @difftree
3918                                or die_error('404 Not Found', "Blob diff not found");
3919
3920                } else {
3921                        die_error('404 Not Found', "Missing one of the blob diff parameters");
3922                }
3923
3924                if (@difftree > 1) {
3925                        die_error('404 Not Found', "Ambiguous blob diff specification");
3926                }
3927
3928                %diffinfo = parse_difftree_raw_line($difftree[0]);
3929                $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
3930                $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
3931
3932                $hash_parent ||= $diffinfo{'from_id'};
3933                $hash        ||= $diffinfo{'to_id'};
3934
3935                # non-textual hash id's can be cached
3936                if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
3937                    $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
3938                        $expires = '+1d';
3939                }
3940
3941                # open patch output
3942                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3943                        '-p', $hash_parent_base, $hash_base,
3944                        "--", $file_name
3945                        or die_error(undef, "Open git-diff-tree failed");
3946        }
3947
3948        # old/legacy style URI
3949        if (!%diffinfo && # if new style URI failed
3950            defined $hash && defined $hash_parent) {
3951                # fake git-diff-tree raw output
3952                $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
3953                $diffinfo{'from_id'} = $hash_parent;
3954                $diffinfo{'to_id'}   = $hash;
3955                if (defined $file_name) {
3956                        if (defined $file_parent) {
3957                                $diffinfo{'status'} = '2';
3958                                $diffinfo{'from_file'} = $file_parent;
3959                                $diffinfo{'to_file'}   = $file_name;
3960                        } else { # assume not renamed
3961                                $diffinfo{'status'} = '1';
3962                                $diffinfo{'from_file'} = $file_name;
3963                                $diffinfo{'to_file'}   = $file_name;
3964                        }
3965                } else { # no filename given
3966                        $diffinfo{'status'} = '2';
3967                        $diffinfo{'from_file'} = $hash_parent;
3968                        $diffinfo{'to_file'}   = $hash;
3969                }
3970
3971                # non-textual hash id's can be cached
3972                if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
3973                    $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3974                        $expires = '+1d';
3975                }
3976
3977                # open patch output
3978                open $fd, "-|", git_cmd(), "diff", '-p', @diff_opts,
3979                        $hash_parent, $hash, "--"
3980                        or die_error(undef, "Open git-diff failed");
3981        } else  {
3982                die_error('404 Not Found', "Missing one of the blob diff parameters")
3983                        unless %diffinfo;
3984        }
3985
3986        # header
3987        if ($format eq 'html') {
3988                my $formats_nav =
3989                        $cgi->a({-href => href(action=>"blobdiff_plain",
3990                                               hash=>$hash, hash_parent=>$hash_parent,
3991                                               hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
3992                                               file_name=>$file_name, file_parent=>$file_parent)},
3993                                "raw");
3994                git_header_html(undef, $expires);
3995                if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3996                        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3997                        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3998                } else {
3999                        print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
4000                        print "<div class=\"title\">$hash vs $hash_parent</div>\n";
4001                }
4002                if (defined $file_name) {
4003                        git_print_page_path($file_name, "blob", $hash_base);
4004                } else {
4005                        print "<div class=\"page_path\"></div>\n";
4006                }
4007
4008        } elsif ($format eq 'plain') {
4009                print $cgi->header(
4010                        -type => 'text/plain',
4011                        -charset => 'utf-8',
4012                        -expires => $expires,
4013                        -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
4014
4015                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4016
4017        } else {
4018                die_error(undef, "Unknown blobdiff format");
4019        }
4020
4021        # patch
4022        if ($format eq 'html') {
4023                print "<div class=\"page_body\">\n";
4024
4025                git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
4026                close $fd;
4027
4028                print "</div>\n"; # class="page_body"
4029                git_footer_html();
4030
4031        } else {
4032                while (my $line = <$fd>) {
4033                        $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
4034                        $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
4035
4036                        print $line;
4037
4038                        last if $line =~ m!^\+\+\+!;
4039                }
4040                local $/ = undef;
4041                print <$fd>;
4042                close $fd;
4043        }
4044}
4045
4046sub git_blobdiff_plain {
4047        git_blobdiff('plain');
4048}
4049
4050sub git_commitdiff {
4051        my $format = shift || 'html';
4052        $hash ||= $hash_base || "HEAD";
4053        my %co = parse_commit($hash);
4054        if (!%co) {
4055                die_error(undef, "Unknown commit object");
4056        }
4057
4058        # we need to prepare $formats_nav before any parameter munging
4059        my $formats_nav;
4060        if ($format eq 'html') {
4061                $formats_nav =
4062                        $cgi->a({-href => href(action=>"commitdiff_plain",
4063                                               hash=>$hash, hash_parent=>$hash_parent)},
4064                                "raw");
4065
4066                if (defined $hash_parent) {
4067                        # commitdiff with two commits given
4068                        my $hash_parent_short = $hash_parent;
4069                        if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4070                                $hash_parent_short = substr($hash_parent, 0, 7);
4071                        }
4072                        $formats_nav .=
4073                                ' (from: ' .
4074                                $cgi->a({-href => href(action=>"commitdiff",
4075                                                       hash=>$hash_parent)},
4076                                        esc_html($hash_parent_short)) .
4077                                ')';
4078                } elsif (!$co{'parent'}) {
4079                        # --root commitdiff
4080                        $formats_nav .= ' (initial)';
4081                } elsif (scalar @{$co{'parents'}} == 1) {
4082                        # single parent commit
4083                        $formats_nav .=
4084                                ' (parent: ' .
4085                                $cgi->a({-href => href(action=>"commitdiff",
4086                                                       hash=>$co{'parent'})},
4087                                        esc_html(substr($co{'parent'}, 0, 7))) .
4088                                ')';
4089                } else {
4090                        # merge commit
4091                        $formats_nav .=
4092                                ' (merge: ' .
4093                                join(' ', map {
4094                                        $cgi->a({-href => href(action=>"commitdiff",
4095                                                               hash=>$_)},
4096                                                esc_html(substr($_, 0, 7)));
4097                                } @{$co{'parents'}} ) .
4098                                ')';
4099                }
4100        }
4101
4102        if (!defined $hash_parent) {
4103                $hash_parent = $co{'parent'} || '--root';
4104        }
4105
4106        # read commitdiff
4107        my $fd;
4108        my @difftree;
4109        if ($format eq 'html') {
4110                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4111                        "--no-commit-id", "--patch-with-raw", "--full-index",
4112                        $hash_parent, $hash, "--"
4113                        or die_error(undef, "Open git-diff-tree failed");
4114
4115                while (my $line = <$fd>) {
4116                        chomp $line;
4117                        # empty line ends raw part of diff-tree output
4118                        last unless $line;
4119                        push @difftree, $line;
4120                }
4121
4122        } elsif ($format eq 'plain') {
4123                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4124                        '-p', $hash_parent, $hash, "--"
4125                        or die_error(undef, "Open git-diff-tree failed");
4126
4127        } else {
4128                die_error(undef, "Unknown commitdiff format");
4129        }
4130
4131        # non-textual hash id's can be cached
4132        my $expires;
4133        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4134                $expires = "+1d";
4135        }
4136
4137        # write commit message
4138        if ($format eq 'html') {
4139                my $refs = git_get_references();
4140                my $ref = format_ref_marker($refs, $co{'id'});
4141
4142                git_header_html(undef, $expires);
4143                git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
4144                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
4145                git_print_authorship(\%co);
4146                print "<div class=\"page_body\">\n";
4147                if (@{$co{'comment'}} > 1) {
4148                        print "<div class=\"log\">\n";
4149                        git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
4150                        print "</div>\n"; # class="log"
4151                }
4152
4153        } elsif ($format eq 'plain') {
4154                my $refs = git_get_references("tags");
4155                my $tagname = git_get_rev_name_tags($hash);
4156                my $filename = basename($project) . "-$hash.patch";
4157
4158                print $cgi->header(
4159                        -type => 'text/plain',
4160                        -charset => 'utf-8',
4161                        -expires => $expires,
4162                        -content_disposition => 'inline; filename="' . "$filename" . '"');
4163                my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4164                print <<TEXT;
4165From: $co{'author'}
4166Date: $ad{'rfc2822'} ($ad{'tz_local'})
4167Subject: $co{'title'}
4168TEXT
4169                print "X-Git-Tag: $tagname\n" if $tagname;
4170                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4171
4172                foreach my $line (@{$co{'comment'}}) {
4173                        print "$line\n";
4174                }
4175                print "---\n\n";
4176        }
4177
4178        # write patch
4179        if ($format eq 'html') {
4180                git_difftree_body(\@difftree, $hash, $hash_parent);
4181                print "<br/>\n";
4182
4183                git_patchset_body($fd, \@difftree, $hash, $hash_parent);
4184                close $fd;
4185                print "</div>\n"; # class="page_body"
4186                git_footer_html();
4187
4188        } elsif ($format eq 'plain') {
4189                local $/ = undef;
4190                print <$fd>;
4191                close $fd
4192                        or print "Reading git-diff-tree failed\n";
4193        }
4194}
4195
4196sub git_commitdiff_plain {
4197        git_commitdiff('plain');
4198}
4199
4200sub git_history {
4201        if (!defined $hash_base) {
4202                $hash_base = git_get_head_hash($project);
4203        }
4204        if (!defined $page) {
4205                $page = 0;
4206        }
4207        my $ftype;
4208        my %co = parse_commit($hash_base);
4209        if (!%co) {
4210                die_error(undef, "Unknown commit object");
4211        }
4212
4213        my $refs = git_get_references();
4214        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
4215
4216        if (!defined $hash && defined $file_name) {
4217                $hash = git_get_hash_by_path($hash_base, $file_name);
4218        }
4219        if (defined $hash) {
4220                $ftype = git_get_type($hash);
4221        }
4222
4223        open my $fd, "-|",
4224                git_cmd(), "rev-list", $limit, "--full-history", $hash_base, "--", $file_name
4225                        or die_error(undef, "Open git-rev-list-failed");
4226        my @revlist = map { chomp; $_ } <$fd>;
4227        close $fd
4228                or die_error(undef, "Reading git-rev-list failed");
4229
4230        my $paging_nav = '';
4231        if ($page > 0) {
4232                $paging_nav .=
4233                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4234                                               file_name=>$file_name)},
4235                                "first");
4236                $paging_nav .= " &sdot; " .
4237                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4238                                               file_name=>$file_name, page=>$page-1),
4239                                 -accesskey => "p", -title => "Alt-p"}, "prev");
4240        } else {
4241                $paging_nav .= "first";
4242                $paging_nav .= " &sdot; prev";
4243        }
4244        if ($#revlist >= (100 * ($page+1)-1)) {
4245                $paging_nav .= " &sdot; " .
4246                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4247                                               file_name=>$file_name, page=>$page+1),
4248                                 -accesskey => "n", -title => "Alt-n"}, "next");
4249        } else {
4250                $paging_nav .= " &sdot; next";
4251        }
4252        my $next_link = '';
4253        if ($#revlist >= (100 * ($page+1)-1)) {
4254                $next_link =
4255                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4256                                               file_name=>$file_name, page=>$page+1),
4257                                 -title => "Alt-n"}, "next");
4258        }
4259
4260        git_header_html();
4261        git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
4262        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4263        git_print_page_path($file_name, $ftype, $hash_base);
4264
4265        git_history_body(\@revlist, ($page * 100), $#revlist,
4266                         $refs, $hash_base, $ftype, $next_link);
4267
4268        git_footer_html();
4269}
4270
4271sub git_search {
4272        my ($have_search) = gitweb_check_feature('search');
4273        if (!$have_search) {
4274                die_error('403 Permission denied', "Permission denied");
4275        }
4276        if (!defined $searchtext) {
4277                die_error(undef, "Text field empty");
4278        }
4279        if (!defined $hash) {
4280                $hash = git_get_head_hash($project);
4281        }
4282        my %co = parse_commit($hash);
4283        if (!%co) {
4284                die_error(undef, "Unknown commit object");
4285        }
4286        if (!defined $page) {
4287                $page = 0;
4288        }
4289
4290        $searchtype ||= 'commit';
4291        if ($searchtype eq 'pickaxe') {
4292                # pickaxe may take all resources of your box and run for several minutes
4293                # with every query - so decide by yourself how public you make this feature
4294                my ($have_pickaxe) = gitweb_check_feature('pickaxe');
4295                if (!$have_pickaxe) {
4296                        die_error('403 Permission denied', "Permission denied");
4297                }
4298        }
4299
4300        git_header_html();
4301
4302        if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
4303                my $greptype;
4304                if ($searchtype eq 'commit') {
4305                        $greptype = "--grep=";
4306                } elsif ($searchtype eq 'author') {
4307                        $greptype = "--author=";
4308                } elsif ($searchtype eq 'committer') {
4309                        $greptype = "--committer=";
4310                }
4311                open my $fd, "-|", git_cmd(), "rev-list",
4312                        ("--max-count=" . (100 * ($page+1))),
4313                        ($greptype . $searchtext),
4314                        $hash, "--"
4315                        or next;
4316                my @revlist = map { chomp; $_ } <$fd>;
4317                close $fd;
4318
4319                my $paging_nav = '';
4320                if ($page > 0) {
4321                        $paging_nav .=
4322                                $cgi->a({-href => href(action=>"search", hash=>$hash,
4323                                                       searchtext=>$searchtext, searchtype=>$searchtype)},
4324                                        "first");
4325                        $paging_nav .= " &sdot; " .
4326                                $cgi->a({-href => href(action=>"search", hash=>$hash,
4327                                                       searchtext=>$searchtext, searchtype=>$searchtype,
4328                                                       page=>$page-1),
4329                                         -accesskey => "p", -title => "Alt-p"}, "prev");
4330                } else {
4331                        $paging_nav .= "first";
4332                        $paging_nav .= " &sdot; prev";
4333                }
4334                if ($#revlist >= (100 * ($page+1)-1)) {
4335                        $paging_nav .= " &sdot; " .
4336                                $cgi->a({-href => href(action=>"search", hash=>$hash,
4337                                                       searchtext=>$searchtext, searchtype=>$searchtype,
4338                                                       page=>$page+1),
4339                                         -accesskey => "n", -title => "Alt-n"}, "next");
4340                } else {
4341                        $paging_nav .= " &sdot; next";
4342                }
4343                my $next_link = '';
4344                if ($#revlist >= (100 * ($page+1)-1)) {
4345                        $next_link =
4346                                $cgi->a({-href => href(action=>"search", hash=>$hash,
4347                                                       searchtext=>$searchtext, searchtype=>$searchtype,
4348                                                       page=>$page+1),
4349                                         -accesskey => "n", -title => "Alt-n"}, "next");
4350                }
4351
4352                git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
4353                git_print_header_div('commit', esc_html($co{'title'}), $hash);
4354                git_search_grep_body(\@revlist, ($page * 100), $#revlist, $next_link);
4355        }
4356
4357        if ($searchtype eq 'pickaxe') {
4358                git_print_page_nav('','', $hash,$co{'tree'},$hash);
4359                git_print_header_div('commit', esc_html($co{'title'}), $hash);
4360
4361                print "<table cellspacing=\"0\">\n";
4362                my $alternate = 1;
4363                $/ = "\n";
4364                my $git_command = git_cmd_str();
4365                open my $fd, "-|", "$git_command rev-list $hash | " .
4366                        "$git_command diff-tree -r --stdin -S\'$searchtext\'";
4367                undef %co;
4368                my @files;
4369                while (my $line = <$fd>) {
4370                        if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
4371                                my %set;
4372                                $set{'file'} = $6;
4373                                $set{'from_id'} = $3;
4374                                $set{'to_id'} = $4;
4375                                $set{'id'} = $set{'to_id'};
4376                                if ($set{'id'} =~ m/0{40}/) {
4377                                        $set{'id'} = $set{'from_id'};
4378                                }
4379                                if ($set{'id'} =~ m/0{40}/) {
4380                                        next;
4381                                }
4382                                push @files, \%set;
4383                        } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
4384                                if (%co) {
4385                                        if ($alternate) {
4386                                                print "<tr class=\"dark\">\n";
4387                                        } else {
4388                                                print "<tr class=\"light\">\n";
4389                                        }
4390                                        $alternate ^= 1;
4391                                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4392                                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
4393                                              "<td>" .
4394                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4395                                                      -class => "list subject"},
4396                                                      esc_html(chop_str($co{'title'}, 50)) . "<br/>");
4397                                        while (my $setref = shift @files) {
4398                                                my %set = %$setref;
4399                                                print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
4400                                                                             hash=>$set{'id'}, file_name=>$set{'file'}),
4401                                                              -class => "list"},
4402                                                              "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
4403                                                      "<br/>\n";
4404                                        }
4405                                        print "</td>\n" .
4406                                              "<td class=\"link\">" .
4407                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4408                                              " | " .
4409                                              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4410                                        print "</td>\n" .
4411                                              "</tr>\n";
4412                                }
4413                                %co = parse_commit($1);
4414                        }
4415                }
4416                close $fd;
4417
4418                print "</table>\n";
4419        }
4420        git_footer_html();
4421}
4422
4423sub git_search_help {
4424        git_header_html();
4425        git_print_page_nav('','', $hash,$hash,$hash);
4426        print <<EOT;
4427<dl>
4428<dt><b>commit</b></dt>
4429<dd>The commit messages and authorship information will be scanned for the given string.</dd>
4430<dt><b>author</b></dt>
4431<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given string.</dd>
4432<dt><b>committer</b></dt>
4433<dd>Name and e-mail of the committer and date of commit will be scanned for the given string.</dd>
4434EOT
4435        my ($have_pickaxe) = gitweb_check_feature('pickaxe');
4436        if ($have_pickaxe) {
4437                print <<EOT;
4438<dt><b>pickaxe</b></dt>
4439<dd>All commits that caused the string to appear or disappear from any file (changes that
4440added, removed or "modified" the string) will be listed. This search can take a while and
4441takes a lot of strain on the server, so please use it wisely.</dd>
4442EOT
4443        }
4444        print "</dl>\n";
4445        git_footer_html();
4446}
4447
4448sub git_shortlog {
4449        my $head = git_get_head_hash($project);
4450        if (!defined $hash) {
4451                $hash = $head;
4452        }
4453        if (!defined $page) {
4454                $page = 0;
4455        }
4456        my $refs = git_get_references();
4457
4458        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
4459        open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash, "--"
4460                or die_error(undef, "Open git-rev-list failed");
4461        my @revlist = map { chomp; $_ } <$fd>;
4462        close $fd;
4463
4464        my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
4465        my $next_link = '';
4466        if ($#revlist >= (100 * ($page+1)-1)) {
4467                $next_link =
4468                        $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
4469                                 -title => "Alt-n"}, "next");
4470        }
4471
4472
4473        git_header_html();
4474        git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
4475        git_print_header_div('summary', $project);
4476
4477        git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
4478
4479        git_footer_html();
4480}
4481
4482## ......................................................................
4483## feeds (RSS, Atom; OPML)
4484
4485sub git_feed {
4486        my $format = shift || 'atom';
4487        my ($have_blame) = gitweb_check_feature('blame');
4488
4489        # Atom: http://www.atomenabled.org/developers/syndication/
4490        # RSS:  http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
4491        if ($format ne 'rss' && $format ne 'atom') {
4492                die_error(undef, "Unknown web feed format");
4493        }
4494
4495        # log/feed of current (HEAD) branch, log of given branch, history of file/directory
4496        my $head = $hash || 'HEAD';
4497        open my $fd, "-|", git_cmd(), "rev-list", "--max-count=150",
4498                $head, "--", (defined $file_name ? $file_name : ())
4499                or die_error(undef, "Open git-rev-list failed");
4500        my @revlist = map { chomp; $_ } <$fd>;
4501        close $fd or die_error(undef, "Reading git-rev-list failed");
4502
4503        my %latest_commit;
4504        my %latest_date;
4505        my $content_type = "application/$format+xml";
4506        if (defined $cgi->http('HTTP_ACCEPT') &&
4507                 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
4508                # browser (feed reader) prefers text/xml
4509                $content_type = 'text/xml';
4510        }
4511        if (defined($revlist[0])) {
4512                %latest_commit = parse_commit($revlist[0]);
4513                %latest_date   = parse_date($latest_commit{'author_epoch'});
4514                print $cgi->header(
4515                        -type => $content_type,
4516                        -charset => 'utf-8',
4517                        -last_modified => $latest_date{'rfc2822'});
4518        } else {
4519                print $cgi->header(
4520                        -type => $content_type,
4521                        -charset => 'utf-8');
4522        }
4523
4524        # Optimization: skip generating the body if client asks only
4525        # for Last-Modified date.
4526        return if ($cgi->request_method() eq 'HEAD');
4527
4528        # header variables
4529        my $title = "$site_name - $project/$action";
4530        my $feed_type = 'log';
4531        if (defined $hash) {
4532                $title .= " - '$hash'";
4533                $feed_type = 'branch log';
4534                if (defined $file_name) {
4535                        $title .= " :: $file_name";
4536                        $feed_type = 'history';
4537                }
4538        } elsif (defined $file_name) {
4539                $title .= " - $file_name";
4540                $feed_type = 'history';
4541        }
4542        $title .= " $feed_type";
4543        my $descr = git_get_project_description($project);
4544        if (defined $descr) {
4545                $descr = esc_html($descr);
4546        } else {
4547                $descr = "$project " .
4548                         ($format eq 'rss' ? 'RSS' : 'Atom') .
4549                         " feed";
4550        }
4551        my $owner = git_get_project_owner($project);
4552        $owner = esc_html($owner);
4553
4554        #header
4555        my $alt_url;
4556        if (defined $file_name) {
4557                $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
4558        } elsif (defined $hash) {
4559                $alt_url = href(-full=>1, action=>"log", hash=>$hash);
4560        } else {
4561                $alt_url = href(-full=>1, action=>"summary");
4562        }
4563        print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
4564        if ($format eq 'rss') {
4565                print <<XML;
4566<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
4567<channel>
4568XML
4569                print "<title>$title</title>\n" .
4570                      "<link>$alt_url</link>\n" .
4571                      "<description>$descr</description>\n" .
4572                      "<language>en</language>\n";
4573        } elsif ($format eq 'atom') {
4574                print <<XML;
4575<feed xmlns="http://www.w3.org/2005/Atom">
4576XML
4577                print "<title>$title</title>\n" .
4578                      "<subtitle>$descr</subtitle>\n" .
4579                      '<link rel="alternate" type="text/html" href="' .
4580                      $alt_url . '" />' . "\n" .
4581                      '<link rel="self" type="' . $content_type . '" href="' .
4582                      $cgi->self_url() . '" />' . "\n" .
4583                      "<id>" . href(-full=>1) . "</id>\n" .
4584                      # use project owner for feed author
4585                      "<author><name>$owner</name></author>\n";
4586                if (defined $favicon) {
4587                        print "<icon>" . esc_url($favicon) . "</icon>\n";
4588                }
4589                if (defined $logo_url) {
4590                        # not twice as wide as tall: 72 x 27 pixels
4591                        print "<logo>" . esc_url($logo) . "</logo>\n";
4592                }
4593                if (! %latest_date) {
4594                        # dummy date to keep the feed valid until commits trickle in:
4595                        print "<updated>1970-01-01T00:00:00Z</updated>\n";
4596                } else {
4597                        print "<updated>$latest_date{'iso-8601'}</updated>\n";
4598                }
4599        }
4600
4601        # contents
4602        for (my $i = 0; $i <= $#revlist; $i++) {
4603                my $commit = $revlist[$i];
4604                my %co = parse_commit($commit);
4605                # we read 150, we always show 30 and the ones more recent than 48 hours
4606                if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
4607                        last;
4608                }
4609                my %cd = parse_date($co{'author_epoch'});
4610
4611                # get list of changed files
4612                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4613                        $co{'parent'}, $co{'id'}, "--", (defined $file_name ? $file_name : ())
4614                        or next;
4615                my @difftree = map { chomp; $_ } <$fd>;
4616                close $fd
4617                        or next;
4618
4619                # print element (entry, item)
4620                my $co_url = href(-full=>1, action=>"commit", hash=>$commit);
4621                if ($format eq 'rss') {
4622                        print "<item>\n" .
4623                              "<title>" . esc_html($co{'title'}) . "</title>\n" .
4624                              "<author>" . esc_html($co{'author'}) . "</author>\n" .
4625                              "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
4626                              "<guid isPermaLink=\"true\">$co_url</guid>\n" .
4627                              "<link>$co_url</link>\n" .
4628                              "<description>" . esc_html($co{'title'}) . "</description>\n" .
4629                              "<content:encoded>" .
4630                              "<![CDATA[\n";
4631                } elsif ($format eq 'atom') {
4632                        print "<entry>\n" .
4633                              "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
4634                              "<updated>$cd{'iso-8601'}</updated>\n" .
4635                              "<author>\n" .
4636                              "  <name>" . esc_html($co{'author_name'}) . "</name>\n";
4637                        if ($co{'author_email'}) {
4638                                print "  <email>" . esc_html($co{'author_email'}) . "</email>\n";
4639                        }
4640                        print "</author>\n" .
4641                              # use committer for contributor
4642                              "<contributor>\n" .
4643                              "  <name>" . esc_html($co{'committer_name'}) . "</name>\n";
4644                        if ($co{'committer_email'}) {
4645                                print "  <email>" . esc_html($co{'committer_email'}) . "</email>\n";
4646                        }
4647                        print "</contributor>\n" .
4648                              "<published>$cd{'iso-8601'}</published>\n" .
4649                              "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
4650                              "<id>$co_url</id>\n" .
4651                              "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
4652                              "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
4653                }
4654                my $comment = $co{'comment'};
4655                print "<pre>\n";
4656                foreach my $line (@$comment) {
4657                        $line = esc_html($line);
4658                        print "$line\n";
4659                }
4660                print "</pre><ul>\n";
4661                foreach my $difftree_line (@difftree) {
4662                        my %difftree = parse_difftree_raw_line($difftree_line);
4663                        next if !$difftree{'from_id'};
4664
4665                        my $file = $difftree{'file'} || $difftree{'to_file'};
4666
4667                        print "<li>" .
4668                              "[" .
4669                              $cgi->a({-href => href(-full=>1, action=>"blobdiff",
4670                                                     hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
4671                                                     hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
4672                                                     file_name=>$file, file_parent=>$difftree{'from_file'}),
4673                                      -title => "diff"}, 'D');
4674                        if ($have_blame) {
4675                                print $cgi->a({-href => href(-full=>1, action=>"blame",
4676                                                             file_name=>$file, hash_base=>$commit),
4677                                              -title => "blame"}, 'B');
4678                        }
4679                        # if this is not a feed of a file history
4680                        if (!defined $file_name || $file_name ne $file) {
4681                                print $cgi->a({-href => href(-full=>1, action=>"history",
4682                                                             file_name=>$file, hash=>$commit),
4683                                              -title => "history"}, 'H');
4684                        }
4685                        $file = esc_path($file);
4686                        print "] ".
4687                              "$file</li>\n";
4688                }
4689                if ($format eq 'rss') {
4690                        print "</ul>]]>\n" .
4691                              "</content:encoded>\n" .
4692                              "</item>\n";
4693                } elsif ($format eq 'atom') {
4694                        print "</ul>\n</div>\n" .
4695                              "</content>\n" .
4696                              "</entry>\n";
4697                }
4698        }
4699
4700        # end of feed
4701        if ($format eq 'rss') {
4702                print "</channel>\n</rss>\n";
4703        }       elsif ($format eq 'atom') {
4704                print "</feed>\n";
4705        }
4706}
4707
4708sub git_rss {
4709        git_feed('rss');
4710}
4711
4712sub git_atom {
4713        git_feed('atom');
4714}
4715
4716sub git_opml {
4717        my @list = git_get_projects_list();
4718
4719        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
4720        print <<XML;
4721<?xml version="1.0" encoding="utf-8"?>
4722<opml version="1.0">
4723<head>
4724  <title>$site_name OPML Export</title>
4725</head>
4726<body>
4727<outline text="git RSS feeds">
4728XML
4729
4730        foreach my $pr (@list) {
4731                my %proj = %$pr;
4732                my $head = git_get_head_hash($proj{'path'});
4733                if (!defined $head) {
4734                        next;
4735                }
4736                $git_dir = "$projectroot/$proj{'path'}";
4737                my %co = parse_commit($head);
4738                if (!%co) {
4739                        next;
4740                }
4741
4742                my $path = esc_html(chop_str($proj{'path'}, 25, 5));
4743                my $rss  = "$my_url?p=$proj{'path'};a=rss";
4744                my $html = "$my_url?p=$proj{'path'};a=summary";
4745                print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
4746        }
4747        print <<XML;
4748</outline>
4749</body>
4750</opml>
4751XML
4752}