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