2db99c360086498fc3cca1d409e08c8e9aa28f90
   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++" || $ENV{'SERVER_NAME'} || "Untitled";
  43
  44# html text to include at home page
  45our $home_text = "++GITWEB_HOMETEXT++";
  46
  47# URI of default stylesheet
  48our $stylesheet = "++GITWEB_CSS++";
  49# URI of GIT logo
  50our $logo = "++GITWEB_LOGO++";
  51
  52# source of projects list
  53our $projects_list = "++GITWEB_LIST++";
  54
  55# list of git base URLs used for URL to where fetch project from,
  56# i.e. full URL is "$git_base_url/$project"
  57our @git_base_url_list = ("++GITWEB_BASE_URL++");
  58
  59# default blob_plain mimetype and default charset for text/plain blob
  60our $default_blob_plain_mimetype = 'text/plain';
  61our $default_text_plain_charset  = undef;
  62
  63# file to use for guessing MIME types before trying /etc/mime.types
  64# (relative to the current git repository)
  65our $mimetypes_file = undef;
  66
  67# You define site-wide feature defaults here; override them with
  68# $GITWEB_CONFIG as necessary.
  69our %feature = (
  70        # feature => {
  71        #       'sub' => feature-sub (subroutine),
  72        #       'override' => allow-override (boolean),
  73        #       'default' => [ default options...] (array reference)}
  74        #
  75        # if feature is overridable (it means that allow-override has true value,
  76        # then feature-sub will be called with default options as parameters;
  77        # return value of feature-sub indicates if to enable specified feature
  78        #
  79        # use gitweb_check_feature(<feature>) to check if <feature> is enabled
  80
  81        'blame' => {
  82                'sub' => \&feature_blame,
  83                'override' => 0,
  84                'default' => [0]},
  85
  86        'snapshot' => {
  87                'sub' => \&feature_snapshot,
  88                'override' => 0,
  89                #         => [content-encoding, suffix, program]
  90                'default' => ['x-gzip', 'gz', 'gzip']},
  91);
  92
  93sub gitweb_check_feature {
  94        my ($name) = @_;
  95        return undef unless exists $feature{$name};
  96        my ($sub, $override, @defaults) = (
  97                $feature{$name}{'sub'},
  98                $feature{$name}{'override'},
  99                @{$feature{$name}{'default'}});
 100        if (!$override) { return @defaults; }
 101        return $sub->(@defaults);
 102}
 103
 104# To enable system wide have in $GITWEB_CONFIG
 105# $feature{'blame'}{'default'} = [1];
 106# To have project specific config enable override in $GITWEB_CONFIG
 107# $feature{'blame'}{'override'} = 1;
 108# and in project config gitweb.blame = 0|1;
 109
 110sub feature_blame {
 111        my ($val) = git_get_project_config('blame', '--bool');
 112
 113        if ($val eq 'true') {
 114                return 1;
 115        } elsif ($val eq 'false') {
 116                return 0;
 117        }
 118
 119        return $_[0];
 120}
 121
 122# To disable system wide have in $GITWEB_CONFIG
 123# $feature{'snapshot'}{'default'} = [undef];
 124# To have project specific config enable override in $GITWEB_CONFIG
 125# $feature{'blame'}{'override'} = 1;
 126# and in project config  gitweb.snapshot = none|gzip|bzip2
 127
 128sub feature_snapshot {
 129        my ($ctype, $suffix, $command) = @_;
 130
 131        my ($val) = git_get_project_config('snapshot');
 132
 133        if ($val eq 'gzip') {
 134                return ('x-gzip', 'gz', 'gzip');
 135        } elsif ($val eq 'bzip2') {
 136                return ('x-bzip2', 'bz2', 'bzip2');
 137        } elsif ($val eq 'none') {
 138                return ();
 139        }
 140
 141        return ($ctype, $suffix, $command);
 142}
 143
 144our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
 145require $GITWEB_CONFIG if -e $GITWEB_CONFIG;
 146
 147# version of the core git binary
 148our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
 149
 150$projects_list ||= $projectroot;
 151
 152# ======================================================================
 153# input validation and dispatch
 154our $action = $cgi->param('a');
 155if (defined $action) {
 156        if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
 157                die_error(undef, "Invalid action parameter");
 158        }
 159}
 160
 161our $project = ($cgi->param('p') || $ENV{'PATH_INFO'});
 162if (defined $project) {
 163        $project =~ s|^/||;
 164        $project =~ s|/$||;
 165        $project = undef unless $project;
 166}
 167if (defined $project) {
 168        if (!validate_input($project)) {
 169                die_error(undef, "Invalid project parameter");
 170        }
 171        if (!(-d "$projectroot/$project")) {
 172                die_error(undef, "No such directory");
 173        }
 174        if (!(-e "$projectroot/$project/HEAD")) {
 175                die_error(undef, "No such project");
 176        }
 177        $ENV{'GIT_DIR'} = "$projectroot/$project";
 178}
 179
 180our $file_name = $cgi->param('f');
 181if (defined $file_name) {
 182        if (!validate_input($file_name)) {
 183                die_error(undef, "Invalid file parameter");
 184        }
 185}
 186
 187our $file_parent = $cgi->param('fp');
 188if (defined $file_parent) {
 189        if (!validate_input($file_parent)) {
 190                die_error(undef, "Invalid file parent parameter");
 191        }
 192}
 193
 194our $hash = $cgi->param('h');
 195if (defined $hash) {
 196        if (!validate_input($hash)) {
 197                die_error(undef, "Invalid hash parameter");
 198        }
 199}
 200
 201our $hash_parent = $cgi->param('hp');
 202if (defined $hash_parent) {
 203        if (!validate_input($hash_parent)) {
 204                die_error(undef, "Invalid hash parent parameter");
 205        }
 206}
 207
 208our $hash_base = $cgi->param('hb');
 209if (defined $hash_base) {
 210        if (!validate_input($hash_base)) {
 211                die_error(undef, "Invalid hash base parameter");
 212        }
 213}
 214
 215our $hash_parent_base = $cgi->param('hpb');
 216if (defined $hash_parent_base) {
 217        if (!validate_input($hash_parent_base)) {
 218                die_error(undef, "Invalid hash parent base parameter");
 219        }
 220}
 221
 222our $page = $cgi->param('pg');
 223if (defined $page) {
 224        if ($page =~ m/[^0-9]$/) {
 225                die_error(undef, "Invalid page parameter");
 226        }
 227}
 228
 229our $searchtext = $cgi->param('s');
 230if (defined $searchtext) {
 231        if ($searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
 232                die_error(undef, "Invalid search parameter");
 233        }
 234        $searchtext = quotemeta $searchtext;
 235}
 236
 237# dispatch
 238my %actions = (
 239        "blame" => \&git_blame2,
 240        "blobdiff" => \&git_blobdiff,
 241        "blobdiff_plain" => \&git_blobdiff_plain,
 242        "blob" => \&git_blob,
 243        "blob_plain" => \&git_blob_plain,
 244        "commitdiff" => \&git_commitdiff,
 245        "commitdiff_plain" => \&git_commitdiff_plain,
 246        "commit" => \&git_commit,
 247        "heads" => \&git_heads,
 248        "history" => \&git_history,
 249        "log" => \&git_log,
 250        "rss" => \&git_rss,
 251        "search" => \&git_search,
 252        "shortlog" => \&git_shortlog,
 253        "summary" => \&git_summary,
 254        "tag" => \&git_tag,
 255        "tags" => \&git_tags,
 256        "tree" => \&git_tree,
 257        "snapshot" => \&git_snapshot,
 258        # those below don't need $project
 259        "opml" => \&git_opml,
 260        "project_list" => \&git_project_list,
 261);
 262
 263if (defined $project) {
 264        $action ||= 'summary';
 265} else {
 266        $action ||= 'project_list';
 267}
 268if (!defined($actions{$action})) {
 269        die_error(undef, "Unknown action");
 270}
 271$actions{$action}->();
 272exit;
 273
 274## ======================================================================
 275## action links
 276
 277sub href(%) {
 278        my %params = @_;
 279
 280        my @mapping = (
 281                project => "p",
 282                action => "a",
 283                file_name => "f",
 284                file_parent => "fp",
 285                hash => "h",
 286                hash_parent => "hp",
 287                hash_base => "hb",
 288                hash_parent_base => "hpb",
 289                page => "pg",
 290                searchtext => "s",
 291        );
 292        my %mapping = @mapping;
 293
 294        $params{"project"} ||= $project;
 295
 296        my @result = ();
 297        for (my $i = 0; $i < @mapping; $i += 2) {
 298                my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
 299                if (defined $params{$name}) {
 300                        push @result, $symbol . "=" . esc_param($params{$name});
 301                }
 302        }
 303        return "$my_uri?" . join(';', @result);
 304}
 305
 306
 307## ======================================================================
 308## validation, quoting/unquoting and escaping
 309
 310sub validate_input {
 311        my $input = shift;
 312
 313        if ($input =~ m/^[0-9a-fA-F]{40}$/) {
 314                return $input;
 315        }
 316        if ($input =~ m/(^|\/)(|\.|\.\.)($|\/)/) {
 317                return undef;
 318        }
 319        if ($input =~ m/[^a-zA-Z0-9_\x80-\xff\ \t\.\/\-\+\#\~\%]/) {
 320                return undef;
 321        }
 322        return $input;
 323}
 324
 325# quote unsafe chars, but keep the slash, even when it's not
 326# correct, but quoted slashes look too horrible in bookmarks
 327sub esc_param {
 328        my $str = shift;
 329        $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
 330        $str =~ s/\+/%2B/g;
 331        $str =~ s/ /\+/g;
 332        return $str;
 333}
 334
 335# replace invalid utf8 character with SUBSTITUTION sequence
 336sub esc_html {
 337        my $str = shift;
 338        $str = decode("utf8", $str, Encode::FB_DEFAULT);
 339        $str = escapeHTML($str);
 340        $str =~ s/\014/^L/g; # escape FORM FEED (FF) character (e.g. in COPYING file)
 341        return $str;
 342}
 343
 344# git may return quoted and escaped filenames
 345sub unquote {
 346        my $str = shift;
 347        if ($str =~ m/^"(.*)"$/) {
 348                $str = $1;
 349                $str =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
 350        }
 351        return $str;
 352}
 353
 354# escape tabs (convert tabs to spaces)
 355sub untabify {
 356        my $line = shift;
 357
 358        while ((my $pos = index($line, "\t")) != -1) {
 359                if (my $count = (8 - ($pos % 8))) {
 360                        my $spaces = ' ' x $count;
 361                        $line =~ s/\t/$spaces/;
 362                }
 363        }
 364
 365        return $line;
 366}
 367
 368## ----------------------------------------------------------------------
 369## HTML aware string manipulation
 370
 371sub chop_str {
 372        my $str = shift;
 373        my $len = shift;
 374        my $add_len = shift || 10;
 375
 376        # allow only $len chars, but don't cut a word if it would fit in $add_len
 377        # if it doesn't fit, cut it if it's still longer than the dots we would add
 378        $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
 379        my $body = $1;
 380        my $tail = $2;
 381        if (length($tail) > 4) {
 382                $tail = " ...";
 383                $body =~ s/&[^;]*$//; # remove chopped character entities
 384        }
 385        return "$body$tail";
 386}
 387
 388## ----------------------------------------------------------------------
 389## functions returning short strings
 390
 391# CSS class for given age value (in seconds)
 392sub age_class {
 393        my $age = shift;
 394
 395        if ($age < 60*60*2) {
 396                return "age0";
 397        } elsif ($age < 60*60*24*2) {
 398                return "age1";
 399        } else {
 400                return "age2";
 401        }
 402}
 403
 404# convert age in seconds to "nn units ago" string
 405sub age_string {
 406        my $age = shift;
 407        my $age_str;
 408
 409        if ($age > 60*60*24*365*2) {
 410                $age_str = (int $age/60/60/24/365);
 411                $age_str .= " years ago";
 412        } elsif ($age > 60*60*24*(365/12)*2) {
 413                $age_str = int $age/60/60/24/(365/12);
 414                $age_str .= " months ago";
 415        } elsif ($age > 60*60*24*7*2) {
 416                $age_str = int $age/60/60/24/7;
 417                $age_str .= " weeks ago";
 418        } elsif ($age > 60*60*24*2) {
 419                $age_str = int $age/60/60/24;
 420                $age_str .= " days ago";
 421        } elsif ($age > 60*60*2) {
 422                $age_str = int $age/60/60;
 423                $age_str .= " hours ago";
 424        } elsif ($age > 60*2) {
 425                $age_str = int $age/60;
 426                $age_str .= " min ago";
 427        } elsif ($age > 2) {
 428                $age_str = int $age;
 429                $age_str .= " sec ago";
 430        } else {
 431                $age_str .= " right now";
 432        }
 433        return $age_str;
 434}
 435
 436# convert file mode in octal to symbolic file mode string
 437sub mode_str {
 438        my $mode = oct shift;
 439
 440        if (S_ISDIR($mode & S_IFMT)) {
 441                return 'drwxr-xr-x';
 442        } elsif (S_ISLNK($mode)) {
 443                return 'lrwxrwxrwx';
 444        } elsif (S_ISREG($mode)) {
 445                # git cares only about the executable bit
 446                if ($mode & S_IXUSR) {
 447                        return '-rwxr-xr-x';
 448                } else {
 449                        return '-rw-r--r--';
 450                };
 451        } else {
 452                return '----------';
 453        }
 454}
 455
 456# convert file mode in octal to file type string
 457sub file_type {
 458        my $mode = shift;
 459
 460        if ($mode !~ m/^[0-7]+$/) {
 461                return $mode;
 462        } else {
 463                $mode = oct $mode;
 464        }
 465
 466        if (S_ISDIR($mode & S_IFMT)) {
 467                return "directory";
 468        } elsif (S_ISLNK($mode)) {
 469                return "symlink";
 470        } elsif (S_ISREG($mode)) {
 471                return "file";
 472        } else {
 473                return "unknown";
 474        }
 475}
 476
 477## ----------------------------------------------------------------------
 478## functions returning short HTML fragments, or transforming HTML fragments
 479## which don't beling to other sections
 480
 481# format line of commit message or tag comment
 482sub format_log_line_html {
 483        my $line = shift;
 484
 485        $line = esc_html($line);
 486        $line =~ s/ /&nbsp;/g;
 487        if ($line =~ m/([0-9a-fA-F]{40})/) {
 488                my $hash_text = $1;
 489                if (git_get_type($hash_text) eq "commit") {
 490                        my $link =
 491                                $cgi->a({-href => href(action=>"commit", hash=>$hash_text),
 492                                        -class => "text"}, $hash_text);
 493                        $line =~ s/$hash_text/$link/;
 494                }
 495        }
 496        return $line;
 497}
 498
 499# format marker of refs pointing to given object
 500sub format_ref_marker {
 501        my ($refs, $id) = @_;
 502        my $markers = '';
 503
 504        if (defined $refs->{$id}) {
 505                foreach my $ref (@{$refs->{$id}}) {
 506                        my ($type, $name) = qw();
 507                        # e.g. tags/v2.6.11 or heads/next
 508                        if ($ref =~ m!^(.*?)s?/(.*)$!) {
 509                                $type = $1;
 510                                $name = $2;
 511                        } else {
 512                                $type = "ref";
 513                                $name = $ref;
 514                        }
 515
 516                        $markers .= " <span class=\"$type\">" . esc_html($name) . "</span>";
 517                }
 518        }
 519
 520        if ($markers) {
 521                return ' <span class="refs">'. $markers . '</span>';
 522        } else {
 523                return "";
 524        }
 525}
 526
 527# format, perhaps shortened and with markers, title line
 528sub format_subject_html {
 529        my ($long, $short, $href, $extra) = @_;
 530        $extra = '' unless defined($extra);
 531
 532        if (length($short) < length($long)) {
 533                return $cgi->a({-href => $href, -class => "list subject",
 534                                -title => $long},
 535                       esc_html($short) . $extra);
 536        } else {
 537                return $cgi->a({-href => $href, -class => "list subject"},
 538                       esc_html($long)  . $extra);
 539        }
 540}
 541
 542sub format_diff_line {
 543        my $line = shift;
 544        my $char = substr($line, 0, 1);
 545        my $diff_class = "";
 546
 547        chomp $line;
 548
 549        if ($char eq '+') {
 550                $diff_class = " add";
 551        } elsif ($char eq "-") {
 552                $diff_class = " rem";
 553        } elsif ($char eq "@") {
 554                $diff_class = " chunk_header";
 555        } elsif ($char eq "\\") {
 556                $diff_class = " incomplete";
 557        }
 558        $line = untabify($line);
 559        return "<div class=\"diff$diff_class\">" . esc_html($line) . "</div>\n";
 560}
 561
 562## ----------------------------------------------------------------------
 563## git utility subroutines, invoking git commands
 564
 565# get HEAD ref of given project as hash
 566sub git_get_head_hash {
 567        my $project = shift;
 568        my $oENV = $ENV{'GIT_DIR'};
 569        my $retval = undef;
 570        $ENV{'GIT_DIR'} = "$projectroot/$project";
 571        if (open my $fd, "-|", $GIT, "rev-parse", "--verify", "HEAD") {
 572                my $head = <$fd>;
 573                close $fd;
 574                if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
 575                        $retval = $1;
 576                }
 577        }
 578        if (defined $oENV) {
 579                $ENV{'GIT_DIR'} = $oENV;
 580        }
 581        return $retval;
 582}
 583
 584# get type of given object
 585sub git_get_type {
 586        my $hash = shift;
 587
 588        open my $fd, "-|", $GIT, "cat-file", '-t', $hash or return;
 589        my $type = <$fd>;
 590        close $fd or return;
 591        chomp $type;
 592        return $type;
 593}
 594
 595sub git_get_project_config {
 596        my ($key, $type) = @_;
 597
 598        return unless ($key);
 599        $key =~ s/^gitweb\.//;
 600        return if ($key =~ m/\W/);
 601
 602        my @x = ($GIT, 'repo-config');
 603        if (defined $type) { push @x, $type; }
 604        push @x, "--get";
 605        push @x, "gitweb.$key";
 606        my $val = qx(@x);
 607        chomp $val;
 608        return ($val);
 609}
 610
 611# get hash of given path at given ref
 612sub git_get_hash_by_path {
 613        my $base = shift;
 614        my $path = shift || return undef;
 615
 616        my $tree = $base;
 617
 618        open my $fd, "-|", $GIT, "ls-tree", $base, "--", $path
 619                or die_error(undef, "Open git-ls-tree failed");
 620        my $line = <$fd>;
 621        close $fd or return undef;
 622
 623        #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
 624        $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
 625        return $3;
 626}
 627
 628# converts symbolic name to hash
 629sub git_to_hash {
 630        my @params = @_;
 631        return undef unless @params;
 632
 633        open my $fd, "-|", $GIT, "rev-parse", @params
 634                or return undef;
 635        my @hashes = map { chomp; $_ } <$fd>;
 636        close $fd;
 637
 638        if (wantarray) {
 639                return @hashes;
 640        } elsif (scalar(@hashes) == 1) {
 641                # single hash
 642                return $hashes[0];
 643        } else {
 644                return \@hashes;
 645        }
 646}
 647
 648## ......................................................................
 649## git utility functions, directly accessing git repository
 650
 651# assumes that PATH is not symref
 652sub git_get_hash_by_ref {
 653        my $path = shift;
 654
 655        open my $fd, "$projectroot/$path" or return undef;
 656        my $head = <$fd>;
 657        close $fd;
 658        chomp $head;
 659        if ($head =~ m/^[0-9a-fA-F]{40}$/) {
 660                return $head;
 661        }
 662}
 663
 664sub git_get_project_description {
 665        my $path = shift;
 666
 667        open my $fd, "$projectroot/$path/description" or return undef;
 668        my $descr = <$fd>;
 669        close $fd;
 670        chomp $descr;
 671        return $descr;
 672}
 673
 674sub git_get_project_url_list {
 675        my $path = shift;
 676
 677        open my $fd, "$projectroot/$path/cloneurl" or return undef;
 678        my @git_project_url_list = map { chomp; $_ } <$fd>;
 679        close $fd;
 680
 681        return wantarray ? @git_project_url_list : \@git_project_url_list;
 682}
 683
 684sub git_get_projects_list {
 685        my @list;
 686
 687        if (-d $projects_list) {
 688                # search in directory
 689                my $dir = $projects_list;
 690                opendir my ($dh), $dir or return undef;
 691                while (my $dir = readdir($dh)) {
 692                        if (-e "$projectroot/$dir/HEAD") {
 693                                my $pr = {
 694                                        path => $dir,
 695                                };
 696                                push @list, $pr
 697                        }
 698                }
 699                closedir($dh);
 700        } elsif (-f $projects_list) {
 701                # read from file(url-encoded):
 702                # 'git%2Fgit.git Linus+Torvalds'
 703                # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
 704                # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
 705                open my ($fd), $projects_list or return undef;
 706                while (my $line = <$fd>) {
 707                        chomp $line;
 708                        my ($path, $owner) = split ' ', $line;
 709                        $path = unescape($path);
 710                        $owner = unescape($owner);
 711                        if (!defined $path) {
 712                                next;
 713                        }
 714                        if (-e "$projectroot/$path/HEAD") {
 715                                my $pr = {
 716                                        path => $path,
 717                                        owner => decode("utf8", $owner, Encode::FB_DEFAULT),
 718                                };
 719                                push @list, $pr
 720                        }
 721                }
 722                close $fd;
 723        }
 724        @list = sort {$a->{'path'} cmp $b->{'path'}} @list;
 725        return @list;
 726}
 727
 728sub git_get_project_owner {
 729        my $project = shift;
 730        my $owner;
 731
 732        return undef unless $project;
 733
 734        # read from file (url-encoded):
 735        # 'git%2Fgit.git Linus+Torvalds'
 736        # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
 737        # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
 738        if (-f $projects_list) {
 739                open (my $fd , $projects_list);
 740                while (my $line = <$fd>) {
 741                        chomp $line;
 742                        my ($pr, $ow) = split ' ', $line;
 743                        $pr = unescape($pr);
 744                        $ow = unescape($ow);
 745                        if ($pr eq $project) {
 746                                $owner = decode("utf8", $ow, Encode::FB_DEFAULT);
 747                                last;
 748                        }
 749                }
 750                close $fd;
 751        }
 752        if (!defined $owner) {
 753                $owner = get_file_owner("$projectroot/$project");
 754        }
 755
 756        return $owner;
 757}
 758
 759sub git_get_references {
 760        my $type = shift || "";
 761        my %refs;
 762        my $fd;
 763        # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c      refs/tags/v2.6.11
 764        # c39ae07f393806ccf406ef966e9a15afc43cc36a      refs/tags/v2.6.11^{}
 765        if (-f "$projectroot/$project/info/refs") {
 766                open $fd, "$projectroot/$project/info/refs"
 767                        or return;
 768        } else {
 769                open $fd, "-|", $GIT, "ls-remote", "."
 770                        or return;
 771        }
 772
 773        while (my $line = <$fd>) {
 774                chomp $line;
 775                if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?[^\^]+)/) {
 776                        if (defined $refs{$1}) {
 777                                push @{$refs{$1}}, $2;
 778                        } else {
 779                                $refs{$1} = [ $2 ];
 780                        }
 781                }
 782        }
 783        close $fd or return;
 784        return \%refs;
 785}
 786
 787sub git_get_following_references {
 788        my $hash = shift || return undef;
 789        my $type = shift;
 790        my $base = shift || $hash_base || "HEAD";
 791
 792        my $refs = git_get_references($type);
 793        open my $fd, "-|", $GIT, "rev-list", $base
 794                or return undef;
 795        my @commits = map { chomp; $_ } <$fd>;
 796        close $fd
 797                or return undef;
 798
 799        my @reflist;
 800        my $lastref;
 801
 802        foreach my $commit (@commits) {
 803                foreach my $ref (@{$refs->{$commit}}) {
 804                        $lastref = $ref;
 805                        push @reflist, $lastref;
 806                }
 807                if ($commit eq $hash) {
 808                        last;
 809                }
 810        }
 811
 812        return wantarray ? @reflist : $lastref;
 813}
 814
 815sub git_get_preceding_references {
 816        my $hash = shift || return undef;
 817        my $type = shift;
 818
 819        my $refs = git_get_references($type);
 820        open my $fd, "-|", $GIT, "rev-list", $hash
 821                or return undef;
 822        my @commits = map { chomp; $_ } <$fd>;
 823        close $fd
 824                or return undef;
 825
 826        my @reflist;
 827
 828        foreach my $commit (@commits) {
 829                foreach my $ref (@{$refs->{$commit}}) {
 830                        return $ref unless wantarray;
 831                        push @reflist, $ref;
 832                }
 833        }
 834
 835        return @reflist;
 836}
 837
 838sub git_get_rev_name_tags {
 839        my $hash = shift || return undef;
 840
 841        open my $fd, "-|", $GIT, "name-rev", "--tags", $hash
 842                or return;
 843        my $name_rev = <$fd>;
 844        close $fd;
 845
 846        if ($name_rev =~ m|^$hash tags/(.*)$|) {
 847                return $1;
 848        } else {
 849                # catches also '$hash undefined' output
 850                return undef;
 851        }
 852}
 853
 854## ----------------------------------------------------------------------
 855## parse to hash functions
 856
 857sub parse_date {
 858        my $epoch = shift;
 859        my $tz = shift || "-0000";
 860
 861        my %date;
 862        my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
 863        my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
 864        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
 865        $date{'hour'} = $hour;
 866        $date{'minute'} = $min;
 867        $date{'mday'} = $mday;
 868        $date{'day'} = $days[$wday];
 869        $date{'month'} = $months[$mon];
 870        $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
 871                           $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
 872        $date{'mday-time'} = sprintf "%d %s %02d:%02d",
 873                             $mday, $months[$mon], $hour ,$min;
 874
 875        $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
 876        my $local = $epoch + ((int $1 + ($2/60)) * 3600);
 877        ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
 878        $date{'hour_local'} = $hour;
 879        $date{'minute_local'} = $min;
 880        $date{'tz_local'} = $tz;
 881        return %date;
 882}
 883
 884sub parse_tag {
 885        my $tag_id = shift;
 886        my %tag;
 887        my @comment;
 888
 889        open my $fd, "-|", $GIT, "cat-file", "tag", $tag_id or return;
 890        $tag{'id'} = $tag_id;
 891        while (my $line = <$fd>) {
 892                chomp $line;
 893                if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
 894                        $tag{'object'} = $1;
 895                } elsif ($line =~ m/^type (.+)$/) {
 896                        $tag{'type'} = $1;
 897                } elsif ($line =~ m/^tag (.+)$/) {
 898                        $tag{'name'} = $1;
 899                } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
 900                        $tag{'author'} = $1;
 901                        $tag{'epoch'} = $2;
 902                        $tag{'tz'} = $3;
 903                } elsif ($line =~ m/--BEGIN/) {
 904                        push @comment, $line;
 905                        last;
 906                } elsif ($line eq "") {
 907                        last;
 908                }
 909        }
 910        push @comment, <$fd>;
 911        $tag{'comment'} = \@comment;
 912        close $fd or return;
 913        if (!defined $tag{'name'}) {
 914                return
 915        };
 916        return %tag
 917}
 918
 919sub parse_commit {
 920        my $commit_id = shift;
 921        my $commit_text = shift;
 922
 923        my @commit_lines;
 924        my %co;
 925
 926        if (defined $commit_text) {
 927                @commit_lines = @$commit_text;
 928        } else {
 929                $/ = "\0";
 930                open my $fd, "-|", $GIT, "rev-list", "--header", "--parents", "--max-count=1", $commit_id
 931                        or return;
 932                @commit_lines = split '\n', <$fd>;
 933                close $fd or return;
 934                $/ = "\n";
 935                pop @commit_lines;
 936        }
 937        my $header = shift @commit_lines;
 938        if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
 939                return;
 940        }
 941        ($co{'id'}, my @parents) = split ' ', $header;
 942        $co{'parents'} = \@parents;
 943        $co{'parent'} = $parents[0];
 944        while (my $line = shift @commit_lines) {
 945                last if $line eq "\n";
 946                if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
 947                        $co{'tree'} = $1;
 948                } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
 949                        $co{'author'} = $1;
 950                        $co{'author_epoch'} = $2;
 951                        $co{'author_tz'} = $3;
 952                        if ($co{'author'} =~ m/^([^<]+) </) {
 953                                $co{'author_name'} = $1;
 954                        } else {
 955                                $co{'author_name'} = $co{'author'};
 956                        }
 957                } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
 958                        $co{'committer'} = $1;
 959                        $co{'committer_epoch'} = $2;
 960                        $co{'committer_tz'} = $3;
 961                        $co{'committer_name'} = $co{'committer'};
 962                        $co{'committer_name'} =~ s/ <.*//;
 963                }
 964        }
 965        if (!defined $co{'tree'}) {
 966                return;
 967        };
 968
 969        foreach my $title (@commit_lines) {
 970                $title =~ s/^    //;
 971                if ($title ne "") {
 972                        $co{'title'} = chop_str($title, 80, 5);
 973                        # remove leading stuff of merges to make the interesting part visible
 974                        if (length($title) > 50) {
 975                                $title =~ s/^Automatic //;
 976                                $title =~ s/^merge (of|with) /Merge ... /i;
 977                                if (length($title) > 50) {
 978                                        $title =~ s/(http|rsync):\/\///;
 979                                }
 980                                if (length($title) > 50) {
 981                                        $title =~ s/(master|www|rsync)\.//;
 982                                }
 983                                if (length($title) > 50) {
 984                                        $title =~ s/kernel.org:?//;
 985                                }
 986                                if (length($title) > 50) {
 987                                        $title =~ s/\/pub\/scm//;
 988                                }
 989                        }
 990                        $co{'title_short'} = chop_str($title, 50, 5);
 991                        last;
 992                }
 993        }
 994        # remove added spaces
 995        foreach my $line (@commit_lines) {
 996                $line =~ s/^    //;
 997        }
 998        $co{'comment'} = \@commit_lines;
 999
1000        my $age = time - $co{'committer_epoch'};
1001        $co{'age'} = $age;
1002        $co{'age_string'} = age_string($age);
1003        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1004        if ($age > 60*60*24*7*2) {
1005                $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1006                $co{'age_string_age'} = $co{'age_string'};
1007        } else {
1008                $co{'age_string_date'} = $co{'age_string'};
1009                $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1010        }
1011        return %co;
1012}
1013
1014# parse ref from ref_file, given by ref_id, with given type
1015sub parse_ref {
1016        my $ref_file = shift;
1017        my $ref_id = shift;
1018        my $type = shift || git_get_type($ref_id);
1019        my %ref_item;
1020
1021        $ref_item{'type'} = $type;
1022        $ref_item{'id'} = $ref_id;
1023        $ref_item{'epoch'} = 0;
1024        $ref_item{'age'} = "unknown";
1025        if ($type eq "tag") {
1026                my %tag = parse_tag($ref_id);
1027                $ref_item{'comment'} = $tag{'comment'};
1028                if ($tag{'type'} eq "commit") {
1029                        my %co = parse_commit($tag{'object'});
1030                        $ref_item{'epoch'} = $co{'committer_epoch'};
1031                        $ref_item{'age'} = $co{'age_string'};
1032                } elsif (defined($tag{'epoch'})) {
1033                        my $age = time - $tag{'epoch'};
1034                        $ref_item{'epoch'} = $tag{'epoch'};
1035                        $ref_item{'age'} = age_string($age);
1036                }
1037                $ref_item{'reftype'} = $tag{'type'};
1038                $ref_item{'name'} = $tag{'name'};
1039                $ref_item{'refid'} = $tag{'object'};
1040        } elsif ($type eq "commit"){
1041                my %co = parse_commit($ref_id);
1042                $ref_item{'reftype'} = "commit";
1043                $ref_item{'name'} = $ref_file;
1044                $ref_item{'title'} = $co{'title'};
1045                $ref_item{'refid'} = $ref_id;
1046                $ref_item{'epoch'} = $co{'committer_epoch'};
1047                $ref_item{'age'} = $co{'age_string'};
1048        } else {
1049                $ref_item{'reftype'} = $type;
1050                $ref_item{'name'} = $ref_file;
1051                $ref_item{'refid'} = $ref_id;
1052        }
1053
1054        return %ref_item;
1055}
1056
1057# parse line of git-diff-tree "raw" output
1058sub parse_difftree_raw_line {
1059        my $line = shift;
1060        my %res;
1061
1062        # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1063        # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1064        if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1065                $res{'from_mode'} = $1;
1066                $res{'to_mode'} = $2;
1067                $res{'from_id'} = $3;
1068                $res{'to_id'} = $4;
1069                $res{'status'} = $5;
1070                $res{'similarity'} = $6;
1071                if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1072                        ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1073                } else {
1074                        $res{'file'} = unquote($7);
1075                }
1076        }
1077        # 'c512b523472485aef4fff9e57b229d9d243c967f'
1078        #elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1079        #       $res{'commit'} = $1;
1080        #}
1081
1082        return wantarray ? %res : \%res;
1083}
1084
1085## ......................................................................
1086## parse to array of hashes functions
1087
1088sub git_get_refs_list {
1089        my $ref_dir = shift;
1090        my @reflist;
1091
1092        my @refs;
1093        my $pfxlen = length("$projectroot/$project/$ref_dir");
1094        File::Find::find(sub {
1095                return if (/^\./);
1096                if (-f $_) {
1097                        push @refs, substr($File::Find::name, $pfxlen + 1);
1098                }
1099        }, "$projectroot/$project/$ref_dir");
1100
1101        foreach my $ref_file (@refs) {
1102                my $ref_id = git_get_hash_by_ref("$project/$ref_dir/$ref_file");
1103                my $type = git_get_type($ref_id) || next;
1104                my %ref_item = parse_ref($ref_file, $ref_id, $type);
1105
1106                push @reflist, \%ref_item;
1107        }
1108        # sort refs by age
1109        @reflist = sort {$b->{'epoch'} <=> $a->{'epoch'}} @reflist;
1110        return \@reflist;
1111}
1112
1113## ----------------------------------------------------------------------
1114## filesystem-related functions
1115
1116sub get_file_owner {
1117        my $path = shift;
1118
1119        my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1120        my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1121        if (!defined $gcos) {
1122                return undef;
1123        }
1124        my $owner = $gcos;
1125        $owner =~ s/[,;].*$//;
1126        return decode("utf8", $owner, Encode::FB_DEFAULT);
1127}
1128
1129## ......................................................................
1130## mimetype related functions
1131
1132sub mimetype_guess_file {
1133        my $filename = shift;
1134        my $mimemap = shift;
1135        -r $mimemap or return undef;
1136
1137        my %mimemap;
1138        open(MIME, $mimemap) or return undef;
1139        while (<MIME>) {
1140                next if m/^#/; # skip comments
1141                my ($mime, $exts) = split(/\t+/);
1142                if (defined $exts) {
1143                        my @exts = split(/\s+/, $exts);
1144                        foreach my $ext (@exts) {
1145                                $mimemap{$ext} = $mime;
1146                        }
1147                }
1148        }
1149        close(MIME);
1150
1151        $filename =~ /\.(.*?)$/;
1152        return $mimemap{$1};
1153}
1154
1155sub mimetype_guess {
1156        my $filename = shift;
1157        my $mime;
1158        $filename =~ /\./ or return undef;
1159
1160        if ($mimetypes_file) {
1161                my $file = $mimetypes_file;
1162                if ($file !~ m!^/!) { # if it is relative path
1163                        # it is relative to project
1164                        $file = "$projectroot/$project/$file";
1165                }
1166                $mime = mimetype_guess_file($filename, $file);
1167        }
1168        $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1169        return $mime;
1170}
1171
1172sub blob_mimetype {
1173        my $fd = shift;
1174        my $filename = shift;
1175
1176        if ($filename) {
1177                my $mime = mimetype_guess($filename);
1178                $mime and return $mime;
1179        }
1180
1181        # just in case
1182        return $default_blob_plain_mimetype unless $fd;
1183
1184        if (-T $fd) {
1185                return 'text/plain' .
1186                       ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1187        } elsif (! $filename) {
1188                return 'application/octet-stream';
1189        } elsif ($filename =~ m/\.png$/i) {
1190                return 'image/png';
1191        } elsif ($filename =~ m/\.gif$/i) {
1192                return 'image/gif';
1193        } elsif ($filename =~ m/\.jpe?g$/i) {
1194                return 'image/jpeg';
1195        } else {
1196                return 'application/octet-stream';
1197        }
1198}
1199
1200## ======================================================================
1201## functions printing HTML: header, footer, error page
1202
1203sub git_header_html {
1204        my $status = shift || "200 OK";
1205        my $expires = shift;
1206
1207        my $title = "$site_name git";
1208        if (defined $project) {
1209                $title .= " - $project";
1210                if (defined $action) {
1211                        $title .= "/$action";
1212                        if (defined $file_name) {
1213                                $title .= " - $file_name";
1214                                if ($action eq "tree" && $file_name !~ m|/$|) {
1215                                        $title .= "/";
1216                                }
1217                        }
1218                }
1219        }
1220        my $content_type;
1221        # require explicit support from the UA if we are to send the page as
1222        # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1223        # we have to do this because MSIE sometimes globs '*/*', pretending to
1224        # support xhtml+xml but choking when it gets what it asked for.
1225        if (defined $cgi->http('HTTP_ACCEPT') &&
1226            $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1227            $cgi->Accept('application/xhtml+xml') != 0) {
1228                $content_type = 'application/xhtml+xml';
1229        } else {
1230                $content_type = 'text/html';
1231        }
1232        print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1233                           -status=> $status, -expires => $expires);
1234        print <<EOF;
1235<?xml version="1.0" encoding="utf-8"?>
1236<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1237<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1238<!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1239<!-- git core binaries version $git_version -->
1240<head>
1241<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1242<meta name="generator" content="gitweb/$version git/$git_version"/>
1243<meta name="robots" content="index, nofollow"/>
1244<title>$title</title>
1245<link rel="stylesheet" type="text/css" href="$stylesheet"/>
1246EOF
1247        if (defined $project) {
1248                printf('<link rel="alternate" title="%s log" '.
1249                       'href="%s" type="application/rss+xml"/>'."\n",
1250                       esc_param($project), href(action=>"rss"));
1251        }
1252
1253        print "</head>\n" .
1254              "<body>\n" .
1255              "<div class=\"page_header\">\n" .
1256              "<a href=\"http://www.kernel.org/pub/software/scm/git/docs/\" title=\"git documentation\">" .
1257              "<img src=\"$logo\" width=\"72\" height=\"27\" alt=\"git\" style=\"float:right; border-width:0px;\"/>" .
1258              "</a>\n";
1259        print $cgi->a({-href => esc_param($home_link)}, $home_link_str) . " / ";
1260        if (defined $project) {
1261                print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1262                if (defined $action) {
1263                        print " / $action";
1264                }
1265                print "\n";
1266                if (!defined $searchtext) {
1267                        $searchtext = "";
1268                }
1269                my $search_hash;
1270                if (defined $hash_base) {
1271                        $search_hash = $hash_base;
1272                } elsif (defined $hash) {
1273                        $search_hash = $hash;
1274                } else {
1275                        $search_hash = "HEAD";
1276                }
1277                $cgi->param("a", "search");
1278                $cgi->param("h", $search_hash);
1279                print $cgi->startform(-method => "get", -action => $my_uri) .
1280                      "<div class=\"search\">\n" .
1281                      $cgi->hidden(-name => "p") . "\n" .
1282                      $cgi->hidden(-name => "a") . "\n" .
1283                      $cgi->hidden(-name => "h") . "\n" .
1284                      $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1285                      "</div>" .
1286                      $cgi->end_form() . "\n";
1287        }
1288        print "</div>\n";
1289}
1290
1291sub git_footer_html {
1292        print "<div class=\"page_footer\">\n";
1293        if (defined $project) {
1294                my $descr = git_get_project_description($project);
1295                if (defined $descr) {
1296                        print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1297                }
1298                print $cgi->a({-href => href(action=>"rss"), -class => "rss_logo"}, "RSS") . "\n";
1299        } else {
1300                print $cgi->a({-href => href(action=>"opml"), -class => "rss_logo"}, "OPML") . "\n";
1301        }
1302        print "</div>\n" .
1303              "</body>\n" .
1304              "</html>";
1305}
1306
1307sub die_error {
1308        my $status = shift || "403 Forbidden";
1309        my $error = shift || "Malformed query, file missing or permission denied";
1310
1311        git_header_html($status);
1312        print <<EOF;
1313<div class="page_body">
1314<br /><br />
1315$status - $error
1316<br />
1317</div>
1318EOF
1319        git_footer_html();
1320        exit;
1321}
1322
1323## ----------------------------------------------------------------------
1324## functions printing or outputting HTML: navigation
1325
1326sub git_print_page_nav {
1327        my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1328        $extra = '' if !defined $extra; # pager or formats
1329
1330        my @navs = qw(summary shortlog log commit commitdiff tree);
1331        if ($suppress) {
1332                @navs = grep { $_ ne $suppress } @navs;
1333        }
1334
1335        my %arg = map { $_ => {action=>$_} } @navs;
1336        if (defined $head) {
1337                for (qw(commit commitdiff)) {
1338                        $arg{$_}{hash} = $head;
1339                }
1340                if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1341                        for (qw(shortlog log)) {
1342                                $arg{$_}{hash} = $head;
1343                        }
1344                }
1345        }
1346        $arg{tree}{hash} = $treehead if defined $treehead;
1347        $arg{tree}{hash_base} = $treebase if defined $treebase;
1348
1349        print "<div class=\"page_nav\">\n" .
1350                (join " | ",
1351                 map { $_ eq $current ?
1352                       $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1353                 } @navs);
1354        print "<br/>\n$extra<br/>\n" .
1355              "</div>\n";
1356}
1357
1358sub format_paging_nav {
1359        my ($action, $hash, $head, $page, $nrevs) = @_;
1360        my $paging_nav;
1361
1362
1363        if ($hash ne $head || $page) {
1364                $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1365        } else {
1366                $paging_nav .= "HEAD";
1367        }
1368
1369        if ($page > 0) {
1370                $paging_nav .= " &sdot; " .
1371                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1372                                 -accesskey => "p", -title => "Alt-p"}, "prev");
1373        } else {
1374                $paging_nav .= " &sdot; prev";
1375        }
1376
1377        if ($nrevs >= (100 * ($page+1)-1)) {
1378                $paging_nav .= " &sdot; " .
1379                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1380                                 -accesskey => "n", -title => "Alt-n"}, "next");
1381        } else {
1382                $paging_nav .= " &sdot; next";
1383        }
1384
1385        return $paging_nav;
1386}
1387
1388## ......................................................................
1389## functions printing or outputting HTML: div
1390
1391sub git_print_header_div {
1392        my ($action, $title, $hash, $hash_base) = @_;
1393        my %args = ();
1394
1395        $args{action} = $action;
1396        $args{hash} = $hash if $hash;
1397        $args{hash_base} = $hash_base if $hash_base;
1398
1399        print "<div class=\"header\">\n" .
1400              $cgi->a({-href => href(%args), -class => "title"},
1401              $title ? $title : $action) .
1402              "\n</div>\n";
1403}
1404
1405sub git_print_page_path {
1406        my $name = shift;
1407        my $type = shift;
1408        my $hb = shift;
1409
1410        if (!defined $name) {
1411                print "<div class=\"page_path\">/</div>\n";
1412        } elsif (defined $type && $type eq 'blob') {
1413                print "<div class=\"page_path\">";
1414                if (defined $hb) {
1415                        print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
1416                                                     hash_base=>$hb)},
1417                                      esc_html($name));
1418                } else {
1419                        print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name)},
1420                                      esc_html($name));
1421                }
1422                print "<br/></div>\n";
1423        } else {
1424                print "<div class=\"page_path\">" . esc_html($name) . "<br/></div>\n";
1425        }
1426}
1427
1428sub git_print_log {
1429        my $log = shift;
1430
1431        # remove leading empty lines
1432        while (defined $log->[0] && $log->[0] eq "") {
1433                shift @$log;
1434        }
1435
1436        # print log
1437        my $signoff = 0;
1438        my $empty = 0;
1439        foreach my $line (@$log) {
1440                # print only one empty line
1441                # do not print empty line after signoff
1442                if ($line eq "") {
1443                        next if ($empty || $signoff);
1444                        $empty = 1;
1445                } else {
1446                        $empty = 0;
1447                }
1448                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1449                        $signoff = 1;
1450                        print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1451                } else {
1452                        $signoff = 0;
1453                        print format_log_line_html($line) . "<br/>\n";
1454                }
1455        }
1456}
1457
1458sub git_print_simplified_log {
1459        my $log = shift;
1460        my $remove_title = shift;
1461
1462        shift @$log if $remove_title;
1463        # remove leading empty lines
1464        while (defined $log->[0] && $log->[0] eq "") {
1465                shift @$log;
1466        }
1467
1468        # simplify and print log
1469        my $empty = 0;
1470        foreach my $line (@$log) {
1471                # remove signoff lines
1472                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1473                        next;
1474                }
1475                # print only one empty line
1476                if ($line eq "") {
1477                        next if $empty;
1478                        $empty = 1;
1479                } else {
1480                        $empty = 0;
1481                }
1482                print format_log_line_html($line) . "<br/>\n";
1483        }
1484        # end with single empty line
1485        print "<br/>\n" unless $empty;
1486}
1487
1488## ......................................................................
1489## functions printing large fragments of HTML
1490
1491sub git_difftree_body {
1492        my ($difftree, $hash, $parent) = @_;
1493
1494        print "<div class=\"list_head\">\n";
1495        if ($#{$difftree} > 10) {
1496                print(($#{$difftree} + 1) . " files changed:\n");
1497        }
1498        print "</div>\n";
1499
1500        print "<table class=\"diff_tree\">\n";
1501        my $alternate = 0;
1502        foreach my $line (@{$difftree}) {
1503                my %diff = parse_difftree_raw_line($line);
1504
1505                if ($alternate) {
1506                        print "<tr class=\"dark\">\n";
1507                } else {
1508                        print "<tr class=\"light\">\n";
1509                }
1510                $alternate ^= 1;
1511
1512                my ($to_mode_oct, $to_mode_str, $to_file_type);
1513                my ($from_mode_oct, $from_mode_str, $from_file_type);
1514                if ($diff{'to_mode'} ne ('0' x 6)) {
1515                        $to_mode_oct = oct $diff{'to_mode'};
1516                        if (S_ISREG($to_mode_oct)) { # only for regular file
1517                                $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
1518                        }
1519                        $to_file_type = file_type($diff{'to_mode'});
1520                }
1521                if ($diff{'from_mode'} ne ('0' x 6)) {
1522                        $from_mode_oct = oct $diff{'from_mode'};
1523                        if (S_ISREG($to_mode_oct)) { # only for regular file
1524                                $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
1525                        }
1526                        $from_file_type = file_type($diff{'from_mode'});
1527                }
1528
1529                if ($diff{'status'} eq "A") { # created
1530                        my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
1531                        $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
1532                        $mode_chng   .= "]</span>";
1533                        print "<td>" .
1534                              $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1535                                                     hash_base=>$hash, file_name=>$diff{'file'}),
1536                                      -class => "list"}, esc_html($diff{'file'})) .
1537                              "</td>\n" .
1538                              "<td>$mode_chng</td>\n" .
1539                              "<td class=\"link\">" .
1540                              $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1541                                                     hash_base=>$hash, file_name=>$diff{'file'})},
1542                                      "blob") .
1543                              "</td>\n";
1544
1545                } elsif ($diff{'status'} eq "D") { # deleted
1546                        my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
1547                        print "<td>" .
1548                              $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1549                                                     hash_base=>$parent, file_name=>$diff{'file'}),
1550                                       -class => "list"}, esc_html($diff{'file'})) .
1551                              "</td>\n" .
1552                              "<td>$mode_chng</td>\n" .
1553                              "<td class=\"link\">" .
1554                              $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1555                                                     hash_base=>$parent, file_name=>$diff{'file'})},
1556                                      "blob") .
1557                              " | " .
1558                              $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1559                                                     file_name=>$diff{'file'})},\
1560                                      "history") .
1561                              "</td>\n";
1562
1563                } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
1564                        my $mode_chnge = "";
1565                        if ($diff{'from_mode'} != $diff{'to_mode'}) {
1566                                $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
1567                                if ($from_file_type != $to_file_type) {
1568                                        $mode_chnge .= " from $from_file_type to $to_file_type";
1569                                }
1570                                if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
1571                                        if ($from_mode_str && $to_mode_str) {
1572                                                $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
1573                                        } elsif ($to_mode_str) {
1574                                                $mode_chnge .= " mode: $to_mode_str";
1575                                        }
1576                                }
1577                                $mode_chnge .= "]</span>\n";
1578                        }
1579                        print "<td>";
1580                        if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1581                                print $cgi->a({-href => href(action=>"blobdiff",
1582                                                             hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1583                                                             hash_base=>$hash, hash_parent_base=>$parent,
1584                                                             file_name=>$diff{'file'}),
1585                                              -class => "list"}, esc_html($diff{'file'}));
1586                        } else { # only mode changed
1587                                print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1588                                                             hash_base=>$hash, file_name=>$diff{'file'}),
1589                                              -class => "list"}, esc_html($diff{'file'}));
1590                        }
1591                        print "</td>\n" .
1592                              "<td>$mode_chnge</td>\n" .
1593                              "<td class=\"link\">" .
1594                                $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1595                                                       hash_base=>$hash, file_name=>$diff{'file'})},
1596                                        "blob");
1597                        if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1598                                print " | " .
1599                                        $cgi->a({-href => href(action=>"blobdiff",
1600                                                               hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1601                                                               hash_base=>$hash, hash_parent_base=>$parent,
1602                                                               file_name=>$diff{'file'})},
1603                                                "diff");
1604                        }
1605                        print " | " .
1606                                $cgi->a({-href => href(action=>"history",
1607                                                       hash_base=>$hash, file_name=>$diff{'file'})},
1608                                        "history");
1609                        print "</td>\n";
1610
1611                } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
1612                        my %status_name = ('R' => 'moved', 'C' => 'copied');
1613                        my $nstatus = $status_name{$diff{'status'}};
1614                        my $mode_chng = "";
1615                        if ($diff{'from_mode'} != $diff{'to_mode'}) {
1616                                # mode also for directories, so we cannot use $to_mode_str
1617                                $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
1618                        }
1619                        print "<td>" .
1620                              $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1621                                                     hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
1622                                      -class => "list"}, esc_html($diff{'to_file'})) . "</td>\n" .
1623                              "<td><span class=\"file_status $nstatus\">[$nstatus from " .
1624                              $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
1625                                                     hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
1626                                      -class => "list"}, esc_html($diff{'from_file'})) .
1627                              " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
1628                              "<td class=\"link\">" .
1629                              $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1630                                                     hash=>$diff{'to_id'}, file_name=>$diff{'to_file'})},
1631                                      "blob");
1632                        if ($diff{'to_id'} ne $diff{'from_id'}) {
1633                                print " | " .
1634                                        $cgi->a({-href => href(action=>"blobdiff",
1635                                                               hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1636                                                               hash_base=>$hash, hash_parent_base=>$parent,
1637                                                               file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
1638                                                "diff");
1639                        }
1640                        print "</td>\n";
1641
1642                } # we should not encounter Unmerged (U) or Unknown (X) status
1643                print "</tr>\n";
1644        }
1645        print "</table>\n";
1646}
1647
1648sub git_patchset_body {
1649        my ($fd, $difftree, $hash, $hash_parent) = @_;
1650
1651        my $patch_idx = 0;
1652        my $in_header = 0;
1653        my $patch_found = 0;
1654        my $diffinfo;
1655
1656        print "<div class=\"patchset\">\n";
1657
1658        LINE:
1659        while (my $patch_line @$fd>) {
1660                chomp $patch_line;
1661
1662                if ($patch_line =~ m/^diff /) { # "git diff" header
1663                        # beginning of patch (in patchset)
1664                        if ($patch_found) {
1665                                # close previous patch
1666                                print "</div>\n"; # class="patch"
1667                        } else {
1668                                # first patch in patchset
1669                                $patch_found = 1;
1670                        }
1671                        print "<div class=\"patch\">\n";
1672
1673                        if (ref($difftree->[$patch_idx]) eq "HASH") {
1674                                $diffinfo = $difftree->[$patch_idx];
1675                        } else {
1676                                $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
1677                        }
1678                        $patch_idx++;
1679
1680                        # for now, no extended header, hence we skip empty patches
1681                        # companion to  next LINE if $in_header;
1682                        if ($diffinfo->{'from_id'} eq $diffinfo->{'to_id'}) { # no change
1683                                $in_header = 1;
1684                                next LINE;
1685                        }
1686
1687                        if ($diffinfo->{'status'} eq "A") { # added
1688                                print "<div class=\"diff_info\">" . file_type($diffinfo->{'to_mode'}) . ":" .
1689                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1690                                                             hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1691                                              $diffinfo->{'to_id'}) . "(new)" .
1692                                      "</div>\n"; # class="diff_info"
1693
1694                        } elsif ($diffinfo->{'status'} eq "D") { # deleted
1695                                print "<div class=\"diff_info\">" . file_type($diffinfo->{'from_mode'}) . ":" .
1696                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1697                                                             hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1698                                              $diffinfo->{'from_id'}) . "(deleted)" .
1699                                      "</div>\n"; # class="diff_info"
1700
1701                        } elsif ($diffinfo->{'status'} eq "R" || # renamed
1702                                 $diffinfo->{'status'} eq "C" || # copied
1703                                 $diffinfo->{'status'} eq "2") { # with two filenames (from git_blobdiff)
1704                                print "<div class=\"diff_info\">" .
1705                                      file_type($diffinfo->{'from_mode'}) . ":" .
1706                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1707                                                             hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'from_file'})},
1708                                              $diffinfo->{'from_id'}) .
1709                                      " -> " .
1710                                      file_type($diffinfo->{'to_mode'}) . ":" .
1711                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1712                                                             hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'to_file'})},
1713                                              $diffinfo->{'to_id'});
1714                                print "</div>\n"; # class="diff_info"
1715
1716                        } else { # modified, mode changed, ...
1717                                print "<div class=\"diff_info\">" .
1718                                      file_type($diffinfo->{'from_mode'}) . ":" .
1719                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1720                                                             hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1721                                              $diffinfo->{'from_id'}) .
1722                                      " -> " .
1723                                      file_type($diffinfo->{'to_mode'}) . ":" .
1724                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1725                                                             hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1726                                              $diffinfo->{'to_id'});
1727                                print "</div>\n"; # class="diff_info"
1728                        }
1729
1730                        #print "<div class=\"diff extended_header\">\n";
1731                        $in_header = 1;
1732                        next LINE;
1733                } # start of patch in patchset
1734
1735
1736                if ($in_header && $patch_line =~ m/^---/) {
1737                        #print "</div>\n"; # class="diff extended_header"
1738                        $in_header = 0;
1739
1740                        my $file = $diffinfo->{'from_file'};
1741                        $file  ||= $diffinfo->{'file'};
1742                        $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1743                                                       hash=>$diffinfo->{'from_id'}, file_name=>$file),
1744                                        -class => "list"}, esc_html($file));
1745                        $patch_line =~ s|a/.*$|a/$file|g;
1746                        print "<div class=\"diff from_file\">$patch_line</div>\n";
1747
1748                        $patch_line = <$fd>;
1749                        chomp $patch_line;
1750
1751                        #$patch_line =~ m/^+++/;
1752                        $file    = $diffinfo->{'to_file'};
1753                        $file  ||= $diffinfo->{'file'};
1754                        $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1755                                                       hash=>$diffinfo->{'to_id'}, file_name=>$file),
1756                                        -class => "list"}, esc_html($file));
1757                        $patch_line =~ s|b/.*|b/$file|g;
1758                        print "<div class=\"diff to_file\">$patch_line</div>\n";
1759
1760                        next LINE;
1761                }
1762                next LINE if $in_header;
1763
1764                print format_diff_line($patch_line);
1765        }
1766        print "</div>\n" if $patch_found; # class="patch"
1767
1768        print "</div>\n"; # class="patchset"
1769}
1770
1771# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1772
1773sub git_shortlog_body {
1774        # uses global variable $project
1775        my ($revlist, $from, $to, $refs, $extra) = @_;
1776
1777        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
1778        my $have_snapshot = (defined $ctype && defined $suffix);
1779
1780        $from = 0 unless defined $from;
1781        $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
1782
1783        print "<table class=\"shortlog\" cellspacing=\"0\">\n";
1784        my $alternate = 0;
1785        for (my $i = $from; $i <= $to; $i++) {
1786                my $commit = $revlist->[$i];
1787                #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
1788                my $ref = format_ref_marker($refs, $commit);
1789                my %co = parse_commit($commit);
1790                if ($alternate) {
1791                        print "<tr class=\"dark\">\n";
1792                } else {
1793                        print "<tr class=\"light\">\n";
1794                }
1795                $alternate ^= 1;
1796                # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
1797                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1798                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
1799                      "<td>";
1800                print format_subject_html($co{'title'}, $co{'title_short'},
1801                                          href(action=>"commit", hash=>$commit), $ref);
1802                print "</td>\n" .
1803                      "<td class=\"link\">" .
1804                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
1805                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
1806                if ($have_snapshot) {
1807                        print " | " .  $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
1808                }
1809                print "</td>\n" .
1810                      "</tr>\n";
1811        }
1812        if (defined $extra) {
1813                print "<tr>\n" .
1814                      "<td colspan=\"4\">$extra</td>\n" .
1815                      "</tr>\n";
1816        }
1817        print "</table>\n";
1818}
1819
1820sub git_history_body {
1821        # Warning: assumes constant type (blob or tree) during history
1822        my ($fd, $refs, $hash_base, $ftype, $extra) = @_;
1823
1824        print "<table class=\"history\" cellspacing=\"0\">\n";
1825        my $alternate = 0;
1826        while (my $line = <$fd>) {
1827                if ($line !~ m/^([0-9a-fA-F]{40})/) {
1828                        next;
1829                }
1830
1831                my $commit = $1;
1832                my %co = parse_commit($commit);
1833                if (!%co) {
1834                        next;
1835                }
1836
1837                my $ref = format_ref_marker($refs, $commit);
1838
1839                if ($alternate) {
1840                        print "<tr class=\"dark\">\n";
1841                } else {
1842                        print "<tr class=\"light\">\n";
1843                }
1844                $alternate ^= 1;
1845                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1846                      # shortlog uses      chop_str($co{'author_name'}, 10)
1847                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
1848                      "<td>";
1849                # originally git_history used chop_str($co{'title'}, 50)
1850                print format_subject_html($co{'title'}, $co{'title_short'},
1851                                          href(action=>"commit", hash=>$commit), $ref);
1852                print "</td>\n" .
1853                      "<td class=\"link\">" .
1854                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
1855                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
1856                      $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype);
1857
1858                if ($ftype eq 'blob') {
1859                        my $blob_current = git_get_hash_by_path($hash_base, $file_name);
1860                        my $blob_parent  = git_get_hash_by_path($commit, $file_name);
1861                        if (defined $blob_current && defined $blob_parent &&
1862                                        $blob_current ne $blob_parent) {
1863                                print " | " .
1864                                        $cgi->a({-href => href(action=>"blobdiff",
1865                                                               hash=>$blob_current, hash_parent=>$blob_parent,
1866                                                               hash_base=>$hash_base, hash_parent_base=>$commit,
1867                                                               file_name=>$file_name)},
1868                                                "diff to current");
1869                        }
1870                }
1871                print "</td>\n" .
1872                      "</tr>\n";
1873        }
1874        if (defined $extra) {
1875                print "<tr>\n" .
1876                      "<td colspan=\"4\">$extra</td>\n" .
1877                      "</tr>\n";
1878        }
1879        print "</table>\n";
1880}
1881
1882sub git_tags_body {
1883        # uses global variable $project
1884        my ($taglist, $from, $to, $extra) = @_;
1885        $from = 0 unless defined $from;
1886        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
1887
1888        print "<table class=\"tags\" cellspacing=\"0\">\n";
1889        my $alternate = 0;
1890        for (my $i = $from; $i <= $to; $i++) {
1891                my $entry = $taglist->[$i];
1892                my %tag = %$entry;
1893                my $comment_lines = $tag{'comment'};
1894                my $comment = shift @$comment_lines;
1895                my $comment_short;
1896                if (defined $comment) {
1897                        $comment_short = chop_str($comment, 30, 5);
1898                }
1899                if ($alternate) {
1900                        print "<tr class=\"dark\">\n";
1901                } else {
1902                        print "<tr class=\"light\">\n";
1903                }
1904                $alternate ^= 1;
1905                print "<td><i>$tag{'age'}</i></td>\n" .
1906                      "<td>" .
1907                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
1908                               -class => "list name"}, esc_html($tag{'name'})) .
1909                      "</td>\n" .
1910                      "<td>";
1911                if (defined $comment) {
1912                        print format_subject_html($comment, $comment_short,
1913                                                  href(action=>"tag", hash=>$tag{'id'}));
1914                }
1915                print "</td>\n" .
1916                      "<td class=\"selflink\">";
1917                if ($tag{'type'} eq "tag") {
1918                        print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
1919                } else {
1920                        print "&nbsp;";
1921                }
1922                print "</td>\n" .
1923                      "<td class=\"link\">" . " | " .
1924                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
1925                if ($tag{'reftype'} eq "commit") {
1926                        print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
1927                              " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'refid'})}, "log");
1928                } elsif ($tag{'reftype'} eq "blob") {
1929                        print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
1930                }
1931                print "</td>\n" .
1932                      "</tr>";
1933        }
1934        if (defined $extra) {
1935                print "<tr>\n" .
1936                      "<td colspan=\"5\">$extra</td>\n" .
1937                      "</tr>\n";
1938        }
1939        print "</table>\n";
1940}
1941
1942sub git_heads_body {
1943        # uses global variable $project
1944        my ($taglist, $head, $from, $to, $extra) = @_;
1945        $from = 0 unless defined $from;
1946        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
1947
1948        print "<table class=\"heads\" cellspacing=\"0\">\n";
1949        my $alternate = 0;
1950        for (my $i = $from; $i <= $to; $i++) {
1951                my $entry = $taglist->[$i];
1952                my %tag = %$entry;
1953                my $curr = $tag{'id'} eq $head;
1954                if ($alternate) {
1955                        print "<tr class=\"dark\">\n";
1956                } else {
1957                        print "<tr class=\"light\">\n";
1958                }
1959                $alternate ^= 1;
1960                print "<td><i>$tag{'age'}</i></td>\n" .
1961                      ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
1962                      $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'}),
1963                               -class => "list name"},esc_html($tag{'name'})) .
1964                      "</td>\n" .
1965                      "<td class=\"link\">" .
1966                      $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") . " | " .
1967                      $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log") .
1968                      "</td>\n" .
1969                      "</tr>";
1970        }
1971        if (defined $extra) {
1972                print "<tr>\n" .
1973                      "<td colspan=\"3\">$extra</td>\n" .
1974                      "</tr>\n";
1975        }
1976        print "</table>\n";
1977}
1978
1979## ======================================================================
1980## ======================================================================
1981## actions
1982
1983sub git_project_list {
1984        my $order = $cgi->param('o');
1985        if (defined $order && $order !~ m/project|descr|owner|age/) {
1986                die_error(undef, "Unknown order parameter");
1987        }
1988
1989        my @list = git_get_projects_list();
1990        my @projects;
1991        if (!@list) {
1992                die_error(undef, "No projects found");
1993        }
1994        foreach my $pr (@list) {
1995                my $head = git_get_head_hash($pr->{'path'});
1996                if (!defined $head) {
1997                        next;
1998                }
1999                $ENV{'GIT_DIR'} = "$projectroot/$pr->{'path'}";
2000                my %co = parse_commit($head);
2001                if (!%co) {
2002                        next;
2003                }
2004                $pr->{'commit'} = \%co;
2005                if (!defined $pr->{'descr'}) {
2006                        my $descr = git_get_project_description($pr->{'path'}) || "";
2007                        $pr->{'descr'} = chop_str($descr, 25, 5);
2008                }
2009                if (!defined $pr->{'owner'}) {
2010                        $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2011                }
2012                push @projects, $pr;
2013        }
2014
2015        git_header_html();
2016        if (-f $home_text) {
2017                print "<div class=\"index_include\">\n";
2018                open (my $fd, $home_text);
2019                print <$fd>;
2020                close $fd;
2021                print "</div>\n";
2022        }
2023        print "<table class=\"project_list\">\n" .
2024              "<tr>\n";
2025        $order ||= "project";
2026        if ($order eq "project") {
2027                @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2028                print "<th>Project</th>\n";
2029        } else {
2030                print "<th>" .
2031                      $cgi->a({-href => "$my_uri?" . esc_param("o=project"),
2032                               -class => "header"}, "Project") .
2033                      "</th>\n";
2034        }
2035        if ($order eq "descr") {
2036                @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2037                print "<th>Description</th>\n";
2038        } else {
2039                print "<th>" .
2040                      $cgi->a({-href => "$my_uri?" . esc_param("o=descr"),
2041                               -class => "header"}, "Description") .
2042                      "</th>\n";
2043        }
2044        if ($order eq "owner") {
2045                @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2046                print "<th>Owner</th>\n";
2047        } else {
2048                print "<th>" .
2049                      $cgi->a({-href => "$my_uri?" . esc_param("o=owner"),
2050                               -class => "header"}, "Owner") .
2051                      "</th>\n";
2052        }
2053        if ($order eq "age") {
2054                @projects = sort {$a->{'commit'}{'age'} <=> $b->{'commit'}{'age'}} @projects;
2055                print "<th>Last Change</th>\n";
2056        } else {
2057                print "<th>" .
2058                      $cgi->a({-href => "$my_uri?" . esc_param("o=age"),
2059                               -class => "header"}, "Last Change") .
2060                      "</th>\n";
2061        }
2062        print "<th></th>\n" .
2063              "</tr>\n";
2064        my $alternate = 0;
2065        foreach my $pr (@projects) {
2066                if ($alternate) {
2067                        print "<tr class=\"dark\">\n";
2068                } else {
2069                        print "<tr class=\"light\">\n";
2070                }
2071                $alternate ^= 1;
2072                print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2073                                        -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2074                      "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
2075                      "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2076                print "<td class=\"". age_class($pr->{'commit'}{'age'}) . "\">" .
2077                      $pr->{'commit'}{'age_string'} . "</td>\n" .
2078                      "<td class=\"link\">" .
2079                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2080                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
2081                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") .
2082                      "</td>\n" .
2083                      "</tr>\n";
2084        }
2085        print "</table>\n";
2086        git_footer_html();
2087}
2088
2089sub git_summary {
2090        my $descr = git_get_project_description($project) || "none";
2091        my $head = git_get_head_hash($project);
2092        my %co = parse_commit($head);
2093        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2094
2095        my $owner = git_get_project_owner($project);
2096
2097        my $refs = git_get_references();
2098        git_header_html();
2099        git_print_page_nav('summary','', $head);
2100
2101        print "<div class=\"title\">&nbsp;</div>\n";
2102        print "<table cellspacing=\"0\">\n" .
2103              "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
2104              "<tr><td>owner</td><td>$owner</td></tr>\n" .
2105              "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
2106        # use per project git URL list in $projectroot/$project/cloneurl
2107        # or make project git URL from git base URL and project name
2108        my $url_tag = "URL";
2109        my @url_list = git_get_project_url_list($project);
2110        @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
2111        foreach my $git_url (@url_list) {
2112                next unless $git_url;
2113                print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
2114                $url_tag = "";
2115        }
2116        print "</table>\n";
2117
2118        open my $fd, "-|", $GIT, "rev-list", "--max-count=17", git_get_head_hash($project)
2119                or die_error(undef, "Open git-rev-list failed");
2120        my @revlist = map { chomp; $_ } <$fd>;
2121        close $fd;
2122        git_print_header_div('shortlog');
2123        git_shortlog_body(\@revlist, 0, 15, $refs,
2124                          $cgi->a({-href => href(action=>"shortlog")}, "..."));
2125
2126        my $taglist = git_get_refs_list("refs/tags");
2127        if (defined @$taglist) {
2128                git_print_header_div('tags');
2129                git_tags_body($taglist, 0, 15,
2130                              $cgi->a({-href => href(action=>"tags")}, "..."));
2131        }
2132
2133        my $headlist = git_get_refs_list("refs/heads");
2134        if (defined @$headlist) {
2135                git_print_header_div('heads');
2136                git_heads_body($headlist, $head, 0, 15,
2137                               $cgi->a({-href => href(action=>"heads")}, "..."));
2138        }
2139
2140        git_footer_html();
2141}
2142
2143sub git_tag {
2144        my $head = git_get_head_hash($project);
2145        git_header_html();
2146        git_print_page_nav('','', $head,undef,$head);
2147        my %tag = parse_tag($hash);
2148        git_print_header_div('commit', esc_html($tag{'name'}), $hash);
2149        print "<div class=\"title_text\">\n" .
2150              "<table cellspacing=\"0\">\n" .
2151              "<tr>\n" .
2152              "<td>object</td>\n" .
2153              "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2154                               $tag{'object'}) . "</td>\n" .
2155              "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2156                                              $tag{'type'}) . "</td>\n" .
2157              "</tr>\n";
2158        if (defined($tag{'author'})) {
2159                my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
2160                print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
2161                print "<tr><td></td><td>" . $ad{'rfc2822'} .
2162                        sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
2163                        "</td></tr>\n";
2164        }
2165        print "</table>\n\n" .
2166              "</div>\n";
2167        print "<div class=\"page_body\">";
2168        my $comment = $tag{'comment'};
2169        foreach my $line (@$comment) {
2170                print esc_html($line) . "<br/>\n";
2171        }
2172        print "</div>\n";
2173        git_footer_html();
2174}
2175
2176sub git_blame2 {
2177        my $fd;
2178        my $ftype;
2179
2180        if (!gitweb_check_feature('blame')) {
2181                die_error('403 Permission denied', "Permission denied");
2182        }
2183        die_error('404 Not Found', "File name not defined") if (!$file_name);
2184        $hash_base ||= git_get_head_hash($project);
2185        die_error(undef, "Couldn't find base commit") unless ($hash_base);
2186        my %co = parse_commit($hash_base)
2187                or die_error(undef, "Reading commit failed");
2188        if (!defined $hash) {
2189                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2190                        or die_error(undef, "Error looking up file");
2191        }
2192        $ftype = git_get_type($hash);
2193        if ($ftype !~ "blob") {
2194                die_error("400 Bad Request", "Object is not a blob");
2195        }
2196        open ($fd, "-|", $GIT, "blame", '-l', $file_name, $hash_base)
2197                or die_error(undef, "Open git-blame failed");
2198        git_header_html();
2199        my $formats_nav =
2200                $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2201                        "blob") .
2202                " | " .
2203                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2204                        "head");
2205        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2206        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2207        git_print_page_path($file_name, $ftype, $hash_base);
2208        my @rev_color = (qw(light2 dark2));
2209        my $num_colors = scalar(@rev_color);
2210        my $current_color = 0;
2211        my $last_rev;
2212        print <<HTML;
2213<div class="page_body">
2214<table class="blame">
2215<tr><th>Commit</th><th>Line</th><th>Data</th></tr>
2216HTML
2217        while (<$fd>) {
2218                /^([0-9a-fA-F]{40}).*?(\d+)\)\s{1}(\s*.*)/;
2219                my $full_rev = $1;
2220                my $rev = substr($full_rev, 0, 8);
2221                my $lineno = $2;
2222                my $data = $3;
2223
2224                if (!defined $last_rev) {
2225                        $last_rev = $full_rev;
2226                } elsif ($last_rev ne $full_rev) {
2227                        $last_rev = $full_rev;
2228                        $current_color = ++$current_color % $num_colors;
2229                }
2230                print "<tr class=\"$rev_color[$current_color]\">\n";
2231                print "<td class=\"sha1\">" .
2232                        $cgi->a({-href => href(action=>"commit", hash=>$full_rev, file_name=>$file_name)},
2233                                esc_html($rev)) . "</td>\n";
2234                print "<td class=\"linenr\"><a id=\"l$lineno\" href=\"#l$lineno\" class=\"linenr\">" .
2235                      esc_html($lineno) . "</a></td>\n";
2236                print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
2237                print "</tr>\n";
2238        }
2239        print "</table>\n";
2240        print "</div>";
2241        close $fd
2242                or print "Reading blob failed\n";
2243        git_footer_html();
2244}
2245
2246sub git_blame {
2247        my $fd;
2248
2249        if (!gitweb_check_feature('blame')) {
2250                die_error('403 Permission denied', "Permission denied");
2251        }
2252        die_error('404 Not Found', "File name not defined") if (!$file_name);
2253        $hash_base ||= git_get_head_hash($project);
2254        die_error(undef, "Couldn't find base commit") unless ($hash_base);
2255        my %co = parse_commit($hash_base)
2256                or die_error(undef, "Reading commit failed");
2257        if (!defined $hash) {
2258                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2259                        or die_error(undef, "Error lookup file");
2260        }
2261        open ($fd, "-|", $GIT, "annotate", '-l', '-t', '-r', $file_name, $hash_base)
2262                or die_error(undef, "Open git-annotate failed");
2263        git_header_html();
2264        my $formats_nav =
2265                $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2266                        "blob") .
2267                " | " .
2268                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2269                        "head");
2270        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2271        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2272        git_print_page_path($file_name, 'blob', $hash_base);
2273        print "<div class=\"page_body\">\n";
2274        print <<HTML;
2275<table class="blame">
2276  <tr>
2277    <th>Commit</th>
2278    <th>Age</th>
2279    <th>Author</th>
2280    <th>Line</th>
2281    <th>Data</th>
2282  </tr>
2283HTML
2284        my @line_class = (qw(light dark));
2285        my $line_class_len = scalar (@line_class);
2286        my $line_class_num = $#line_class;
2287        while (my $line = <$fd>) {
2288                my $long_rev;
2289                my $short_rev;
2290                my $author;
2291                my $time;
2292                my $lineno;
2293                my $data;
2294                my $age;
2295                my $age_str;
2296                my $age_class;
2297
2298                chomp $line;
2299                $line_class_num = ($line_class_num + 1) % $line_class_len;
2300
2301                if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
2302                        $long_rev = $1;
2303                        $author   = $2;
2304                        $time     = $3;
2305                        $lineno   = $4;
2306                        $data     = $5;
2307                } else {
2308                        print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
2309                        next;
2310                }
2311                $short_rev  = substr ($long_rev, 0, 8);
2312                $age        = time () - $time;
2313                $age_str    = age_string ($age);
2314                $age_str    =~ s/ /&nbsp;/g;
2315                $age_class  = age_class($age);
2316                $author     = esc_html ($author);
2317                $author     =~ s/ /&nbsp;/g;
2318
2319                $data = untabify($data);
2320                $data = esc_html ($data);
2321
2322                print <<HTML;
2323  <tr class="$line_class[$line_class_num]">
2324    <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
2325    <td class="$age_class">$age_str</td>
2326    <td>$author</td>
2327    <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
2328    <td class="pre">$data</td>
2329  </tr>
2330HTML
2331        } # while (my $line = <$fd>)
2332        print "</table>\n\n";
2333        close $fd
2334                or print "Reading blob failed.\n";
2335        print "</div>";
2336        git_footer_html();
2337}
2338
2339sub git_tags {
2340        my $head = git_get_head_hash($project);
2341        git_header_html();
2342        git_print_page_nav('','', $head,undef,$head);
2343        git_print_header_div('summary', $project);
2344
2345        my $taglist = git_get_refs_list("refs/tags");
2346        if (defined @$taglist) {
2347                git_tags_body($taglist);
2348        }
2349        git_footer_html();
2350}
2351
2352sub git_heads {
2353        my $head = git_get_head_hash($project);
2354        git_header_html();
2355        git_print_page_nav('','', $head,undef,$head);
2356        git_print_header_div('summary', $project);
2357
2358        my $taglist = git_get_refs_list("refs/heads");
2359        if (defined @$taglist) {
2360                git_heads_body($taglist, $head);
2361        }
2362        git_footer_html();
2363}
2364
2365sub git_blob_plain {
2366        if (!defined $hash) {
2367                if (defined $file_name) {
2368                        my $base = $hash_base || git_get_head_hash($project);
2369                        $hash = git_get_hash_by_path($base, $file_name, "blob")
2370                                or die_error(undef, "Error lookup file");
2371                } else {
2372                        die_error(undef, "No file name defined");
2373                }
2374        }
2375        my $type = shift;
2376        open my $fd, "-|", $GIT, "cat-file", "blob", $hash
2377                or die_error(undef, "Couldn't cat $file_name, $hash");
2378
2379        $type ||= blob_mimetype($fd, $file_name);
2380
2381        # save as filename, even when no $file_name is given
2382        my $save_as = "$hash";
2383        if (defined $file_name) {
2384                $save_as = $file_name;
2385        } elsif ($type =~ m/^text\//) {
2386                $save_as .= '.txt';
2387        }
2388
2389        print $cgi->header(-type => "$type",
2390                           -content_disposition => "inline; filename=\"$save_as\"");
2391        undef $/;
2392        binmode STDOUT, ':raw';
2393        print <$fd>;
2394        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2395        $/ = "\n";
2396        close $fd;
2397}
2398
2399sub git_blob {
2400        if (!defined $hash) {
2401                if (defined $file_name) {
2402                        my $base = $hash_base || git_get_head_hash($project);
2403                        $hash = git_get_hash_by_path($base, $file_name, "blob")
2404                                or die_error(undef, "Error lookup file");
2405                } else {
2406                        die_error(undef, "No file name defined");
2407                }
2408        }
2409        my $have_blame = gitweb_check_feature('blame');
2410        open my $fd, "-|", $GIT, "cat-file", "blob", $hash
2411                or die_error(undef, "Couldn't cat $file_name, $hash");
2412        my $mimetype = blob_mimetype($fd, $file_name);
2413        if ($mimetype !~ m/^text\//) {
2414                close $fd;
2415                return git_blob_plain($mimetype);
2416        }
2417        git_header_html();
2418        my $formats_nav = '';
2419        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2420                if (defined $file_name) {
2421                        if ($have_blame) {
2422                                $formats_nav .=
2423                                        $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
2424                                                               hash=>$hash, file_name=>$file_name)},
2425                                                "blame") .
2426                                        " | ";
2427                        }
2428                        $formats_nav .=
2429                                $cgi->a({-href => href(action=>"blob_plain",
2430                                                       hash=>$hash, file_name=>$file_name)},
2431                                        "plain") .
2432                                " | " .
2433                                $cgi->a({-href => href(action=>"blob",
2434                                                       hash_base=>"HEAD", file_name=>$file_name)},
2435                                        "head");
2436                } else {
2437                        $formats_nav .=
2438                                $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "plain");
2439                }
2440                git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2441                git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2442        } else {
2443                print "<div class=\"page_nav\">\n" .
2444                      "<br/><br/></div>\n" .
2445                      "<div class=\"title\">$hash</div>\n";
2446        }
2447        git_print_page_path($file_name, "blob", $hash_base);
2448        print "<div class=\"page_body\">\n";
2449        my $nr;
2450        while (my $line = <$fd>) {
2451                chomp $line;
2452                $nr++;
2453                $line = untabify($line);
2454                printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
2455                       $nr, $nr, $nr, esc_html($line);
2456        }
2457        close $fd
2458                or print "Reading blob failed.\n";
2459        print "</div>";
2460        git_footer_html();
2461}
2462
2463sub git_tree {
2464        if (!defined $hash) {
2465                $hash = git_get_head_hash($project);
2466                if (defined $file_name) {
2467                        my $base = $hash_base || $hash;
2468                        $hash = git_get_hash_by_path($base, $file_name, "tree");
2469                }
2470                if (!defined $hash_base) {
2471                        $hash_base = $hash;
2472                }
2473        }
2474        $/ = "\0";
2475        open my $fd, "-|", $GIT, "ls-tree", '-z', $hash
2476                or die_error(undef, "Open git-ls-tree failed");
2477        my @entries = map { chomp; $_ } <$fd>;
2478        close $fd or die_error(undef, "Reading tree failed");
2479        $/ = "\n";
2480
2481        my $refs = git_get_references();
2482        my $ref = format_ref_marker($refs, $hash_base);
2483        git_header_html();
2484        my %base_key = ();
2485        my $base = "";
2486        my $have_blame = gitweb_check_feature('blame');
2487        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2488                $base_key{hash_base} = $hash_base;
2489                git_print_page_nav('tree','', $hash_base);
2490                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
2491        } else {
2492                print "<div class=\"page_nav\">\n";
2493                print "<br/><br/></div>\n";
2494                print "<div class=\"title\">$hash</div>\n";
2495        }
2496        if (defined $file_name) {
2497                $base = esc_html("$file_name/");
2498        }
2499        git_print_page_path($file_name, 'tree', $hash_base);
2500        print "<div class=\"page_body\">\n";
2501        print "<table cellspacing=\"0\">\n";
2502        my $alternate = 0;
2503        foreach my $line (@entries) {
2504                #'100644        blob    0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa        panic.c'
2505                $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
2506                my $t_mode = $1;
2507                my $t_type = $2;
2508                my $t_hash = $3;
2509                my $t_name = validate_input($4);
2510                if ($alternate) {
2511                        print "<tr class=\"dark\">\n";
2512                } else {
2513                        print "<tr class=\"light\">\n";
2514                }
2515                $alternate ^= 1;
2516                print "<td class=\"mode\">" . mode_str($t_mode) . "</td>\n";
2517                if ($t_type eq "blob") {
2518                        print "<td class=\"list\">" .
2519                              $cgi->a({-href => href(action=>"blob", hash=>$t_hash, file_name=>"$base$t_name", %base_key),
2520                                      -class => "list"}, esc_html($t_name)) .
2521                              "</td>\n" .
2522                              "<td class=\"link\">" .
2523                              $cgi->a({-href => href(action=>"blob", hash=>$t_hash, file_name=>"$base$t_name", %base_key)},
2524                                      "blob");
2525                        if ($have_blame) {
2526                                print " | " .
2527                                        $cgi->a({-href => href(action=>"blame", hash=>$t_hash, file_name=>"$base$t_name", %base_key)},
2528                                                "blame");
2529                        }
2530                        print " | " .
2531                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2532                                                     hash=>$t_hash, file_name=>"$base$t_name")},
2533                                      "history") .
2534                              " | " .
2535                              $cgi->a({-href => href(action=>"blob_plain",
2536                                                     hash=>$t_hash, file_name=>"$base$t_name")},
2537                                      "raw") .
2538                              "</td>\n";
2539                } elsif ($t_type eq "tree") {
2540                        print "<td class=\"list\">" .
2541                              $cgi->a({-href => href(action=>"tree", hash=>$t_hash, file_name=>"$base$t_name", %base_key)},
2542                                      esc_html($t_name)) .
2543                              "</td>\n" .
2544                              "<td class=\"link\">" .
2545                              $cgi->a({-href => href(action=>"tree", hash=>$t_hash, file_name=>"$base$t_name", %base_key)},
2546                                      "tree") .
2547                              " | " .
2548                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base, file_name=>"$base$t_name")},
2549                                      "history") .
2550                              "</td>\n";
2551                }
2552                print "</tr>\n";
2553        }
2554        print "</table>\n" .
2555              "</div>";
2556        git_footer_html();
2557}
2558
2559sub git_snapshot {
2560
2561        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2562        my $have_snapshot = (defined $ctype && defined $suffix);
2563        if (!$have_snapshot) {
2564                die_error('403 Permission denied', "Permission denied");
2565        }
2566
2567        if (!defined $hash) {
2568                $hash = git_get_head_hash($project);
2569        }
2570
2571        my $filename = basename($project) . "-$hash.tar.$suffix";
2572
2573        print $cgi->header(-type => 'application/x-tar',
2574                           -content_encoding => $ctype,
2575                           -content_disposition => "inline; filename=\"$filename\"",
2576                           -status => '200 OK');
2577
2578        open my $fd, "-|", "$GIT tar-tree $hash \'$project\' | $command" or
2579                die_error(undef, "Execute git-tar-tree failed.");
2580        binmode STDOUT, ':raw';
2581        print <$fd>;
2582        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2583        close $fd;
2584
2585}
2586
2587sub git_log {
2588        my $head = git_get_head_hash($project);
2589        if (!defined $hash) {
2590                $hash = $head;
2591        }
2592        if (!defined $page) {
2593                $page = 0;
2594        }
2595        my $refs = git_get_references();
2596
2597        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2598        open my $fd, "-|", $GIT, "rev-list", $limit, $hash
2599                or die_error(undef, "Open git-rev-list failed");
2600        my @revlist = map { chomp; $_ } <$fd>;
2601        close $fd;
2602
2603        my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
2604
2605        git_header_html();
2606        git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
2607
2608        if (!@revlist) {
2609                my %co = parse_commit($hash);
2610
2611                git_print_header_div('summary', $project);
2612                print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
2613        }
2614        for (my $i = ($page * 100); $i <= $#revlist; $i++) {
2615                my $commit = $revlist[$i];
2616                my $ref = format_ref_marker($refs, $commit);
2617                my %co = parse_commit($commit);
2618                next if !%co;
2619                my %ad = parse_date($co{'author_epoch'});
2620                git_print_header_div('commit',
2621                               "<span class=\"age\">$co{'age_string'}</span>" .
2622                               esc_html($co{'title'}) . $ref,
2623                               $commit);
2624                print "<div class=\"title_text\">\n" .
2625                      "<div class=\"log_link\">\n" .
2626                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
2627                      " | " .
2628                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
2629                      "<br/>\n" .
2630                      "</div>\n" .
2631                      "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
2632                      "</div>\n";
2633
2634                print "<div class=\"log_body\">\n";
2635                git_print_simplified_log($co{'comment'});
2636                print "</div>\n";
2637        }
2638        git_footer_html();
2639}
2640
2641sub git_commit {
2642        my %co = parse_commit($hash);
2643        if (!%co) {
2644                die_error(undef, "Unknown commit object");
2645        }
2646        my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2647        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2648
2649        my $parent = $co{'parent'};
2650        if (!defined $parent) {
2651                $parent = "--root";
2652        }
2653        open my $fd, "-|", $GIT, "diff-tree", '-r', '-M', $parent, $hash
2654                or die_error(undef, "Open git-diff-tree failed");
2655        my @difftree = map { chomp; $_ } <$fd>;
2656        close $fd or die_error(undef, "Reading git-diff-tree failed");
2657
2658        # non-textual hash id's can be cached
2659        my $expires;
2660        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2661                $expires = "+1d";
2662        }
2663        my $refs = git_get_references();
2664        my $ref = format_ref_marker($refs, $co{'id'});
2665
2666        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2667        my $have_snapshot = (defined $ctype && defined $suffix);
2668
2669        my $formats_nav = '';
2670        if (defined $file_name && defined $co{'parent'}) {
2671                my $parent = $co{'parent'};
2672                $formats_nav .=
2673                        $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)},
2674                                "blame");
2675        }
2676        git_header_html(undef, $expires);
2677        git_print_page_nav('commit', defined $co{'parent'} ? '' : 'commitdiff',
2678                           $hash, $co{'tree'}, $hash,
2679                           $formats_nav);
2680
2681        if (defined $co{'parent'}) {
2682                git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
2683        } else {
2684                git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
2685        }
2686        print "<div class=\"title_text\">\n" .
2687              "<table cellspacing=\"0\">\n";
2688        print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
2689              "<tr>" .
2690              "<td></td><td> $ad{'rfc2822'}";
2691        if ($ad{'hour_local'} < 6) {
2692                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2693                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2694        } else {
2695                printf(" (%02d:%02d %s)",
2696                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2697        }
2698        print "</td>" .
2699              "</tr>\n";
2700        print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
2701        print "<tr><td></td><td> $cd{'rfc2822'}" .
2702              sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
2703              "</td></tr>\n";
2704        print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
2705        print "<tr>" .
2706              "<td>tree</td>" .
2707              "<td class=\"sha1\">" .
2708              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
2709                       class => "list"}, $co{'tree'}) .
2710              "</td>" .
2711              "<td class=\"link\">" .
2712              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
2713                      "tree");
2714        if ($have_snapshot) {
2715                print " | " .
2716                      $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
2717        }
2718        print "</td>" .
2719              "</tr>\n";
2720        my $parents = $co{'parents'};
2721        foreach my $par (@$parents) {
2722                print "<tr>" .
2723                      "<td>parent</td>" .
2724                      "<td class=\"sha1\">" .
2725                      $cgi->a({-href => href(action=>"commit", hash=>$par),
2726                               class => "list"}, $par) .
2727                      "</td>" .
2728                      "<td class=\"link\">" .
2729                      $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
2730                      " | " .
2731                      $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "commitdiff") .
2732                      "</td>" .
2733                      "</tr>\n";
2734        }
2735        print "</table>".
2736              "</div>\n";
2737
2738        print "<div class=\"page_body\">\n";
2739        git_print_log($co{'comment'});
2740        print "</div>\n";
2741
2742        git_difftree_body(\@difftree, $hash, $parent);
2743
2744        git_footer_html();
2745}
2746
2747sub git_blobdiff {
2748        my $format = shift || 'html';
2749
2750        my $fd;
2751        my @difftree;
2752        my %diffinfo;
2753        my $expires;
2754
2755        # preparing $fd and %diffinfo for git_patchset_body
2756        # new style URI
2757        if (defined $hash_base && defined $hash_parent_base) {
2758                if (defined $file_name) {
2759                        # read raw output
2760                        open $fd, "-|", $GIT, "diff-tree", '-r', '-M', '-C', $hash_parent_base, $hash_base,
2761                                "--", $file_name
2762                                or die_error(undef, "Open git-diff-tree failed");
2763                        @difftree = map { chomp; $_ } <$fd>;
2764                        close $fd
2765                                or die_error(undef, "Reading git-diff-tree failed");
2766                        @difftree
2767                                or die_error('404 Not Found', "Blob diff not found");
2768
2769                } elsif (defined $hash) { # try to find filename from $hash
2770                        if ($hash !~ /[0-9a-fA-F]{40}/) {
2771                                $hash = git_to_hash($hash);
2772                        }
2773
2774                        # read filtered raw output
2775                        open $fd, "-|", $GIT, "diff-tree", '-r', '-M', '-C', $hash_parent_base, $hash_base
2776                                or die_error(undef, "Open git-diff-tree failed");
2777                        @difftree =
2778                                # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
2779                                # $hash == to_id
2780                                grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
2781                                map { chomp; $_ } <$fd>;
2782                        close $fd
2783                                or die_error(undef, "Reading git-diff-tree failed");
2784                        @difftree
2785                                or die_error('404 Not Found', "Blob diff not found");
2786
2787                } else {
2788                        die_error('404 Not Found', "Missing one of the blob diff parameters");
2789                }
2790
2791                if (@difftree > 1) {
2792                        die_error('404 Not Found', "Ambiguous blob diff specification");
2793                }
2794
2795                %diffinfo = parse_difftree_raw_line($difftree[0]);
2796                $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
2797                $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
2798
2799                $hash_parent ||= $diffinfo{'from_id'};
2800                $hash        ||= $diffinfo{'to_id'};
2801
2802                # non-textual hash id's can be cached
2803                if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
2804                    $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
2805                        $expires = '+1d';
2806                }
2807
2808                # open patch output
2809                open $fd, "-|", $GIT, "diff-tree", '-r', '-p', '-M', '-C', $hash_parent_base, $hash_base,
2810                        "--", $file_name
2811                        or die_error(undef, "Open git-diff-tree failed");
2812        }
2813
2814        # old/legacy style URI
2815        if (!%diffinfo && # if new style URI failed
2816            defined $hash && defined $hash_parent) {
2817                # fake git-diff-tree raw output
2818                $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
2819                $diffinfo{'from_id'} = $hash_parent;
2820                $diffinfo{'to_id'}   = $hash;
2821                if (defined $file_name) {
2822                        if (defined $file_parent) {
2823                                $diffinfo{'status'} = '2';
2824                                $diffinfo{'from_file'} = $file_parent;
2825                                $diffinfo{'to_file'}   = $file_name;
2826                        } else { # assume not renamed
2827                                $diffinfo{'status'} = '1';
2828                                $diffinfo{'from_file'} = $file_name;
2829                                $diffinfo{'to_file'}   = $file_name;
2830                        }
2831                } else { # no filename given
2832                        $diffinfo{'status'} = '2';
2833                        $diffinfo{'from_file'} = $hash_parent;
2834                        $diffinfo{'to_file'}   = $hash;
2835                }
2836
2837                # non-textual hash id's can be cached
2838                if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
2839                    $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
2840                        $expires = '+1d';
2841                }
2842
2843                # open patch output
2844                open $fd, "-|", $GIT, "diff", '-p', $hash_parent, $hash
2845                        or die_error(undef, "Open git-diff failed");
2846        } else  {
2847                die_error('404 Not Found', "Missing one of the blob diff parameters")
2848                        unless %diffinfo;
2849        }
2850
2851        # header
2852        if ($format eq 'html') {
2853                my $formats_nav =
2854                        $cgi->a({-href => href(action=>"blobdiff_plain",
2855                                               hash=>$hash, hash_parent=>$hash_parent,
2856                                               hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
2857                                               file_name=>$file_name, file_parent=>$file_parent)},
2858                                "plain");
2859                git_header_html(undef, $expires);
2860                if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2861                        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2862                        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2863                } else {
2864                        print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
2865                        print "<div class=\"title\">$hash vs $hash_parent</div>\n";
2866                }
2867                if (defined $file_name) {
2868                        git_print_page_path($file_name, "blob", $hash_base);
2869                } else {
2870                        print "<div class=\"page_path\"></div>\n";
2871                }
2872
2873        } elsif ($format eq 'plain') {
2874                print $cgi->header(
2875                        -type => 'text/plain',
2876                        -charset => 'utf-8',
2877                        -expires => $expires,
2878                        -content_disposition => qq(inline; filename="${file_name}.patch"));
2879
2880                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
2881
2882        } else {
2883                die_error(undef, "Unknown blobdiff format");
2884        }
2885
2886        # patch
2887        if ($format eq 'html') {
2888                print "<div class=\"page_body\">\n";
2889
2890                git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
2891                close $fd;
2892
2893                print "</div>\n"; # class="page_body"
2894                git_footer_html();
2895
2896        } else {
2897                while (my $line = <$fd>) {
2898                        $line =~ s!a/($hash|$hash_parent)!a/$diffinfo{'from_file'}!g;
2899                        $line =~ s!b/($hash|$hash_parent)!b/$diffinfo{'to_file'}!g;
2900
2901                        print $line;
2902
2903                        last if $line =~ m!^\+\+\+!;
2904                }
2905                local $/ = undef;
2906                print <$fd>;
2907                close $fd;
2908        }
2909}
2910
2911sub git_blobdiff_plain {
2912        git_blobdiff('plain');
2913}
2914
2915sub git_commitdiff {
2916        my $format = shift || 'html';
2917        my %co = parse_commit($hash);
2918        if (!%co) {
2919                die_error(undef, "Unknown commit object");
2920        }
2921        if (!defined $hash_parent) {
2922                $hash_parent = $co{'parent'} || '--root';
2923        }
2924
2925        # read commitdiff
2926        my $fd;
2927        my @difftree;
2928        if ($format eq 'html') {
2929                open $fd, "-|", $GIT, "diff-tree", '-r', '-M', '-C',
2930                        "--patch-with-raw", "--full-index", $hash_parent, $hash
2931                        or die_error(undef, "Open git-diff-tree failed");
2932
2933                while (chomp(my $line = <$fd>)) {
2934                        # empty line ends raw part of diff-tree output
2935                        last unless $line;
2936                        push @difftree, $line;
2937                }
2938
2939        } elsif ($format eq 'plain') {
2940                open $fd, "-|", $GIT, "diff-tree", '-r', '-p', '-B', $hash_parent, $hash
2941                        or die_error(undef, "Open git-diff-tree failed");
2942
2943        } else {
2944                die_error(undef, "Unknown commitdiff format");
2945        }
2946
2947        # non-textual hash id's can be cached
2948        my $expires;
2949        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2950                $expires = "+1d";
2951        }
2952
2953        # write commit message
2954        if ($format eq 'html') {
2955                my $refs = git_get_references();
2956                my $ref = format_ref_marker($refs, $co{'id'});
2957                my $formats_nav =
2958                        $cgi->a({-href => href(action=>"commitdiff_plain",
2959                                               hash=>$hash, hash_parent=>$hash_parent)},
2960                                "plain");
2961
2962                git_header_html(undef, $expires);
2963                git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
2964                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
2965                print "<div class=\"page_body\">\n";
2966                print "<div class=\"log\">\n";
2967                git_print_simplified_log($co{'comment'}, 1); # skip title
2968                print "</div>\n"; # class="log"
2969
2970        } elsif ($format eq 'plain') {
2971                my $refs = git_get_references("tags");
2972                my $tagname = git_get_rev_name_tags($hash);
2973                my $filename = basename($project) . "-$hash.patch";
2974
2975                print $cgi->header(
2976                        -type => 'text/plain',
2977                        -charset => 'utf-8',
2978                        -expires => $expires,
2979                        -content_disposition => qq(inline; filename="$filename"));
2980                my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2981                print <<TEXT;
2982From: $co{'author'}
2983Date: $ad{'rfc2822'} ($ad{'tz_local'})
2984Subject: $co{'title'}
2985TEXT
2986                print "X-Git-Tag: $tagname\n" if $tagname;
2987                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
2988
2989                foreach my $line (@{$co{'comment'}}) {
2990                        print "$line\n";
2991                }
2992                print "---\n\n";
2993        }
2994
2995        # write patch
2996        if ($format eq 'html') {
2997                #git_difftree_body(\@difftree, $hash, $hash_parent);
2998                #print "<br/>\n";
2999
3000                git_patchset_body($fd, \@difftree, $hash, $hash_parent);
3001                close $fd;
3002                print "</div>\n"; # class="page_body"
3003                git_footer_html();
3004
3005        } elsif ($format eq 'plain') {
3006                local $/ = undef;
3007                print <$fd>;
3008                close $fd
3009                        or print "Reading git-diff-tree failed\n";
3010        }
3011}
3012
3013sub git_commitdiff_plain {
3014        git_commitdiff('plain');
3015}
3016
3017sub git_history {
3018        if (!defined $hash_base) {
3019                $hash_base = git_get_head_hash($project);
3020        }
3021        my $ftype;
3022        my %co = parse_commit($hash_base);
3023        if (!%co) {
3024                die_error(undef, "Unknown commit object");
3025        }
3026        my $refs = git_get_references();
3027        git_header_html();
3028        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base);
3029        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3030        if (!defined $hash && defined $file_name) {
3031                $hash = git_get_hash_by_path($hash_base, $file_name);
3032        }
3033        if (defined $hash) {
3034                $ftype = git_get_type($hash);
3035        }
3036        git_print_page_path($file_name, $ftype, $hash_base);
3037
3038        open my $fd, "-|",
3039                $GIT, "rev-list", "--full-history", $hash_base, "--", $file_name;
3040        git_history_body($fd, $refs, $hash_base, $ftype);
3041
3042        close $fd;
3043        git_footer_html();
3044}
3045
3046sub git_search {
3047        if (!defined $searchtext) {
3048                die_error(undef, "Text field empty");
3049        }
3050        if (!defined $hash) {
3051                $hash = git_get_head_hash($project);
3052        }
3053        my %co = parse_commit($hash);
3054        if (!%co) {
3055                die_error(undef, "Unknown commit object");
3056        }
3057        # pickaxe may take all resources of your box and run for several minutes
3058        # with every query - so decide by yourself how public you make this feature :)
3059        my $commit_search = 1;
3060        my $author_search = 0;
3061        my $committer_search = 0;
3062        my $pickaxe_search = 0;
3063        if ($searchtext =~ s/^author\\://i) {
3064                $author_search = 1;
3065        } elsif ($searchtext =~ s/^committer\\://i) {
3066                $committer_search = 1;
3067        } elsif ($searchtext =~ s/^pickaxe\\://i) {
3068                $commit_search = 0;
3069                $pickaxe_search = 1;
3070        }
3071        git_header_html();
3072        git_print_page_nav('','', $hash,$co{'tree'},$hash);
3073        git_print_header_div('commit', esc_html($co{'title'}), $hash);
3074
3075        print "<table cellspacing=\"0\">\n";
3076        my $alternate = 0;
3077        if ($commit_search) {
3078                $/ = "\0";
3079                open my $fd, "-|", $GIT, "rev-list", "--header", "--parents", $hash or next;
3080                while (my $commit_text = <$fd>) {
3081                        if (!grep m/$searchtext/i, $commit_text) {
3082                                next;
3083                        }
3084                        if ($author_search && !grep m/\nauthor .*$searchtext/i, $commit_text) {
3085                                next;
3086                        }
3087                        if ($committer_search && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
3088                                next;
3089                        }
3090                        my @commit_lines = split "\n", $commit_text;
3091                        my %co = parse_commit(undef, \@commit_lines);
3092                        if (!%co) {
3093                                next;
3094                        }
3095                        if ($alternate) {
3096                                print "<tr class=\"dark\">\n";
3097                        } else {
3098                                print "<tr class=\"light\">\n";
3099                        }
3100                        $alternate ^= 1;
3101                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3102                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3103                              "<td>" .
3104                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3105                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3106                        my $comment = $co{'comment'};
3107                        foreach my $line (@$comment) {
3108                                if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
3109                                        my $lead = esc_html($1) || "";
3110                                        $lead = chop_str($lead, 30, 10);
3111                                        my $match = esc_html($2) || "";
3112                                        my $trail = esc_html($3) || "";
3113                                        $trail = chop_str($trail, 30, 10);
3114                                        my $text = "$lead<span class=\"match\">$match</span>$trail";
3115                                        print chop_str($text, 80, 5) . "<br/>\n";
3116                                }
3117                        }
3118                        print "</td>\n" .
3119                              "<td class=\"link\">" .
3120                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3121                              " | " .
3122                              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3123                        print "</td>\n" .
3124                              "</tr>\n";
3125                }
3126                close $fd;
3127        }
3128
3129        if ($pickaxe_search) {
3130                $/ = "\n";
3131                open my $fd, "-|", "$GIT rev-list $hash | $GIT diff-tree -r --stdin -S\'$searchtext\'";
3132                undef %co;
3133                my @files;
3134                while (my $line = <$fd>) {
3135                        if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
3136                                my %set;
3137                                $set{'file'} = $6;
3138                                $set{'from_id'} = $3;
3139                                $set{'to_id'} = $4;
3140                                $set{'id'} = $set{'to_id'};
3141                                if ($set{'id'} =~ m/0{40}/) {
3142                                        $set{'id'} = $set{'from_id'};
3143                                }
3144                                if ($set{'id'} =~ m/0{40}/) {
3145                                        next;
3146                                }
3147                                push @files, \%set;
3148                        } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
3149                                if (%co) {
3150                                        if ($alternate) {
3151                                                print "<tr class=\"dark\">\n";
3152                                        } else {
3153                                                print "<tr class=\"light\">\n";
3154                                        }
3155                                        $alternate ^= 1;
3156                                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3157                                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3158                                              "<td>" .
3159                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
3160                                                      -class => "list subject"},
3161                                                      esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3162                                        while (my $setref = shift @files) {
3163                                                my %set = %$setref;
3164                                                print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
3165                                                                             hash=>$set{'id'}, file_name=>$set{'file'}),
3166                                                              -class => "list"},
3167                                                              "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
3168                                                      "<br/>\n";
3169                                        }
3170                                        print "</td>\n" .
3171                                              "<td class=\"link\">" .
3172                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3173                                              " | " .
3174                                              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3175                                        print "</td>\n" .
3176                                              "</tr>\n";
3177                                }
3178                                %co = parse_commit($1);
3179                        }
3180                }
3181                close $fd;
3182        }
3183        print "</table>\n";
3184        git_footer_html();
3185}
3186
3187sub git_shortlog {
3188        my $head = git_get_head_hash($project);
3189        if (!defined $hash) {
3190                $hash = $head;
3191        }
3192        if (!defined $page) {
3193                $page = 0;
3194        }
3195        my $refs = git_get_references();
3196
3197        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3198        open my $fd, "-|", $GIT, "rev-list", $limit, $hash
3199                or die_error(undef, "Open git-rev-list failed");
3200        my @revlist = map { chomp; $_ } <$fd>;
3201        close $fd;
3202
3203        my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
3204        my $next_link = '';
3205        if ($#revlist >= (100 * ($page+1)-1)) {
3206                $next_link =
3207                        $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
3208                                 -title => "Alt-n"}, "next");
3209        }
3210
3211
3212        git_header_html();
3213        git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
3214        git_print_header_div('summary', $project);
3215
3216        git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
3217
3218        git_footer_html();
3219}
3220
3221## ......................................................................
3222## feeds (RSS, OPML)
3223
3224sub git_rss {
3225        # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
3226        open my $fd, "-|", $GIT, "rev-list", "--max-count=150", git_get_head_hash($project)
3227                or die_error(undef, "Open git-rev-list failed");
3228        my @revlist = map { chomp; $_ } <$fd>;
3229        close $fd or die_error(undef, "Reading git-rev-list failed");
3230        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3231        print <<XML;
3232<?xml version="1.0" encoding="utf-8"?>
3233<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
3234<channel>
3235<title>$project $my_uri $my_url</title>
3236<link>${\esc_html("$my_url?p=$project;a=summary")}</link>
3237<description>$project log</description>
3238<language>en</language>
3239XML
3240
3241        for (my $i = 0; $i <= $#revlist; $i++) {
3242                my $commit = $revlist[$i];
3243                my %co = parse_commit($commit);
3244                # we read 150, we always show 30 and the ones more recent than 48 hours
3245                if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
3246                        last;
3247                }
3248                my %cd = parse_date($co{'committer_epoch'});
3249                open $fd, "-|", $GIT, "diff-tree", '-r', $co{'parent'}, $co{'id'} or next;
3250                my @difftree = map { chomp; $_ } <$fd>;
3251                close $fd or next;
3252                print "<item>\n" .
3253                      "<title>" .
3254                      sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
3255                      "</title>\n" .
3256                      "<author>" . esc_html($co{'author'}) . "</author>\n" .
3257                      "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
3258                      "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
3259                      "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
3260                      "<description>" . esc_html($co{'title'}) . "</description>\n" .
3261                      "<content:encoded>" .
3262                      "<![CDATA[\n";
3263                my $comment = $co{'comment'};
3264                foreach my $line (@$comment) {
3265                        $line = decode("utf8", $line, Encode::FB_DEFAULT);
3266                        print "$line<br/>\n";
3267                }
3268                print "<br/>\n";
3269                foreach my $line (@difftree) {
3270                        if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
3271                                next;
3272                        }
3273                        my $file = validate_input(unquote($7));
3274                        $file = decode("utf8", $file, Encode::FB_DEFAULT);
3275                        print "$file<br/>\n";
3276                }
3277                print "]]>\n" .
3278                      "</content:encoded>\n" .
3279                      "</item>\n";
3280        }
3281        print "</channel></rss>";
3282}
3283
3284sub git_opml {
3285        my @list = git_get_projects_list();
3286
3287        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3288        print <<XML;
3289<?xml version="1.0" encoding="utf-8"?>
3290<opml version="1.0">
3291<head>
3292  <title>$site_name Git OPML Export</title>
3293</head>
3294<body>
3295<outline text="git RSS feeds">
3296XML
3297
3298        foreach my $pr (@list) {
3299                my %proj = %$pr;
3300                my $head = git_get_head_hash($proj{'path'});
3301                if (!defined $head) {
3302                        next;
3303                }
3304                $ENV{'GIT_DIR'} = "$projectroot/$proj{'path'}";
3305                my %co = parse_commit($head);
3306                if (!%co) {
3307                        next;
3308                }
3309
3310                my $path = esc_html(chop_str($proj{'path'}, 25, 5));
3311                my $rss  = "$my_url?p=$proj{'path'};a=rss";
3312                my $html = "$my_url?p=$proj{'path'};a=summary";
3313                print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
3314        }
3315        print <<XML;
3316</outline>
3317</body>
3318</opml>
3319XML
3320}