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