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