902b96a914c9e571289924bcef02def2e7d77f3e
   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();
  18binmode STDOUT, ':utf8';
  19
  20our $cgi = new CGI;
  21our $version = "267";
  22our $my_url = $cgi->url();
  23our $my_uri = $cgi->url(-absolute => 1);
  24our $rss_link = "";
  25
  26# core git executable to use
  27# this can just be "git" if your webserver has a sensible PATH
  28our $GIT = "/usr/bin/git";
  29
  30# absolute fs-path which will be prepended to the project path
  31#our $projectroot = "/pub/scm";
  32our $projectroot = "/home/kay/public_html/pub/scm";
  33
  34# version of the core git binary
  35our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
  36
  37# location for temporary files needed for diffs
  38our $git_temp = "/tmp/gitweb";
  39if (! -d $git_temp) {
  40        mkdir($git_temp, 0700) || die_error("Couldn't mkdir $git_temp");
  41}
  42
  43# target of the home link on top of all pages
  44our $home_link = $my_uri;
  45
  46# name of your site or organization to appear in page titles
  47# replace this with something more descriptive for clearer bookmarks
  48our $site_name = $ENV{'SERVER_NAME'} || "Untitled";
  49
  50# html text to include at home page
  51our $home_text = "indextext.html";
  52
  53# URI of default stylesheet
  54our $stylesheet = "gitweb.css";
  55
  56# source of projects list
  57#our $projects_list = $projectroot;
  58our $projects_list = "index/index.aux";
  59
  60# default blob_plain mimetype and default charset for text/plain blob
  61our $default_blob_plain_mimetype = 'text/plain';
  62our $default_text_plain_charset  = undef;
  63
  64# file to use for guessing MIME types before trying /etc/mime.types
  65# (relative to the current git repository)
  66our $mimetypes_file = undef;
  67
  68# input validation and dispatch
  69our $action = $cgi->param('a');
  70if (defined $action) {
  71        if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
  72                undef $action;
  73                die_error(undef, "Invalid action parameter.");
  74        }
  75        if ($action eq "git-logo.png") {
  76                git_logo();
  77                exit;
  78        } elsif ($action eq "opml") {
  79                git_opml();
  80                exit;
  81        }
  82}
  83
  84our $order = $cgi->param('o');
  85if (defined $order) {
  86        if ($order =~ m/[^0-9a-zA-Z_]/) {
  87                undef $order;
  88                die_error(undef, "Invalid order parameter.");
  89        }
  90}
  91
  92our $project = ($cgi->param('p') || $ENV{'PATH_INFO'});
  93if (defined $project) {
  94        $project =~ s|^/||; $project =~ s|/$||;
  95        $project = validate_input($project);
  96        if (!defined($project)) {
  97                die_error(undef, "Invalid project parameter.");
  98        }
  99        if (!(-d "$projectroot/$project")) {
 100                undef $project;
 101                die_error(undef, "No such directory.");
 102        }
 103        if (!(-e "$projectroot/$project/HEAD")) {
 104                undef $project;
 105                die_error(undef, "No such project.");
 106        }
 107        $rss_link = "<link rel=\"alternate\" title=\"" . esc_param($project) . " log\" href=\"" .
 108                    "$my_uri?" . esc_param("p=$project;a=rss") . "\" type=\"application/rss+xml\"/>";
 109        $ENV{'GIT_DIR'} = "$projectroot/$project";
 110} else {
 111        git_project_list();
 112        exit;
 113}
 114
 115our $file_name = $cgi->param('f');
 116if (defined $file_name) {
 117        $file_name = validate_input($file_name);
 118        if (!defined($file_name)) {
 119                die_error(undef, "Invalid file parameter.");
 120        }
 121}
 122
 123our $hash = $cgi->param('h');
 124if (defined $hash) {
 125        $hash = validate_input($hash);
 126        if (!defined($hash)) {
 127                die_error(undef, "Invalid hash parameter.");
 128        }
 129}
 130
 131our $hash_parent = $cgi->param('hp');
 132if (defined $hash_parent) {
 133        $hash_parent = validate_input($hash_parent);
 134        if (!defined($hash_parent)) {
 135                die_error(undef, "Invalid hash parent parameter.");
 136        }
 137}
 138
 139our $hash_base = $cgi->param('hb');
 140if (defined $hash_base) {
 141        $hash_base = validate_input($hash_base);
 142        if (!defined($hash_base)) {
 143                die_error(undef, "Invalid hash base parameter.");
 144        }
 145}
 146
 147our $page = $cgi->param('pg');
 148if (defined $page) {
 149        if ($page =~ m/[^0-9]$/) {
 150                undef $page;
 151                die_error(undef, "Invalid page parameter.");
 152        }
 153}
 154
 155our $searchtext = $cgi->param('s');
 156if (defined $searchtext) {
 157        if ($searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
 158                undef $searchtext;
 159                die_error(undef, "Invalid search parameter.");
 160        }
 161        $searchtext = quotemeta $searchtext;
 162}
 163
 164# dispatch
 165my %actions = (
 166        "blame" => \&git_blame2,
 167        "blobdiff" => \&git_blobdiff,
 168        "blobdiff_plain" => \&git_blobdiff_plain,
 169        "blob" => \&git_blob,
 170        "blob_plain" => \&git_blob_plain,
 171        "commitdiff" => \&git_commitdiff,
 172        "commitdiff_plain" => \&git_commitdiff_plain,
 173        "commit" => \&git_commit,
 174        "heads" => \&git_heads,
 175        "history" => \&git_history,
 176        "log" => \&git_log,
 177        "rss" => \&git_rss,
 178        "search" => \&git_search,
 179        "shortlog" => \&git_shortlog,
 180        "summary" => \&git_summary,
 181        "tag" => \&git_tag,
 182        "tags" => \&git_tags,
 183        "tree" => \&git_tree,
 184);
 185
 186$action = 'summary' if (!defined($action));
 187if (!defined($actions{$action})) {
 188        undef $action;
 189        die_error(undef, "Unknown action.");
 190}
 191$actions{$action}->();
 192exit;
 193
 194## ======================================================================
 195## validation, quoting/unquoting and escaping
 196
 197sub validate_input {
 198        my $input = shift;
 199
 200        if ($input =~ m/^[0-9a-fA-F]{40}$/) {
 201                return $input;
 202        }
 203        if ($input =~ m/(^|\/)(|\.|\.\.)($|\/)/) {
 204                return undef;
 205        }
 206        if ($input =~ m/[^a-zA-Z0-9_\x80-\xff\ \t\.\/\-\+\#\~\%]/) {
 207                return undef;
 208        }
 209        return $input;
 210}
 211
 212# quote unsafe chars, but keep the slash, even when it's not
 213# correct, but quoted slashes look too horrible in bookmarks
 214sub esc_param {
 215        my $str = shift;
 216        $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
 217        $str =~ s/\+/%2B/g;
 218        $str =~ s/ /\+/g;
 219        return $str;
 220}
 221
 222# replace invalid utf8 character with SUBSTITUTION sequence
 223sub esc_html {
 224        my $str = shift;
 225        $str = decode("utf8", $str, Encode::FB_DEFAULT);
 226        $str = escapeHTML($str);
 227        $str =~ s/\014/^L/g; # escape FORM FEED (FF) character (e.g. in COPYING file)
 228        return $str;
 229}
 230
 231# git may return quoted and escaped filenames
 232sub unquote {
 233        my $str = shift;
 234        if ($str =~ m/^"(.*)"$/) {
 235                $str = $1;
 236                $str =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
 237        }
 238        return $str;
 239}
 240
 241## ----------------------------------------------------------------------
 242## HTML aware string manipulation
 243
 244sub chop_str {
 245        my $str = shift;
 246        my $len = shift;
 247        my $add_len = shift || 10;
 248
 249        # allow only $len chars, but don't cut a word if it would fit in $add_len
 250        # if it doesn't fit, cut it if it's still longer than the dots we would add
 251        $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
 252        my $body = $1;
 253        my $tail = $2;
 254        if (length($tail) > 4) {
 255                $tail = " ...";
 256                $body =~ s/&[^;]*$//; # remove chopped character entities
 257        }
 258        return "$body$tail";
 259}
 260
 261## ----------------------------------------------------------------------
 262## functions returning short strings
 263
 264# CSS class for given age value (in seconds)
 265sub age_class {
 266        my $age = shift;
 267
 268        if ($age < 60*60*2) {
 269                return "age0";
 270        } elsif ($age < 60*60*24*2) {
 271                return "age1";
 272        } else {
 273                return "age2";
 274        }
 275}
 276
 277# convert age in seconds to "nn units ago" string
 278sub age_string {
 279        my $age = shift;
 280        my $age_str;
 281
 282        if ($age > 60*60*24*365*2) {
 283                $age_str = (int $age/60/60/24/365);
 284                $age_str .= " years ago";
 285        } elsif ($age > 60*60*24*(365/12)*2) {
 286                $age_str = int $age/60/60/24/(365/12);
 287                $age_str .= " months ago";
 288        } elsif ($age > 60*60*24*7*2) {
 289                $age_str = int $age/60/60/24/7;
 290                $age_str .= " weeks ago";
 291        } elsif ($age > 60*60*24*2) {
 292                $age_str = int $age/60/60/24;
 293                $age_str .= " days ago";
 294        } elsif ($age > 60*60*2) {
 295                $age_str = int $age/60/60;
 296                $age_str .= " hours ago";
 297        } elsif ($age > 60*2) {
 298                $age_str = int $age/60;
 299                $age_str .= " min ago";
 300        } elsif ($age > 2) {
 301                $age_str = int $age;
 302                $age_str .= " sec ago";
 303        } else {
 304                $age_str .= " right now";
 305        }
 306        return $age_str;
 307}
 308
 309# convert file mode in octal to symbolic file mode string
 310sub mode_str {
 311        my $mode = oct shift;
 312
 313        if (S_ISDIR($mode & S_IFMT)) {
 314                return 'drwxr-xr-x';
 315        } elsif (S_ISLNK($mode)) {
 316                return 'lrwxrwxrwx';
 317        } elsif (S_ISREG($mode)) {
 318                # git cares only about the executable bit
 319                if ($mode & S_IXUSR) {
 320                        return '-rwxr-xr-x';
 321                } else {
 322                        return '-rw-r--r--';
 323                };
 324        } else {
 325                return '----------';
 326        }
 327}
 328
 329# convert file mode in octal to file type string
 330sub file_type {
 331        my $mode = oct shift;
 332
 333        if (S_ISDIR($mode & S_IFMT)) {
 334                return "directory";
 335        } elsif (S_ISLNK($mode)) {
 336                return "symlink";
 337        } elsif (S_ISREG($mode)) {
 338                return "file";
 339        } else {
 340                return "unknown";
 341        }
 342}
 343
 344## ----------------------------------------------------------------------
 345## functions returning short HTML fragments, or transforming HTML fragments
 346## which don't beling to other sections
 347
 348# format line of commit message or tag comment
 349sub format_log_line_html {
 350        my $line = shift;
 351
 352        $line = esc_html($line);
 353        $line =~ s/ /&nbsp;/g;
 354        if ($line =~ m/([0-9a-fA-F]{40})/) {
 355                my $hash_text = $1;
 356                if (git_get_type($hash_text) eq "commit") {
 357                        my $link = $cgi->a({-class => "text", -href => "$my_uri?" . esc_param("p=$project;a=commit;h=$hash_text")}, $hash_text);
 358                        $line =~ s/$hash_text/$link/;
 359                }
 360        }
 361        return $line;
 362}
 363
 364# format marker of refs pointing to given object
 365sub git_get_referencing {
 366        my ($refs, $id) = @_;
 367
 368        if (defined $refs->{$id}) {
 369                return ' <span class="tag">' . esc_html($refs->{$id}) . '</span>';
 370        } else {
 371                return "";
 372        }
 373}
 374
 375## ----------------------------------------------------------------------
 376## git utility subroutines, invoking git commands
 377
 378# get HEAD ref of given project as hash
 379sub git_read_head {
 380        my $project = shift;
 381        my $oENV = $ENV{'GIT_DIR'};
 382        my $retval = undef;
 383        $ENV{'GIT_DIR'} = "$projectroot/$project";
 384        if (open my $fd, "-|", $GIT, "rev-parse", "--verify", "HEAD") {
 385                my $head = <$fd>;
 386                close $fd;
 387                if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
 388                        $retval = $1;
 389                }
 390        }
 391        if (defined $oENV) {
 392                $ENV{'GIT_DIR'} = $oENV;
 393        }
 394        return $retval;
 395}
 396
 397# get type of given object
 398sub git_get_type {
 399        my $hash = shift;
 400
 401        open my $fd, "-|", $GIT, "cat-file", '-t', $hash or return;
 402        my $type = <$fd>;
 403        close $fd or return;
 404        chomp $type;
 405        return $type;
 406}
 407
 408sub git_get_project_config {
 409        my $key = shift;
 410
 411        return unless ($key);
 412        $key =~ s/^gitweb\.//;
 413        return if ($key =~ m/\W/);
 414
 415        my $val = qx($GIT repo-config --get gitweb.$key);
 416        return ($val);
 417}
 418
 419sub git_get_project_config_bool {
 420        my $val = git_get_project_config (@_);
 421        if ($val and $val =~ m/true|yes|on/) {
 422                return (1);
 423        }
 424        return; # implicit false
 425}
 426
 427# get hash of given path at given ref
 428sub git_get_hash_by_path {
 429        my $base = shift;
 430        my $path = shift || return undef;
 431
 432        my $tree = $base;
 433
 434        open my $fd, "-|", $GIT, "ls-tree", $base, "--", $path
 435                or die_error(undef, "Open git-ls-tree failed.");
 436        my $line = <$fd>;
 437        close $fd or return undef;
 438
 439        #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
 440        $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
 441        return $3;
 442}
 443
 444## ......................................................................
 445## git utility functions, directly accessing git repository
 446
 447# assumes that PATH is not symref
 448sub git_read_hash {
 449        my $path = shift;
 450
 451        open my $fd, "$projectroot/$path" or return undef;
 452        my $head = <$fd>;
 453        close $fd;
 454        chomp $head;
 455        if ($head =~ m/^[0-9a-fA-F]{40}$/) {
 456                return $head;
 457        }
 458}
 459
 460sub git_read_description {
 461        my $path = shift;
 462
 463        open my $fd, "$projectroot/$path/description" or return undef;
 464        my $descr = <$fd>;
 465        close $fd;
 466        chomp $descr;
 467        return $descr;
 468}
 469
 470sub git_read_projects {
 471        my @list;
 472
 473        if (-d $projects_list) {
 474                # search in directory
 475                my $dir = $projects_list;
 476                opendir my ($dh), $dir or return undef;
 477                while (my $dir = readdir($dh)) {
 478                        if (-e "$projectroot/$dir/HEAD") {
 479                                my $pr = {
 480                                        path => $dir,
 481                                };
 482                                push @list, $pr
 483                        }
 484                }
 485                closedir($dh);
 486        } elsif (-f $projects_list) {
 487                # read from file(url-encoded):
 488                # 'git%2Fgit.git Linus+Torvalds'
 489                # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
 490                # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
 491                open my ($fd), $projects_list or return undef;
 492                while (my $line = <$fd>) {
 493                        chomp $line;
 494                        my ($path, $owner) = split ' ', $line;
 495                        $path = unescape($path);
 496                        $owner = unescape($owner);
 497                        if (!defined $path) {
 498                                next;
 499                        }
 500                        if (-e "$projectroot/$path/HEAD") {
 501                                my $pr = {
 502                                        path => $path,
 503                                        owner => decode("utf8", $owner, Encode::FB_DEFAULT),
 504                                };
 505                                push @list, $pr
 506                        }
 507                }
 508                close $fd;
 509        }
 510        @list = sort {$a->{'path'} cmp $b->{'path'}} @list;
 511        return @list;
 512}
 513
 514sub read_info_ref {
 515        my $type = shift || "";
 516        my %refs;
 517        # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c      refs/tags/v2.6.11
 518        # c39ae07f393806ccf406ef966e9a15afc43cc36a      refs/tags/v2.6.11^{}
 519        open my $fd, "$projectroot/$project/info/refs" or return;
 520        while (my $line = <$fd>) {
 521                chomp $line;
 522                # attention: for $type == "" it saves only last path part of ref name
 523                # e.g. from 'refs/heads/jn/gitweb' it would leave only 'gitweb'
 524                if ($line =~ m/^([0-9a-fA-F]{40})\t.*$type\/([^\^]+)/) {
 525                        if (defined $refs{$1}) {
 526                                $refs{$1} .= " / $2";
 527                        } else {
 528                                $refs{$1} = $2;
 529                        }
 530                }
 531        }
 532        close $fd or return;
 533        return \%refs;
 534}
 535
 536## ----------------------------------------------------------------------
 537## parse to hash functions
 538
 539sub date_str {
 540        my $epoch = shift;
 541        my $tz = shift || "-0000";
 542
 543        my %date;
 544        my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
 545        my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
 546        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
 547        $date{'hour'} = $hour;
 548        $date{'minute'} = $min;
 549        $date{'mday'} = $mday;
 550        $date{'day'} = $days[$wday];
 551        $date{'month'} = $months[$mon];
 552        $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000", $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
 553        $date{'mday-time'} = sprintf "%d %s %02d:%02d", $mday, $months[$mon], $hour ,$min;
 554
 555        $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
 556        my $local = $epoch + ((int $1 + ($2/60)) * 3600);
 557        ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
 558        $date{'hour_local'} = $hour;
 559        $date{'minute_local'} = $min;
 560        $date{'tz_local'} = $tz;
 561        return %date;
 562}
 563
 564sub git_read_tag {
 565        my $tag_id = shift;
 566        my %tag;
 567        my @comment;
 568
 569        open my $fd, "-|", $GIT, "cat-file", "tag", $tag_id or return;
 570        $tag{'id'} = $tag_id;
 571        while (my $line = <$fd>) {
 572                chomp $line;
 573                if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
 574                        $tag{'object'} = $1;
 575                } elsif ($line =~ m/^type (.+)$/) {
 576                        $tag{'type'} = $1;
 577                } elsif ($line =~ m/^tag (.+)$/) {
 578                        $tag{'name'} = $1;
 579                } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
 580                        $tag{'author'} = $1;
 581                        $tag{'epoch'} = $2;
 582                        $tag{'tz'} = $3;
 583                } elsif ($line =~ m/--BEGIN/) {
 584                        push @comment, $line;
 585                        last;
 586                } elsif ($line eq "") {
 587                        last;
 588                }
 589        }
 590        push @comment, <$fd>;
 591        $tag{'comment'} = \@comment;
 592        close $fd or return;
 593        if (!defined $tag{'name'}) {
 594                return
 595        };
 596        return %tag
 597}
 598
 599sub git_read_commit {
 600        my $commit_id = shift;
 601        my $commit_text = shift;
 602
 603        my @commit_lines;
 604        my %co;
 605
 606        if (defined $commit_text) {
 607                @commit_lines = @$commit_text;
 608        } else {
 609                $/ = "\0";
 610                open my $fd, "-|", $GIT, "rev-list", "--header", "--parents", "--max-count=1", $commit_id or return;
 611                @commit_lines = split '\n', <$fd>;
 612                close $fd or return;
 613                $/ = "\n";
 614                pop @commit_lines;
 615        }
 616        my $header = shift @commit_lines;
 617        if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
 618                return;
 619        }
 620        ($co{'id'}, my @parents) = split ' ', $header;
 621        $co{'parents'} = \@parents;
 622        $co{'parent'} = $parents[0];
 623        while (my $line = shift @commit_lines) {
 624                last if $line eq "\n";
 625                if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
 626                        $co{'tree'} = $1;
 627                } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
 628                        $co{'author'} = $1;
 629                        $co{'author_epoch'} = $2;
 630                        $co{'author_tz'} = $3;
 631                        if ($co{'author'} =~ m/^([^<]+) </) {
 632                                $co{'author_name'} = $1;
 633                        } else {
 634                                $co{'author_name'} = $co{'author'};
 635                        }
 636                } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
 637                        $co{'committer'} = $1;
 638                        $co{'committer_epoch'} = $2;
 639                        $co{'committer_tz'} = $3;
 640                        $co{'committer_name'} = $co{'committer'};
 641                        $co{'committer_name'} =~ s/ <.*//;
 642                }
 643        }
 644        if (!defined $co{'tree'}) {
 645                return;
 646        };
 647
 648        foreach my $title (@commit_lines) {
 649                $title =~ s/^    //;
 650                if ($title ne "") {
 651                        $co{'title'} = chop_str($title, 80, 5);
 652                        # remove leading stuff of merges to make the interesting part visible
 653                        if (length($title) > 50) {
 654                                $title =~ s/^Automatic //;
 655                                $title =~ s/^merge (of|with) /Merge ... /i;
 656                                if (length($title) > 50) {
 657                                        $title =~ s/(http|rsync):\/\///;
 658                                }
 659                                if (length($title) > 50) {
 660                                        $title =~ s/(master|www|rsync)\.//;
 661                                }
 662                                if (length($title) > 50) {
 663                                        $title =~ s/kernel.org:?//;
 664                                }
 665                                if (length($title) > 50) {
 666                                        $title =~ s/\/pub\/scm//;
 667                                }
 668                        }
 669                        $co{'title_short'} = chop_str($title, 50, 5);
 670                        last;
 671                }
 672        }
 673        # remove added spaces
 674        foreach my $line (@commit_lines) {
 675                $line =~ s/^    //;
 676        }
 677        $co{'comment'} = \@commit_lines;
 678
 679        my $age = time - $co{'committer_epoch'};
 680        $co{'age'} = $age;
 681        $co{'age_string'} = age_string($age);
 682        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
 683        if ($age > 60*60*24*7*2) {
 684                $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
 685                $co{'age_string_age'} = $co{'age_string'};
 686        } else {
 687                $co{'age_string_date'} = $co{'age_string'};
 688                $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
 689        }
 690        return %co;
 691}
 692
 693## ......................................................................
 694## parse to array of hashes functions
 695
 696sub git_read_refs {
 697        my $ref_dir = shift;
 698        my @reflist;
 699
 700        my @refs;
 701        my $pfxlen = length("$projectroot/$project/$ref_dir");
 702        File::Find::find(sub {
 703                return if (/^\./);
 704                if (-f $_) {
 705                        push @refs, substr($File::Find::name, $pfxlen + 1);
 706                }
 707        }, "$projectroot/$project/$ref_dir");
 708
 709        foreach my $ref_file (@refs) {
 710                my $ref_id = git_read_hash("$project/$ref_dir/$ref_file");
 711                my $type = git_get_type($ref_id) || next;
 712                my %ref_item;
 713                my %co;
 714                $ref_item{'type'} = $type;
 715                $ref_item{'id'} = $ref_id;
 716                $ref_item{'epoch'} = 0;
 717                $ref_item{'age'} = "unknown";
 718                if ($type eq "tag") {
 719                        my %tag = git_read_tag($ref_id);
 720                        $ref_item{'comment'} = $tag{'comment'};
 721                        if ($tag{'type'} eq "commit") {
 722                                %co = git_read_commit($tag{'object'});
 723                                $ref_item{'epoch'} = $co{'committer_epoch'};
 724                                $ref_item{'age'} = $co{'age_string'};
 725                        } elsif (defined($tag{'epoch'})) {
 726                                my $age = time - $tag{'epoch'};
 727                                $ref_item{'epoch'} = $tag{'epoch'};
 728                                $ref_item{'age'} = age_string($age);
 729                        }
 730                        $ref_item{'reftype'} = $tag{'type'};
 731                        $ref_item{'name'} = $tag{'name'};
 732                        $ref_item{'refid'} = $tag{'object'};
 733                } elsif ($type eq "commit"){
 734                        %co = git_read_commit($ref_id);
 735                        $ref_item{'reftype'} = "commit";
 736                        $ref_item{'name'} = $ref_file;
 737                        $ref_item{'title'} = $co{'title'};
 738                        $ref_item{'refid'} = $ref_id;
 739                        $ref_item{'epoch'} = $co{'committer_epoch'};
 740                        $ref_item{'age'} = $co{'age_string'};
 741                } else {
 742                        $ref_item{'reftype'} = $type;
 743                        $ref_item{'name'} = $ref_file;
 744                        $ref_item{'refid'} = $ref_id;
 745                }
 746
 747                push @reflist, \%ref_item;
 748        }
 749        # sort tags by age
 750        @reflist = sort {$b->{'epoch'} <=> $a->{'epoch'}} @reflist;
 751        return \@reflist;
 752}
 753
 754## ----------------------------------------------------------------------
 755## filesystem-related functions
 756
 757sub get_file_owner {
 758        my $path = shift;
 759
 760        my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
 761        my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
 762        if (!defined $gcos) {
 763                return undef;
 764        }
 765        my $owner = $gcos;
 766        $owner =~ s/[,;].*$//;
 767        return decode("utf8", $owner, Encode::FB_DEFAULT);
 768}
 769
 770## ......................................................................
 771## mimetype related functions
 772
 773sub mimetype_guess_file {
 774        my $filename = shift;
 775        my $mimemap = shift;
 776        -r $mimemap or return undef;
 777
 778        my %mimemap;
 779        open(MIME, $mimemap) or return undef;
 780        while (<MIME>) {
 781                my ($mime, $exts) = split(/\t+/);
 782                my @exts = split(/\s+/, $exts);
 783                foreach my $ext (@exts) {
 784                        $mimemap{$ext} = $mime;
 785                }
 786        }
 787        close(MIME);
 788
 789        $filename =~ /\.(.*?)$/;
 790        return $mimemap{$1};
 791}
 792
 793sub mimetype_guess {
 794        my $filename = shift;
 795        my $mime;
 796        $filename =~ /\./ or return undef;
 797
 798        if ($mimetypes_file) {
 799                my $file = $mimetypes_file;
 800                #$file =~ m#^/# or $file = "$projectroot/$path/$file";
 801                $mime = mimetype_guess_file($filename, $file);
 802        }
 803        $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
 804        return $mime;
 805}
 806
 807sub git_blob_plain_mimetype {
 808        my $fd = shift;
 809        my $filename = shift;
 810
 811        if ($filename) {
 812                my $mime = mimetype_guess($filename);
 813                $mime and return $mime;
 814        }
 815
 816        # just in case
 817        return $default_blob_plain_mimetype unless $fd;
 818
 819        if (-T $fd) {
 820                return 'text/plain' .
 821                       ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
 822        } elsif (! $filename) {
 823                return 'application/octet-stream';
 824        } elsif ($filename =~ m/\.png$/i) {
 825                return 'image/png';
 826        } elsif ($filename =~ m/\.gif$/i) {
 827                return 'image/gif';
 828        } elsif ($filename =~ m/\.jpe?g$/i) {
 829                return 'image/jpeg';
 830        } else {
 831                return 'application/octet-stream';
 832        }
 833}
 834
 835## ======================================================================
 836## functions printing HTML: header, footer, error page
 837
 838sub git_header_html {
 839        my $status = shift || "200 OK";
 840        my $expires = shift;
 841
 842        my $title = "$site_name git";
 843        if (defined $project) {
 844                $title .= " - $project";
 845                if (defined $action) {
 846                        $title .= "/$action";
 847                        if (defined $file_name) {
 848                                $title .= " - $file_name";
 849                                if ($action eq "tree" && $file_name !~ m|/$|) {
 850                                        $title .= "/";
 851                                }
 852                        }
 853                }
 854        }
 855        my $content_type;
 856        # require explicit support from the UA if we are to send the page as
 857        # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
 858        # we have to do this because MSIE sometimes globs '*/*', pretending to
 859        # support xhtml+xml but choking when it gets what it asked for.
 860        if ($cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ && $cgi->Accept('application/xhtml+xml') != 0) {
 861                $content_type = 'application/xhtml+xml';
 862        } else {
 863                $content_type = 'text/html';
 864        }
 865        print $cgi->header(-type=>$content_type, -charset => 'utf-8', -status=> $status, -expires => $expires);
 866        print <<EOF;
 867<?xml version="1.0" encoding="utf-8"?>
 868<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 869<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
 870<!-- git web interface v$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
 871<!-- git core binaries version $git_version -->
 872<head>
 873<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
 874<meta name="robots" content="index, nofollow"/>
 875<title>$title</title>
 876<link rel="stylesheet" type="text/css" href="$stylesheet"/>
 877$rss_link
 878</head>
 879<body>
 880EOF
 881        print "<div class=\"page_header\">\n" .
 882              "<a href=\"http://www.kernel.org/pub/software/scm/git/docs/\" title=\"git documentation\">" .
 883              "<img src=\"$my_uri?" . esc_param("a=git-logo.png") . "\" width=\"72\" height=\"27\" alt=\"git\" style=\"float:right; border-width:0px;\"/>" .
 884              "</a>\n";
 885        print $cgi->a({-href => esc_param($home_link)}, "projects") . " / ";
 886        if (defined $project) {
 887                print $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=summary")}, esc_html($project));
 888                if (defined $action) {
 889                        print " / $action";
 890                }
 891                print "\n";
 892                if (!defined $searchtext) {
 893                        $searchtext = "";
 894                }
 895                my $search_hash;
 896                if (defined $hash_base) {
 897                        $search_hash = $hash_base;
 898                } elsif (defined $hash) {
 899                        $search_hash = $hash;
 900                } else {
 901                        $search_hash = "HEAD";
 902                }
 903                $cgi->param("a", "search");
 904                $cgi->param("h", $search_hash);
 905                print $cgi->startform(-method => "get", -action => $my_uri) .
 906                      "<div class=\"search\">\n" .
 907                      $cgi->hidden(-name => "p") . "\n" .
 908                      $cgi->hidden(-name => "a") . "\n" .
 909                      $cgi->hidden(-name => "h") . "\n" .
 910                      $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
 911                      "</div>" .
 912                      $cgi->end_form() . "\n";
 913        }
 914        print "</div>\n";
 915}
 916
 917sub git_footer_html {
 918        print "<div class=\"page_footer\">\n";
 919        if (defined $project) {
 920                my $descr = git_read_description($project);
 921                if (defined $descr) {
 922                        print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
 923                }
 924                print $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=rss"), -class => "rss_logo"}, "RSS") . "\n";
 925        } else {
 926                print $cgi->a({-href => "$my_uri?" . esc_param("a=opml"), -class => "rss_logo"}, "OPML") . "\n";
 927        }
 928        print "</div>\n" .
 929              "</body>\n" .
 930              "</html>";
 931}
 932
 933sub die_error {
 934        my $status = shift || "403 Forbidden";
 935        my $error = shift || "Malformed query, file missing or permission denied";
 936
 937        git_header_html($status);
 938        print "<div class=\"page_body\">\n" .
 939              "<br/><br/>\n" .
 940              "$status - $error\n" .
 941              "<br/>\n" .
 942              "</div>\n";
 943        git_footer_html();
 944        exit;
 945}
 946
 947## ----------------------------------------------------------------------
 948## functions printing or outputting HTML: navigation
 949
 950sub git_page_nav {
 951        my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
 952        $extra = '' if !defined $extra; # pager or formats
 953
 954        my @navs = qw(summary shortlog log commit commitdiff tree);
 955        if ($suppress) {
 956                @navs = grep { $_ ne $suppress } @navs;
 957        }
 958
 959        my %arg = map { $_, ''} @navs;
 960        if (defined $head) {
 961                for (qw(commit commitdiff)) {
 962                        $arg{$_} = ";h=$head";
 963                }
 964                if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
 965                        for (qw(shortlog log)) {
 966                                $arg{$_} = ";h=$head";
 967                        }
 968                }
 969        }
 970        $arg{tree} .= ";h=$treehead" if defined $treehead;
 971        $arg{tree} .= ";hb=$treebase" if defined $treebase;
 972
 973        print "<div class=\"page_nav\">\n" .
 974                (join " | ",
 975                 map { $_ eq $current
 976                                         ? $_
 977                                         : $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=$_$arg{$_}")}, "$_")
 978                                 }
 979                 @navs);
 980        print "<br/>\n$extra<br/>\n" .
 981              "</div>\n";
 982}
 983
 984sub git_get_paging_nav {
 985        my ($action, $hash, $head, $page, $nrevs) = @_;
 986        my $paging_nav;
 987
 988
 989        if ($hash ne $head || $page) {
 990                $paging_nav .= $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=$action")}, "HEAD");
 991        } else {
 992                $paging_nav .= "HEAD";
 993        }
 994
 995        if ($page > 0) {
 996                $paging_nav .= " &sdot; " .
 997                        $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=$action;h=$hash;pg=" . ($page-1)),
 998                                                         -accesskey => "p", -title => "Alt-p"}, "prev");
 999        } else {
1000                $paging_nav .= " &sdot; prev";
1001        }
1002
1003        if ($nrevs >= (100 * ($page+1)-1)) {
1004                $paging_nav .= " &sdot; " .
1005                        $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=$action;h=$hash;pg=" . ($page+1)),
1006                                                         -accesskey => "n", -title => "Alt-n"}, "next");
1007        } else {
1008                $paging_nav .= " &sdot; next";
1009        }
1010
1011        return $paging_nav;
1012}
1013
1014## ......................................................................
1015## functions printing or outputting HTML: div
1016
1017sub git_header_div {
1018        my ($action, $title, $hash, $hash_base) = @_;
1019        my $rest = '';
1020
1021        $rest .= ";h=$hash" if $hash;
1022        $rest .= ";hb=$hash_base" if $hash_base;
1023
1024        print "<div class=\"header\">\n" .
1025              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=$action$rest"),
1026                       -class => "title"}, $title ? $title : $action) . "\n" .
1027              "</div>\n";
1028}
1029
1030sub git_print_page_path {
1031        my $name = shift;
1032        my $type = shift;
1033
1034        if (!defined $name) {
1035                print "<div class=\"page_path\"><b>/</b></div>\n";
1036        } elsif ($type =~ "blob") {
1037                print "<div class=\"page_path\"><b>" .
1038                        $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob_plain;f=$file_name")}, esc_html($name)) . "</b><br/></div>\n";
1039        } else {
1040                print "<div class=\"page_path\"><b>" . esc_html($name) . "</b><br/></div>\n";
1041        }
1042}
1043
1044## ......................................................................
1045## functions printing large fragments of HTML
1046
1047sub git_shortlog_body {
1048        # uses global variable $project
1049        my ($revlist, $from, $to, $refs, $extra) = @_;
1050        $from = 0 unless defined $from;
1051        $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
1052
1053        print "<table class=\"shortlog\" cellspacing=\"0\">\n";
1054        my $alternate = 0;
1055        for (my $i = $from; $i <= $to; $i++) {
1056                my $commit = $revlist->[$i];
1057                #my $ref = defined $refs ? git_get_referencing($refs, $commit) : '';
1058                my $ref = git_get_referencing($refs, $commit);
1059                my %co = git_read_commit($commit);
1060                my %ad = date_str($co{'author_epoch'});
1061                if ($alternate) {
1062                        print "<tr class=\"dark\">\n";
1063                } else {
1064                        print "<tr class=\"light\">\n";
1065                }
1066                $alternate ^= 1;
1067                # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
1068                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1069                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
1070                      "<td>";
1071                if (length($co{'title_short'}) < length($co{'title'})) {
1072                        print $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$commit"),
1073                                       -class => "list", -title => "$co{'title'}"},
1074                              "<b>" . esc_html($co{'title_short'}) . "$ref</b>");
1075                } else {
1076                        print $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$commit"),
1077                                       -class => "list"},
1078                              "<b>" . esc_html($co{'title'}) . "$ref</b>");
1079                }
1080                print "</td>\n" .
1081                      "<td class=\"link\">" .
1082                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$commit")}, "commit") . " | " .
1083                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commitdiff;h=$commit")}, "commitdiff") .
1084                      "</td>\n" .
1085                      "</tr>\n";
1086        }
1087        if (defined $extra) {
1088                print "<tr>\n" .
1089                      "<td colspan=\"4\">$extra</td>\n" .
1090                      "</tr>\n";
1091        }
1092        print "</table>\n";
1093}
1094
1095sub git_tags_body {
1096        # uses global variable $project
1097        my ($taglist, $from, $to, $extra) = @_;
1098        $from = 0 unless defined $from;
1099        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
1100
1101        print "<table class=\"tags\" cellspacing=\"0\">\n";
1102        my $alternate = 0;
1103        for (my $i = $from; $i <= $to; $i++) {
1104                my $entry = $taglist->[$i];
1105                my %tag = %$entry;
1106                my $comment_lines = $tag{'comment'};
1107                my $comment = shift @$comment_lines;
1108                my $comment_short;
1109                if (defined $comment) {
1110                        $comment_short = chop_str($comment, 30, 5);
1111                }
1112                if ($alternate) {
1113                        print "<tr class=\"dark\">\n";
1114                } else {
1115                        print "<tr class=\"light\">\n";
1116                }
1117                $alternate ^= 1;
1118                print "<td><i>$tag{'age'}</i></td>\n" .
1119                      "<td>" .
1120                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=$tag{'reftype'};h=$tag{'refid'}"),
1121                               -class => "list"}, "<b>" . esc_html($tag{'name'}) . "</b>") .
1122                      "</td>\n" .
1123                      "<td>";
1124                if (defined $comment) {
1125                        if (length($comment_short) < length($comment)) {
1126                                print $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tag;h=$tag{'id'}"),
1127                                               -class => "list", -title => $comment}, $comment_short);
1128                        } else {
1129                                print $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tag;h=$tag{'id'}"),
1130                                               -class => "list"}, $comment);
1131                        }
1132                }
1133                print "</td>\n" .
1134                      "<td class=\"selflink\">";
1135                if ($tag{'type'} eq "tag") {
1136                        print $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tag;h=$tag{'id'}")}, "tag");
1137                } else {
1138                        print "&nbsp;";
1139                }
1140                print "</td>\n" .
1141                      "<td class=\"link\">" . " | " .
1142                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=$tag{'reftype'};h=$tag{'refid'}")}, $tag{'reftype'});
1143                if ($tag{'reftype'} eq "commit") {
1144                        print " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=shortlog;h=$tag{'name'}")}, "shortlog") .
1145                              " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=log;h=$tag{'refid'}")}, "log");
1146                } elsif ($tag{'reftype'} eq "blob") {
1147                        print " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob_plain;h=$tag{'refid'}")}, "raw");
1148                }
1149                print "</td>\n" .
1150                      "</tr>";
1151        }
1152        if (defined $extra) {
1153                print "<tr>\n" .
1154                      "<td colspan=\"5\">$extra</td>\n" .
1155                      "</tr>\n";
1156        }
1157        print "</table>\n";
1158}
1159
1160sub git_heads_body {
1161        # uses global variable $project
1162        my ($taglist, $head, $from, $to, $extra) = @_;
1163        $from = 0 unless defined $from;
1164        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
1165
1166        print "<table class=\"heads\" cellspacing=\"0\">\n";
1167        my $alternate = 0;
1168        for (my $i = $from; $i <= $to; $i++) {
1169                my $entry = $taglist->[$i];
1170                my %tag = %$entry;
1171                my $curr = $tag{'id'} eq $head;
1172                if ($alternate) {
1173                        print "<tr class=\"dark\">\n";
1174                } else {
1175                        print "<tr class=\"light\">\n";
1176                }
1177                $alternate ^= 1;
1178                print "<td><i>$tag{'age'}</i></td>\n" .
1179                      ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
1180                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=shortlog;h=$tag{'name'}"),
1181                               -class => "list"}, "<b>" . esc_html($tag{'name'}) . "</b>") .
1182                      "</td>\n" .
1183                      "<td class=\"link\">" .
1184                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=shortlog;h=$tag{'name'}")}, "shortlog") . " | " .
1185                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=log;h=$tag{'name'}")}, "log") .
1186                      "</td>\n" .
1187                      "</tr>";
1188        }
1189        if (defined $extra) {
1190                print "<tr>\n" .
1191                      "<td colspan=\"3\">$extra</td>\n" .
1192                      "</tr>\n";
1193        }
1194        print "</table>\n";
1195}
1196
1197## ----------------------------------------------------------------------
1198## functions printing large fragments, format as one of arguments
1199
1200sub git_diff_print {
1201        my $from = shift;
1202        my $from_name = shift;
1203        my $to = shift;
1204        my $to_name = shift;
1205        my $format = shift || "html";
1206
1207        my $from_tmp = "/dev/null";
1208        my $to_tmp = "/dev/null";
1209        my $pid = $$;
1210
1211        # create tmp from-file
1212        if (defined $from) {
1213                $from_tmp = "$git_temp/gitweb_" . $$ . "_from";
1214                open my $fd2, "> $from_tmp";
1215                open my $fd, "-|", $GIT, "cat-file", "blob", $from;
1216                my @file = <$fd>;
1217                print $fd2 @file;
1218                close $fd2;
1219                close $fd;
1220        }
1221
1222        # create tmp to-file
1223        if (defined $to) {
1224                $to_tmp = "$git_temp/gitweb_" . $$ . "_to";
1225                open my $fd2, "> $to_tmp";
1226                open my $fd, "-|", $GIT, "cat-file", "blob", $to;
1227                my @file = <$fd>;
1228                print $fd2 @file;
1229                close $fd2;
1230                close $fd;
1231        }
1232
1233        open my $fd, "-|", "/usr/bin/diff -u -p -L \'$from_name\' -L \'$to_name\' $from_tmp $to_tmp";
1234        if ($format eq "plain") {
1235                undef $/;
1236                print <$fd>;
1237                $/ = "\n";
1238        } else {
1239                while (my $line = <$fd>) {
1240                        chomp $line;
1241                        my $char = substr($line, 0, 1);
1242                        my $diff_class = "";
1243                        if ($char eq '+') {
1244                                $diff_class = " add";
1245                        } elsif ($char eq "-") {
1246                                $diff_class = " rem";
1247                        } elsif ($char eq "@") {
1248                                $diff_class = " chunk_header";
1249                        } elsif ($char eq "\\") {
1250                                # skip errors
1251                                next;
1252                        }
1253                        while ((my $pos = index($line, "\t")) != -1) {
1254                                if (my $count = (8 - (($pos-1) % 8))) {
1255                                        my $spaces = ' ' x $count;
1256                                        $line =~ s/\t/$spaces/;
1257                                }
1258                        }
1259                        print "<div class=\"diff$diff_class\">" . esc_html($line) . "</div>\n";
1260                }
1261        }
1262        close $fd;
1263
1264        if (defined $from) {
1265                unlink($from_tmp);
1266        }
1267        if (defined $to) {
1268                unlink($to_tmp);
1269        }
1270}
1271
1272
1273## ======================================================================
1274## ======================================================================
1275## actions
1276
1277# git-logo (cached in browser for one day)
1278sub git_logo {
1279        binmode STDOUT, ':raw';
1280        print $cgi->header(-type => 'image/png', -expires => '+1d');
1281        # cat git-logo.png | hexdump -e '16/1 " %02x"  "\n"' | sed 's/ /\\x/g'
1282        print   "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52" .
1283                "\x00\x00\x00\x48\x00\x00\x00\x1b\x04\x03\x00\x00\x00\x2d\xd9\xd4" .
1284                "\x2d\x00\x00\x00\x18\x50\x4c\x54\x45\xff\xff\xff\x60\x60\x5d\xb0" .
1285                "\xaf\xaa\x00\x80\x00\xce\xcd\xc7\xc0\x00\x00\xe8\xe8\xe6\xf7\xf7" .
1286                "\xf6\x95\x0c\xa7\x47\x00\x00\x00\x73\x49\x44\x41\x54\x28\xcf\x63" .
1287                "\x48\x67\x20\x04\x4a\x5c\x18\x0a\x08\x2a\x62\x53\x61\x20\x02\x08" .
1288                "\x0d\x69\x45\xac\xa1\xa1\x01\x30\x0c\x93\x60\x36\x26\x52\x91\xb1" .
1289                "\x01\x11\xd6\xe1\x55\x64\x6c\x6c\xcc\x6c\x6c\x0c\xa2\x0c\x70\x2a" .
1290                "\x62\x06\x2a\xc1\x62\x1d\xb3\x01\x02\x53\xa4\x08\xe8\x00\x03\x18" .
1291                "\x26\x56\x11\xd4\xe1\x20\x97\x1b\xe0\xb4\x0e\x35\x24\x71\x29\x82" .
1292                "\x99\x30\xb8\x93\x0a\x11\xb9\x45\x88\xc1\x8d\xa0\xa2\x44\x21\x06" .
1293                "\x27\x41\x82\x40\x85\xc1\x45\x89\x20\x70\x01\x00\xa4\x3d\x21\xc5" .
1294                "\x12\x1c\x9a\xfe\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82";
1295}
1296
1297sub git_project_list {
1298        my @list = git_read_projects();
1299        my @projects;
1300        if (!@list) {
1301                die_error(undef, "No project found.");
1302        }
1303        foreach my $pr (@list) {
1304                my $head = git_read_head($pr->{'path'});
1305                if (!defined $head) {
1306                        next;
1307                }
1308                $ENV{'GIT_DIR'} = "$projectroot/$pr->{'path'}";
1309                my %co = git_read_commit($head);
1310                if (!%co) {
1311                        next;
1312                }
1313                $pr->{'commit'} = \%co;
1314                if (!defined $pr->{'descr'}) {
1315                        my $descr = git_read_description($pr->{'path'}) || "";
1316                        $pr->{'descr'} = chop_str($descr, 25, 5);
1317                }
1318                if (!defined $pr->{'owner'}) {
1319                        $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
1320                }
1321                push @projects, $pr;
1322        }
1323        git_header_html();
1324        if (-f $home_text) {
1325                print "<div class=\"index_include\">\n";
1326                open (my $fd, $home_text);
1327                print <$fd>;
1328                close $fd;
1329                print "</div>\n";
1330        }
1331        print "<table class=\"project_list\">\n" .
1332              "<tr>\n";
1333        if (!defined($order) || (defined($order) && ($order eq "project"))) {
1334                @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
1335                print "<th>Project</th>\n";
1336        } else {
1337                print "<th>" . $cgi->a({-class => "header", -href => "$my_uri?" . esc_param("o=project")}, "Project") . "</th>\n";
1338        }
1339        if (defined($order) && ($order eq "descr")) {
1340                @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
1341                print "<th>Description</th>\n";
1342        } else {
1343                print "<th>" . $cgi->a({-class => "header", -href => "$my_uri?" . esc_param("o=descr")}, "Description") . "</th>\n";
1344        }
1345        if (defined($order) && ($order eq "owner")) {
1346                @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
1347                print "<th>Owner</th>\n";
1348        } else {
1349                print "<th>" . $cgi->a({-class => "header", -href => "$my_uri?" . esc_param("o=owner")}, "Owner") . "</th>\n";
1350        }
1351        if (defined($order) && ($order eq "age")) {
1352                @projects = sort {$a->{'commit'}{'age'} <=> $b->{'commit'}{'age'}} @projects;
1353                print "<th>Last Change</th>\n";
1354        } else {
1355                print "<th>" . $cgi->a({-class => "header", -href => "$my_uri?" . esc_param("o=age")}, "Last Change") . "</th>\n";
1356        }
1357        print "<th></th>\n" .
1358              "</tr>\n";
1359        my $alternate = 0;
1360        foreach my $pr (@projects) {
1361                if ($alternate) {
1362                        print "<tr class=\"dark\">\n";
1363                } else {
1364                        print "<tr class=\"light\">\n";
1365                }
1366                $alternate ^= 1;
1367                print "<td>" . $cgi->a({-href => "$my_uri?" . esc_param("p=$pr->{'path'};a=summary"), -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
1368                      "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
1369                      "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
1370                print "<td class=\"". age_class($pr->{'commit'}{'age'}) . "\">" . $pr->{'commit'}{'age_string'} . "</td>\n" .
1371                      "<td class=\"link\">" .
1372                      $cgi->a({-href => "$my_uri?" . esc_param("p=$pr->{'path'};a=summary")}, "summary") .
1373                      " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$pr->{'path'};a=shortlog")}, "shortlog") .
1374                      " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$pr->{'path'};a=log")}, "log") .
1375                      "</td>\n" .
1376                      "</tr>\n";
1377        }
1378        print "</table>\n";
1379        git_footer_html();
1380}
1381
1382sub git_summary {
1383        my $descr = git_read_description($project) || "none";
1384        my $head = git_read_head($project);
1385        my %co = git_read_commit($head);
1386        my %cd = date_str($co{'committer_epoch'}, $co{'committer_tz'});
1387
1388        my $owner;
1389        if (-f $projects_list) {
1390                open (my $fd , $projects_list);
1391                while (my $line = <$fd>) {
1392                        chomp $line;
1393                        my ($pr, $ow) = split ' ', $line;
1394                        $pr = unescape($pr);
1395                        $ow = unescape($ow);
1396                        if ($pr eq $project) {
1397                                $owner = decode("utf8", $ow, Encode::FB_DEFAULT);
1398                                last;
1399                        }
1400                }
1401                close $fd;
1402        }
1403        if (!defined $owner) {
1404                $owner = get_file_owner("$projectroot/$project");
1405        }
1406
1407        my $refs = read_info_ref();
1408        git_header_html();
1409        git_page_nav('summary','', $head);
1410
1411        print "<div class=\"title\">&nbsp;</div>\n";
1412        print "<table cellspacing=\"0\">\n" .
1413              "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
1414              "<tr><td>owner</td><td>$owner</td></tr>\n" .
1415              "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n" .
1416              "</table>\n";
1417
1418        open my $fd, "-|", $GIT, "rev-list", "--max-count=17", git_read_head($project)
1419                or die_error(undef, "Open git-rev-list failed.");
1420        my @revlist = map { chomp; $_ } <$fd>;
1421        close $fd;
1422        git_header_div('shortlog');
1423        git_shortlog_body(\@revlist, 0, 15, $refs,
1424                          $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=shortlog")}, "..."));
1425
1426        my $taglist = git_read_refs("refs/tags");
1427        if (defined @$taglist) {
1428                git_header_div('tags');
1429                git_tags_body($taglist, 0, 15,
1430                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tags")}, "..."));
1431        }
1432
1433        my $headlist = git_read_refs("refs/heads");
1434        if (defined @$headlist) {
1435                git_header_div('heads');
1436                git_heads_body($headlist, $head, 0, 15,
1437                               $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=heads")}, "..."));
1438        }
1439
1440        git_footer_html();
1441}
1442
1443sub git_tag {
1444        my $head = git_read_head($project);
1445        git_header_html();
1446        git_page_nav('','', $head,undef,$head);
1447        my %tag = git_read_tag($hash);
1448        git_header_div('commit', esc_html($tag{'name'}), $hash);
1449        print "<div class=\"title_text\">\n" .
1450              "<table cellspacing=\"0\">\n" .
1451              "<tr>\n" .
1452              "<td>object</td>\n" .
1453              "<td>" . $cgi->a({-class => "list", -href => "$my_uri?" . esc_param("p=$project;a=$tag{'type'};h=$tag{'object'}")}, $tag{'object'}) . "</td>\n" .
1454              "<td class=\"link\">" . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=$tag{'type'};h=$tag{'object'}")}, $tag{'type'}) . "</td>\n" .
1455              "</tr>\n";
1456        if (defined($tag{'author'})) {
1457                my %ad = date_str($tag{'epoch'}, $tag{'tz'});
1458                print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
1459                print "<tr><td></td><td>" . $ad{'rfc2822'} . sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) . "</td></tr>\n";
1460        }
1461        print "</table>\n\n" .
1462              "</div>\n";
1463        print "<div class=\"page_body\">";
1464        my $comment = $tag{'comment'};
1465        foreach my $line (@$comment) {
1466                print esc_html($line) . "<br/>\n";
1467        }
1468        print "</div>\n";
1469        git_footer_html();
1470}
1471
1472sub git_blame2 {
1473        my $fd;
1474        my $ftype;
1475        die_error(undef, "Permission denied.") if (!git_get_project_config_bool ('blame'));
1476        die_error('404 Not Found', "File name not defined") if (!$file_name);
1477        $hash_base ||= git_read_head($project);
1478        die_error(undef, "Reading commit failed") unless ($hash_base);
1479        my %co = git_read_commit($hash_base)
1480                or die_error(undef, "Reading commit failed");
1481        if (!defined $hash) {
1482                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
1483                        or die_error(undef, "Error looking up file");
1484        }
1485        $ftype = git_get_type($hash);
1486        if ($ftype !~ "blob") {
1487                die_error("400 Bad Request", "object is not a blob");
1488        }
1489        open ($fd, "-|", $GIT, "blame", '-l', $file_name, $hash_base)
1490                or die_error(undef, "Open git-blame failed.");
1491        git_header_html();
1492        my $formats_nav =
1493                $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$hash;hb=$hash_base;f=$file_name")}, "blob") .
1494                " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blame;f=$file_name")}, "head");
1495        git_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
1496        git_header_div('commit', esc_html($co{'title'}), $hash_base);
1497        git_print_page_path($file_name, $ftype);
1498        my @rev_color = (qw(light dark));
1499        my $num_colors = scalar(@rev_color);
1500        my $current_color = 0;
1501        my $last_rev;
1502        print "<div class=\"page_body\">\n";
1503        print "<table class=\"blame\">\n";
1504        print "<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n";
1505        while (<$fd>) {
1506                /^([0-9a-fA-F]{40}).*?(\d+)\)\s{1}(\s*.*)/;
1507                my $full_rev = $1;
1508                my $rev = substr($full_rev, 0, 8);
1509                my $lineno = $2;
1510                my $data = $3;
1511
1512                if (!defined $last_rev) {
1513                        $last_rev = $full_rev;
1514                } elsif ($last_rev ne $full_rev) {
1515                        $last_rev = $full_rev;
1516                        $current_color = ++$current_color % $num_colors;
1517                }
1518                print "<tr class=\"$rev_color[$current_color]\">\n";
1519                print "<td class=\"sha1\">" .
1520                        $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$full_rev;f=$file_name")}, esc_html($rev)) . "</td>\n";
1521                print "<td class=\"linenr\"><a id=\"l$lineno\" href=\"#l$lineno\" class=\"linenr\">" . esc_html($lineno) . "</a></td>\n";
1522                print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
1523                print "</tr>\n";
1524        }
1525        print "</table>\n";
1526        print "</div>";
1527        close $fd or print "Reading blob failed\n";
1528        git_footer_html();
1529}
1530
1531sub git_blame {
1532        my $fd;
1533        die_error('403 Permission denied', "Permission denied.") if (!git_get_project_config_bool ('blame'));
1534        die_error('404 Not Found', "What file will it be, master?") if (!$file_name);
1535        $hash_base ||= git_read_head($project);
1536        die_error(undef, "Reading commit failed.") unless ($hash_base);
1537        my %co = git_read_commit($hash_base)
1538                or die_error(undef, "Reading commit failed.");
1539        if (!defined $hash) {
1540                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
1541                        or die_error(undef, "Error lookup file.");
1542        }
1543        open ($fd, "-|", $GIT, "annotate", '-l', '-t', '-r', $file_name, $hash_base)
1544                or die_error(undef, "Open git-annotate failed.");
1545        git_header_html();
1546        my $formats_nav =
1547                $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$hash;hb=$hash_base;f=$file_name")}, "blob") .
1548                " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blame;f=$file_name")}, "head");
1549        git_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
1550        git_header_div('commit', esc_html($co{'title'}), $hash_base);
1551        git_print_page_path($file_name);
1552        print "<div class=\"page_body\">\n";
1553        print <<HTML;
1554<table class="blame">
1555  <tr>
1556    <th>Commit</th>
1557    <th>Age</th>
1558    <th>Author</th>
1559    <th>Line</th>
1560    <th>Data</th>
1561  </tr>
1562HTML
1563        my @line_class = (qw(light dark));
1564        my $line_class_len = scalar (@line_class);
1565        my $line_class_num = $#line_class;
1566        while (my $line = <$fd>) {
1567                my $long_rev;
1568                my $short_rev;
1569                my $author;
1570                my $time;
1571                my $lineno;
1572                my $data;
1573                my $age;
1574                my $age_str;
1575                my $age_class;
1576
1577                chomp $line;
1578                $line_class_num = ($line_class_num + 1) % $line_class_len;
1579
1580                if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) \+\d\d\d\d\t(\d+)\)(.*)$/) {
1581                        $long_rev = $1;
1582                        $author   = $2;
1583                        $time     = $3;
1584                        $lineno   = $4;
1585                        $data     = $5;
1586                } else {
1587                        print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
1588                        next;
1589                }
1590                $short_rev  = substr ($long_rev, 0, 8);
1591                $age        = time () - $time;
1592                $age_str    = age_string ($age);
1593                $age_str    =~ s/ /&nbsp;/g;
1594                $age_class  = age_class($age);
1595                $author     = esc_html ($author);
1596                $author     =~ s/ /&nbsp;/g;
1597                # escape tabs
1598                while ((my $pos = index($data, "\t")) != -1) {
1599                        if (my $count = (8 - ($pos % 8))) {
1600                                my $spaces = ' ' x $count;
1601                                $data =~ s/\t/$spaces/;
1602                        }
1603                }
1604                $data = esc_html ($data);
1605
1606                print <<HTML;
1607  <tr class="$line_class[$line_class_num]">
1608    <td class="sha1"><a href="$my_uri?${\esc_param ("p=$project;a=commit;h=$long_rev")}" class="text">$short_rev..</a></td>
1609    <td class="$age_class">$age_str</td>
1610    <td>$author</td>
1611    <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
1612    <td class="pre">$data</td>
1613  </tr>
1614HTML
1615        } # while (my $line = <$fd>)
1616        print "</table>\n\n";
1617        close $fd or print "Reading blob failed.\n";
1618        print "</div>";
1619        git_footer_html();
1620}
1621
1622sub git_tags {
1623        my $head = git_read_head($project);
1624        git_header_html();
1625        git_page_nav('','', $head,undef,$head);
1626        git_header_div('summary', $project);
1627
1628        my $taglist = git_read_refs("refs/tags");
1629        if (defined @$taglist) {
1630                git_tags_body($taglist);
1631        }
1632        git_footer_html();
1633}
1634
1635sub git_heads {
1636        my $head = git_read_head($project);
1637        git_header_html();
1638        git_page_nav('','', $head,undef,$head);
1639        git_header_div('summary', $project);
1640
1641        my $taglist = git_read_refs("refs/heads");
1642        my $alternate = 0;
1643        if (defined @$taglist) {
1644                git_heads_body($taglist, $head);
1645        }
1646        git_footer_html();
1647}
1648
1649sub git_blob_plain {
1650        if (!defined $hash) {
1651                if (defined $file_name) {
1652                        my $base = $hash_base || git_read_head($project);
1653                        $hash = git_get_hash_by_path($base, $file_name, "blob")
1654                                or die_error(undef, "Error lookup file.");
1655                } else {
1656                        die_error(undef, "No file name defined.");
1657                }
1658        }
1659        my $type = shift;
1660        open my $fd, "-|", $GIT, "cat-file", "blob", $hash
1661                or die_error("Couldn't cat $file_name, $hash");
1662
1663        $type ||= git_blob_plain_mimetype($fd, $file_name);
1664
1665        # save as filename, even when no $file_name is given
1666        my $save_as = "$hash";
1667        if (defined $file_name) {
1668                $save_as = $file_name;
1669        } elsif ($type =~ m/^text\//) {
1670                $save_as .= '.txt';
1671        }
1672
1673        print $cgi->header(-type => "$type", '-content-disposition' => "inline; filename=\"$save_as\"");
1674        undef $/;
1675        binmode STDOUT, ':raw';
1676        print <$fd>;
1677        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
1678        $/ = "\n";
1679        close $fd;
1680}
1681
1682sub git_blob {
1683        if (!defined $hash) {
1684                if (defined $file_name) {
1685                        my $base = $hash_base || git_read_head($project);
1686                        $hash = git_get_hash_by_path($base, $file_name, "blob")
1687                                or die_error(undef, "Error lookup file.");
1688                } else {
1689                        die_error(undef, "No file name defined.");
1690                }
1691        }
1692        my $have_blame = git_get_project_config_bool ('blame');
1693        open my $fd, "-|", $GIT, "cat-file", "blob", $hash
1694                or die_error(undef, "Couldn't cat $file_name, $hash.");
1695        my $mimetype = git_blob_plain_mimetype($fd, $file_name);
1696        if ($mimetype !~ m/^text\//) {
1697                close $fd;
1698                return git_blob_plain($mimetype);
1699        }
1700        git_header_html();
1701        my $formats_nav = '';
1702        if (defined $hash_base && (my %co = git_read_commit($hash_base))) {
1703                if (defined $file_name) {
1704                        if ($have_blame) {
1705                                $formats_nav .= $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blame;h=$hash;hb=$hash_base;f=$file_name")}, "blame") . " | ";
1706                        }
1707                        $formats_nav .=
1708                                $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob_plain;h=$hash;f=$file_name")}, "plain") .
1709                                " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;hb=HEAD;f=$file_name")}, "head");
1710                } else {
1711                        $formats_nav .= $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob_plain;h=$hash")}, "plain");
1712                }
1713                git_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
1714                git_header_div('commit', esc_html($co{'title'}), $hash_base);
1715        } else {
1716                print "<div class=\"page_nav\">\n" .
1717                      "<br/><br/></div>\n" .
1718                      "<div class=\"title\">$hash</div>\n";
1719        }
1720        git_print_page_path($file_name, "blob");
1721        print "<div class=\"page_body\">\n";
1722        my $nr;
1723        while (my $line = <$fd>) {
1724                chomp $line;
1725                $nr++;
1726                while ((my $pos = index($line, "\t")) != -1) {
1727                        if (my $count = (8 - ($pos % 8))) {
1728                                my $spaces = ' ' x $count;
1729                                $line =~ s/\t/$spaces/;
1730                        }
1731                }
1732                printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n", $nr, $nr, $nr, esc_html($line);
1733        }
1734        close $fd or print "Reading blob failed.\n";
1735        print "</div>";
1736        git_footer_html();
1737}
1738
1739sub git_tree {
1740        if (!defined $hash) {
1741                $hash = git_read_head($project);
1742                if (defined $file_name) {
1743                        my $base = $hash_base || $hash;
1744                        $hash = git_get_hash_by_path($base, $file_name, "tree");
1745                }
1746                if (!defined $hash_base) {
1747                        $hash_base = $hash;
1748                }
1749        }
1750        $/ = "\0";
1751        open my $fd, "-|", $GIT, "ls-tree", '-z', $hash
1752                or die_error(undef, "Open git-ls-tree failed.");
1753        my @entries = map { chomp; $_ } <$fd>;
1754        close $fd or die_error(undef, "Reading tree failed.");
1755        $/ = "\n";
1756
1757        my $refs = read_info_ref();
1758        my $ref = git_get_referencing($refs, $hash_base);
1759        git_header_html();
1760        my $base_key = "";
1761        my $base = "";
1762        if (defined $hash_base && (my %co = git_read_commit($hash_base))) {
1763                $base_key = ";hb=$hash_base";
1764                git_page_nav('tree','', $hash_base);
1765                git_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
1766        } else {
1767                print "<div class=\"page_nav\">\n";
1768                print "<br/><br/></div>\n";
1769                print "<div class=\"title\">$hash</div>\n";
1770        }
1771        if (defined $file_name) {
1772                $base = esc_html("$file_name/");
1773        }
1774        git_print_page_path($file_name);
1775        print "<div class=\"page_body\">\n";
1776        print "<table cellspacing=\"0\">\n";
1777        my $alternate = 0;
1778        foreach my $line (@entries) {
1779                #'100644        blob    0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa        panic.c'
1780                $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
1781                my $t_mode = $1;
1782                my $t_type = $2;
1783                my $t_hash = $3;
1784                my $t_name = validate_input($4);
1785                if ($alternate) {
1786                        print "<tr class=\"dark\">\n";
1787                } else {
1788                        print "<tr class=\"light\">\n";
1789                }
1790                $alternate ^= 1;
1791                print "<td class=\"mode\">" . mode_str($t_mode) . "</td>\n";
1792                if ($t_type eq "blob") {
1793                        print "<td class=\"list\">" .
1794                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$t_hash$base_key;f=$base$t_name"), -class => "list"}, esc_html($t_name)) .
1795                              "</td>\n" .
1796                              "<td class=\"link\">" .
1797                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$t_hash$base_key;f=$base$t_name")}, "blob") .
1798#                             " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blame;h=$t_hash$base_key;f=$base$t_name")}, "blame") .
1799                              " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=history;h=$t_hash;hb=$hash_base;f=$base$t_name")}, "history") .
1800                              " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob_plain;h=$t_hash;f=$base$t_name")}, "raw") .
1801                              "</td>\n";
1802                } elsif ($t_type eq "tree") {
1803                        print "<td class=\"list\">" .
1804                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tree;h=$t_hash$base_key;f=$base$t_name")}, esc_html($t_name)) .
1805                              "</td>\n" .
1806                              "<td class=\"link\">" .
1807                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tree;h=$t_hash$base_key;f=$base$t_name")}, "tree") .
1808                              " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=history;hb=$hash_base;f=$base$t_name")}, "history") .
1809                              "</td>\n";
1810                }
1811                print "</tr>\n";
1812        }
1813        print "</table>\n" .
1814              "</div>";
1815        git_footer_html();
1816}
1817
1818sub git_log {
1819        my $head = git_read_head($project);
1820        if (!defined $hash) {
1821                $hash = $head;
1822        }
1823        if (!defined $page) {
1824                $page = 0;
1825        }
1826        my $refs = read_info_ref();
1827
1828        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
1829        open my $fd, "-|", $GIT, "rev-list", $limit, $hash
1830                or die_error(undef, "Open git-rev-list failed.");
1831        my @revlist = map { chomp; $_ } <$fd>;
1832        close $fd;
1833
1834        my $paging_nav = git_get_paging_nav('log', $hash, $head, $page, $#revlist);
1835
1836        git_header_html();
1837        git_page_nav('log','', $hash,undef,undef, $paging_nav);
1838
1839        if (!@revlist) {
1840                my %co = git_read_commit($hash);
1841
1842                git_header_div('summary', $project);
1843                print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
1844        }
1845        for (my $i = ($page * 100); $i <= $#revlist; $i++) {
1846                my $commit = $revlist[$i];
1847                my $ref = git_get_referencing($refs, $commit);
1848                my %co = git_read_commit($commit);
1849                next if !%co;
1850                my %ad = date_str($co{'author_epoch'});
1851                git_header_div('commit',
1852                                                                         "<span class=\"age\">$co{'age_string'}</span>" .
1853                                                                         esc_html($co{'title'}) . $ref,
1854                                                                         $commit);
1855                print "<div class=\"title_text\">\n" .
1856                      "<div class=\"log_link\">\n" .
1857                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$commit")}, "commit") .
1858                      " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commitdiff;h=$commit")}, "commitdiff") .
1859                      "<br/>\n" .
1860                      "</div>\n" .
1861                      "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
1862                      "</div>\n" .
1863                      "<div class=\"log_body\">\n";
1864                my $comment = $co{'comment'};
1865                my $empty = 0;
1866                foreach my $line (@$comment) {
1867                        if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1868                                next;
1869                        }
1870                        if ($line eq "") {
1871                                if ($empty) {
1872                                        next;
1873                                }
1874                                $empty = 1;
1875                        } else {
1876                                $empty = 0;
1877                        }
1878                        print format_log_line_html($line) . "<br/>\n";
1879                }
1880                if (!$empty) {
1881                        print "<br/>\n";
1882                }
1883                print "</div>\n";
1884        }
1885        git_footer_html();
1886}
1887
1888sub git_commit {
1889        my %co = git_read_commit($hash);
1890        if (!%co) {
1891                die_error(undef, "Unknown commit object.");
1892        }
1893        my %ad = date_str($co{'author_epoch'}, $co{'author_tz'});
1894        my %cd = date_str($co{'committer_epoch'}, $co{'committer_tz'});
1895
1896        my $parent = $co{'parent'};
1897        if (!defined $parent) {
1898                $parent = "--root";
1899        }
1900        open my $fd, "-|", $GIT, "diff-tree", '-r', '-M', $parent, $hash
1901                or die_error(undef, "Open git-diff-tree failed.");
1902        my @difftree = map { chomp; $_ } <$fd>;
1903        close $fd or die_error(undef, "Reading git-diff-tree failed.");
1904
1905        # non-textual hash id's can be cached
1906        my $expires;
1907        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
1908                $expires = "+1d";
1909        }
1910        my $refs = read_info_ref();
1911        my $ref = git_get_referencing($refs, $co{'id'});
1912        my $formats_nav = '';
1913        if (defined $file_name && defined $co{'parent'}) {
1914                my $parent = $co{'parent'};
1915                $formats_nav .= $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blame;hb=$parent;f=$file_name")}, "blame");
1916        }
1917        git_header_html(undef, $expires);
1918        git_page_nav('commit', defined $co{'parent'} ? '' : 'commitdiff',
1919                                                         $hash, $co{'tree'}, $hash,
1920                                                         $formats_nav);
1921
1922        if (defined $co{'parent'}) {
1923                git_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
1924        } else {
1925                git_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
1926        }
1927        print "<div class=\"title_text\">\n" .
1928              "<table cellspacing=\"0\">\n";
1929        print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
1930              "<tr>" .
1931              "<td></td><td> $ad{'rfc2822'}";
1932        if ($ad{'hour_local'} < 6) {
1933                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1934        } else {
1935                printf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1936        }
1937        print "</td>" .
1938              "</tr>\n";
1939        print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
1940        print "<tr><td></td><td> $cd{'rfc2822'}" . sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) . "</td></tr>\n";
1941        print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
1942        print "<tr>" .
1943              "<td>tree</td>" .
1944              "<td class=\"sha1\">" .
1945              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tree;h=$co{'tree'};hb=$hash"), class => "list"}, $co{'tree'}) .
1946              "</td>" .
1947              "<td class=\"link\">" . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tree;h=$co{'tree'};hb=$hash")}, "tree") .
1948              "</td>" .
1949              "</tr>\n";
1950        my $parents = $co{'parents'};
1951        foreach my $par (@$parents) {
1952                print "<tr>" .
1953                      "<td>parent</td>" .
1954                      "<td class=\"sha1\">" . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$par"), class => "list"}, $par) . "</td>" .
1955                      "<td class=\"link\">" .
1956                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$par")}, "commit") .
1957                      " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commitdiff;h=$hash;hp=$par")}, "commitdiff") .
1958                      "</td>" .
1959                      "</tr>\n";
1960        }
1961        print "</table>".
1962              "</div>\n";
1963        print "<div class=\"page_body\">\n";
1964        my $comment = $co{'comment'};
1965        my $empty = 0;
1966        my $signed = 0;
1967        foreach my $line (@$comment) {
1968                # print only one empty line
1969                if ($line eq "") {
1970                        if ($empty || $signed) {
1971                                next;
1972                        }
1973                        $empty = 1;
1974                } else {
1975                        $empty = 0;
1976                }
1977                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1978                        $signed = 1;
1979                        print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1980                } else {
1981                        $signed = 0;
1982                        print format_log_line_html($line) . "<br/>\n";
1983                }
1984        }
1985        print "</div>\n";
1986        print "<div class=\"list_head\">\n";
1987        if ($#difftree > 10) {
1988                print(($#difftree + 1) . " files changed:\n");
1989        }
1990        print "</div>\n";
1991        print "<table class=\"diff_tree\">\n";
1992        my $alternate = 0;
1993        foreach my $line (@difftree) {
1994                # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M      ls-files.c'
1995                # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M      rev-tree.c'
1996                if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
1997                        next;
1998                }
1999                my $from_mode = $1;
2000                my $to_mode = $2;
2001                my $from_id = $3;
2002                my $to_id = $4;
2003                my $status = $5;
2004                my $similarity = $6;
2005                my $file = validate_input(unquote($7));
2006                if ($alternate) {
2007                        print "<tr class=\"dark\">\n";
2008                } else {
2009                        print "<tr class=\"light\">\n";
2010                }
2011                $alternate ^= 1;
2012                if ($status eq "A") {
2013                        my $mode_chng = "";
2014                        if (S_ISREG(oct $to_mode)) {
2015                                $mode_chng = sprintf(" with mode: %04o", (oct $to_mode) & 0777);
2016                        }
2017                        print "<td>" .
2018                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$to_id;hb=$hash;f=$file"), -class => "list"}, esc_html($file)) . "</td>\n" .
2019                              "<td><span class=\"file_status new\">[new " . file_type($to_mode) . "$mode_chng]</span></td>\n" .
2020                              "<td class=\"link\">" . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$to_id;hb=$hash;f=$file")}, "blob") . "</td>\n";
2021                } elsif ($status eq "D") {
2022                        print "<td>" .
2023                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$from_id;hb=$hash;f=$file"), -class => "list"}, esc_html($file)) . "</td>\n" .
2024                              "<td><span class=\"file_status deleted\">[deleted " . file_type($from_mode). "]</span></td>\n" .
2025                              "<td class=\"link\">" .
2026                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$from_id;hb=$hash;f=$file")}, "blob") .
2027                              " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=history;hb=$hash;f=$file")}, "history") .
2028                              "</td>\n"
2029                } elsif ($status eq "M" || $status eq "T") {
2030                        my $mode_chnge = "";
2031                        if ($from_mode != $to_mode) {
2032                                $mode_chnge = " <span class=\"file_status mode_chnge\">[changed";
2033                                if (((oct $from_mode) & S_IFMT) != ((oct $to_mode) & S_IFMT)) {
2034                                        $mode_chnge .= " from " . file_type($from_mode) . " to " . file_type($to_mode);
2035                                }
2036                                if (((oct $from_mode) & 0777) != ((oct $to_mode) & 0777)) {
2037                                        if (S_ISREG($from_mode) && S_ISREG($to_mode)) {
2038                                                $mode_chnge .= sprintf(" mode: %04o->%04o", (oct $from_mode) & 0777, (oct $to_mode) & 0777);
2039                                        } elsif (S_ISREG($to_mode)) {
2040                                                $mode_chnge .= sprintf(" mode: %04o", (oct $to_mode) & 0777);
2041                                        }
2042                                }
2043                                $mode_chnge .= "]</span>\n";
2044                        }
2045                        print "<td>";
2046                        if ($to_id ne $from_id) {
2047                                print $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blobdiff;h=$to_id;hp=$from_id;hb=$hash;f=$file"), -class => "list"}, esc_html($file));
2048                        } else {
2049                                print $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$to_id;hb=$hash;f=$file"), -class => "list"}, esc_html($file));
2050                        }
2051                        print "</td>\n" .
2052                              "<td>$mode_chnge</td>\n" .
2053                              "<td class=\"link\">";
2054                        print $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$to_id;hb=$hash;f=$file")}, "blob");
2055                        if ($to_id ne $from_id) {
2056                                print " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blobdiff;h=$to_id;hp=$from_id;hb=$hash;f=$file")}, "diff");
2057                        }
2058                        print " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=history;hb=$hash;f=$file")}, "history") . "\n";
2059                        print "</td>\n";
2060                } elsif ($status eq "R") {
2061                        my ($from_file, $to_file) = split "\t", $file;
2062                        my $mode_chng = "";
2063                        if ($from_mode != $to_mode) {
2064                                $mode_chng = sprintf(", mode: %04o", (oct $to_mode) & 0777);
2065                        }
2066                        print "<td>" .
2067                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$to_id;hb=$hash;f=$to_file"), -class => "list"}, esc_html($to_file)) . "</td>\n" .
2068                              "<td><span class=\"file_status moved\">[moved from " .
2069                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$from_id;hb=$hash;f=$from_file"), -class => "list"}, esc_html($from_file)) .
2070                              " with " . (int $similarity) . "% similarity$mode_chng]</span></td>\n" .
2071                              "<td class=\"link\">" .
2072                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$to_id;hb=$hash;f=$to_file")}, "blob");
2073                        if ($to_id ne $from_id) {
2074                                print " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blobdiff;h=$to_id;hp=$from_id;hb=$hash;f=$to_file")}, "diff");
2075                        }
2076                        print "</td>\n";
2077                }
2078                print "</tr>\n";
2079        }
2080        print "</table>\n";
2081        git_footer_html();
2082}
2083
2084sub git_blobdiff {
2085        mkdir($git_temp, 0700);
2086        git_header_html();
2087        if (defined $hash_base && (my %co = git_read_commit($hash_base))) {
2088                my $formats_nav =
2089                        $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blobdiff_plain;h=$hash;hp=$hash_parent")}, "plain");
2090                git_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2091                git_header_div('commit', esc_html($co{'title'}), $hash_base);
2092        } else {
2093                print "<div class=\"page_nav\">\n" .
2094                      "<br/><br/></div>\n" .
2095                      "<div class=\"title\">$hash vs $hash_parent</div>\n";
2096        }
2097        git_print_page_path($file_name, "blob");
2098        print "<div class=\"page_body\">\n" .
2099              "<div class=\"diff_info\">blob:" .
2100              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$hash_parent;hb=$hash_base;f=$file_name")}, $hash_parent) .
2101              " -> blob:" .
2102              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$hash;hb=$hash_base;f=$file_name")}, $hash) .
2103              "</div>\n";
2104        git_diff_print($hash_parent, $file_name || $hash_parent, $hash, $file_name || $hash);
2105        print "</div>";
2106        git_footer_html();
2107}
2108
2109sub git_blobdiff_plain {
2110        mkdir($git_temp, 0700);
2111        print $cgi->header(-type => "text/plain", -charset => 'utf-8');
2112        git_diff_print($hash_parent, $file_name || $hash_parent, $hash, $file_name || $hash, "plain");
2113}
2114
2115sub git_commitdiff {
2116        mkdir($git_temp, 0700);
2117        my %co = git_read_commit($hash);
2118        if (!%co) {
2119                die_error(undef, "Unknown commit object.");
2120        }
2121        if (!defined $hash_parent) {
2122                $hash_parent = $co{'parent'};
2123        }
2124        open my $fd, "-|", $GIT, "diff-tree", '-r', $hash_parent, $hash
2125                or die_error(undef, "Open git-diff-tree failed.");
2126        my @difftree = map { chomp; $_ } <$fd>;
2127        close $fd or die_error(undef, "Reading diff-tree failed.");
2128
2129        # non-textual hash id's can be cached
2130        my $expires;
2131        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2132                $expires = "+1d";
2133        }
2134        my $refs = read_info_ref();
2135        my $ref = git_get_referencing($refs, $co{'id'});
2136        my $formats_nav =
2137                $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commitdiff_plain;h=$hash;hp=$hash_parent")}, "plain");
2138        git_header_html(undef, $expires);
2139        git_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
2140        git_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
2141        print "<div class=\"page_body\">\n";
2142        my $comment = $co{'comment'};
2143        my $empty = 0;
2144        my $signed = 0;
2145        my @log = @$comment;
2146        # remove first and empty lines after that
2147        shift @log;
2148        while (defined $log[0] && $log[0] eq "") {
2149                shift @log;
2150        }
2151        foreach my $line (@log) {
2152                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
2153                        next;
2154                }
2155                if ($line eq "") {
2156                        if ($empty) {
2157                                next;
2158                        }
2159                        $empty = 1;
2160                } else {
2161                        $empty = 0;
2162                }
2163                print format_log_line_html($line) . "<br/>\n";
2164        }
2165        print "<br/>\n";
2166        foreach my $line (@difftree) {
2167                # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M      ls-files.c'
2168                # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M      rev-tree.c'
2169                $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/;
2170                my $from_mode = $1;
2171                my $to_mode = $2;
2172                my $from_id = $3;
2173                my $to_id = $4;
2174                my $status = $5;
2175                my $file = validate_input(unquote($6));
2176                if ($status eq "A") {
2177                        print "<div class=\"diff_info\">" . file_type($to_mode) . ":" .
2178                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$to_id;hb=$hash;f=$file")}, $to_id) . "(new)" .
2179                              "</div>\n";
2180                        git_diff_print(undef, "/dev/null", $to_id, "b/$file");
2181                } elsif ($status eq "D") {
2182                        print "<div class=\"diff_info\">" . file_type($from_mode) . ":" .
2183                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$from_id;hb=$hash;f=$file")}, $from_id) . "(deleted)" .
2184                              "</div>\n";
2185                        git_diff_print($from_id, "a/$file", undef, "/dev/null");
2186                } elsif ($status eq "M") {
2187                        if ($from_id ne $to_id) {
2188                                print "<div class=\"diff_info\">" .
2189                                      file_type($from_mode) . ":" . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$from_id;hb=$hash;f=$file")}, $from_id) .
2190                                      " -> " .
2191                                      file_type($to_mode) . ":" . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$to_id;hb=$hash;f=$file")}, $to_id);
2192                                print "</div>\n";
2193                                git_diff_print($from_id, "a/$file",  $to_id, "b/$file");
2194                        }
2195                }
2196        }
2197        print "<br/>\n" .
2198              "</div>";
2199        git_footer_html();
2200}
2201
2202sub git_commitdiff_plain {
2203        mkdir($git_temp, 0700);
2204        open my $fd, "-|", $GIT, "diff-tree", '-r', $hash_parent, $hash
2205                or die_error(undef, "Open git-diff-tree failed.");
2206        my @difftree = map { chomp; $_ } <$fd>;
2207        close $fd or die_error(undef, "Reading diff-tree failed.");
2208
2209        # try to figure out the next tag after this commit
2210        my $tagname;
2211        my $refs = read_info_ref("tags");
2212        open $fd, "-|", $GIT, "rev-list", "HEAD";
2213        my @commits = map { chomp; $_ } <$fd>;
2214        close $fd;
2215        foreach my $commit (@commits) {
2216                if (defined $refs->{$commit}) {
2217                        $tagname = $refs->{$commit}
2218                }
2219                if ($commit eq $hash) {
2220                        last;
2221                }
2222        }
2223
2224        print $cgi->header(-type => "text/plain", -charset => 'utf-8', '-content-disposition' => "inline; filename=\"git-$hash.patch\"");
2225        my %co = git_read_commit($hash);
2226        my %ad = date_str($co{'author_epoch'}, $co{'author_tz'});
2227        my $comment = $co{'comment'};
2228        print "From: $co{'author'}\n" .
2229              "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n".
2230              "Subject: $co{'title'}\n";
2231        if (defined $tagname) {
2232                print "X-Git-Tag: $tagname\n";
2233        }
2234        print "X-Git-Url: $my_url?p=$project;a=commitdiff;h=$hash\n" .
2235              "\n";
2236
2237        foreach my $line (@$comment) {;
2238                print "$line\n";
2239        }
2240        print "---\n\n";
2241
2242        foreach my $line (@difftree) {
2243                $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/;
2244                my $from_id = $3;
2245                my $to_id = $4;
2246                my $status = $5;
2247                my $file = $6;
2248                if ($status eq "A") {
2249                        git_diff_print(undef, "/dev/null", $to_id, "b/$file", "plain");
2250                } elsif ($status eq "D") {
2251                        git_diff_print($from_id, "a/$file", undef, "/dev/null", "plain");
2252                } elsif ($status eq "M") {
2253                        git_diff_print($from_id, "a/$file",  $to_id, "b/$file", "plain");
2254                }
2255        }
2256}
2257
2258sub git_history {
2259        if (!defined $hash_base) {
2260                $hash_base = git_read_head($project);
2261        }
2262        my $ftype;
2263        my %co = git_read_commit($hash_base);
2264        if (!%co) {
2265                die_error(undef, "Unknown commit object.");
2266        }
2267        my $refs = read_info_ref();
2268        git_header_html();
2269        git_page_nav('','', $hash_base,$co{'tree'},$hash_base);
2270        git_header_div('commit', esc_html($co{'title'}), $hash_base);
2271        if (!defined $hash && defined $file_name) {
2272                $hash = git_get_hash_by_path($hash_base, $file_name);
2273        }
2274        if (defined $hash) {
2275                $ftype = git_get_type($hash);
2276        }
2277        git_print_page_path($file_name, $ftype);
2278
2279        open my $fd, "-|",
2280                $GIT, "rev-list", "--full-history", $hash_base, "--", $file_name;
2281        print "<table cellspacing=\"0\">\n";
2282        my $alternate = 0;
2283        while (my $line = <$fd>) {
2284                if ($line =~ m/^([0-9a-fA-F]{40})/){
2285                        my $commit = $1;
2286                        my %co = git_read_commit($commit);
2287                        if (!%co) {
2288                                next;
2289                        }
2290                        my $ref = git_get_referencing($refs, $commit);
2291                        if ($alternate) {
2292                                print "<tr class=\"dark\">\n";
2293                        } else {
2294                                print "<tr class=\"light\">\n";
2295                        }
2296                        $alternate ^= 1;
2297                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2298                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
2299                              "<td>" . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$commit"), -class => "list"}, "<b>" .
2300                              esc_html(chop_str($co{'title'}, 50)) . "$ref</b>") . "</td>\n" .
2301                              "<td class=\"link\">" .
2302                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$commit")}, "commit") .
2303                              " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commitdiff;h=$commit")}, "commitdiff") .
2304                              " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;hb=$commit;f=$file_name")}, "blob");
2305                        my $blob = git_get_hash_by_path($hash_base, $file_name);
2306                        my $blob_parent = git_get_hash_by_path($commit, $file_name);
2307                        if (defined $blob && defined $blob_parent && $blob ne $blob_parent) {
2308                                print " | " .
2309                                $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blobdiff;h=$blob;hp=$blob_parent;hb=$commit;f=$file_name")},
2310                                "diff to current");
2311                        }
2312                        print "</td>\n" .
2313                              "</tr>\n";
2314                }
2315        }
2316        print "</table>\n";
2317        close $fd;
2318        git_footer_html();
2319}
2320
2321sub git_search {
2322        if (!defined $searchtext) {
2323                die_error("", "Text field empty.");
2324        }
2325        if (!defined $hash) {
2326                $hash = git_read_head($project);
2327        }
2328        my %co = git_read_commit($hash);
2329        if (!%co) {
2330                die_error(undef, "Unknown commit object.");
2331        }
2332        # pickaxe may take all resources of your box and run for several minutes
2333        # with every query - so decide by yourself how public you make this feature :)
2334        my $commit_search = 1;
2335        my $author_search = 0;
2336        my $committer_search = 0;
2337        my $pickaxe_search = 0;
2338        if ($searchtext =~ s/^author\\://i) {
2339                $author_search = 1;
2340        } elsif ($searchtext =~ s/^committer\\://i) {
2341                $committer_search = 1;
2342        } elsif ($searchtext =~ s/^pickaxe\\://i) {
2343                $commit_search = 0;
2344                $pickaxe_search = 1;
2345        }
2346        git_header_html();
2347        git_page_nav('','', $hash,$co{'tree'},$hash);
2348        git_header_div('commit', esc_html($co{'title'}), $hash);
2349
2350        print "<table cellspacing=\"0\">\n";
2351        my $alternate = 0;
2352        if ($commit_search) {
2353                $/ = "\0";
2354                open my $fd, "-|", $GIT, "rev-list", "--header", "--parents", $hash or next;
2355                while (my $commit_text = <$fd>) {
2356                        if (!grep m/$searchtext/i, $commit_text) {
2357                                next;
2358                        }
2359                        if ($author_search && !grep m/\nauthor .*$searchtext/i, $commit_text) {
2360                                next;
2361                        }
2362                        if ($committer_search && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
2363                                next;
2364                        }
2365                        my @commit_lines = split "\n", $commit_text;
2366                        my %co = git_read_commit(undef, \@commit_lines);
2367                        if (!%co) {
2368                                next;
2369                        }
2370                        if ($alternate) {
2371                                print "<tr class=\"dark\">\n";
2372                        } else {
2373                                print "<tr class=\"light\">\n";
2374                        }
2375                        $alternate ^= 1;
2376                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2377                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
2378                              "<td>" .
2379                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$co{'id'}"), -class => "list"}, "<b>" . esc_html(chop_str($co{'title'}, 50)) . "</b><br/>");
2380                        my $comment = $co{'comment'};
2381                        foreach my $line (@$comment) {
2382                                if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
2383                                        my $lead = esc_html($1) || "";
2384                                        $lead = chop_str($lead, 30, 10);
2385                                        my $match = esc_html($2) || "";
2386                                        my $trail = esc_html($3) || "";
2387                                        $trail = chop_str($trail, 30, 10);
2388                                        my $text = "$lead<span class=\"match\">$match</span>$trail";
2389                                        print chop_str($text, 80, 5) . "<br/>\n";
2390                                }
2391                        }
2392                        print "</td>\n" .
2393                              "<td class=\"link\">" .
2394                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$co{'id'}")}, "commit") .
2395                              " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tree;h=$co{'tree'};hb=$co{'id'}")}, "tree");
2396                        print "</td>\n" .
2397                              "</tr>\n";
2398                }
2399                close $fd;
2400        }
2401
2402        if ($pickaxe_search) {
2403                $/ = "\n";
2404                open my $fd, "-|", "$GIT rev-list $hash | $GIT diff-tree -r --stdin -S\'$searchtext\'";
2405                undef %co;
2406                my @files;
2407                while (my $line = <$fd>) {
2408                        if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
2409                                my %set;
2410                                $set{'file'} = $6;
2411                                $set{'from_id'} = $3;
2412                                $set{'to_id'} = $4;
2413                                $set{'id'} = $set{'to_id'};
2414                                if ($set{'id'} =~ m/0{40}/) {
2415                                        $set{'id'} = $set{'from_id'};
2416                                }
2417                                if ($set{'id'} =~ m/0{40}/) {
2418                                        next;
2419                                }
2420                                push @files, \%set;
2421                        } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
2422                                if (%co) {
2423                                        if ($alternate) {
2424                                                print "<tr class=\"dark\">\n";
2425                                        } else {
2426                                                print "<tr class=\"light\">\n";
2427                                        }
2428                                        $alternate ^= 1;
2429                                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2430                                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
2431                                              "<td>" .
2432                                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$co{'id'}"), -class => "list"}, "<b>" .
2433                                              esc_html(chop_str($co{'title'}, 50)) . "</b><br/>");
2434                                        while (my $setref = shift @files) {
2435                                                my %set = %$setref;
2436                                                print $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$set{'id'};hb=$co{'id'};f=$set{'file'}"), class => "list"},
2437                                                      "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
2438                                                      "<br/>\n";
2439                                        }
2440                                        print "</td>\n" .
2441                                              "<td class=\"link\">" .
2442                                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$co{'id'}")}, "commit") .
2443                                              " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tree;h=$co{'tree'};hb=$co{'id'}")}, "tree");
2444                                        print "</td>\n" .
2445                                              "</tr>\n";
2446                                }
2447                                %co = git_read_commit($1);
2448                        }
2449                }
2450                close $fd;
2451        }
2452        print "</table>\n";
2453        git_footer_html();
2454}
2455
2456sub git_shortlog {
2457        my $head = git_read_head($project);
2458        if (!defined $hash) {
2459                $hash = $head;
2460        }
2461        if (!defined $page) {
2462                $page = 0;
2463        }
2464        my $refs = read_info_ref();
2465
2466        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2467        open my $fd, "-|", $GIT, "rev-list", $limit, $hash
2468                or die_error(undef, "Open git-rev-list failed.");
2469        my @revlist = map { chomp; $_ } <$fd>;
2470        close $fd;
2471
2472        my $paging_nav = git_get_paging_nav('shortlog', $hash, $head, $page, $#revlist);
2473        my $next_link = '';
2474        if ($#revlist >= (100 * ($page+1)-1)) {
2475                $next_link =
2476                        $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=shortlog;h=$hash;pg=" . ($page+1)),
2477                                 -title => "Alt-n"}, "next");
2478        }
2479
2480
2481        git_header_html();
2482        git_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
2483        git_header_div('summary', $project);
2484
2485        git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
2486
2487        git_footer_html();
2488}
2489
2490## ......................................................................
2491## feeds (RSS, OPML)
2492
2493sub git_rss {
2494        # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
2495        open my $fd, "-|", $GIT, "rev-list", "--max-count=150", git_read_head($project)
2496                or die_error(undef, "Open git-rev-list failed.");
2497        my @revlist = map { chomp; $_ } <$fd>;
2498        close $fd or die_error(undef, "Reading rev-list failed.");
2499        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
2500        print "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".
2501              "<rss version=\"2.0\" xmlns:content=\"http://purl.org/rss/1.0/modules/content/\">\n";
2502        print "<channel>\n";
2503        print "<title>$project</title>\n".
2504              "<link>" . esc_html("$my_url?p=$project;a=summary") . "</link>\n".
2505              "<description>$project log</description>\n".
2506              "<language>en</language>\n";
2507
2508        for (my $i = 0; $i <= $#revlist; $i++) {
2509                my $commit = $revlist[$i];
2510                my %co = git_read_commit($commit);
2511                # we read 150, we always show 30 and the ones more recent than 48 hours
2512                if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
2513                        last;
2514                }
2515                my %cd = date_str($co{'committer_epoch'});
2516                open $fd, "-|", $GIT, "diff-tree", '-r', $co{'parent'}, $co{'id'} or next;
2517                my @difftree = map { chomp; $_ } <$fd>;
2518                close $fd or next;
2519                print "<item>\n" .
2520                      "<title>" .
2521                      sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
2522                      "</title>\n" .
2523                      "<author>" . esc_html($co{'author'}) . "</author>\n" .
2524                      "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
2525                      "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
2526                      "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
2527                      "<description>" . esc_html($co{'title'}) . "</description>\n" .
2528                      "<content:encoded>" .
2529                      "<![CDATA[\n";
2530                my $comment = $co{'comment'};
2531                foreach my $line (@$comment) {
2532                        $line = decode("utf8", $line, Encode::FB_DEFAULT);
2533                        print "$line<br/>\n";
2534                }
2535                print "<br/>\n";
2536                foreach my $line (@difftree) {
2537                        if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
2538                                next;
2539                        }
2540                        my $file = validate_input(unquote($7));
2541                        $file = decode("utf8", $file, Encode::FB_DEFAULT);
2542                        print "$file<br/>\n";
2543                }
2544                print "]]>\n" .
2545                      "</content:encoded>\n" .
2546                      "</item>\n";
2547        }
2548        print "</channel></rss>";
2549}
2550
2551sub git_opml {
2552        my @list = git_read_projects();
2553
2554        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
2555        print "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".
2556              "<opml version=\"1.0\">\n".
2557              "<head>".
2558              "  <title>$site_name Git OPML Export</title>\n".
2559              "</head>\n".
2560              "<body>\n".
2561              "<outline text=\"git RSS feeds\">\n";
2562
2563        foreach my $pr (@list) {
2564                my %proj = %$pr;
2565                my $head = git_read_head($proj{'path'});
2566                if (!defined $head) {
2567                        next;
2568                }
2569                $ENV{'GIT_DIR'} = "$projectroot/$proj{'path'}";
2570                my %co = git_read_commit($head);
2571                if (!%co) {
2572                        next;
2573                }
2574
2575                my $path = esc_html(chop_str($proj{'path'}, 25, 5));
2576                my $rss  = "$my_url?p=$proj{'path'};a=rss";
2577                my $html = "$my_url?p=$proj{'path'};a=summary";
2578                print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
2579        }
2580        print "</outline>\n".
2581              "</body>\n".
2582              "</opml>\n";
2583}