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