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