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