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