52ae2aa8613e7831c2ebff8f9f9d791d62cfc214
   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                #$file =~ m#^/# or $file = "$projectroot/$path/$file";
 884                $mime = mimetype_guess_file($filename, $file);
 885        }
 886        $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
 887        return $mime;
 888}
 889
 890sub blob_mimetype {
 891        my $fd = shift;
 892        my $filename = shift;
 893
 894        if ($filename) {
 895                my $mime = mimetype_guess($filename);
 896                $mime and return $mime;
 897        }
 898
 899        # just in case
 900        return $default_blob_plain_mimetype unless $fd;
 901
 902        if (-T $fd) {
 903                return 'text/plain' .
 904                       ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
 905        } elsif (! $filename) {
 906                return 'application/octet-stream';
 907        } elsif ($filename =~ m/\.png$/i) {
 908                return 'image/png';
 909        } elsif ($filename =~ m/\.gif$/i) {
 910                return 'image/gif';
 911        } elsif ($filename =~ m/\.jpe?g$/i) {
 912                return 'image/jpeg';
 913        } else {
 914                return 'application/octet-stream';
 915        }
 916}
 917
 918## ======================================================================
 919## functions printing HTML: header, footer, error page
 920
 921sub git_header_html {
 922        my $status = shift || "200 OK";
 923        my $expires = shift;
 924
 925        my $title = "$site_name git";
 926        if (defined $project) {
 927                $title .= " - $project";
 928                if (defined $action) {
 929                        $title .= "/$action";
 930                        if (defined $file_name) {
 931                                $title .= " - $file_name";
 932                                if ($action eq "tree" && $file_name !~ m|/$|) {
 933                                        $title .= "/";
 934                                }
 935                        }
 936                }
 937        }
 938        my $content_type;
 939        # require explicit support from the UA if we are to send the page as
 940        # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
 941        # we have to do this because MSIE sometimes globs '*/*', pretending to
 942        # support xhtml+xml but choking when it gets what it asked for.
 943        if (defined $cgi->http('HTTP_ACCEPT') && $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ && $cgi->Accept('application/xhtml+xml') != 0) {
 944                $content_type = 'application/xhtml+xml';
 945        } else {
 946                $content_type = 'text/html';
 947        }
 948        print $cgi->header(-type=>$content_type, -charset => 'utf-8', -status=> $status, -expires => $expires);
 949        print <<EOF;
 950<?xml version="1.0" encoding="utf-8"?>
 951<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 952<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
 953<!-- git web interface v$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
 954<!-- git core binaries version $git_version -->
 955<head>
 956<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
 957<meta name="robots" content="index, nofollow"/>
 958<title>$title</title>
 959<link rel="stylesheet" type="text/css" href="$stylesheet"/>
 960EOF
 961        if (defined $project) {
 962                printf('<link rel="alternate" title="%s log" '.
 963                       'href="%s" type="application/rss+xml"/>'."\n",
 964                       esc_param($project),
 965                       esc_param("$my_uri?p=$project;a=rss"));
 966        }
 967
 968        print "</head>\n" .
 969              "<body>\n" .
 970              "<div class=\"page_header\">\n" .
 971              "<a href=\"http://www.kernel.org/pub/software/scm/git/docs/\" title=\"git documentation\">" .
 972              "<img src=\"$logo\" width=\"72\" height=\"27\" alt=\"git\" style=\"float:right; border-width:0px;\"/>" .
 973              "</a>\n";
 974        print $cgi->a({-href => esc_param($home_link)}, "projects") . " / ";
 975        if (defined $project) {
 976                print $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=summary")}, esc_html($project));
 977                if (defined $action) {
 978                        print " / $action";
 979                }
 980                print "\n";
 981                if (!defined $searchtext) {
 982                        $searchtext = "";
 983                }
 984                my $search_hash;
 985                if (defined $hash_base) {
 986                        $search_hash = $hash_base;
 987                } elsif (defined $hash) {
 988                        $search_hash = $hash;
 989                } else {
 990                        $search_hash = "HEAD";
 991                }
 992                $cgi->param("a", "search");
 993                $cgi->param("h", $search_hash);
 994                print $cgi->startform(-method => "get", -action => $my_uri) .
 995                      "<div class=\"search\">\n" .
 996                      $cgi->hidden(-name => "p") . "\n" .
 997                      $cgi->hidden(-name => "a") . "\n" .
 998                      $cgi->hidden(-name => "h") . "\n" .
 999                      $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1000                      "</div>" .
1001                      $cgi->end_form() . "\n";
1002        }
1003        print "</div>\n";
1004}
1005
1006sub git_footer_html {
1007        print "<div class=\"page_footer\">\n";
1008        if (defined $project) {
1009                my $descr = git_get_project_description($project);
1010                if (defined $descr) {
1011                        print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1012                }
1013                print $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=rss"), -class => "rss_logo"}, "RSS") . "\n";
1014        } else {
1015                print $cgi->a({-href => "$my_uri?" . esc_param("a=opml"), -class => "rss_logo"}, "OPML") . "\n";
1016        }
1017        print "</div>\n" .
1018              "</body>\n" .
1019              "</html>";
1020}
1021
1022sub die_error {
1023        my $status = shift || "403 Forbidden";
1024        my $error = shift || "Malformed query, file missing or permission denied";
1025
1026        git_header_html($status);
1027        print "<div class=\"page_body\">\n" .
1028              "<br/><br/>\n" .
1029              "$status - $error\n" .
1030              "<br/>\n" .
1031              "</div>\n";
1032        git_footer_html();
1033        exit;
1034}
1035
1036## ----------------------------------------------------------------------
1037## functions printing or outputting HTML: navigation
1038
1039sub git_print_page_nav {
1040        my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1041        $extra = '' if !defined $extra; # pager or formats
1042
1043        my @navs = qw(summary shortlog log commit commitdiff tree);
1044        if ($suppress) {
1045                @navs = grep { $_ ne $suppress } @navs;
1046        }
1047
1048        my %arg = map { $_, ''} @navs;
1049        if (defined $head) {
1050                for (qw(commit commitdiff)) {
1051                        $arg{$_} = ";h=$head";
1052                }
1053                if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1054                        for (qw(shortlog log)) {
1055                                $arg{$_} = ";h=$head";
1056                        }
1057                }
1058        }
1059        $arg{tree} .= ";h=$treehead" if defined $treehead;
1060        $arg{tree} .= ";hb=$treebase" if defined $treebase;
1061
1062        print "<div class=\"page_nav\">\n" .
1063                (join " | ",
1064                 map { $_ eq $current
1065                                         ? $_
1066                                         : $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=$_$arg{$_}")}, "$_")
1067                                 }
1068                 @navs);
1069        print "<br/>\n$extra<br/>\n" .
1070              "</div>\n";
1071}
1072
1073sub format_paging_nav {
1074        my ($action, $hash, $head, $page, $nrevs) = @_;
1075        my $paging_nav;
1076
1077
1078        if ($hash ne $head || $page) {
1079                $paging_nav .= $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=$action")}, "HEAD");
1080        } else {
1081                $paging_nav .= "HEAD";
1082        }
1083
1084        if ($page > 0) {
1085                $paging_nav .= " &sdot; " .
1086                        $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=$action;h=$hash;pg=" . ($page-1)),
1087                                 -accesskey => "p", -title => "Alt-p"}, "prev");
1088        } else {
1089                $paging_nav .= " &sdot; prev";
1090        }
1091
1092        if ($nrevs >= (100 * ($page+1)-1)) {
1093                $paging_nav .= " &sdot; " .
1094                        $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=$action;h=$hash;pg=" . ($page+1)),
1095                                 -accesskey => "n", -title => "Alt-n"}, "next");
1096        } else {
1097                $paging_nav .= " &sdot; next";
1098        }
1099
1100        return $paging_nav;
1101}
1102
1103## ......................................................................
1104## functions printing or outputting HTML: div
1105
1106sub git_print_header_div {
1107        my ($action, $title, $hash, $hash_base) = @_;
1108        my $rest = '';
1109
1110        $rest .= ";h=$hash" if $hash;
1111        $rest .= ";hb=$hash_base" if $hash_base;
1112
1113        print "<div class=\"header\">\n" .
1114              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=$action$rest"),
1115                       -class => "title"}, $title ? $title : $action) . "\n" .
1116              "</div>\n";
1117}
1118
1119sub git_print_page_path {
1120        my $name = shift;
1121        my $type = shift;
1122
1123        if (!defined $name) {
1124                print "<div class=\"page_path\"><b>/</b></div>\n";
1125        } elsif (defined $type && $type eq 'blob') {
1126                print "<div class=\"page_path\"><b>" .
1127                        $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob_plain;f=$file_name")}, esc_html($name)) . "</b><br/></div>\n";
1128        } else {
1129                print "<div class=\"page_path\"><b>" . esc_html($name) . "</b><br/></div>\n";
1130        }
1131}
1132
1133## ......................................................................
1134## functions printing large fragments of HTML
1135
1136sub git_shortlog_body {
1137        # uses global variable $project
1138        my ($revlist, $from, $to, $refs, $extra) = @_;
1139        $from = 0 unless defined $from;
1140        $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
1141
1142        print "<table class=\"shortlog\" cellspacing=\"0\">\n";
1143        my $alternate = 0;
1144        for (my $i = $from; $i <= $to; $i++) {
1145                my $commit = $revlist->[$i];
1146                #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
1147                my $ref = format_ref_marker($refs, $commit);
1148                my %co = parse_commit($commit);
1149                if ($alternate) {
1150                        print "<tr class=\"dark\">\n";
1151                } else {
1152                        print "<tr class=\"light\">\n";
1153                }
1154                $alternate ^= 1;
1155                # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
1156                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1157                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
1158                      "<td>";
1159                print format_subject_html($co{'title'}, $co{'title_short'}, "p=$project;a=commit;h=$commit", $ref);
1160                print "</td>\n" .
1161                      "<td class=\"link\">" .
1162                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$commit")}, "commit") . " | " .
1163                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commitdiff;h=$commit")}, "commitdiff") .
1164                      "</td>\n" .
1165                      "</tr>\n";
1166        }
1167        if (defined $extra) {
1168                print "<tr>\n" .
1169                      "<td colspan=\"4\">$extra</td>\n" .
1170                      "</tr>\n";
1171        }
1172        print "</table>\n";
1173}
1174
1175sub git_history_body {
1176        # Warning: assumes constant type (blob or tree) during history
1177        my ($fd, $refs, $hash_base, $ftype, $extra) = @_;
1178
1179        print "<table class=\"history\" cellspacing=\"0\">\n";
1180        my $alternate = 0;
1181        while (my $line = <$fd>) {
1182                if ($line !~ m/^([0-9a-fA-F]{40})/) {
1183                        next;
1184                }
1185
1186                my $commit = $1;
1187                my %co = parse_commit($commit);
1188                if (!%co) {
1189                        next;
1190                }
1191
1192                my $ref = format_ref_marker($refs, $commit);
1193
1194                if ($alternate) {
1195                        print "<tr class=\"dark\">\n";
1196                } else {
1197                        print "<tr class=\"light\">\n";
1198                }
1199                $alternate ^= 1;
1200                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1201                      # shortlog uses      chop_str($co{'author_name'}, 10)
1202                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
1203                      "<td>";
1204                # originally git_history used chop_str($co{'title'}, 50)
1205                print format_subject_html($co{'title'}, $co{'title_short'}, "p=$project;a=commit;h=$commit", $ref);
1206                print "</td>\n" .
1207                      "<td class=\"link\">" .
1208                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$commit")}, "commit") . " | " .
1209                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commitdiff;h=$commit")}, "commitdiff") . " | " .
1210                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=$ftype;hb=$commit;f=$file_name")}, $ftype);
1211
1212                if ($ftype eq 'blob') {
1213                        my $blob_current = git_get_hash_by_path($hash_base, $file_name);
1214                        my $blob_parent  = git_get_hash_by_path($commit, $file_name);
1215                        if (defined $blob_current && defined $blob_parent &&
1216                                        $blob_current ne $blob_parent) {
1217                                print " | " .
1218                                        $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blobdiff;h=$blob_current;hp=$blob_parent;hb=$commit;f=$file_name")},
1219                                                "diff to current");
1220                        }
1221                }
1222                print "</td>\n" .
1223                      "</tr>\n";
1224        }
1225        if (defined $extra) {
1226                print "<tr>\n" .
1227                      "<td colspan=\"4\">$extra</td>\n" .
1228                      "</tr>\n";
1229        }
1230        print "</table>\n";
1231}
1232
1233sub git_tags_body {
1234        # uses global variable $project
1235        my ($taglist, $from, $to, $extra) = @_;
1236        $from = 0 unless defined $from;
1237        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
1238
1239        print "<table class=\"tags\" cellspacing=\"0\">\n";
1240        my $alternate = 0;
1241        for (my $i = $from; $i <= $to; $i++) {
1242                my $entry = $taglist->[$i];
1243                my %tag = %$entry;
1244                my $comment_lines = $tag{'comment'};
1245                my $comment = shift @$comment_lines;
1246                my $comment_short;
1247                if (defined $comment) {
1248                        $comment_short = chop_str($comment, 30, 5);
1249                }
1250                if ($alternate) {
1251                        print "<tr class=\"dark\">\n";
1252                } else {
1253                        print "<tr class=\"light\">\n";
1254                }
1255                $alternate ^= 1;
1256                print "<td><i>$tag{'age'}</i></td>\n" .
1257                      "<td>" .
1258                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=$tag{'reftype'};h=$tag{'refid'}"),
1259                               -class => "list"}, "<b>" . esc_html($tag{'name'}) . "</b>") .
1260                      "</td>\n" .
1261                      "<td>";
1262                if (defined $comment) {
1263                        print format_subject_html($comment, $comment_short, "p=$project;a=tag;h=$tag{'id'}");
1264                }
1265                print "</td>\n" .
1266                      "<td class=\"selflink\">";
1267                if ($tag{'type'} eq "tag") {
1268                        print $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tag;h=$tag{'id'}")}, "tag");
1269                } else {
1270                        print "&nbsp;";
1271                }
1272                print "</td>\n" .
1273                      "<td class=\"link\">" . " | " .
1274                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=$tag{'reftype'};h=$tag{'refid'}")}, $tag{'reftype'});
1275                if ($tag{'reftype'} eq "commit") {
1276                        print " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=shortlog;h=$tag{'name'}")}, "shortlog") .
1277                              " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=log;h=$tag{'refid'}")}, "log");
1278                } elsif ($tag{'reftype'} eq "blob") {
1279                        print " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob_plain;h=$tag{'refid'}")}, "raw");
1280                }
1281                print "</td>\n" .
1282                      "</tr>";
1283        }
1284        if (defined $extra) {
1285                print "<tr>\n" .
1286                      "<td colspan=\"5\">$extra</td>\n" .
1287                      "</tr>\n";
1288        }
1289        print "</table>\n";
1290}
1291
1292sub git_heads_body {
1293        # uses global variable $project
1294        my ($taglist, $head, $from, $to, $extra) = @_;
1295        $from = 0 unless defined $from;
1296        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
1297
1298        print "<table class=\"heads\" cellspacing=\"0\">\n";
1299        my $alternate = 0;
1300        for (my $i = $from; $i <= $to; $i++) {
1301                my $entry = $taglist->[$i];
1302                my %tag = %$entry;
1303                my $curr = $tag{'id'} eq $head;
1304                if ($alternate) {
1305                        print "<tr class=\"dark\">\n";
1306                } else {
1307                        print "<tr class=\"light\">\n";
1308                }
1309                $alternate ^= 1;
1310                print "<td><i>$tag{'age'}</i></td>\n" .
1311                      ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
1312                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=shortlog;h=$tag{'name'}"),
1313                               -class => "list"}, "<b>" . esc_html($tag{'name'}) . "</b>") .
1314                      "</td>\n" .
1315                      "<td class=\"link\">" .
1316                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=shortlog;h=$tag{'name'}")}, "shortlog") . " | " .
1317                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=log;h=$tag{'name'}")}, "log") .
1318                      "</td>\n" .
1319                      "</tr>";
1320        }
1321        if (defined $extra) {
1322                print "<tr>\n" .
1323                      "<td colspan=\"3\">$extra</td>\n" .
1324                      "</tr>\n";
1325        }
1326        print "</table>\n";
1327}
1328
1329## ----------------------------------------------------------------------
1330## functions printing large fragments, format as one of arguments
1331
1332sub git_diff_print {
1333        my $from = shift;
1334        my $from_name = shift;
1335        my $to = shift;
1336        my $to_name = shift;
1337        my $format = shift || "html";
1338
1339        my $from_tmp = "/dev/null";
1340        my $to_tmp = "/dev/null";
1341        my $pid = $$;
1342
1343        # create tmp from-file
1344        if (defined $from) {
1345                $from_tmp = "$git_temp/gitweb_" . $$ . "_from";
1346                open my $fd2, "> $from_tmp";
1347                open my $fd, "-|", $GIT, "cat-file", "blob", $from;
1348                my @file = <$fd>;
1349                print $fd2 @file;
1350                close $fd2;
1351                close $fd;
1352        }
1353
1354        # create tmp to-file
1355        if (defined $to) {
1356                $to_tmp = "$git_temp/gitweb_" . $$ . "_to";
1357                open my $fd2, "> $to_tmp";
1358                open my $fd, "-|", $GIT, "cat-file", "blob", $to;
1359                my @file = <$fd>;
1360                print $fd2 @file;
1361                close $fd2;
1362                close $fd;
1363        }
1364
1365        open my $fd, "-|", "/usr/bin/diff -u -p -L \'$from_name\' -L \'$to_name\' $from_tmp $to_tmp";
1366        if ($format eq "plain") {
1367                undef $/;
1368                print <$fd>;
1369                $/ = "\n";
1370        } else {
1371                while (my $line = <$fd>) {
1372                        chomp $line;
1373                        my $char = substr($line, 0, 1);
1374                        my $diff_class = "";
1375                        if ($char eq '+') {
1376                                $diff_class = " add";
1377                        } elsif ($char eq "-") {
1378                                $diff_class = " rem";
1379                        } elsif ($char eq "@") {
1380                                $diff_class = " chunk_header";
1381                        } elsif ($char eq "\\") {
1382                                # skip errors
1383                                next;
1384                        }
1385                        $line = untabify($line);
1386                        print "<div class=\"diff$diff_class\">" . esc_html($line) . "</div>\n";
1387                }
1388        }
1389        close $fd;
1390
1391        if (defined $from) {
1392                unlink($from_tmp);
1393        }
1394        if (defined $to) {
1395                unlink($to_tmp);
1396        }
1397}
1398
1399
1400## ======================================================================
1401## ======================================================================
1402## actions
1403
1404sub git_project_list {
1405        my $order = $cgi->param('o');
1406        if (defined $order && $order !~ m/project|descr|owner|age/) {
1407                die_error(undef, "Unknown order parameter");
1408        }
1409
1410        my @list = git_get_projects_list();
1411        my @projects;
1412        if (!@list) {
1413                die_error(undef, "No projects found");
1414        }
1415        foreach my $pr (@list) {
1416                my $head = git_get_head_hash($pr->{'path'});
1417                if (!defined $head) {
1418                        next;
1419                }
1420                $ENV{'GIT_DIR'} = "$projectroot/$pr->{'path'}";
1421                my %co = parse_commit($head);
1422                if (!%co) {
1423                        next;
1424                }
1425                $pr->{'commit'} = \%co;
1426                if (!defined $pr->{'descr'}) {
1427                        my $descr = git_get_project_description($pr->{'path'}) || "";
1428                        $pr->{'descr'} = chop_str($descr, 25, 5);
1429                }
1430                if (!defined $pr->{'owner'}) {
1431                        $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
1432                }
1433                push @projects, $pr;
1434        }
1435
1436        git_header_html();
1437        if (-f $home_text) {
1438                print "<div class=\"index_include\">\n";
1439                open (my $fd, $home_text);
1440                print <$fd>;
1441                close $fd;
1442                print "</div>\n";
1443        }
1444        print "<table class=\"project_list\">\n" .
1445              "<tr>\n";
1446        $order ||= "project";
1447        if ($order eq "project") {
1448                @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
1449                print "<th>Project</th>\n";
1450        } else {
1451                print "<th>" .
1452                      $cgi->a({-href => "$my_uri?" . esc_param("o=project"),
1453                               -class => "header"}, "Project") .
1454                      "</th>\n";
1455        }
1456        if ($order eq "descr") {
1457                @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
1458                print "<th>Description</th>\n";
1459        } else {
1460                print "<th>" .
1461                      $cgi->a({-href => "$my_uri?" . esc_param("o=descr"),
1462                               -class => "header"}, "Description") .
1463                      "</th>\n";
1464        }
1465        if ($order eq "owner") {
1466                @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
1467                print "<th>Owner</th>\n";
1468        } else {
1469                print "<th>" .
1470                      $cgi->a({-href => "$my_uri?" . esc_param("o=owner"),
1471                               -class => "header"}, "Owner") .
1472                      "</th>\n";
1473        }
1474        if ($order eq "age") {
1475                @projects = sort {$a->{'commit'}{'age'} <=> $b->{'commit'}{'age'}} @projects;
1476                print "<th>Last Change</th>\n";
1477        } else {
1478                print "<th>" .
1479                      $cgi->a({-href => "$my_uri?" . esc_param("o=age"),
1480                               -class => "header"}, "Last Change") .
1481                      "</th>\n";
1482        }
1483        print "<th></th>\n" .
1484              "</tr>\n";
1485        my $alternate = 0;
1486        foreach my $pr (@projects) {
1487                if ($alternate) {
1488                        print "<tr class=\"dark\">\n";
1489                } else {
1490                        print "<tr class=\"light\">\n";
1491                }
1492                $alternate ^= 1;
1493                print "<td>" . $cgi->a({-href => "$my_uri?" . esc_param("p=$pr->{'path'};a=summary"),
1494                                        -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
1495                      "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
1496                      "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
1497                print "<td class=\"". age_class($pr->{'commit'}{'age'}) . "\">" .
1498                      $pr->{'commit'}{'age_string'} . "</td>\n" .
1499                      "<td class=\"link\">" .
1500                      $cgi->a({-href => "$my_uri?" . esc_param("p=$pr->{'path'};a=summary")}, "summary")   . " | " .
1501                      $cgi->a({-href => "$my_uri?" . esc_param("p=$pr->{'path'};a=shortlog")}, "shortlog") . " | " .
1502                      $cgi->a({-href => "$my_uri?" . esc_param("p=$pr->{'path'};a=log")}, "log") .
1503                      "</td>\n" .
1504                      "</tr>\n";
1505        }
1506        print "</table>\n";
1507        git_footer_html();
1508}
1509
1510sub git_summary {
1511        my $descr = git_get_project_description($project) || "none";
1512        my $head = git_get_head_hash($project);
1513        my %co = parse_commit($head);
1514        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
1515
1516        my $owner = git_get_project_owner($project);
1517
1518        my $refs = git_get_references();
1519        git_header_html();
1520        git_print_page_nav('summary','', $head);
1521
1522        print "<div class=\"title\">&nbsp;</div>\n";
1523        print "<table cellspacing=\"0\">\n" .
1524              "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
1525              "<tr><td>owner</td><td>$owner</td></tr>\n" .
1526              "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n" .
1527              "</table>\n";
1528
1529        open my $fd, "-|", $GIT, "rev-list", "--max-count=17", git_get_head_hash($project)
1530                or die_error(undef, "Open git-rev-list failed");
1531        my @revlist = map { chomp; $_ } <$fd>;
1532        close $fd;
1533        git_print_header_div('shortlog');
1534        git_shortlog_body(\@revlist, 0, 15, $refs,
1535                          $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=shortlog")}, "..."));
1536
1537        my $taglist = git_get_refs_list("refs/tags");
1538        if (defined @$taglist) {
1539                git_print_header_div('tags');
1540                git_tags_body($taglist, 0, 15,
1541                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tags")}, "..."));
1542        }
1543
1544        my $headlist = git_get_refs_list("refs/heads");
1545        if (defined @$headlist) {
1546                git_print_header_div('heads');
1547                git_heads_body($headlist, $head, 0, 15,
1548                               $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=heads")}, "..."));
1549        }
1550
1551        git_footer_html();
1552}
1553
1554sub git_tag {
1555        my $head = git_get_head_hash($project);
1556        git_header_html();
1557        git_print_page_nav('','', $head,undef,$head);
1558        my %tag = parse_tag($hash);
1559        git_print_header_div('commit', esc_html($tag{'name'}), $hash);
1560        print "<div class=\"title_text\">\n" .
1561              "<table cellspacing=\"0\">\n" .
1562              "<tr>\n" .
1563              "<td>object</td>\n" .
1564              "<td>" . $cgi->a({-class => "list", -href => "$my_uri?" . esc_param("p=$project;a=$tag{'type'};h=$tag{'object'}")}, $tag{'object'}) . "</td>\n" .
1565              "<td class=\"link\">" . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=$tag{'type'};h=$tag{'object'}")}, $tag{'type'}) . "</td>\n" .
1566              "</tr>\n";
1567        if (defined($tag{'author'})) {
1568                my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
1569                print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
1570                print "<tr><td></td><td>" . $ad{'rfc2822'} . sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) . "</td></tr>\n";
1571        }
1572        print "</table>\n\n" .
1573              "</div>\n";
1574        print "<div class=\"page_body\">";
1575        my $comment = $tag{'comment'};
1576        foreach my $line (@$comment) {
1577                print esc_html($line) . "<br/>\n";
1578        }
1579        print "</div>\n";
1580        git_footer_html();
1581}
1582
1583sub git_blame2 {
1584        my $fd;
1585        my $ftype;
1586        die_error(undef, "Permission denied") if (!git_get_project_config_bool ('blame'));
1587        die_error('404 Not Found', "File name not defined") if (!$file_name);
1588        $hash_base ||= git_get_head_hash($project);
1589        die_error(undef, "Couldn't find base commit") unless ($hash_base);
1590        my %co = parse_commit($hash_base)
1591                or die_error(undef, "Reading commit failed");
1592        if (!defined $hash) {
1593                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
1594                        or die_error(undef, "Error looking up file");
1595        }
1596        $ftype = git_get_type($hash);
1597        if ($ftype !~ "blob") {
1598                die_error("400 Bad Request", "Object is not a blob");
1599        }
1600        open ($fd, "-|", $GIT, "blame", '-l', $file_name, $hash_base)
1601                or die_error(undef, "Open git-blame failed");
1602        git_header_html();
1603        my $formats_nav =
1604                $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$hash;hb=$hash_base;f=$file_name")}, "blob") .
1605                " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blame;f=$file_name")}, "head");
1606        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
1607        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
1608        git_print_page_path($file_name, $ftype);
1609        my @rev_color = (qw(light2 dark2));
1610        my $num_colors = scalar(@rev_color);
1611        my $current_color = 0;
1612        my $last_rev;
1613        print "<div class=\"page_body\">\n";
1614        print "<table class=\"blame\">\n";
1615        print "<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n";
1616        while (<$fd>) {
1617                /^([0-9a-fA-F]{40}).*?(\d+)\)\s{1}(\s*.*)/;
1618                my $full_rev = $1;
1619                my $rev = substr($full_rev, 0, 8);
1620                my $lineno = $2;
1621                my $data = $3;
1622
1623                if (!defined $last_rev) {
1624                        $last_rev = $full_rev;
1625                } elsif ($last_rev ne $full_rev) {
1626                        $last_rev = $full_rev;
1627                        $current_color = ++$current_color % $num_colors;
1628                }
1629                print "<tr class=\"$rev_color[$current_color]\">\n";
1630                print "<td class=\"sha1\">" .
1631                        $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$full_rev;f=$file_name")}, esc_html($rev)) . "</td>\n";
1632                print "<td class=\"linenr\"><a id=\"l$lineno\" href=\"#l$lineno\" class=\"linenr\">" . esc_html($lineno) . "</a></td>\n";
1633                print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
1634                print "</tr>\n";
1635        }
1636        print "</table>\n";
1637        print "</div>";
1638        close $fd or print "Reading blob failed\n";
1639        git_footer_html();
1640}
1641
1642sub git_blame {
1643        my $fd;
1644        die_error('403 Permission denied', "Permission denied") if (!git_get_project_config_bool ('blame'));
1645        die_error('404 Not Found', "File name not defined") if (!$file_name);
1646        $hash_base ||= git_get_head_hash($project);
1647        die_error(undef, "Couldn't find base commit") unless ($hash_base);
1648        my %co = parse_commit($hash_base)
1649                or die_error(undef, "Reading commit failed");
1650        if (!defined $hash) {
1651                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
1652                        or die_error(undef, "Error lookup file");
1653        }
1654        open ($fd, "-|", $GIT, "annotate", '-l', '-t', '-r', $file_name, $hash_base)
1655                or die_error(undef, "Open git-annotate failed");
1656        git_header_html();
1657        my $formats_nav =
1658                $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$hash;hb=$hash_base;f=$file_name")}, "blob") .
1659                " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blame;f=$file_name")}, "head");
1660        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
1661        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
1662        git_print_page_path($file_name, 'blob');
1663        print "<div class=\"page_body\">\n";
1664        print <<HTML;
1665<table class="blame">
1666  <tr>
1667    <th>Commit</th>
1668    <th>Age</th>
1669    <th>Author</th>
1670    <th>Line</th>
1671    <th>Data</th>
1672  </tr>
1673HTML
1674        my @line_class = (qw(light dark));
1675        my $line_class_len = scalar (@line_class);
1676        my $line_class_num = $#line_class;
1677        while (my $line = <$fd>) {
1678                my $long_rev;
1679                my $short_rev;
1680                my $author;
1681                my $time;
1682                my $lineno;
1683                my $data;
1684                my $age;
1685                my $age_str;
1686                my $age_class;
1687
1688                chomp $line;
1689                $line_class_num = ($line_class_num + 1) % $line_class_len;
1690
1691                if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) \+\d\d\d\d\t(\d+)\)(.*)$/) {
1692                        $long_rev = $1;
1693                        $author   = $2;
1694                        $time     = $3;
1695                        $lineno   = $4;
1696                        $data     = $5;
1697                } else {
1698                        print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
1699                        next;
1700                }
1701                $short_rev  = substr ($long_rev, 0, 8);
1702                $age        = time () - $time;
1703                $age_str    = age_string ($age);
1704                $age_str    =~ s/ /&nbsp;/g;
1705                $age_class  = age_class($age);
1706                $author     = esc_html ($author);
1707                $author     =~ s/ /&nbsp;/g;
1708
1709                $data = untabify($data);
1710                $data = esc_html ($data);
1711
1712                print <<HTML;
1713  <tr class="$line_class[$line_class_num]">
1714    <td class="sha1"><a href="$my_uri?${\esc_param ("p=$project;a=commit;h=$long_rev")}" class="text">$short_rev..</a></td>
1715    <td class="$age_class">$age_str</td>
1716    <td>$author</td>
1717    <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
1718    <td class="pre">$data</td>
1719  </tr>
1720HTML
1721        } # while (my $line = <$fd>)
1722        print "</table>\n\n";
1723        close $fd or print "Reading blob failed.\n";
1724        print "</div>";
1725        git_footer_html();
1726}
1727
1728sub git_tags {
1729        my $head = git_get_head_hash($project);
1730        git_header_html();
1731        git_print_page_nav('','', $head,undef,$head);
1732        git_print_header_div('summary', $project);
1733
1734        my $taglist = git_get_refs_list("refs/tags");
1735        if (defined @$taglist) {
1736                git_tags_body($taglist);
1737        }
1738        git_footer_html();
1739}
1740
1741sub git_heads {
1742        my $head = git_get_head_hash($project);
1743        git_header_html();
1744        git_print_page_nav('','', $head,undef,$head);
1745        git_print_header_div('summary', $project);
1746
1747        my $taglist = git_get_refs_list("refs/heads");
1748        if (defined @$taglist) {
1749                git_heads_body($taglist, $head);
1750        }
1751        git_footer_html();
1752}
1753
1754sub git_blob_plain {
1755        if (!defined $hash) {
1756                if (defined $file_name) {
1757                        my $base = $hash_base || git_get_head_hash($project);
1758                        $hash = git_get_hash_by_path($base, $file_name, "blob")
1759                                or die_error(undef, "Error lookup file");
1760                } else {
1761                        die_error(undef, "No file name defined");
1762                }
1763        }
1764        my $type = shift;
1765        open my $fd, "-|", $GIT, "cat-file", "blob", $hash
1766                or die_error(undef, "Couldn't cat $file_name, $hash");
1767
1768        $type ||= blob_mimetype($fd, $file_name);
1769
1770        # save as filename, even when no $file_name is given
1771        my $save_as = "$hash";
1772        if (defined $file_name) {
1773                $save_as = $file_name;
1774        } elsif ($type =~ m/^text\//) {
1775                $save_as .= '.txt';
1776        }
1777
1778        print $cgi->header(-type => "$type", '-content-disposition' => "inline; filename=\"$save_as\"");
1779        undef $/;
1780        binmode STDOUT, ':raw';
1781        print <$fd>;
1782        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
1783        $/ = "\n";
1784        close $fd;
1785}
1786
1787sub git_blob {
1788        if (!defined $hash) {
1789                if (defined $file_name) {
1790                        my $base = $hash_base || git_get_head_hash($project);
1791                        $hash = git_get_hash_by_path($base, $file_name, "blob")
1792                                or die_error(undef, "Error lookup file");
1793                } else {
1794                        die_error(undef, "No file name defined");
1795                }
1796        }
1797        my $have_blame = git_get_project_config_bool ('blame');
1798        open my $fd, "-|", $GIT, "cat-file", "blob", $hash
1799                or die_error(undef, "Couldn't cat $file_name, $hash");
1800        my $mimetype = blob_mimetype($fd, $file_name);
1801        if ($mimetype !~ m/^text\//) {
1802                close $fd;
1803                return git_blob_plain($mimetype);
1804        }
1805        git_header_html();
1806        my $formats_nav = '';
1807        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
1808                if (defined $file_name) {
1809                        if ($have_blame) {
1810                                $formats_nav .= $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blame;h=$hash;hb=$hash_base;f=$file_name")}, "blame") . " | ";
1811                        }
1812                        $formats_nav .=
1813                                $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob_plain;h=$hash;f=$file_name")}, "plain") .
1814                                " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;hb=HEAD;f=$file_name")}, "head");
1815                } else {
1816                        $formats_nav .= $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob_plain;h=$hash")}, "plain");
1817                }
1818                git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
1819                git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
1820        } else {
1821                print "<div class=\"page_nav\">\n" .
1822                      "<br/><br/></div>\n" .
1823                      "<div class=\"title\">$hash</div>\n";
1824        }
1825        git_print_page_path($file_name, "blob");
1826        print "<div class=\"page_body\">\n";
1827        my $nr;
1828        while (my $line = <$fd>) {
1829                chomp $line;
1830                $nr++;
1831                $line = untabify($line);
1832                printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n", $nr, $nr, $nr, esc_html($line);
1833        }
1834        close $fd or print "Reading blob failed.\n";
1835        print "</div>";
1836        git_footer_html();
1837}
1838
1839sub git_tree {
1840        if (!defined $hash) {
1841                $hash = git_get_head_hash($project);
1842                if (defined $file_name) {
1843                        my $base = $hash_base || $hash;
1844                        $hash = git_get_hash_by_path($base, $file_name, "tree");
1845                }
1846                if (!defined $hash_base) {
1847                        $hash_base = $hash;
1848                }
1849        }
1850        $/ = "\0";
1851        open my $fd, "-|", $GIT, "ls-tree", '-z', $hash
1852                or die_error(undef, "Open git-ls-tree failed");
1853        my @entries = map { chomp; $_ } <$fd>;
1854        close $fd or die_error(undef, "Reading tree failed");
1855        $/ = "\n";
1856
1857        my $refs = git_get_references();
1858        my $ref = format_ref_marker($refs, $hash_base);
1859        git_header_html();
1860        my $base_key = "";
1861        my $base = "";
1862        my $have_blame = git_get_project_config_bool ('blame');
1863        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
1864                $base_key = ";hb=$hash_base";
1865                git_print_page_nav('tree','', $hash_base);
1866                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
1867        } else {
1868                print "<div class=\"page_nav\">\n";
1869                print "<br/><br/></div>\n";
1870                print "<div class=\"title\">$hash</div>\n";
1871        }
1872        if (defined $file_name) {
1873                $base = esc_html("$file_name/");
1874        }
1875        git_print_page_path($file_name, 'tree');
1876        print "<div class=\"page_body\">\n";
1877        print "<table cellspacing=\"0\">\n";
1878        my $alternate = 0;
1879        foreach my $line (@entries) {
1880                #'100644        blob    0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa        panic.c'
1881                $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
1882                my $t_mode = $1;
1883                my $t_type = $2;
1884                my $t_hash = $3;
1885                my $t_name = validate_input($4);
1886                if ($alternate) {
1887                        print "<tr class=\"dark\">\n";
1888                } else {
1889                        print "<tr class=\"light\">\n";
1890                }
1891                $alternate ^= 1;
1892                print "<td class=\"mode\">" . mode_str($t_mode) . "</td>\n";
1893                if ($t_type eq "blob") {
1894                        print "<td class=\"list\">" .
1895                              $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)) .
1896                              "</td>\n" .
1897                              "<td class=\"link\">" .
1898                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$t_hash$base_key;f=$base$t_name")}, "blob");
1899                        if ($have_blame) {
1900                                print " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blame;h=$t_hash$base_key;f=$base$t_name")}, "blame");
1901                        }
1902                        print " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=history;h=$t_hash;hb=$hash_base;f=$base$t_name")}, "history") .
1903                              " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob_plain;h=$t_hash;f=$base$t_name")}, "raw") .
1904                              "</td>\n";
1905                } elsif ($t_type eq "tree") {
1906                        print "<td class=\"list\">" .
1907                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tree;h=$t_hash$base_key;f=$base$t_name")}, esc_html($t_name)) .
1908                              "</td>\n" .
1909                              "<td class=\"link\">" .
1910                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tree;h=$t_hash$base_key;f=$base$t_name")}, "tree") .
1911                              " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=history;hb=$hash_base;f=$base$t_name")}, "history") .
1912                              "</td>\n";
1913                }
1914                print "</tr>\n";
1915        }
1916        print "</table>\n" .
1917              "</div>";
1918        git_footer_html();
1919}
1920
1921sub git_log {
1922        my $head = git_get_head_hash($project);
1923        if (!defined $hash) {
1924                $hash = $head;
1925        }
1926        if (!defined $page) {
1927                $page = 0;
1928        }
1929        my $refs = git_get_references();
1930
1931        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
1932        open my $fd, "-|", $GIT, "rev-list", $limit, $hash
1933                or die_error(undef, "Open git-rev-list failed");
1934        my @revlist = map { chomp; $_ } <$fd>;
1935        close $fd;
1936
1937        my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
1938
1939        git_header_html();
1940        git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
1941
1942        if (!@revlist) {
1943                my %co = parse_commit($hash);
1944
1945                git_print_header_div('summary', $project);
1946                print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
1947        }
1948        for (my $i = ($page * 100); $i <= $#revlist; $i++) {
1949                my $commit = $revlist[$i];
1950                my $ref = format_ref_marker($refs, $commit);
1951                my %co = parse_commit($commit);
1952                next if !%co;
1953                my %ad = parse_date($co{'author_epoch'});
1954                git_print_header_div('commit',
1955                               "<span class=\"age\">$co{'age_string'}</span>" .
1956                               esc_html($co{'title'}) . $ref,
1957                               $commit);
1958                print "<div class=\"title_text\">\n" .
1959                      "<div class=\"log_link\">\n" .
1960                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$commit")}, "commit") .
1961                      " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commitdiff;h=$commit")}, "commitdiff") .
1962                      "<br/>\n" .
1963                      "</div>\n" .
1964                      "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
1965                      "</div>\n" .
1966                      "<div class=\"log_body\">\n";
1967                my $comment = $co{'comment'};
1968                my $empty = 0;
1969                foreach my $line (@$comment) {
1970                        if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1971                                next;
1972                        }
1973                        if ($line eq "") {
1974                                if ($empty) {
1975                                        next;
1976                                }
1977                                $empty = 1;
1978                        } else {
1979                                $empty = 0;
1980                        }
1981                        print format_log_line_html($line) . "<br/>\n";
1982                }
1983                if (!$empty) {
1984                        print "<br/>\n";
1985                }
1986                print "</div>\n";
1987        }
1988        git_footer_html();
1989}
1990
1991sub git_commit {
1992        my %co = parse_commit($hash);
1993        if (!%co) {
1994                die_error(undef, "Unknown commit object");
1995        }
1996        my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
1997        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
1998
1999        my $parent = $co{'parent'};
2000        if (!defined $parent) {
2001                $parent = "--root";
2002        }
2003        open my $fd, "-|", $GIT, "diff-tree", '-r', '-M', $parent, $hash
2004                or die_error(undef, "Open git-diff-tree failed");
2005        my @difftree = map { chomp; $_ } <$fd>;
2006        close $fd or die_error(undef, "Reading git-diff-tree failed");
2007
2008        # non-textual hash id's can be cached
2009        my $expires;
2010        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2011                $expires = "+1d";
2012        }
2013        my $refs = git_get_references();
2014        my $ref = format_ref_marker($refs, $co{'id'});
2015        my $formats_nav = '';
2016        if (defined $file_name && defined $co{'parent'}) {
2017                my $parent = $co{'parent'};
2018                $formats_nav .= $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blame;hb=$parent;f=$file_name")}, "blame");
2019        }
2020        git_header_html(undef, $expires);
2021        git_print_page_nav('commit', defined $co{'parent'} ? '' : 'commitdiff',
2022                     $hash, $co{'tree'}, $hash,
2023                     $formats_nav);
2024
2025        if (defined $co{'parent'}) {
2026                git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
2027        } else {
2028                git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
2029        }
2030        print "<div class=\"title_text\">\n" .
2031              "<table cellspacing=\"0\">\n";
2032        print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
2033              "<tr>" .
2034              "<td></td><td> $ad{'rfc2822'}";
2035        if ($ad{'hour_local'} < 6) {
2036                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2037        } else {
2038                printf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2039        }
2040        print "</td>" .
2041              "</tr>\n";
2042        print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
2043        print "<tr><td></td><td> $cd{'rfc2822'}" . sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) . "</td></tr>\n";
2044        print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
2045        print "<tr>" .
2046              "<td>tree</td>" .
2047              "<td class=\"sha1\">" .
2048              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tree;h=$co{'tree'};hb=$hash"), class => "list"}, $co{'tree'}) .
2049              "</td>" .
2050              "<td class=\"link\">" . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tree;h=$co{'tree'};hb=$hash")}, "tree") .
2051              "</td>" .
2052              "</tr>\n";
2053        my $parents = $co{'parents'};
2054        foreach my $par (@$parents) {
2055                print "<tr>" .
2056                      "<td>parent</td>" .
2057                      "<td class=\"sha1\">" . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$par"), class => "list"}, $par) . "</td>" .
2058                      "<td class=\"link\">" .
2059                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$par")}, "commit") .
2060                      " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commitdiff;h=$hash;hp=$par")}, "commitdiff") .
2061                      "</td>" .
2062                      "</tr>\n";
2063        }
2064        print "</table>".
2065              "</div>\n";
2066        print "<div class=\"page_body\">\n";
2067        my $comment = $co{'comment'};
2068        my $empty = 0;
2069        my $signed = 0;
2070        foreach my $line (@$comment) {
2071                # print only one empty line
2072                if ($line eq "") {
2073                        if ($empty || $signed) {
2074                                next;
2075                        }
2076                        $empty = 1;
2077                } else {
2078                        $empty = 0;
2079                }
2080                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
2081                        $signed = 1;
2082                        print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
2083                } else {
2084                        $signed = 0;
2085                        print format_log_line_html($line) . "<br/>\n";
2086                }
2087        }
2088        print "</div>\n";
2089        print "<div class=\"list_head\">\n";
2090        if ($#difftree > 10) {
2091                print(($#difftree + 1) . " files changed:\n");
2092        }
2093        print "</div>\n";
2094        print "<table class=\"diff_tree\">\n";
2095        my $alternate = 0;
2096        foreach my $line (@difftree) {
2097                # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M      ls-files.c'
2098                # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M      rev-tree.c'
2099                if ($line !~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2100                        next;
2101                }
2102                my $from_mode = $1;
2103                my $to_mode = $2;
2104                my $from_id = $3;
2105                my $to_id = $4;
2106                my $status = $5;
2107                my $similarity = $6;
2108                my $file = validate_input(unquote($7));
2109                if ($alternate) {
2110                        print "<tr class=\"dark\">\n";
2111                } else {
2112                        print "<tr class=\"light\">\n";
2113                }
2114                $alternate ^= 1;
2115                if ($status eq "A") {
2116                        my $mode_chng = "";
2117                        if (S_ISREG(oct $to_mode)) {
2118                                $mode_chng = sprintf(" with mode: %04o", (oct $to_mode) & 0777);
2119                        }
2120                        print "<td>" .
2121                              $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" .
2122                              "<td><span class=\"file_status new\">[new " . file_type($to_mode) . "$mode_chng]</span></td>\n" .
2123                              "<td class=\"link\">" . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$to_id;hb=$hash;f=$file")}, "blob") . "</td>\n";
2124                } elsif ($status eq "D") {
2125                        print "<td>" .
2126                              $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" .
2127                              "<td><span class=\"file_status deleted\">[deleted " . file_type($from_mode). "]</span></td>\n" .
2128                              "<td class=\"link\">" .
2129                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$from_id;hb=$parent;f=$file")}, "blob") .
2130                              " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=history;hb=$parent;f=$file")}, "history") .
2131                              "</td>\n"
2132                } elsif ($status eq "M" || $status eq "T") {
2133                        my $mode_chnge = "";
2134                        if ($from_mode != $to_mode) {
2135                                $mode_chnge = " <span class=\"file_status mode_chnge\">[changed";
2136                                if (((oct $from_mode) & S_IFMT) != ((oct $to_mode) & S_IFMT)) {
2137                                        $mode_chnge .= " from " . file_type($from_mode) . " to " . file_type($to_mode);
2138                                }
2139                                if (((oct $from_mode) & 0777) != ((oct $to_mode) & 0777)) {
2140                                        if (S_ISREG($from_mode) && S_ISREG($to_mode)) {
2141                                                $mode_chnge .= sprintf(" mode: %04o->%04o", (oct $from_mode) & 0777, (oct $to_mode) & 0777);
2142                                        } elsif (S_ISREG($to_mode)) {
2143                                                $mode_chnge .= sprintf(" mode: %04o", (oct $to_mode) & 0777);
2144                                        }
2145                                }
2146                                $mode_chnge .= "]</span>\n";
2147                        }
2148                        print "<td>";
2149                        if ($to_id ne $from_id) {
2150                                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));
2151                        } else {
2152                                print $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$to_id;hb=$hash;f=$file"), -class => "list"}, esc_html($file));
2153                        }
2154                        print "</td>\n" .
2155                              "<td>$mode_chnge</td>\n" .
2156                              "<td class=\"link\">";
2157                        print $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$to_id;hb=$hash;f=$file")}, "blob");
2158                        if ($to_id ne $from_id) {
2159                                print " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blobdiff;h=$to_id;hp=$from_id;hb=$hash;f=$file")}, "diff");
2160                        }
2161                        print " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=history;hb=$hash;f=$file")}, "history") . "\n";
2162                        print "</td>\n";
2163                } elsif ($status eq "R") {
2164                        my ($from_file, $to_file) = split "\t", $file;
2165                        my $mode_chng = "";
2166                        if ($from_mode != $to_mode) {
2167                                $mode_chng = sprintf(", mode: %04o", (oct $to_mode) & 0777);
2168                        }
2169                        print "<td>" .
2170                              $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" .
2171                              "<td><span class=\"file_status moved\">[moved from " .
2172                              $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)) .
2173                              " with " . (int $similarity) . "% similarity$mode_chng]</span></td>\n" .
2174                              "<td class=\"link\">" .
2175                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$to_id;hb=$hash;f=$to_file")}, "blob");
2176                        if ($to_id ne $from_id) {
2177                                print " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blobdiff;h=$to_id;hp=$from_id;hb=$hash;f=$to_file")}, "diff");
2178                        }
2179                        print "</td>\n";
2180                }
2181                print "</tr>\n";
2182        }
2183        print "</table>\n";
2184        git_footer_html();
2185}
2186
2187sub git_blobdiff {
2188        mkdir($git_temp, 0700);
2189        git_header_html();
2190        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2191                my $formats_nav =
2192                        $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blobdiff_plain;h=$hash;hp=$hash_parent")}, "plain");
2193                git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2194                git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2195        } else {
2196                print "<div class=\"page_nav\">\n" .
2197                      "<br/><br/></div>\n" .
2198                      "<div class=\"title\">$hash vs $hash_parent</div>\n";
2199        }
2200        git_print_page_path($file_name, "blob");
2201        print "<div class=\"page_body\">\n" .
2202              "<div class=\"diff_info\">blob:" .
2203              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$hash_parent;hb=$hash_base;f=$file_name")}, $hash_parent) .
2204              " -> blob:" .
2205              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$hash;hb=$hash_base;f=$file_name")}, $hash) .
2206              "</div>\n";
2207        git_diff_print($hash_parent, $file_name || $hash_parent, $hash, $file_name || $hash);
2208        print "</div>";
2209        git_footer_html();
2210}
2211
2212sub git_blobdiff_plain {
2213        mkdir($git_temp, 0700);
2214        print $cgi->header(-type => "text/plain", -charset => 'utf-8');
2215        git_diff_print($hash_parent, $file_name || $hash_parent, $hash, $file_name || $hash, "plain");
2216}
2217
2218sub git_commitdiff {
2219        mkdir($git_temp, 0700);
2220        my %co = parse_commit($hash);
2221        if (!%co) {
2222                die_error(undef, "Unknown commit object");
2223        }
2224        if (!defined $hash_parent) {
2225                $hash_parent = $co{'parent'} || '--root';
2226        }
2227        open my $fd, "-|", $GIT, "diff-tree", '-r', $hash_parent, $hash
2228                or die_error(undef, "Open git-diff-tree failed");
2229        my @difftree = map { chomp; $_ } <$fd>;
2230        close $fd or die_error(undef, "Reading git-diff-tree failed");
2231
2232        # non-textual hash id's can be cached
2233        my $expires;
2234        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2235                $expires = "+1d";
2236        }
2237        my $refs = git_get_references();
2238        my $ref = format_ref_marker($refs, $co{'id'});
2239        my $formats_nav =
2240                $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commitdiff_plain;h=$hash;hp=$hash_parent")}, "plain");
2241        git_header_html(undef, $expires);
2242        git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
2243        git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
2244        print "<div class=\"page_body\">\n";
2245        my $comment = $co{'comment'};
2246        my $empty = 0;
2247        my $signed = 0;
2248        my @log = @$comment;
2249        # remove first and empty lines after that
2250        shift @log;
2251        while (defined $log[0] && $log[0] eq "") {
2252                shift @log;
2253        }
2254        foreach my $line (@log) {
2255                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
2256                        next;
2257                }
2258                if ($line eq "") {
2259                        if ($empty) {
2260                                next;
2261                        }
2262                        $empty = 1;
2263                } else {
2264                        $empty = 0;
2265                }
2266                print format_log_line_html($line) . "<br/>\n";
2267        }
2268        print "<br/>\n";
2269        foreach my $line (@difftree) {
2270                # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M      ls-files.c'
2271                # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M      rev-tree.c'
2272                if ($line !~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
2273                        next;
2274                }
2275                my $from_mode = $1;
2276                my $to_mode = $2;
2277                my $from_id = $3;
2278                my $to_id = $4;
2279                my $status = $5;
2280                my $file = validate_input(unquote($6));
2281                if ($status eq "A") {
2282                        print "<div class=\"diff_info\">" . file_type($to_mode) . ":" .
2283                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$to_id;hb=$hash;f=$file")}, $to_id) . "(new)" .
2284                              "</div>\n";
2285                        git_diff_print(undef, "/dev/null", $to_id, "b/$file");
2286                } elsif ($status eq "D") {
2287                        print "<div class=\"diff_info\">" . file_type($from_mode) . ":" .
2288                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$from_id;hb=$hash_parent;f=$file")}, $from_id) . "(deleted)" .
2289                              "</div>\n";
2290                        git_diff_print($from_id, "a/$file", undef, "/dev/null");
2291                } elsif ($status eq "M") {
2292                        if ($from_id ne $to_id) {
2293                                print "<div class=\"diff_info\">" .
2294                                      file_type($from_mode) . ":" .
2295                                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$from_id;hb=$hash_parent;f=$file")}, $from_id) .
2296                                      " -> " .
2297                                      file_type($to_mode) . ":" .
2298                                      $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$to_id;hb=$hash;f=$file")}, $to_id);
2299                                print "</div>\n";
2300                                git_diff_print($from_id, "a/$file",  $to_id, "b/$file");
2301                        }
2302                }
2303        }
2304        print "<br/>\n" .
2305              "</div>";
2306        git_footer_html();
2307}
2308
2309sub git_commitdiff_plain {
2310        mkdir($git_temp, 0700);
2311        my %co = parse_commit($hash);
2312        if (!%co) {
2313                die_error(undef, "Unknown commit object");
2314        }
2315        if (!defined $hash_parent) {
2316                $hash_parent = $co{'parent'} || '--root';
2317        }
2318        open my $fd, "-|", $GIT, "diff-tree", '-r', $hash_parent, $hash
2319                or die_error(undef, "Open git-diff-tree failed");
2320        my @difftree = map { chomp; $_ } <$fd>;
2321        close $fd or die_error(undef, "Reading diff-tree failed");
2322
2323        # try to figure out the next tag after this commit
2324        my $tagname;
2325        my $refs = git_get_references("tags");
2326        open $fd, "-|", $GIT, "rev-list", "HEAD";
2327        my @commits = map { chomp; $_ } <$fd>;
2328        close $fd;
2329        foreach my $commit (@commits) {
2330                if (defined $refs->{$commit}) {
2331                        $tagname = $refs->{$commit}
2332                }
2333                if ($commit eq $hash) {
2334                        last;
2335                }
2336        }
2337
2338        print $cgi->header(-type => "text/plain", -charset => 'utf-8', '-content-disposition' => "inline; filename=\"git-$hash.patch\"");
2339        my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2340        my $comment = $co{'comment'};
2341        print "From: $co{'author'}\n" .
2342              "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n".
2343              "Subject: $co{'title'}\n";
2344        if (defined $tagname) {
2345                print "X-Git-Tag: $tagname\n";
2346        }
2347        print "X-Git-Url: $my_url?p=$project;a=commitdiff;h=$hash\n" .
2348              "\n";
2349
2350        foreach my $line (@$comment) {;
2351                print "$line\n";
2352        }
2353        print "---\n\n";
2354
2355        foreach my $line (@difftree) {
2356                if ($line !~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
2357                        next;
2358                }
2359                my $from_id = $3;
2360                my $to_id = $4;
2361                my $status = $5;
2362                my $file = $6;
2363                if ($status eq "A") {
2364                        git_diff_print(undef, "/dev/null", $to_id, "b/$file", "plain");
2365                } elsif ($status eq "D") {
2366                        git_diff_print($from_id, "a/$file", undef, "/dev/null", "plain");
2367                } elsif ($status eq "M") {
2368                        git_diff_print($from_id, "a/$file",  $to_id, "b/$file", "plain");
2369                }
2370        }
2371}
2372
2373sub git_history {
2374        if (!defined $hash_base) {
2375                $hash_base = git_get_head_hash($project);
2376        }
2377        my $ftype;
2378        my %co = parse_commit($hash_base);
2379        if (!%co) {
2380                die_error(undef, "Unknown commit object");
2381        }
2382        my $refs = git_get_references();
2383        git_header_html();
2384        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base);
2385        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2386        if (!defined $hash && defined $file_name) {
2387                $hash = git_get_hash_by_path($hash_base, $file_name);
2388        }
2389        if (defined $hash) {
2390                $ftype = git_get_type($hash);
2391        }
2392        git_print_page_path($file_name, $ftype);
2393
2394        open my $fd, "-|",
2395                $GIT, "rev-list", "--full-history", $hash_base, "--", $file_name;
2396        git_history_body($fd, $refs, $hash_base, $ftype);
2397
2398        close $fd;
2399        git_footer_html();
2400}
2401
2402sub git_search {
2403        if (!defined $searchtext) {
2404                die_error(undef, "Text field empty");
2405        }
2406        if (!defined $hash) {
2407                $hash = git_get_head_hash($project);
2408        }
2409        my %co = parse_commit($hash);
2410        if (!%co) {
2411                die_error(undef, "Unknown commit object");
2412        }
2413        # pickaxe may take all resources of your box and run for several minutes
2414        # with every query - so decide by yourself how public you make this feature :)
2415        my $commit_search = 1;
2416        my $author_search = 0;
2417        my $committer_search = 0;
2418        my $pickaxe_search = 0;
2419        if ($searchtext =~ s/^author\\://i) {
2420                $author_search = 1;
2421        } elsif ($searchtext =~ s/^committer\\://i) {
2422                $committer_search = 1;
2423        } elsif ($searchtext =~ s/^pickaxe\\://i) {
2424                $commit_search = 0;
2425                $pickaxe_search = 1;
2426        }
2427        git_header_html();
2428        git_print_page_nav('','', $hash,$co{'tree'},$hash);
2429        git_print_header_div('commit', esc_html($co{'title'}), $hash);
2430
2431        print "<table cellspacing=\"0\">\n";
2432        my $alternate = 0;
2433        if ($commit_search) {
2434                $/ = "\0";
2435                open my $fd, "-|", $GIT, "rev-list", "--header", "--parents", $hash or next;
2436                while (my $commit_text = <$fd>) {
2437                        if (!grep m/$searchtext/i, $commit_text) {
2438                                next;
2439                        }
2440                        if ($author_search && !grep m/\nauthor .*$searchtext/i, $commit_text) {
2441                                next;
2442                        }
2443                        if ($committer_search && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
2444                                next;
2445                        }
2446                        my @commit_lines = split "\n", $commit_text;
2447                        my %co = parse_commit(undef, \@commit_lines);
2448                        if (!%co) {
2449                                next;
2450                        }
2451                        if ($alternate) {
2452                                print "<tr class=\"dark\">\n";
2453                        } else {
2454                                print "<tr class=\"light\">\n";
2455                        }
2456                        $alternate ^= 1;
2457                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2458                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
2459                              "<td>" .
2460                              $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/>");
2461                        my $comment = $co{'comment'};
2462                        foreach my $line (@$comment) {
2463                                if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
2464                                        my $lead = esc_html($1) || "";
2465                                        $lead = chop_str($lead, 30, 10);
2466                                        my $match = esc_html($2) || "";
2467                                        my $trail = esc_html($3) || "";
2468                                        $trail = chop_str($trail, 30, 10);
2469                                        my $text = "$lead<span class=\"match\">$match</span>$trail";
2470                                        print chop_str($text, 80, 5) . "<br/>\n";
2471                                }
2472                        }
2473                        print "</td>\n" .
2474                              "<td class=\"link\">" .
2475                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$co{'id'}")}, "commit") .
2476                              " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tree;h=$co{'tree'};hb=$co{'id'}")}, "tree");
2477                        print "</td>\n" .
2478                              "</tr>\n";
2479                }
2480                close $fd;
2481        }
2482
2483        if ($pickaxe_search) {
2484                $/ = "\n";
2485                open my $fd, "-|", "$GIT rev-list $hash | $GIT diff-tree -r --stdin -S\'$searchtext\'";
2486                undef %co;
2487                my @files;
2488                while (my $line = <$fd>) {
2489                        if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
2490                                my %set;
2491                                $set{'file'} = $6;
2492                                $set{'from_id'} = $3;
2493                                $set{'to_id'} = $4;
2494                                $set{'id'} = $set{'to_id'};
2495                                if ($set{'id'} =~ m/0{40}/) {
2496                                        $set{'id'} = $set{'from_id'};
2497                                }
2498                                if ($set{'id'} =~ m/0{40}/) {
2499                                        next;
2500                                }
2501                                push @files, \%set;
2502                        } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
2503                                if (%co) {
2504                                        if ($alternate) {
2505                                                print "<tr class=\"dark\">\n";
2506                                        } else {
2507                                                print "<tr class=\"light\">\n";
2508                                        }
2509                                        $alternate ^= 1;
2510                                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2511                                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
2512                                              "<td>" .
2513                                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$co{'id'}"), -class => "list"}, "<b>" .
2514                                              esc_html(chop_str($co{'title'}, 50)) . "</b><br/>");
2515                                        while (my $setref = shift @files) {
2516                                                my %set = %$setref;
2517                                                print $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=blob;h=$set{'id'};hb=$co{'id'};f=$set{'file'}"), class => "list"},
2518                                                      "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
2519                                                      "<br/>\n";
2520                                        }
2521                                        print "</td>\n" .
2522                                              "<td class=\"link\">" .
2523                                              $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=commit;h=$co{'id'}")}, "commit") .
2524                                              " | " . $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=tree;h=$co{'tree'};hb=$co{'id'}")}, "tree");
2525                                        print "</td>\n" .
2526                                              "</tr>\n";
2527                                }
2528                                %co = parse_commit($1);
2529                        }
2530                }
2531                close $fd;
2532        }
2533        print "</table>\n";
2534        git_footer_html();
2535}
2536
2537sub git_shortlog {
2538        my $head = git_get_head_hash($project);
2539        if (!defined $hash) {
2540                $hash = $head;
2541        }
2542        if (!defined $page) {
2543                $page = 0;
2544        }
2545        my $refs = git_get_references();
2546
2547        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2548        open my $fd, "-|", $GIT, "rev-list", $limit, $hash
2549                or die_error(undef, "Open git-rev-list failed");
2550        my @revlist = map { chomp; $_ } <$fd>;
2551        close $fd;
2552
2553        my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
2554        my $next_link = '';
2555        if ($#revlist >= (100 * ($page+1)-1)) {
2556                $next_link =
2557                        $cgi->a({-href => "$my_uri?" . esc_param("p=$project;a=shortlog;h=$hash;pg=" . ($page+1)),
2558                                 -title => "Alt-n"}, "next");
2559        }
2560
2561
2562        git_header_html();
2563        git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
2564        git_print_header_div('summary', $project);
2565
2566        git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
2567
2568        git_footer_html();
2569}
2570
2571## ......................................................................
2572## feeds (RSS, OPML)
2573
2574sub git_rss {
2575        # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
2576        open my $fd, "-|", $GIT, "rev-list", "--max-count=150", git_get_head_hash($project)
2577                or die_error(undef, "Open git-rev-list failed");
2578        my @revlist = map { chomp; $_ } <$fd>;
2579        close $fd or die_error(undef, "Reading git-rev-list failed");
2580        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
2581        print "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".
2582              "<rss version=\"2.0\" xmlns:content=\"http://purl.org/rss/1.0/modules/content/\">\n";
2583        print "<channel>\n";
2584        print "<title>$project</title>\n".
2585              "<link>" . esc_html("$my_url?p=$project;a=summary") . "</link>\n".
2586              "<description>$project log</description>\n".
2587              "<language>en</language>\n";
2588
2589        for (my $i = 0; $i <= $#revlist; $i++) {
2590                my $commit = $revlist[$i];
2591                my %co = parse_commit($commit);
2592                # we read 150, we always show 30 and the ones more recent than 48 hours
2593                if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
2594                        last;
2595                }
2596                my %cd = parse_date($co{'committer_epoch'});
2597                open $fd, "-|", $GIT, "diff-tree", '-r', $co{'parent'}, $co{'id'} or next;
2598                my @difftree = map { chomp; $_ } <$fd>;
2599                close $fd or next;
2600                print "<item>\n" .
2601                      "<title>" .
2602                      sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
2603                      "</title>\n" .
2604                      "<author>" . esc_html($co{'author'}) . "</author>\n" .
2605                      "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
2606                      "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
2607                      "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
2608                      "<description>" . esc_html($co{'title'}) . "</description>\n" .
2609                      "<content:encoded>" .
2610                      "<![CDATA[\n";
2611                my $comment = $co{'comment'};
2612                foreach my $line (@$comment) {
2613                        $line = decode("utf8", $line, Encode::FB_DEFAULT);
2614                        print "$line<br/>\n";
2615                }
2616                print "<br/>\n";
2617                foreach my $line (@difftree) {
2618                        if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
2619                                next;
2620                        }
2621                        my $file = validate_input(unquote($7));
2622                        $file = decode("utf8", $file, Encode::FB_DEFAULT);
2623                        print "$file<br/>\n";
2624                }
2625                print "]]>\n" .
2626                      "</content:encoded>\n" .
2627                      "</item>\n";
2628        }
2629        print "</channel></rss>";
2630}
2631
2632sub git_opml {
2633        my @list = git_get_projects_list();
2634
2635        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
2636        print "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".
2637              "<opml version=\"1.0\">\n".
2638              "<head>".
2639              "  <title>$site_name Git OPML Export</title>\n".
2640              "</head>\n".
2641              "<body>\n".
2642              "<outline text=\"git RSS feeds\">\n";
2643
2644        foreach my $pr (@list) {
2645                my %proj = %$pr;
2646                my $head = git_get_head_hash($proj{'path'});
2647                if (!defined $head) {
2648                        next;
2649                }
2650                $ENV{'GIT_DIR'} = "$projectroot/$proj{'path'}";
2651                my %co = parse_commit($head);
2652                if (!%co) {
2653                        next;
2654                }
2655
2656                my $path = esc_html(chop_str($proj{'path'}, 25, 5));
2657                my $rss  = "$my_url?p=$proj{'path'};a=rss";
2658                my $html = "$my_url?p=$proj{'path'};a=summary";
2659                print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
2660        }
2661        print "</outline>\n".
2662              "</body>\n".
2663              "</opml>\n";
2664}