gitweb / gitweb.perlon commit gitweb: Support for 'forks' (e30496d)
   1#!/usr/bin/perl
   2
   3# gitweb - simple web interface to track changes in git repositories
   4#
   5# (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
   6# (C) 2005, Christian Gierke
   7#
   8# This program is licensed under the GPLv2
   9
  10use strict;
  11use warnings;
  12use CGI qw(:standard :escapeHTML -nosticky);
  13use CGI::Util qw(unescape);
  14use CGI::Carp qw(fatalsToBrowser);
  15use Encode;
  16use Fcntl ':mode';
  17use File::Find qw();
  18use File::Basename qw(basename);
  19binmode STDOUT, ':utf8';
  20
  21our $cgi = new CGI;
  22our $version = "++GIT_VERSION++";
  23our $my_url = $cgi->url();
  24our $my_uri = $cgi->url(-absolute => 1);
  25
  26# core git executable to use
  27# this can just be "git" if your webserver has a sensible PATH
  28our $GIT = "++GIT_BINDIR++/git";
  29
  30# absolute fs-path which will be prepended to the project path
  31#our $projectroot = "/pub/scm";
  32our $projectroot = "++GITWEB_PROJECTROOT++";
  33
  34# target of the home link on top of all pages
  35our $home_link = $my_uri || "/";
  36
  37# string of the home link on top of all pages
  38our $home_link_str = "++GITWEB_HOME_LINK_STR++";
  39
  40# name of your site or organization to appear in page titles
  41# replace this with something more descriptive for clearer bookmarks
  42our $site_name = "++GITWEB_SITENAME++"
  43                 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
  44
  45# filename of html text to include at top of each page
  46our $site_header = "++GITWEB_SITE_HEADER++";
  47# html text to include at home page
  48our $home_text = "++GITWEB_HOMETEXT++";
  49# filename of html text to include at bottom of each page
  50our $site_footer = "++GITWEB_SITE_FOOTER++";
  51
  52# URI of stylesheets
  53our @stylesheets = ("++GITWEB_CSS++");
  54our $stylesheet;
  55# default is not to define style sheet, but it can be overwritten later
  56undef $stylesheet;
  57
  58# URI of default stylesheet
  59our $stylesheet = "++GITWEB_CSS++";
  60# URI of GIT logo (72x27 size)
  61our $logo = "++GITWEB_LOGO++";
  62# URI of GIT favicon, assumed to be image/png type
  63our $favicon = "++GITWEB_FAVICON++";
  64
  65# URI and label (title) of GIT logo link
  66#our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
  67#our $logo_label = "git documentation";
  68our $logo_url = "http://git.or.cz/";
  69our $logo_label = "git homepage";
  70
  71# source of projects list
  72our $projects_list = "++GITWEB_LIST++";
  73
  74# show repository only if this file exists
  75# (only effective if this variable evaluates to true)
  76our $export_ok = "++GITWEB_EXPORT_OK++";
  77
  78# only allow viewing of repositories also shown on the overview page
  79our $strict_export = "++GITWEB_STRICT_EXPORT++";
  80
  81# list of git base URLs used for URL to where fetch project from,
  82# i.e. full URL is "$git_base_url/$project"
  83our @git_base_url_list = ("++GITWEB_BASE_URL++");
  84
  85# default blob_plain mimetype and default charset for text/plain blob
  86our $default_blob_plain_mimetype = 'text/plain';
  87our $default_text_plain_charset  = undef;
  88
  89# file to use for guessing MIME types before trying /etc/mime.types
  90# (relative to the current git repository)
  91our $mimetypes_file = undef;
  92
  93# You define site-wide feature defaults here; override them with
  94# $GITWEB_CONFIG as necessary.
  95our %feature = (
  96        # feature => {
  97        #       'sub' => feature-sub (subroutine),
  98        #       'override' => allow-override (boolean),
  99        #       'default' => [ default options...] (array reference)}
 100        #
 101        # if feature is overridable (it means that allow-override has true value,
 102        # then feature-sub will be called with default options as parameters;
 103        # return value of feature-sub indicates if to enable specified feature
 104        #
 105        # use gitweb_check_feature(<feature>) to check if <feature> is enabled
 106
 107        # Enable the 'blame' blob view, showing the last commit that modified
 108        # each line in the file. This can be very CPU-intensive.
 109
 110        # To enable system wide have in $GITWEB_CONFIG
 111        # $feature{'blame'}{'default'} = [1];
 112        # To have project specific config enable override in $GITWEB_CONFIG
 113        # $feature{'blame'}{'override'} = 1;
 114        # and in project config gitweb.blame = 0|1;
 115        'blame' => {
 116                'sub' => \&feature_blame,
 117                'override' => 0,
 118                'default' => [0]},
 119
 120        # Enable the 'snapshot' link, providing a compressed tarball of any
 121        # tree. This can potentially generate high traffic if you have large
 122        # project.
 123
 124        # To disable system wide have in $GITWEB_CONFIG
 125        # $feature{'snapshot'}{'default'} = [undef];
 126        # To have project specific config enable override in $GITWEB_CONFIG
 127        # $feature{'blame'}{'override'} = 1;
 128        # and in project config gitweb.snapshot = none|gzip|bzip2;
 129        'snapshot' => {
 130                'sub' => \&feature_snapshot,
 131                'override' => 0,
 132                #         => [content-encoding, suffix, program]
 133                'default' => ['x-gzip', 'gz', 'gzip']},
 134
 135        # Enable the pickaxe search, which will list the commits that modified
 136        # a given string in a file. This can be practical and quite faster
 137        # alternative to 'blame', but still potentially CPU-intensive.
 138
 139        # To enable system wide have in $GITWEB_CONFIG
 140        # $feature{'pickaxe'}{'default'} = [1];
 141        # To have project specific config enable override in $GITWEB_CONFIG
 142        # $feature{'pickaxe'}{'override'} = 1;
 143        # and in project config gitweb.pickaxe = 0|1;
 144        'pickaxe' => {
 145                'sub' => \&feature_pickaxe,
 146                'override' => 0,
 147                'default' => [1]},
 148
 149        # Make gitweb use an alternative format of the URLs which can be
 150        # more readable and natural-looking: project name is embedded
 151        # directly in the path and the query string contains other
 152        # auxiliary information. All gitweb installations recognize
 153        # URL in either format; this configures in which formats gitweb
 154        # generates links.
 155
 156        # To enable system wide have in $GITWEB_CONFIG
 157        # $feature{'pathinfo'}{'default'} = [1];
 158        # Project specific override is not supported.
 159
 160        # Note that you will need to change the default location of CSS,
 161        # favicon, logo and possibly other files to an absolute URL. Also,
 162        # if gitweb.cgi serves as your indexfile, you will need to force
 163        # $my_uri to contain the script name in your $GITWEB_CONFIG.
 164        'pathinfo' => {
 165                'override' => 0,
 166                'default' => [0]},
 167
 168        # Make gitweb consider projects in project root subdirectories
 169        # to be forks of existing projects. Given project $projname.git,
 170        # projects matching $projname/*.git will not be shown in the main
 171        # projects list, instead a '+' mark will be added to $projname
 172        # there and a 'forks' view will be enabled for the project, listing
 173        # all the forks. This feature is supported only if project list
 174        # is taken from a directory, not file.
 175
 176        # To enable system wide have in $GITWEB_CONFIG
 177        # $feature{'forks'}{'default'} = [1];
 178        # Project specific override is not supported.
 179        'forks' => {
 180                'override' => 0,
 181                'default' => [0]},
 182);
 183
 184sub gitweb_check_feature {
 185        my ($name) = @_;
 186        return unless exists $feature{$name};
 187        my ($sub, $override, @defaults) = (
 188                $feature{$name}{'sub'},
 189                $feature{$name}{'override'},
 190                @{$feature{$name}{'default'}});
 191        if (!$override) { return @defaults; }
 192        if (!defined $sub) {
 193                warn "feature $name is not overrideable";
 194                return @defaults;
 195        }
 196        return $sub->(@defaults);
 197}
 198
 199sub feature_blame {
 200        my ($val) = git_get_project_config('blame', '--bool');
 201
 202        if ($val eq 'true') {
 203                return 1;
 204        } elsif ($val eq 'false') {
 205                return 0;
 206        }
 207
 208        return $_[0];
 209}
 210
 211sub feature_snapshot {
 212        my ($ctype, $suffix, $command) = @_;
 213
 214        my ($val) = git_get_project_config('snapshot');
 215
 216        if ($val eq 'gzip') {
 217                return ('x-gzip', 'gz', 'gzip');
 218        } elsif ($val eq 'bzip2') {
 219                return ('x-bzip2', 'bz2', 'bzip2');
 220        } elsif ($val eq 'none') {
 221                return ();
 222        }
 223
 224        return ($ctype, $suffix, $command);
 225}
 226
 227sub gitweb_have_snapshot {
 228        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
 229        my $have_snapshot = (defined $ctype && defined $suffix);
 230
 231        return $have_snapshot;
 232}
 233
 234sub feature_pickaxe {
 235        my ($val) = git_get_project_config('pickaxe', '--bool');
 236
 237        if ($val eq 'true') {
 238                return (1);
 239        } elsif ($val eq 'false') {
 240                return (0);
 241        }
 242
 243        return ($_[0]);
 244}
 245
 246# checking HEAD file with -e is fragile if the repository was
 247# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
 248# and then pruned.
 249sub check_head_link {
 250        my ($dir) = @_;
 251        my $headfile = "$dir/HEAD";
 252        return ((-e $headfile) ||
 253                (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
 254}
 255
 256sub check_export_ok {
 257        my ($dir) = @_;
 258        return (check_head_link($dir) &&
 259                (!$export_ok || -e "$dir/$export_ok"));
 260}
 261
 262# rename detection options for git-diff and git-diff-tree
 263# - default is '-M', with the cost proportional to
 264#   (number of removed files) * (number of new files).
 265# - more costly is '-C' (or '-C', '-M'), with the cost proportional to
 266#   (number of changed files + number of removed files) * (number of new files)
 267# - even more costly is '-C', '--find-copies-harder' with cost
 268#   (number of files in the original tree) * (number of new files)
 269# - one might want to include '-B' option, e.g. '-B', '-M'
 270our @diff_opts = ('-M'); # taken from git_commit
 271
 272our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
 273do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
 274
 275# version of the core git binary
 276our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
 277
 278$projects_list ||= $projectroot;
 279
 280# ======================================================================
 281# input validation and dispatch
 282our $action = $cgi->param('a');
 283if (defined $action) {
 284        if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
 285                die_error(undef, "Invalid action parameter");
 286        }
 287}
 288
 289# parameters which are pathnames
 290our $project = $cgi->param('p');
 291if (defined $project) {
 292        if (!validate_pathname($project) ||
 293            !(-d "$projectroot/$project") ||
 294            !check_head_link("$projectroot/$project") ||
 295            ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
 296            ($strict_export && !project_in_list($project))) {
 297                undef $project;
 298                die_error(undef, "No such project");
 299        }
 300}
 301
 302our $file_name = $cgi->param('f');
 303if (defined $file_name) {
 304        if (!validate_pathname($file_name)) {
 305                die_error(undef, "Invalid file parameter");
 306        }
 307}
 308
 309our $file_parent = $cgi->param('fp');
 310if (defined $file_parent) {
 311        if (!validate_pathname($file_parent)) {
 312                die_error(undef, "Invalid file parent parameter");
 313        }
 314}
 315
 316# parameters which are refnames
 317our $hash = $cgi->param('h');
 318if (defined $hash) {
 319        if (!validate_refname($hash)) {
 320                die_error(undef, "Invalid hash parameter");
 321        }
 322}
 323
 324our $hash_parent = $cgi->param('hp');
 325if (defined $hash_parent) {
 326        if (!validate_refname($hash_parent)) {
 327                die_error(undef, "Invalid hash parent parameter");
 328        }
 329}
 330
 331our $hash_base = $cgi->param('hb');
 332if (defined $hash_base) {
 333        if (!validate_refname($hash_base)) {
 334                die_error(undef, "Invalid hash base parameter");
 335        }
 336}
 337
 338our $hash_parent_base = $cgi->param('hpb');
 339if (defined $hash_parent_base) {
 340        if (!validate_refname($hash_parent_base)) {
 341                die_error(undef, "Invalid hash parent base parameter");
 342        }
 343}
 344
 345# other parameters
 346our $page = $cgi->param('pg');
 347if (defined $page) {
 348        if ($page =~ m/[^0-9]/) {
 349                die_error(undef, "Invalid page parameter");
 350        }
 351}
 352
 353our $searchtext = $cgi->param('s');
 354if (defined $searchtext) {
 355        if ($searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
 356                die_error(undef, "Invalid search parameter");
 357        }
 358        $searchtext = quotemeta $searchtext;
 359}
 360
 361our $searchtype = $cgi->param('st');
 362if (defined $searchtype) {
 363        if ($searchtype =~ m/[^a-z]/) {
 364                die_error(undef, "Invalid searchtype parameter");
 365        }
 366}
 367
 368# now read PATH_INFO and use it as alternative to parameters
 369sub evaluate_path_info {
 370        return if defined $project;
 371        my $path_info = $ENV{"PATH_INFO"};
 372        return if !$path_info;
 373        $path_info =~ s,^/+,,;
 374        return if !$path_info;
 375        # find which part of PATH_INFO is project
 376        $project = $path_info;
 377        $project =~ s,/+$,,;
 378        while ($project && !check_head_link("$projectroot/$project")) {
 379                $project =~ s,/*[^/]*$,,;
 380        }
 381        # validate project
 382        $project = validate_pathname($project);
 383        if (!$project ||
 384            ($export_ok && !-e "$projectroot/$project/$export_ok") ||
 385            ($strict_export && !project_in_list($project))) {
 386                undef $project;
 387                return;
 388        }
 389        # do not change any parameters if an action is given using the query string
 390        return if $action;
 391        $path_info =~ s,^$project/*,,;
 392        my ($refname, $pathname) = split(/:/, $path_info, 2);
 393        if (defined $pathname) {
 394                # we got "project.git/branch:filename" or "project.git/branch:dir/"
 395                # we could use git_get_type(branch:pathname), but it needs $git_dir
 396                $pathname =~ s,^/+,,;
 397                if (!$pathname || substr($pathname, -1) eq "/") {
 398                        $action  ||= "tree";
 399                        $pathname =~ s,/$,,;
 400                } else {
 401                        $action  ||= "blob_plain";
 402                }
 403                $hash_base ||= validate_refname($refname);
 404                $file_name ||= validate_pathname($pathname);
 405        } elsif (defined $refname) {
 406                # we got "project.git/branch"
 407                $action ||= "shortlog";
 408                $hash   ||= validate_refname($refname);
 409        }
 410}
 411evaluate_path_info();
 412
 413# path to the current git repository
 414our $git_dir;
 415$git_dir = "$projectroot/$project" if $project;
 416
 417# dispatch
 418my %actions = (
 419        "blame" => \&git_blame2,
 420        "blobdiff" => \&git_blobdiff,
 421        "blobdiff_plain" => \&git_blobdiff_plain,
 422        "blob" => \&git_blob,
 423        "blob_plain" => \&git_blob_plain,
 424        "commitdiff" => \&git_commitdiff,
 425        "commitdiff_plain" => \&git_commitdiff_plain,
 426        "commit" => \&git_commit,
 427        "forks" => \&git_forks,
 428        "heads" => \&git_heads,
 429        "history" => \&git_history,
 430        "log" => \&git_log,
 431        "rss" => \&git_rss,
 432        "search" => \&git_search,
 433        "search_help" => \&git_search_help,
 434        "shortlog" => \&git_shortlog,
 435        "summary" => \&git_summary,
 436        "tag" => \&git_tag,
 437        "tags" => \&git_tags,
 438        "tree" => \&git_tree,
 439        "snapshot" => \&git_snapshot,
 440        # those below don't need $project
 441        "opml" => \&git_opml,
 442        "project_list" => \&git_project_list,
 443        "project_index" => \&git_project_index,
 444);
 445
 446if (defined $project) {
 447        $action ||= 'summary';
 448} else {
 449        $action ||= 'project_list';
 450}
 451if (!defined($actions{$action})) {
 452        die_error(undef, "Unknown action");
 453}
 454if ($action !~ m/^(opml|project_list|project_index)$/ &&
 455    !$project) {
 456        die_error(undef, "Project needed");
 457}
 458$actions{$action}->();
 459exit;
 460
 461## ======================================================================
 462## action links
 463
 464sub href(%) {
 465        my %params = @_;
 466        my $href = $my_uri;
 467
 468        # XXX: Warning: If you touch this, check the search form for updating,
 469        # too.
 470
 471        my @mapping = (
 472                project => "p",
 473                action => "a",
 474                file_name => "f",
 475                file_parent => "fp",
 476                hash => "h",
 477                hash_parent => "hp",
 478                hash_base => "hb",
 479                hash_parent_base => "hpb",
 480                page => "pg",
 481                order => "o",
 482                searchtext => "s",
 483                searchtype => "st",
 484        );
 485        my %mapping = @mapping;
 486
 487        $params{'project'} = $project unless exists $params{'project'};
 488
 489        my ($use_pathinfo) = gitweb_check_feature('pathinfo');
 490        if ($use_pathinfo) {
 491                # use PATH_INFO for project name
 492                $href .= "/$params{'project'}" if defined $params{'project'};
 493                delete $params{'project'};
 494
 495                # Summary just uses the project path URL
 496                if (defined $params{'action'} && $params{'action'} eq 'summary') {
 497                        delete $params{'action'};
 498                }
 499        }
 500
 501        # now encode the parameters explicitly
 502        my @result = ();
 503        for (my $i = 0; $i < @mapping; $i += 2) {
 504                my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
 505                if (defined $params{$name}) {
 506                        push @result, $symbol . "=" . esc_param($params{$name});
 507                }
 508        }
 509        $href .= "?" . join(';', @result) if scalar @result;
 510
 511        return $href;
 512}
 513
 514
 515## ======================================================================
 516## validation, quoting/unquoting and escaping
 517
 518sub validate_pathname {
 519        my $input = shift || return undef;
 520
 521        # no '.' or '..' as elements of path, i.e. no '.' nor '..'
 522        # at the beginning, at the end, and between slashes.
 523        # also this catches doubled slashes
 524        if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
 525                return undef;
 526        }
 527        # no null characters
 528        if ($input =~ m!\0!) {
 529                return undef;
 530        }
 531        return $input;
 532}
 533
 534sub validate_refname {
 535        my $input = shift || return undef;
 536
 537        # textual hashes are O.K.
 538        if ($input =~ m/^[0-9a-fA-F]{40}$/) {
 539                return $input;
 540        }
 541        # it must be correct pathname
 542        $input = validate_pathname($input)
 543                or return undef;
 544        # restrictions on ref name according to git-check-ref-format
 545        if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
 546                return undef;
 547        }
 548        return $input;
 549}
 550
 551# very thin wrapper for decode("utf8", $str, Encode::FB_DEFAULT);
 552sub to_utf8 {
 553        my $str = shift;
 554        return decode("utf8", $str, Encode::FB_DEFAULT);
 555}
 556
 557# quote unsafe chars, but keep the slash, even when it's not
 558# correct, but quoted slashes look too horrible in bookmarks
 559sub esc_param {
 560        my $str = shift;
 561        $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
 562        $str =~ s/\+/%2B/g;
 563        $str =~ s/ /\+/g;
 564        return $str;
 565}
 566
 567# quote unsafe chars in whole URL, so some charactrs cannot be quoted
 568sub esc_url {
 569        my $str = shift;
 570        $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
 571        $str =~ s/\+/%2B/g;
 572        $str =~ s/ /\+/g;
 573        return $str;
 574}
 575
 576# replace invalid utf8 character with SUBSTITUTION sequence
 577sub esc_html {
 578        my $str = shift;
 579        $str = to_utf8($str);
 580        $str = escapeHTML($str);
 581        $str =~ s/\014/^L/g; # escape FORM FEED (FF) character (e.g. in COPYING file)
 582        $str =~ s/\033/^[/g; # "escape" ESCAPE (\e) character (e.g. commit 20a3847d8a5032ce41f90dcc68abfb36e6fee9b1)
 583        return $str;
 584}
 585
 586# git may return quoted and escaped filenames
 587sub unquote {
 588        my $str = shift;
 589        if ($str =~ m/^"(.*)"$/) {
 590                $str = $1;
 591                $str =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
 592        }
 593        return $str;
 594}
 595
 596# escape tabs (convert tabs to spaces)
 597sub untabify {
 598        my $line = shift;
 599
 600        while ((my $pos = index($line, "\t")) != -1) {
 601                if (my $count = (8 - ($pos % 8))) {
 602                        my $spaces = ' ' x $count;
 603                        $line =~ s/\t/$spaces/;
 604                }
 605        }
 606
 607        return $line;
 608}
 609
 610sub project_in_list {
 611        my $project = shift;
 612        my @list = git_get_projects_list();
 613        return @list && scalar(grep { $_->{'path'} eq $project } @list);
 614}
 615
 616## ----------------------------------------------------------------------
 617## HTML aware string manipulation
 618
 619sub chop_str {
 620        my $str = shift;
 621        my $len = shift;
 622        my $add_len = shift || 10;
 623
 624        # allow only $len chars, but don't cut a word if it would fit in $add_len
 625        # if it doesn't fit, cut it if it's still longer than the dots we would add
 626        $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
 627        my $body = $1;
 628        my $tail = $2;
 629        if (length($tail) > 4) {
 630                $tail = " ...";
 631                $body =~ s/&[^;]*$//; # remove chopped character entities
 632        }
 633        return "$body$tail";
 634}
 635
 636## ----------------------------------------------------------------------
 637## functions returning short strings
 638
 639# CSS class for given age value (in seconds)
 640sub age_class {
 641        my $age = shift;
 642
 643        if ($age < 60*60*2) {
 644                return "age0";
 645        } elsif ($age < 60*60*24*2) {
 646                return "age1";
 647        } else {
 648                return "age2";
 649        }
 650}
 651
 652# convert age in seconds to "nn units ago" string
 653sub age_string {
 654        my $age = shift;
 655        my $age_str;
 656
 657        if ($age > 60*60*24*365*2) {
 658                $age_str = (int $age/60/60/24/365);
 659                $age_str .= " years ago";
 660        } elsif ($age > 60*60*24*(365/12)*2) {
 661                $age_str = int $age/60/60/24/(365/12);
 662                $age_str .= " months ago";
 663        } elsif ($age > 60*60*24*7*2) {
 664                $age_str = int $age/60/60/24/7;
 665                $age_str .= " weeks ago";
 666        } elsif ($age > 60*60*24*2) {
 667                $age_str = int $age/60/60/24;
 668                $age_str .= " days ago";
 669        } elsif ($age > 60*60*2) {
 670                $age_str = int $age/60/60;
 671                $age_str .= " hours ago";
 672        } elsif ($age > 60*2) {
 673                $age_str = int $age/60;
 674                $age_str .= " min ago";
 675        } elsif ($age > 2) {
 676                $age_str = int $age;
 677                $age_str .= " sec ago";
 678        } else {
 679                $age_str .= " right now";
 680        }
 681        return $age_str;
 682}
 683
 684# convert file mode in octal to symbolic file mode string
 685sub mode_str {
 686        my $mode = oct shift;
 687
 688        if (S_ISDIR($mode & S_IFMT)) {
 689                return 'drwxr-xr-x';
 690        } elsif (S_ISLNK($mode)) {
 691                return 'lrwxrwxrwx';
 692        } elsif (S_ISREG($mode)) {
 693                # git cares only about the executable bit
 694                if ($mode & S_IXUSR) {
 695                        return '-rwxr-xr-x';
 696                } else {
 697                        return '-rw-r--r--';
 698                };
 699        } else {
 700                return '----------';
 701        }
 702}
 703
 704# convert file mode in octal to file type string
 705sub file_type {
 706        my $mode = shift;
 707
 708        if ($mode !~ m/^[0-7]+$/) {
 709                return $mode;
 710        } else {
 711                $mode = oct $mode;
 712        }
 713
 714        if (S_ISDIR($mode & S_IFMT)) {
 715                return "directory";
 716        } elsif (S_ISLNK($mode)) {
 717                return "symlink";
 718        } elsif (S_ISREG($mode)) {
 719                return "file";
 720        } else {
 721                return "unknown";
 722        }
 723}
 724
 725## ----------------------------------------------------------------------
 726## functions returning short HTML fragments, or transforming HTML fragments
 727## which don't beling to other sections
 728
 729# format line of commit message or tag comment
 730sub format_log_line_html {
 731        my $line = shift;
 732
 733        $line = esc_html($line);
 734        $line =~ s/ /&nbsp;/g;
 735        if ($line =~ m/([0-9a-fA-F]{40})/) {
 736                my $hash_text = $1;
 737                if (git_get_type($hash_text) eq "commit") {
 738                        my $link =
 739                                $cgi->a({-href => href(action=>"commit", hash=>$hash_text),
 740                                        -class => "text"}, $hash_text);
 741                        $line =~ s/$hash_text/$link/;
 742                }
 743        }
 744        return $line;
 745}
 746
 747# format marker of refs pointing to given object
 748sub format_ref_marker {
 749        my ($refs, $id) = @_;
 750        my $markers = '';
 751
 752        if (defined $refs->{$id}) {
 753                foreach my $ref (@{$refs->{$id}}) {
 754                        my ($type, $name) = qw();
 755                        # e.g. tags/v2.6.11 or heads/next
 756                        if ($ref =~ m!^(.*?)s?/(.*)$!) {
 757                                $type = $1;
 758                                $name = $2;
 759                        } else {
 760                                $type = "ref";
 761                                $name = $ref;
 762                        }
 763
 764                        $markers .= " <span class=\"$type\">" . esc_html($name) . "</span>";
 765                }
 766        }
 767
 768        if ($markers) {
 769                return ' <span class="refs">'. $markers . '</span>';
 770        } else {
 771                return "";
 772        }
 773}
 774
 775# format, perhaps shortened and with markers, title line
 776sub format_subject_html {
 777        my ($long, $short, $href, $extra) = @_;
 778        $extra = '' unless defined($extra);
 779
 780        if (length($short) < length($long)) {
 781                return $cgi->a({-href => $href, -class => "list subject",
 782                                -title => to_utf8($long)},
 783                       esc_html($short) . $extra);
 784        } else {
 785                return $cgi->a({-href => $href, -class => "list subject"},
 786                       esc_html($long)  . $extra);
 787        }
 788}
 789
 790sub format_diff_line {
 791        my $line = shift;
 792        my $char = substr($line, 0, 1);
 793        my $diff_class = "";
 794
 795        chomp $line;
 796
 797        if ($char eq '+') {
 798                $diff_class = " add";
 799        } elsif ($char eq "-") {
 800                $diff_class = " rem";
 801        } elsif ($char eq "@") {
 802                $diff_class = " chunk_header";
 803        } elsif ($char eq "\\") {
 804                $diff_class = " incomplete";
 805        }
 806        $line = untabify($line);
 807        return "<div class=\"diff$diff_class\">" . esc_html($line) . "</div>\n";
 808}
 809
 810## ----------------------------------------------------------------------
 811## git utility subroutines, invoking git commands
 812
 813# returns path to the core git executable and the --git-dir parameter as list
 814sub git_cmd {
 815        return $GIT, '--git-dir='.$git_dir;
 816}
 817
 818# returns path to the core git executable and the --git-dir parameter as string
 819sub git_cmd_str {
 820        return join(' ', git_cmd());
 821}
 822
 823# get HEAD ref of given project as hash
 824sub git_get_head_hash {
 825        my $project = shift;
 826        my $o_git_dir = $git_dir;
 827        my $retval = undef;
 828        $git_dir = "$projectroot/$project";
 829        if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
 830                my $head = <$fd>;
 831                close $fd;
 832                if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
 833                        $retval = $1;
 834                }
 835        }
 836        if (defined $o_git_dir) {
 837                $git_dir = $o_git_dir;
 838        }
 839        return $retval;
 840}
 841
 842# get type of given object
 843sub git_get_type {
 844        my $hash = shift;
 845
 846        open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
 847        my $type = <$fd>;
 848        close $fd or return;
 849        chomp $type;
 850        return $type;
 851}
 852
 853sub git_get_project_config {
 854        my ($key, $type) = @_;
 855
 856        return unless ($key);
 857        $key =~ s/^gitweb\.//;
 858        return if ($key =~ m/\W/);
 859
 860        my @x = (git_cmd(), 'repo-config');
 861        if (defined $type) { push @x, $type; }
 862        push @x, "--get";
 863        push @x, "gitweb.$key";
 864        my $val = qx(@x);
 865        chomp $val;
 866        return ($val);
 867}
 868
 869# get hash of given path at given ref
 870sub git_get_hash_by_path {
 871        my $base = shift;
 872        my $path = shift || return undef;
 873        my $type = shift;
 874
 875        $path =~ s,/+$,,;
 876
 877        open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
 878                or die_error(undef, "Open git-ls-tree failed");
 879        my $line = <$fd>;
 880        close $fd or return undef;
 881
 882        #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
 883        $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
 884        if (defined $type && $type ne $2) {
 885                # type doesn't match
 886                return undef;
 887        }
 888        return $3;
 889}
 890
 891## ......................................................................
 892## git utility functions, directly accessing git repository
 893
 894sub git_get_project_description {
 895        my $path = shift;
 896
 897        open my $fd, "$projectroot/$path/description" or return undef;
 898        my $descr = <$fd>;
 899        close $fd;
 900        chomp $descr;
 901        return $descr;
 902}
 903
 904sub git_get_project_url_list {
 905        my $path = shift;
 906
 907        open my $fd, "$projectroot/$path/cloneurl" or return;
 908        my @git_project_url_list = map { chomp; $_ } <$fd>;
 909        close $fd;
 910
 911        return wantarray ? @git_project_url_list : \@git_project_url_list;
 912}
 913
 914sub git_get_projects_list {
 915        my ($filter) = @_;
 916        my @list;
 917
 918        $filter ||= '';
 919        $filter =~ s/\.git$//;
 920
 921        if (-d $projects_list) {
 922                # search in directory
 923                my $dir = $projects_list . ($filter ? "/$filter" : '');
 924                my $pfxlen = length("$dir");
 925
 926                my $check_forks = gitweb_check_feature('forks');
 927
 928                File::Find::find({
 929                        follow_fast => 1, # follow symbolic links
 930                        dangling_symlinks => 0, # ignore dangling symlinks, silently
 931                        wanted => sub {
 932                                # skip project-list toplevel, if we get it.
 933                                return if (m!^[/.]$!);
 934                                # only directories can be git repositories
 935                                return unless (-d $_);
 936
 937                                my $subdir = substr($File::Find::name, $pfxlen + 1);
 938                                # we check related file in $projectroot
 939                                if ($check_forks and $subdir =~ m#/.#) {
 940                                        $File::Find::prune = 1;
 941                                } elsif (check_export_ok("$projectroot/$filter/$subdir")) {
 942                                        push @list, { path => ($filter ? "$filter/" : '') . $subdir };
 943                                        $File::Find::prune = 1;
 944                                }
 945                        },
 946                }, "$dir");
 947
 948        } elsif (-f $projects_list) {
 949                # read from file(url-encoded):
 950                # 'git%2Fgit.git Linus+Torvalds'
 951                # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
 952                # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
 953                open my ($fd), $projects_list or return;
 954                while (my $line = <$fd>) {
 955                        chomp $line;
 956                        my ($path, $owner) = split ' ', $line;
 957                        $path = unescape($path);
 958                        $owner = unescape($owner);
 959                        if (!defined $path) {
 960                                next;
 961                        }
 962                        if (check_export_ok("$projectroot/$path")) {
 963                                my $pr = {
 964                                        path => $path,
 965                                        owner => to_utf8($owner),
 966                                };
 967                                push @list, $pr
 968                        }
 969                }
 970                close $fd;
 971        }
 972        @list = sort {$a->{'path'} cmp $b->{'path'}} @list;
 973        return @list;
 974}
 975
 976sub git_get_project_owner {
 977        my $project = shift;
 978        my $owner;
 979
 980        return undef unless $project;
 981
 982        # read from file (url-encoded):
 983        # 'git%2Fgit.git Linus+Torvalds'
 984        # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
 985        # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
 986        if (-f $projects_list) {
 987                open (my $fd , $projects_list);
 988                while (my $line = <$fd>) {
 989                        chomp $line;
 990                        my ($pr, $ow) = split ' ', $line;
 991                        $pr = unescape($pr);
 992                        $ow = unescape($ow);
 993                        if ($pr eq $project) {
 994                                $owner = to_utf8($ow);
 995                                last;
 996                        }
 997                }
 998                close $fd;
 999        }
1000        if (!defined $owner) {
1001                $owner = get_file_owner("$projectroot/$project");
1002        }
1003
1004        return $owner;
1005}
1006
1007sub git_get_references {
1008        my $type = shift || "";
1009        my %refs;
1010        # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c      refs/tags/v2.6.11
1011        # c39ae07f393806ccf406ef966e9a15afc43cc36a      refs/tags/v2.6.11^{}
1012        open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
1013                or return;
1014
1015        while (my $line = <$fd>) {
1016                chomp $line;
1017                if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?[^\^]+)/) {
1018                        if (defined $refs{$1}) {
1019                                push @{$refs{$1}}, $2;
1020                        } else {
1021                                $refs{$1} = [ $2 ];
1022                        }
1023                }
1024        }
1025        close $fd or return;
1026        return \%refs;
1027}
1028
1029sub git_get_rev_name_tags {
1030        my $hash = shift || return undef;
1031
1032        open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
1033                or return;
1034        my $name_rev = <$fd>;
1035        close $fd;
1036
1037        if ($name_rev =~ m|^$hash tags/(.*)$|) {
1038                return $1;
1039        } else {
1040                # catches also '$hash undefined' output
1041                return undef;
1042        }
1043}
1044
1045## ----------------------------------------------------------------------
1046## parse to hash functions
1047
1048sub parse_date {
1049        my $epoch = shift;
1050        my $tz = shift || "-0000";
1051
1052        my %date;
1053        my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
1054        my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
1055        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
1056        $date{'hour'} = $hour;
1057        $date{'minute'} = $min;
1058        $date{'mday'} = $mday;
1059        $date{'day'} = $days[$wday];
1060        $date{'month'} = $months[$mon];
1061        $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
1062                           $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
1063        $date{'mday-time'} = sprintf "%d %s %02d:%02d",
1064                             $mday, $months[$mon], $hour ,$min;
1065
1066        $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
1067        my $local = $epoch + ((int $1 + ($2/60)) * 3600);
1068        ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
1069        $date{'hour_local'} = $hour;
1070        $date{'minute_local'} = $min;
1071        $date{'tz_local'} = $tz;
1072        $date{'iso-tz'} = sprintf ("%04d-%02d-%02d %02d:%02d:%02d %s",
1073                                   1900+$year, $mon+1, $mday,
1074                                   $hour, $min, $sec, $tz);
1075        return %date;
1076}
1077
1078sub parse_tag {
1079        my $tag_id = shift;
1080        my %tag;
1081        my @comment;
1082
1083        open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
1084        $tag{'id'} = $tag_id;
1085        while (my $line = <$fd>) {
1086                chomp $line;
1087                if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
1088                        $tag{'object'} = $1;
1089                } elsif ($line =~ m/^type (.+)$/) {
1090                        $tag{'type'} = $1;
1091                } elsif ($line =~ m/^tag (.+)$/) {
1092                        $tag{'name'} = $1;
1093                } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
1094                        $tag{'author'} = $1;
1095                        $tag{'epoch'} = $2;
1096                        $tag{'tz'} = $3;
1097                } elsif ($line =~ m/--BEGIN/) {
1098                        push @comment, $line;
1099                        last;
1100                } elsif ($line eq "") {
1101                        last;
1102                }
1103        }
1104        push @comment, <$fd>;
1105        $tag{'comment'} = \@comment;
1106        close $fd or return;
1107        if (!defined $tag{'name'}) {
1108                return
1109        };
1110        return %tag
1111}
1112
1113sub git_get_last_activity {
1114        my ($path) = @_;
1115        my $fd;
1116
1117        $git_dir = "$projectroot/$path";
1118        open($fd, "-|", git_cmd(), 'for-each-ref',
1119             '--format=%(refname) %(committer)',
1120             '--sort=-committerdate',
1121             'refs/heads') or return;
1122        my $most_recent = <$fd>;
1123        close $fd or return;
1124        if ($most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
1125                my $timestamp = $1;
1126                my $age = time - $timestamp;
1127                return ($age, age_string($age));
1128        }
1129}
1130
1131sub parse_commit {
1132        my $commit_id = shift;
1133        my $commit_text = shift;
1134
1135        my @commit_lines;
1136        my %co;
1137
1138        if (defined $commit_text) {
1139                @commit_lines = @$commit_text;
1140        } else {
1141                local $/ = "\0";
1142                open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", "--max-count=1", $commit_id
1143                        or return;
1144                @commit_lines = split '\n', <$fd>;
1145                close $fd or return;
1146                pop @commit_lines;
1147        }
1148        my $header = shift @commit_lines;
1149        if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
1150                return;
1151        }
1152        ($co{'id'}, my @parents) = split ' ', $header;
1153        $co{'parents'} = \@parents;
1154        $co{'parent'} = $parents[0];
1155        while (my $line = shift @commit_lines) {
1156                last if $line eq "\n";
1157                if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1158                        $co{'tree'} = $1;
1159                } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1160                        $co{'author'} = $1;
1161                        $co{'author_epoch'} = $2;
1162                        $co{'author_tz'} = $3;
1163                        if ($co{'author'} =~ m/^([^<]+) </) {
1164                                $co{'author_name'} = $1;
1165                        } else {
1166                                $co{'author_name'} = $co{'author'};
1167                        }
1168                } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1169                        $co{'committer'} = $1;
1170                        $co{'committer_epoch'} = $2;
1171                        $co{'committer_tz'} = $3;
1172                        $co{'committer_name'} = $co{'committer'};
1173                        $co{'committer_name'} =~ s/ <.*//;
1174                }
1175        }
1176        if (!defined $co{'tree'}) {
1177                return;
1178        };
1179
1180        foreach my $title (@commit_lines) {
1181                $title =~ s/^    //;
1182                if ($title ne "") {
1183                        $co{'title'} = chop_str($title, 80, 5);
1184                        # remove leading stuff of merges to make the interesting part visible
1185                        if (length($title) > 50) {
1186                                $title =~ s/^Automatic //;
1187                                $title =~ s/^merge (of|with) /Merge ... /i;
1188                                if (length($title) > 50) {
1189                                        $title =~ s/(http|rsync):\/\///;
1190                                }
1191                                if (length($title) > 50) {
1192                                        $title =~ s/(master|www|rsync)\.//;
1193                                }
1194                                if (length($title) > 50) {
1195                                        $title =~ s/kernel.org:?//;
1196                                }
1197                                if (length($title) > 50) {
1198                                        $title =~ s/\/pub\/scm//;
1199                                }
1200                        }
1201                        $co{'title_short'} = chop_str($title, 50, 5);
1202                        last;
1203                }
1204        }
1205        if ($co{'title'} eq "") {
1206                $co{'title'} = $co{'title_short'} = '(no commit message)';
1207        }
1208        # remove added spaces
1209        foreach my $line (@commit_lines) {
1210                $line =~ s/^    //;
1211        }
1212        $co{'comment'} = \@commit_lines;
1213
1214        my $age = time - $co{'committer_epoch'};
1215        $co{'age'} = $age;
1216        $co{'age_string'} = age_string($age);
1217        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1218        if ($age > 60*60*24*7*2) {
1219                $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1220                $co{'age_string_age'} = $co{'age_string'};
1221        } else {
1222                $co{'age_string_date'} = $co{'age_string'};
1223                $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1224        }
1225        return %co;
1226}
1227
1228# parse ref from ref_file, given by ref_id, with given type
1229sub parse_ref {
1230        my $ref_file = shift;
1231        my $ref_id = shift;
1232        my $type = shift || git_get_type($ref_id);
1233        my %ref_item;
1234
1235        $ref_item{'type'} = $type;
1236        $ref_item{'id'} = $ref_id;
1237        $ref_item{'epoch'} = 0;
1238        $ref_item{'age'} = "unknown";
1239        if ($type eq "tag") {
1240                my %tag = parse_tag($ref_id);
1241                $ref_item{'comment'} = $tag{'comment'};
1242                if ($tag{'type'} eq "commit") {
1243                        my %co = parse_commit($tag{'object'});
1244                        $ref_item{'epoch'} = $co{'committer_epoch'};
1245                        $ref_item{'age'} = $co{'age_string'};
1246                } elsif (defined($tag{'epoch'})) {
1247                        my $age = time - $tag{'epoch'};
1248                        $ref_item{'epoch'} = $tag{'epoch'};
1249                        $ref_item{'age'} = age_string($age);
1250                }
1251                $ref_item{'reftype'} = $tag{'type'};
1252                $ref_item{'name'} = $tag{'name'};
1253                $ref_item{'refid'} = $tag{'object'};
1254        } elsif ($type eq "commit"){
1255                my %co = parse_commit($ref_id);
1256                $ref_item{'reftype'} = "commit";
1257                $ref_item{'name'} = $ref_file;
1258                $ref_item{'title'} = $co{'title'};
1259                $ref_item{'refid'} = $ref_id;
1260                $ref_item{'epoch'} = $co{'committer_epoch'};
1261                $ref_item{'age'} = $co{'age_string'};
1262        } else {
1263                $ref_item{'reftype'} = $type;
1264                $ref_item{'name'} = $ref_file;
1265                $ref_item{'refid'} = $ref_id;
1266        }
1267
1268        return %ref_item;
1269}
1270
1271# parse line of git-diff-tree "raw" output
1272sub parse_difftree_raw_line {
1273        my $line = shift;
1274        my %res;
1275
1276        # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1277        # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1278        if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1279                $res{'from_mode'} = $1;
1280                $res{'to_mode'} = $2;
1281                $res{'from_id'} = $3;
1282                $res{'to_id'} = $4;
1283                $res{'status'} = $5;
1284                $res{'similarity'} = $6;
1285                if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1286                        ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1287                } else {
1288                        $res{'file'} = unquote($7);
1289                }
1290        }
1291        # 'c512b523472485aef4fff9e57b229d9d243c967f'
1292        elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1293                $res{'commit'} = $1;
1294        }
1295
1296        return wantarray ? %res : \%res;
1297}
1298
1299# parse line of git-ls-tree output
1300sub parse_ls_tree_line ($;%) {
1301        my $line = shift;
1302        my %opts = @_;
1303        my %res;
1304
1305        #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1306        $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
1307
1308        $res{'mode'} = $1;
1309        $res{'type'} = $2;
1310        $res{'hash'} = $3;
1311        if ($opts{'-z'}) {
1312                $res{'name'} = $4;
1313        } else {
1314                $res{'name'} = unquote($4);
1315        }
1316
1317        return wantarray ? %res : \%res;
1318}
1319
1320## ......................................................................
1321## parse to array of hashes functions
1322
1323sub git_get_refs_list {
1324        my $type = shift || "";
1325        my %refs;
1326        my @reflist;
1327
1328        my @refs;
1329        open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
1330                or return;
1331        while (my $line = <$fd>) {
1332                chomp $line;
1333                if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?([^\^]+))(\^\{\})?$/) {
1334                        if (defined $refs{$1}) {
1335                                push @{$refs{$1}}, $2;
1336                        } else {
1337                                $refs{$1} = [ $2 ];
1338                        }
1339
1340                        if (! $4) { # unpeeled, direct reference
1341                                push @refs, { hash => $1, name => $3 }; # without type
1342                        } elsif ($3 eq $refs[-1]{'name'}) {
1343                                # most likely a tag is followed by its peeled
1344                                # (deref) one, and when that happens we know the
1345                                # previous one was of type 'tag'.
1346                                $refs[-1]{'type'} = "tag";
1347                        }
1348                }
1349        }
1350        close $fd;
1351
1352        foreach my $ref (@refs) {
1353                my $ref_file = $ref->{'name'};
1354                my $ref_id   = $ref->{'hash'};
1355
1356                my $type = $ref->{'type'} || git_get_type($ref_id) || next;
1357                my %ref_item = parse_ref($ref_file, $ref_id, $type);
1358
1359                push @reflist, \%ref_item;
1360        }
1361        # sort refs by age
1362        @reflist = sort {$b->{'epoch'} <=> $a->{'epoch'}} @reflist;
1363        return (\@reflist, \%refs);
1364}
1365
1366## ----------------------------------------------------------------------
1367## filesystem-related functions
1368
1369sub get_file_owner {
1370        my $path = shift;
1371
1372        my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1373        my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1374        if (!defined $gcos) {
1375                return undef;
1376        }
1377        my $owner = $gcos;
1378        $owner =~ s/[,;].*$//;
1379        return to_utf8($owner);
1380}
1381
1382## ......................................................................
1383## mimetype related functions
1384
1385sub mimetype_guess_file {
1386        my $filename = shift;
1387        my $mimemap = shift;
1388        -r $mimemap or return undef;
1389
1390        my %mimemap;
1391        open(MIME, $mimemap) or return undef;
1392        while (<MIME>) {
1393                next if m/^#/; # skip comments
1394                my ($mime, $exts) = split(/\t+/);
1395                if (defined $exts) {
1396                        my @exts = split(/\s+/, $exts);
1397                        foreach my $ext (@exts) {
1398                                $mimemap{$ext} = $mime;
1399                        }
1400                }
1401        }
1402        close(MIME);
1403
1404        $filename =~ /\.([^.]*)$/;
1405        return $mimemap{$1};
1406}
1407
1408sub mimetype_guess {
1409        my $filename = shift;
1410        my $mime;
1411        $filename =~ /\./ or return undef;
1412
1413        if ($mimetypes_file) {
1414                my $file = $mimetypes_file;
1415                if ($file !~ m!^/!) { # if it is relative path
1416                        # it is relative to project
1417                        $file = "$projectroot/$project/$file";
1418                }
1419                $mime = mimetype_guess_file($filename, $file);
1420        }
1421        $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1422        return $mime;
1423}
1424
1425sub blob_mimetype {
1426        my $fd = shift;
1427        my $filename = shift;
1428
1429        if ($filename) {
1430                my $mime = mimetype_guess($filename);
1431                $mime and return $mime;
1432        }
1433
1434        # just in case
1435        return $default_blob_plain_mimetype unless $fd;
1436
1437        if (-T $fd) {
1438                return 'text/plain' .
1439                       ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1440        } elsif (! $filename) {
1441                return 'application/octet-stream';
1442        } elsif ($filename =~ m/\.png$/i) {
1443                return 'image/png';
1444        } elsif ($filename =~ m/\.gif$/i) {
1445                return 'image/gif';
1446        } elsif ($filename =~ m/\.jpe?g$/i) {
1447                return 'image/jpeg';
1448        } else {
1449                return 'application/octet-stream';
1450        }
1451}
1452
1453## ======================================================================
1454## functions printing HTML: header, footer, error page
1455
1456sub git_header_html {
1457        my $status = shift || "200 OK";
1458        my $expires = shift;
1459
1460        my $title = "$site_name";
1461        if (defined $project) {
1462                $title .= " - $project";
1463                if (defined $action) {
1464                        $title .= "/$action";
1465                        if (defined $file_name) {
1466                                $title .= " - " . esc_html($file_name);
1467                                if ($action eq "tree" && $file_name !~ m|/$|) {
1468                                        $title .= "/";
1469                                }
1470                        }
1471                }
1472        }
1473        my $content_type;
1474        # require explicit support from the UA if we are to send the page as
1475        # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1476        # we have to do this because MSIE sometimes globs '*/*', pretending to
1477        # support xhtml+xml but choking when it gets what it asked for.
1478        if (defined $cgi->http('HTTP_ACCEPT') &&
1479            $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1480            $cgi->Accept('application/xhtml+xml') != 0) {
1481                $content_type = 'application/xhtml+xml';
1482        } else {
1483                $content_type = 'text/html';
1484        }
1485        print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1486                           -status=> $status, -expires => $expires);
1487        print <<EOF;
1488<?xml version="1.0" encoding="utf-8"?>
1489<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1490<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1491<!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1492<!-- git core binaries version $git_version -->
1493<head>
1494<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1495<meta name="generator" content="gitweb/$version git/$git_version"/>
1496<meta name="robots" content="index, nofollow"/>
1497<title>$title</title>
1498EOF
1499# print out each stylesheet that exist
1500        if (defined $stylesheet) {
1501#provides backwards capability for those people who define style sheet in a config file
1502                print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
1503        } else {
1504                foreach my $stylesheet (@stylesheets) {
1505                        next unless $stylesheet;
1506                        print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
1507                }
1508        }
1509        if (defined $project) {
1510                printf('<link rel="alternate" title="%s log" '.
1511                       'href="%s" type="application/rss+xml"/>'."\n",
1512                       esc_param($project), href(action=>"rss"));
1513        } else {
1514                printf('<link rel="alternate" title="%s projects list" '.
1515                       'href="%s" type="text/plain; charset=utf-8"/>'."\n",
1516                       $site_name, href(project=>undef, action=>"project_index"));
1517                printf('<link rel="alternate" title="%s projects logs" '.
1518                       'href="%s" type="text/x-opml"/>'."\n",
1519                       $site_name, href(project=>undef, action=>"opml"));
1520        }
1521        if (defined $favicon) {
1522                print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
1523        }
1524
1525        print "</head>\n" .
1526              "<body>\n";
1527
1528        if (-f $site_header) {
1529                open (my $fd, $site_header);
1530                print <$fd>;
1531                close $fd;
1532        }
1533
1534        print "<div class=\"page_header\">\n" .
1535              $cgi->a({-href => esc_url($logo_url),
1536                       -title => $logo_label},
1537                      qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
1538        print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
1539        if (defined $project) {
1540                print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1541                if (defined $action) {
1542                        print " / $action";
1543                }
1544                print "\n";
1545                if (!defined $searchtext) {
1546                        $searchtext = "";
1547                }
1548                my $search_hash;
1549                if (defined $hash_base) {
1550                        $search_hash = $hash_base;
1551                } elsif (defined $hash) {
1552                        $search_hash = $hash;
1553                } else {
1554                        $search_hash = "HEAD";
1555                }
1556                $cgi->param("a", "search");
1557                $cgi->param("h", $search_hash);
1558                $cgi->param("p", $project);
1559                print $cgi->startform(-method => "get", -action => $my_uri) .
1560                      "<div class=\"search\">\n" .
1561                      $cgi->hidden(-name => "p") . "\n" .
1562                      $cgi->hidden(-name => "a") . "\n" .
1563                      $cgi->hidden(-name => "h") . "\n" .
1564                      $cgi->popup_menu(-name => 'st', -default => 'commit',
1565                                       -values => ['commit', 'author', 'committer', 'pickaxe']) .
1566                      $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
1567                      " search:\n",
1568                      $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1569                      "</div>" .
1570                      $cgi->end_form() . "\n";
1571        }
1572        print "</div>\n";
1573}
1574
1575sub git_footer_html {
1576        print "<div class=\"page_footer\">\n";
1577        if (defined $project) {
1578                my $descr = git_get_project_description($project);
1579                if (defined $descr) {
1580                        print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1581                }
1582                print $cgi->a({-href => href(action=>"rss"),
1583                              -class => "rss_logo"}, "RSS") . "\n";
1584        } else {
1585                print $cgi->a({-href => href(project=>undef, action=>"opml"),
1586                              -class => "rss_logo"}, "OPML") . " ";
1587                print $cgi->a({-href => href(project=>undef, action=>"project_index"),
1588                              -class => "rss_logo"}, "TXT") . "\n";
1589        }
1590        print "</div>\n" ;
1591
1592        if (-f $site_footer) {
1593                open (my $fd, $site_footer);
1594                print <$fd>;
1595                close $fd;
1596        }
1597
1598        print "</body>\n" .
1599              "</html>";
1600}
1601
1602sub die_error {
1603        my $status = shift || "403 Forbidden";
1604        my $error = shift || "Malformed query, file missing or permission denied";
1605
1606        git_header_html($status);
1607        print <<EOF;
1608<div class="page_body">
1609<br /><br />
1610$status - $error
1611<br />
1612</div>
1613EOF
1614        git_footer_html();
1615        exit;
1616}
1617
1618## ----------------------------------------------------------------------
1619## functions printing or outputting HTML: navigation
1620
1621sub git_print_page_nav {
1622        my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1623        $extra = '' if !defined $extra; # pager or formats
1624
1625        my @navs = qw(summary shortlog log commit commitdiff tree);
1626        if ($suppress) {
1627                @navs = grep { $_ ne $suppress } @navs;
1628        }
1629
1630        my %arg = map { $_ => {action=>$_} } @navs;
1631        if (defined $head) {
1632                for (qw(commit commitdiff)) {
1633                        $arg{$_}{hash} = $head;
1634                }
1635                if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1636                        for (qw(shortlog log)) {
1637                                $arg{$_}{hash} = $head;
1638                        }
1639                }
1640        }
1641        $arg{tree}{hash} = $treehead if defined $treehead;
1642        $arg{tree}{hash_base} = $treebase if defined $treebase;
1643
1644        print "<div class=\"page_nav\">\n" .
1645                (join " | ",
1646                 map { $_ eq $current ?
1647                       $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1648                 } @navs);
1649        print "<br/>\n$extra<br/>\n" .
1650              "</div>\n";
1651}
1652
1653sub format_paging_nav {
1654        my ($action, $hash, $head, $page, $nrevs) = @_;
1655        my $paging_nav;
1656
1657
1658        if ($hash ne $head || $page) {
1659                $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1660        } else {
1661                $paging_nav .= "HEAD";
1662        }
1663
1664        if ($page > 0) {
1665                $paging_nav .= " &sdot; " .
1666                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1667                                 -accesskey => "p", -title => "Alt-p"}, "prev");
1668        } else {
1669                $paging_nav .= " &sdot; prev";
1670        }
1671
1672        if ($nrevs >= (100 * ($page+1)-1)) {
1673                $paging_nav .= " &sdot; " .
1674                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1675                                 -accesskey => "n", -title => "Alt-n"}, "next");
1676        } else {
1677                $paging_nav .= " &sdot; next";
1678        }
1679
1680        return $paging_nav;
1681}
1682
1683## ......................................................................
1684## functions printing or outputting HTML: div
1685
1686sub git_print_header_div {
1687        my ($action, $title, $hash, $hash_base) = @_;
1688        my %args = ();
1689
1690        $args{action} = $action;
1691        $args{hash} = $hash if $hash;
1692        $args{hash_base} = $hash_base if $hash_base;
1693
1694        print "<div class=\"header\">\n" .
1695              $cgi->a({-href => href(%args), -class => "title"},
1696              $title ? $title : $action) .
1697              "\n</div>\n";
1698}
1699
1700#sub git_print_authorship (\%) {
1701sub git_print_authorship {
1702        my $co = shift;
1703
1704        my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
1705        print "<div class=\"author_date\">" .
1706              esc_html($co->{'author_name'}) .
1707              " [$ad{'rfc2822'}";
1708        if ($ad{'hour_local'} < 6) {
1709                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
1710                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1711        } else {
1712                printf(" (%02d:%02d %s)",
1713                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1714        }
1715        print "]</div>\n";
1716}
1717
1718sub git_print_page_path {
1719        my $name = shift;
1720        my $type = shift;
1721        my $hb = shift;
1722
1723
1724        print "<div class=\"page_path\">";
1725        print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
1726                      -title => 'tree root'}, "[$project]");
1727        print " / ";
1728        if (defined $name) {
1729                my @dirname = split '/', $name;
1730                my $basename = pop @dirname;
1731                my $fullname = '';
1732
1733                foreach my $dir (@dirname) {
1734                        $fullname .= ($fullname ? '/' : '') . $dir;
1735                        print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
1736                                                     hash_base=>$hb),
1737                                      -title => $fullname}, esc_html($dir));
1738                        print " / ";
1739                }
1740                if (defined $type && $type eq 'blob') {
1741                        print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
1742                                                     hash_base=>$hb),
1743                                      -title => $name}, esc_html($basename));
1744                } elsif (defined $type && $type eq 'tree') {
1745                        print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
1746                                                     hash_base=>$hb),
1747                                      -title => $name}, esc_html($basename));
1748                        print " / ";
1749                } else {
1750                        print esc_html($basename);
1751                }
1752        }
1753        print "<br/></div>\n";
1754}
1755
1756# sub git_print_log (\@;%) {
1757sub git_print_log ($;%) {
1758        my $log = shift;
1759        my %opts = @_;
1760
1761        if ($opts{'-remove_title'}) {
1762                # remove title, i.e. first line of log
1763                shift @$log;
1764        }
1765        # remove leading empty lines
1766        while (defined $log->[0] && $log->[0] eq "") {
1767                shift @$log;
1768        }
1769
1770        # print log
1771        my $signoff = 0;
1772        my $empty = 0;
1773        foreach my $line (@$log) {
1774                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1775                        $signoff = 1;
1776                        $empty = 0;
1777                        if (! $opts{'-remove_signoff'}) {
1778                                print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1779                                next;
1780                        } else {
1781                                # remove signoff lines
1782                                next;
1783                        }
1784                } else {
1785                        $signoff = 0;
1786                }
1787
1788                # print only one empty line
1789                # do not print empty line after signoff
1790                if ($line eq "") {
1791                        next if ($empty || $signoff);
1792                        $empty = 1;
1793                } else {
1794                        $empty = 0;
1795                }
1796
1797                print format_log_line_html($line) . "<br/>\n";
1798        }
1799
1800        if ($opts{'-final_empty_line'}) {
1801                # end with single empty line
1802                print "<br/>\n" unless $empty;
1803        }
1804}
1805
1806# print tree entry (row of git_tree), but without encompassing <tr> element
1807sub git_print_tree_entry {
1808        my ($t, $basedir, $hash_base, $have_blame) = @_;
1809
1810        my %base_key = ();
1811        $base_key{hash_base} = $hash_base if defined $hash_base;
1812
1813        # The format of a table row is: mode list link.  Where mode is
1814        # the mode of the entry, list is the name of the entry, an href,
1815        # and link is the action links of the entry.
1816
1817        print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
1818        if ($t->{'type'} eq "blob") {
1819                print "<td class=\"list\">" .
1820                        $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1821                                               file_name=>"$basedir$t->{'name'}", %base_key),
1822                                -class => "list"}, esc_html($t->{'name'})) . "</td>\n";
1823                print "<td class=\"link\">";
1824                print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1825                                             file_name=>"$basedir$t->{'name'}", %base_key)},
1826                              "blob");
1827                if ($have_blame) {
1828                        print " | " .
1829                              $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
1830                                                           file_name=>"$basedir$t->{'name'}", %base_key)},
1831                                            "blame");
1832                }
1833                if (defined $hash_base) {
1834                        print " | " .
1835                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1836                                                     hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
1837                                      "history");
1838                }
1839                print " | " .
1840                        $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
1841                                               file_name=>"$basedir$t->{'name'}")},
1842                                "raw");
1843                print "</td>\n";
1844
1845        } elsif ($t->{'type'} eq "tree") {
1846                print "<td class=\"list\">";
1847                print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1848                                             file_name=>"$basedir$t->{'name'}", %base_key)},
1849                              esc_html($t->{'name'}));
1850                print "</td>\n";
1851                print "<td class=\"link\">";
1852                print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1853                                             file_name=>"$basedir$t->{'name'}", %base_key)},
1854                              "tree");
1855                if (defined $hash_base) {
1856                        print " | " .
1857                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1858                                                     file_name=>"$basedir$t->{'name'}")},
1859                                      "history");
1860                }
1861                print "</td>\n";
1862        }
1863}
1864
1865## ......................................................................
1866## functions printing large fragments of HTML
1867
1868sub git_difftree_body {
1869        my ($difftree, $hash, $parent) = @_;
1870
1871        print "<div class=\"list_head\">\n";
1872        if ($#{$difftree} > 10) {
1873                print(($#{$difftree} + 1) . " files changed:\n");
1874        }
1875        print "</div>\n";
1876
1877        print "<table class=\"diff_tree\">\n";
1878        my $alternate = 1;
1879        my $patchno = 0;
1880        foreach my $line (@{$difftree}) {
1881                my %diff = parse_difftree_raw_line($line);
1882
1883                if ($alternate) {
1884                        print "<tr class=\"dark\">\n";
1885                } else {
1886                        print "<tr class=\"light\">\n";
1887                }
1888                $alternate ^= 1;
1889
1890                my ($to_mode_oct, $to_mode_str, $to_file_type);
1891                my ($from_mode_oct, $from_mode_str, $from_file_type);
1892                if ($diff{'to_mode'} ne ('0' x 6)) {
1893                        $to_mode_oct = oct $diff{'to_mode'};
1894                        if (S_ISREG($to_mode_oct)) { # only for regular file
1895                                $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
1896                        }
1897                        $to_file_type = file_type($diff{'to_mode'});
1898                }
1899                if ($diff{'from_mode'} ne ('0' x 6)) {
1900                        $from_mode_oct = oct $diff{'from_mode'};
1901                        if (S_ISREG($to_mode_oct)) { # only for regular file
1902                                $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
1903                        }
1904                        $from_file_type = file_type($diff{'from_mode'});
1905                }
1906
1907                if ($diff{'status'} eq "A") { # created
1908                        my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
1909                        $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
1910                        $mode_chng   .= "]</span>";
1911                        print "<td>";
1912                        print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1913                                                     hash_base=>$hash, file_name=>$diff{'file'}),
1914                                      -class => "list"}, esc_html($diff{'file'}));
1915                        print "</td>\n";
1916                        print "<td>$mode_chng</td>\n";
1917                        print "<td class=\"link\">";
1918                        if ($action eq 'commitdiff') {
1919                                # link to patch
1920                                $patchno++;
1921                                print $cgi->a({-href => "#patch$patchno"}, "patch");
1922                        }
1923                        print "</td>\n";
1924
1925                } elsif ($diff{'status'} eq "D") { # deleted
1926                        my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
1927                        print "<td>";
1928                        print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1929                                                     hash_base=>$parent, file_name=>$diff{'file'}),
1930                                       -class => "list"}, esc_html($diff{'file'}));
1931                        print "</td>\n";
1932                        print "<td>$mode_chng</td>\n";
1933                        print "<td class=\"link\">";
1934                        if ($action eq 'commitdiff') {
1935                                # link to patch
1936                                $patchno++;
1937                                print $cgi->a({-href => "#patch$patchno"}, "patch");
1938                                print " | ";
1939                        }
1940                        print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1941                                                     hash_base=>$parent, file_name=>$diff{'file'})},
1942                                      "blob") . " | ";
1943                        print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
1944                                                     file_name=>$diff{'file'})},
1945                                      "blame") . " | ";
1946                        print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1947                                                     file_name=>$diff{'file'})},
1948                                      "history");
1949                        print "</td>\n";
1950
1951                } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
1952                        my $mode_chnge = "";
1953                        if ($diff{'from_mode'} != $diff{'to_mode'}) {
1954                                $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
1955                                if ($from_file_type != $to_file_type) {
1956                                        $mode_chnge .= " from $from_file_type to $to_file_type";
1957                                }
1958                                if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
1959                                        if ($from_mode_str && $to_mode_str) {
1960                                                $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
1961                                        } elsif ($to_mode_str) {
1962                                                $mode_chnge .= " mode: $to_mode_str";
1963                                        }
1964                                }
1965                                $mode_chnge .= "]</span>\n";
1966                        }
1967                        print "<td>";
1968                        print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1969                                                     hash_base=>$hash, file_name=>$diff{'file'}),
1970                                      -class => "list"}, esc_html($diff{'file'}));
1971                        print "</td>\n";
1972                        print "<td>$mode_chnge</td>\n";
1973                        print "<td class=\"link\">";
1974                        if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1975                                if ($action eq 'commitdiff') {
1976                                        # link to patch
1977                                        $patchno++;
1978                                        print $cgi->a({-href => "#patch$patchno"}, "patch");
1979                                } else {
1980                                        print $cgi->a({-href => href(action=>"blobdiff",
1981                                                                     hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1982                                                                     hash_base=>$hash, hash_parent_base=>$parent,
1983                                                                     file_name=>$diff{'file'})},
1984                                                      "diff");
1985                                }
1986                                print " | ";
1987                        }
1988                        print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1989                                                     hash_base=>$hash, file_name=>$diff{'file'})},
1990                                      "blob") . " | ";
1991                        print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
1992                                                     file_name=>$diff{'file'})},
1993                                      "blame") . " | ";
1994                        print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
1995                                                     file_name=>$diff{'file'})},
1996                                      "history");
1997                        print "</td>\n";
1998
1999                } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
2000                        my %status_name = ('R' => 'moved', 'C' => 'copied');
2001                        my $nstatus = $status_name{$diff{'status'}};
2002                        my $mode_chng = "";
2003                        if ($diff{'from_mode'} != $diff{'to_mode'}) {
2004                                # mode also for directories, so we cannot use $to_mode_str
2005                                $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
2006                        }
2007                        print "<td>" .
2008                              $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2009                                                     hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
2010                                      -class => "list"}, esc_html($diff{'to_file'})) . "</td>\n" .
2011                              "<td><span class=\"file_status $nstatus\">[$nstatus from " .
2012                              $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
2013                                                     hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
2014                                      -class => "list"}, esc_html($diff{'from_file'})) .
2015                              " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
2016                              "<td class=\"link\">";
2017                        if ($diff{'to_id'} ne $diff{'from_id'}) {
2018                                if ($action eq 'commitdiff') {
2019                                        # link to patch
2020                                        $patchno++;
2021                                        print $cgi->a({-href => "#patch$patchno"}, "patch");
2022                                } else {
2023                                        print $cgi->a({-href => href(action=>"blobdiff",
2024                                                                     hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
2025                                                                     hash_base=>$hash, hash_parent_base=>$parent,
2026                                                                     file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
2027                                                      "diff");
2028                                }
2029                                print " | ";
2030                        }
2031                        print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
2032                                                     hash_base=>$parent, file_name=>$diff{'from_file'})},
2033                                      "blob") . " | ";
2034                        print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
2035                                                     file_name=>$diff{'from_file'})},
2036                                      "blame") . " | ";
2037                        print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
2038                                                    file_name=>$diff{'from_file'})},
2039                                      "history");
2040                        print "</td>\n";
2041
2042                } # we should not encounter Unmerged (U) or Unknown (X) status
2043                print "</tr>\n";
2044        }
2045        print "</table>\n";
2046}
2047
2048sub git_patchset_body {
2049        my ($fd, $difftree, $hash, $hash_parent) = @_;
2050
2051        my $patch_idx = 0;
2052        my $in_header = 0;
2053        my $patch_found = 0;
2054        my $diffinfo;
2055
2056        print "<div class=\"patchset\">\n";
2057
2058        LINE:
2059        while (my $patch_line = <$fd>) {
2060                chomp $patch_line;
2061
2062                if ($patch_line =~ m/^diff /) { # "git diff" header
2063                        # beginning of patch (in patchset)
2064                        if ($patch_found) {
2065                                # close previous patch
2066                                print "</div>\n"; # class="patch"
2067                        } else {
2068                                # first patch in patchset
2069                                $patch_found = 1;
2070                        }
2071                        print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
2072
2073                        if (ref($difftree->[$patch_idx]) eq "HASH") {
2074                                $diffinfo = $difftree->[$patch_idx];
2075                        } else {
2076                                $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
2077                        }
2078                        $patch_idx++;
2079
2080                        # for now, no extended header, hence we skip empty patches
2081                        # companion to  next LINE if $in_header;
2082                        if ($diffinfo->{'from_id'} eq $diffinfo->{'to_id'}) { # no change
2083                                $in_header = 1;
2084                                next LINE;
2085                        }
2086
2087                        if ($diffinfo->{'status'} eq "A") { # added
2088                                print "<div class=\"diff_info\">" . file_type($diffinfo->{'to_mode'}) . ":" .
2089                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2090                                                             hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
2091                                              $diffinfo->{'to_id'}) . " (new)" .
2092                                      "</div>\n"; # class="diff_info"
2093
2094                        } elsif ($diffinfo->{'status'} eq "D") { # deleted
2095                                print "<div class=\"diff_info\">" . file_type($diffinfo->{'from_mode'}) . ":" .
2096                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
2097                                                             hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
2098                                              $diffinfo->{'from_id'}) . " (deleted)" .
2099                                      "</div>\n"; # class="diff_info"
2100
2101                        } elsif ($diffinfo->{'status'} eq "R" || # renamed
2102                                 $diffinfo->{'status'} eq "C" || # copied
2103                                 $diffinfo->{'status'} eq "2") { # with two filenames (from git_blobdiff)
2104                                print "<div class=\"diff_info\">" .
2105                                      file_type($diffinfo->{'from_mode'}) . ":" .
2106                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
2107                                                             hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'from_file'})},
2108                                              $diffinfo->{'from_id'}) .
2109                                      " -> " .
2110                                      file_type($diffinfo->{'to_mode'}) . ":" .
2111                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2112                                                             hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'to_file'})},
2113                                              $diffinfo->{'to_id'});
2114                                print "</div>\n"; # class="diff_info"
2115
2116                        } else { # modified, mode changed, ...
2117                                print "<div class=\"diff_info\">" .
2118                                      file_type($diffinfo->{'from_mode'}) . ":" .
2119                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
2120                                                             hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
2121                                              $diffinfo->{'from_id'}) .
2122                                      " -> " .
2123                                      file_type($diffinfo->{'to_mode'}) . ":" .
2124                                      $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2125                                                             hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
2126                                              $diffinfo->{'to_id'});
2127                                print "</div>\n"; # class="diff_info"
2128                        }
2129
2130                        #print "<div class=\"diff extended_header\">\n";
2131                        $in_header = 1;
2132                        next LINE;
2133                } # start of patch in patchset
2134
2135
2136                if ($in_header && $patch_line =~ m/^---/) {
2137                        #print "</div>\n"; # class="diff extended_header"
2138                        $in_header = 0;
2139
2140                        my $file = $diffinfo->{'from_file'};
2141                        $file  ||= $diffinfo->{'file'};
2142                        $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
2143                                                       hash=>$diffinfo->{'from_id'}, file_name=>$file),
2144                                        -class => "list"}, esc_html($file));
2145                        $patch_line =~ s|a/.*$|a/$file|g;
2146                        print "<div class=\"diff from_file\">$patch_line</div>\n";
2147
2148                        $patch_line = <$fd>;
2149                        chomp $patch_line;
2150
2151                        #$patch_line =~ m/^+++/;
2152                        $file    = $diffinfo->{'to_file'};
2153                        $file  ||= $diffinfo->{'file'};
2154                        $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2155                                                       hash=>$diffinfo->{'to_id'}, file_name=>$file),
2156                                        -class => "list"}, esc_html($file));
2157                        $patch_line =~ s|b/.*|b/$file|g;
2158                        print "<div class=\"diff to_file\">$patch_line</div>\n";
2159
2160                        next LINE;
2161                }
2162                next LINE if $in_header;
2163
2164                print format_diff_line($patch_line);
2165        }
2166        print "</div>\n" if $patch_found; # class="patch"
2167
2168        print "</div>\n"; # class="patchset"
2169}
2170
2171# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2172
2173sub git_project_list_body {
2174        my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
2175
2176        my $check_forks = gitweb_check_feature('forks');
2177
2178        my @projects;
2179        foreach my $pr (@$projlist) {
2180                my (@aa) = git_get_last_activity($pr->{'path'});
2181                unless (@aa) {
2182                        next;
2183                }
2184                ($pr->{'age'}, $pr->{'age_string'}) = @aa;
2185                if (!defined $pr->{'descr'}) {
2186                        my $descr = git_get_project_description($pr->{'path'}) || "";
2187                        $pr->{'descr'} = chop_str($descr, 25, 5);
2188                }
2189                if (!defined $pr->{'owner'}) {
2190                        $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2191                }
2192                if ($check_forks) {
2193                        my $pname = $pr->{'path'};
2194                        $pname =~ s/\.git$//;
2195                        $pr->{'forks'} = -d "$projectroot/$pname";
2196                }
2197                push @projects, $pr;
2198        }
2199
2200        $order ||= "project";
2201        $from = 0 unless defined $from;
2202        $to = $#projects if (!defined $to || $#projects < $to);
2203
2204        print "<table class=\"project_list\">\n";
2205        unless ($no_header) {
2206                print "<tr>\n";
2207                if ($check_forks) {
2208                        print "<th></th>\n";
2209                }
2210                if ($order eq "project") {
2211                        @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2212                        print "<th>Project</th>\n";
2213                } else {
2214                        print "<th>" .
2215                              $cgi->a({-href => href(project=>undef, order=>'project'),
2216                                       -class => "header"}, "Project") .
2217                              "</th>\n";
2218                }
2219                if ($order eq "descr") {
2220                        @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2221                        print "<th>Description</th>\n";
2222                } else {
2223                        print "<th>" .
2224                              $cgi->a({-href => href(project=>undef, order=>'descr'),
2225                                       -class => "header"}, "Description") .
2226                              "</th>\n";
2227                }
2228                if ($order eq "owner") {
2229                        @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2230                        print "<th>Owner</th>\n";
2231                } else {
2232                        print "<th>" .
2233                              $cgi->a({-href => href(project=>undef, order=>'owner'),
2234                                       -class => "header"}, "Owner") .
2235                              "</th>\n";
2236                }
2237                if ($order eq "age") {
2238                        @projects = sort {$a->{'age'} <=> $b->{'age'}} @projects;
2239                        print "<th>Last Change</th>\n";
2240                } else {
2241                        print "<th>" .
2242                              $cgi->a({-href => href(project=>undef, order=>'age'),
2243                                       -class => "header"}, "Last Change") .
2244                              "</th>\n";
2245                }
2246                print "<th></th>\n" .
2247                      "</tr>\n";
2248        }
2249        my $alternate = 1;
2250        for (my $i = $from; $i <= $to; $i++) {
2251                my $pr = $projects[$i];
2252                if ($alternate) {
2253                        print "<tr class=\"dark\">\n";
2254                } else {
2255                        print "<tr class=\"light\">\n";
2256                }
2257                $alternate ^= 1;
2258                if ($check_forks) {
2259                        print "<td>";
2260                        if ($pr->{'forks'}) {
2261                                print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
2262                        }
2263                        print "</td>\n";
2264                }
2265                print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2266                                        -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2267                      "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
2268                      "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2269                print "<td class=\"". age_class($pr->{'age'}) . "\">" .
2270                      $pr->{'age_string'} . "</td>\n" .
2271                      "<td class=\"link\">" .
2272                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2273                      $cgi->a({-href => '/git-browser/by-commit.html?r='.$pr->{'path'}}, "graphiclog") . " | " .
2274                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
2275                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
2276                      ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
2277                      "</td>\n" .
2278                      "</tr>\n";
2279        }
2280        if (defined $extra) {
2281                print "<tr>\n";
2282                if ($check_forks) {
2283                        print "<td></td>\n";
2284                }
2285                print "<td colspan=\"5\">$extra</td>\n" .
2286                      "</tr>\n";
2287        }
2288        print "</table>\n";
2289}
2290
2291sub git_shortlog_body {
2292        # uses global variable $project
2293        my ($revlist, $from, $to, $refs, $extra) = @_;
2294
2295        $from = 0 unless defined $from;
2296        $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
2297
2298        print "<table class=\"shortlog\" cellspacing=\"0\">\n";
2299        my $alternate = 1;
2300        for (my $i = $from; $i <= $to; $i++) {
2301                my $commit = $revlist->[$i];
2302                #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
2303                my $ref = format_ref_marker($refs, $commit);
2304                my %co = parse_commit($commit);
2305                if ($alternate) {
2306                        print "<tr class=\"dark\">\n";
2307                } else {
2308                        print "<tr class=\"light\">\n";
2309                }
2310                $alternate ^= 1;
2311                # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
2312                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2313                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
2314                      "<td>";
2315                print format_subject_html($co{'title'}, $co{'title_short'},
2316                                          href(action=>"commit", hash=>$commit), $ref);
2317                print "</td>\n" .
2318                      "<td class=\"link\">" .
2319                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
2320                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
2321                      $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
2322                if (gitweb_have_snapshot()) {
2323                        print " | " . $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
2324                }
2325                print "</td>\n" .
2326                      "</tr>\n";
2327        }
2328        if (defined $extra) {
2329                print "<tr>\n" .
2330                      "<td colspan=\"4\">$extra</td>\n" .
2331                      "</tr>\n";
2332        }
2333        print "</table>\n";
2334}
2335
2336sub git_history_body {
2337        # Warning: assumes constant type (blob or tree) during history
2338        my ($revlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
2339
2340        $from = 0 unless defined $from;
2341        $to = $#{$revlist} unless (defined $to && $to <= $#{$revlist});
2342
2343        print "<table class=\"history\" cellspacing=\"0\">\n";
2344        my $alternate = 1;
2345        for (my $i = $from; $i <= $to; $i++) {
2346                if ($revlist->[$i] !~ m/^([0-9a-fA-F]{40})/) {
2347                        next;
2348                }
2349
2350                my $commit = $1;
2351                my %co = parse_commit($commit);
2352                if (!%co) {
2353                        next;
2354                }
2355
2356                my $ref = format_ref_marker($refs, $commit);
2357
2358                if ($alternate) {
2359                        print "<tr class=\"dark\">\n";
2360                } else {
2361                        print "<tr class=\"light\">\n";
2362                }
2363                $alternate ^= 1;
2364                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2365                      # shortlog uses      chop_str($co{'author_name'}, 10)
2366                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
2367                      "<td>";
2368                # originally git_history used chop_str($co{'title'}, 50)
2369                print format_subject_html($co{'title'}, $co{'title_short'},
2370                                          href(action=>"commit", hash=>$commit), $ref);
2371                print "</td>\n" .
2372                      "<td class=\"link\">" .
2373                      $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
2374                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
2375
2376                if ($ftype eq 'blob') {
2377                        my $blob_current = git_get_hash_by_path($hash_base, $file_name);
2378                        my $blob_parent  = git_get_hash_by_path($commit, $file_name);
2379                        if (defined $blob_current && defined $blob_parent &&
2380                                        $blob_current ne $blob_parent) {
2381                                print " | " .
2382                                        $cgi->a({-href => href(action=>"blobdiff",
2383                                                               hash=>$blob_current, hash_parent=>$blob_parent,
2384                                                               hash_base=>$hash_base, hash_parent_base=>$commit,
2385                                                               file_name=>$file_name)},
2386                                                "diff to current");
2387                        }
2388                }
2389                print "</td>\n" .
2390                      "</tr>\n";
2391        }
2392        if (defined $extra) {
2393                print "<tr>\n" .
2394                      "<td colspan=\"4\">$extra</td>\n" .
2395                      "</tr>\n";
2396        }
2397        print "</table>\n";
2398}
2399
2400sub git_tags_body {
2401        # uses global variable $project
2402        my ($taglist, $from, $to, $extra) = @_;
2403        $from = 0 unless defined $from;
2404        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2405
2406        print "<table class=\"tags\" cellspacing=\"0\">\n";
2407        my $alternate = 1;
2408        for (my $i = $from; $i <= $to; $i++) {
2409                my $entry = $taglist->[$i];
2410                my %tag = %$entry;
2411                my $comment_lines = $tag{'comment'};
2412                my $comment = shift @$comment_lines;
2413                my $comment_short;
2414                if (defined $comment) {
2415                        $comment_short = chop_str($comment, 30, 5);
2416                }
2417                if ($alternate) {
2418                        print "<tr class=\"dark\">\n";
2419                } else {
2420                        print "<tr class=\"light\">\n";
2421                }
2422                $alternate ^= 1;
2423                print "<td><i>$tag{'age'}</i></td>\n" .
2424                      "<td>" .
2425                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
2426                               -class => "list name"}, esc_html($tag{'name'})) .
2427                      "</td>\n" .
2428                      "<td>";
2429                if (defined $comment) {
2430                        print format_subject_html($comment, $comment_short,
2431                                                  href(action=>"tag", hash=>$tag{'id'}));
2432                }
2433                print "</td>\n" .
2434                      "<td class=\"selflink\">";
2435                if ($tag{'type'} eq "tag") {
2436                        print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
2437                } else {
2438                        print "&nbsp;";
2439                }
2440                print "</td>\n" .
2441                      "<td class=\"link\">" . " | " .
2442                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
2443                if ($tag{'reftype'} eq "commit") {
2444                        print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
2445                              " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'refid'})}, "log");
2446                } elsif ($tag{'reftype'} eq "blob") {
2447                        print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
2448                }
2449                print "</td>\n" .
2450                      "</tr>";
2451        }
2452        if (defined $extra) {
2453                print "<tr>\n" .
2454                      "<td colspan=\"5\">$extra</td>\n" .
2455                      "</tr>\n";
2456        }
2457        print "</table>\n";
2458}
2459
2460sub git_heads_body {
2461        # uses global variable $project
2462        my ($headlist, $head, $from, $to, $extra) = @_;
2463        $from = 0 unless defined $from;
2464        $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
2465
2466        print "<table class=\"heads\" cellspacing=\"0\">\n";
2467        my $alternate = 1;
2468        for (my $i = $from; $i <= $to; $i++) {
2469                my $entry = $headlist->[$i];
2470                my %tag = %$entry;
2471                my $curr = $tag{'id'} eq $head;
2472                if ($alternate) {
2473                        print "<tr class=\"dark\">\n";
2474                } else {
2475                        print "<tr class=\"light\">\n";
2476                }
2477                $alternate ^= 1;
2478                print "<td><i>$tag{'age'}</i></td>\n" .
2479                      ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
2480                      $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'}),
2481                               -class => "list name"},esc_html($tag{'name'})) .
2482                      "</td>\n" .
2483                      "<td class=\"link\">" .
2484                      $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") . " | " .
2485                      $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log") . " | " .
2486                      $cgi->a({-href => href(action=>"tree", hash=>$tag{'name'}, hash_base=>$tag{'name'})}, "tree") .
2487                      "</td>\n" .
2488                      "</tr>";
2489        }
2490        if (defined $extra) {
2491                print "<tr>\n" .
2492                      "<td colspan=\"3\">$extra</td>\n" .
2493                      "</tr>\n";
2494        }
2495        print "</table>\n";
2496}
2497
2498## ======================================================================
2499## ======================================================================
2500## actions
2501
2502sub git_project_list {
2503        my $order = $cgi->param('o');
2504        if (defined $order && $order !~ m/project|descr|owner|age/) {
2505                die_error(undef, "Unknown order parameter");
2506        }
2507
2508        my @list = git_get_projects_list();
2509        if (!@list) {
2510                die_error(undef, "No projects found");
2511        }
2512
2513        git_header_html();
2514        if (-f $home_text) {
2515                print "<div class=\"index_include\">\n";
2516                open (my $fd, $home_text);
2517                print <$fd>;
2518                close $fd;
2519                print "</div>\n";
2520        }
2521        git_project_list_body(\@list, $order);
2522        git_footer_html();
2523}
2524
2525sub git_forks {
2526        my $order = $cgi->param('o');
2527        if (defined $order && $order !~ m/project|descr|owner|age/) {
2528                die_error(undef, "Unknown order parameter");
2529        }
2530
2531        my @list = git_get_projects_list($project);
2532        if (!@list) {
2533                die_error(undef, "No forks found");
2534        }
2535
2536        git_header_html();
2537        git_print_page_nav('','');
2538        git_print_header_div('summary', "$project forks");
2539        git_project_list_body(\@list, $order);
2540        git_footer_html();
2541}
2542
2543sub git_project_index {
2544        my @projects = git_get_projects_list($project);
2545
2546        print $cgi->header(
2547                -type => 'text/plain',
2548                -charset => 'utf-8',
2549                -content_disposition => 'inline; filename="index.aux"');
2550
2551        foreach my $pr (@projects) {
2552                if (!exists $pr->{'owner'}) {
2553                        $pr->{'owner'} = get_file_owner("$projectroot/$project");
2554                }
2555
2556                my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
2557                # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
2558                $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2559                $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2560                $path  =~ s/ /\+/g;
2561                $owner =~ s/ /\+/g;
2562
2563                print "$path $owner\n";
2564        }
2565}
2566
2567sub git_summary {
2568        my $descr = git_get_project_description($project) || "none";
2569        my $head = git_get_head_hash($project);
2570        my %co = parse_commit($head);
2571        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2572
2573        my $owner = git_get_project_owner($project);
2574
2575        my ($reflist, $refs) = git_get_refs_list();
2576
2577        my @taglist;
2578        my @headlist;
2579        foreach my $ref (@$reflist) {
2580                if ($ref->{'name'} =~ s!^heads/!!) {
2581                        push @headlist, $ref;
2582                } else {
2583                        $ref->{'name'} =~ s!^tags/!!;
2584                        push @taglist, $ref;
2585                }
2586        }
2587        my @forklist;
2588        if (gitweb_check_feature('forks')) {
2589                @forklist = git_get_projects_list($project);
2590        }
2591
2592        git_header_html();
2593        git_print_page_nav('summary','', $head);
2594
2595        print "<div class=\"title\">&nbsp;</div>\n";
2596        print "<table cellspacing=\"0\">\n" .
2597              "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
2598              "<tr><td>owner</td><td>$owner</td></tr>\n" .
2599              "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
2600        # use per project git URL list in $projectroot/$project/cloneurl
2601        # or make project git URL from git base URL and project name
2602        my $url_tag = "URL";
2603        my @url_list = git_get_project_url_list($project);
2604        @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
2605        foreach my $git_url (@url_list) {
2606                next unless $git_url;
2607                print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
2608                $url_tag = "";
2609        }
2610        print "</table>\n";
2611
2612        if (-s "$projectroot/$project/README.html") {
2613                if (open my $fd, "$projectroot/$project/README.html") {
2614                        print "<div class=\"title\">readme</div>\n";
2615                        print $_ while (<$fd>);
2616                        close $fd;
2617                }
2618        }
2619
2620        open my $fd, "-|", git_cmd(), "rev-list", "--max-count=17",
2621                git_get_head_hash($project)
2622                or die_error(undef, "Open git-rev-list failed");
2623        my @revlist = map { chomp; $_ } <$fd>;
2624        close $fd;
2625        git_print_header_div('shortlog');
2626        git_shortlog_body(\@revlist, 0, 15, $refs,
2627                          $cgi->a({-href => href(action=>"shortlog")}, "..."));
2628
2629        if (@taglist) {
2630                git_print_header_div('tags');
2631                git_tags_body(\@taglist, 0, 15,
2632                              $cgi->a({-href => href(action=>"tags")}, "..."));
2633        }
2634
2635        if (@headlist) {
2636                git_print_header_div('heads');
2637                git_heads_body(\@headlist, $head, 0, 15,
2638                               $cgi->a({-href => href(action=>"heads")}, "..."));
2639        }
2640
2641        if (@forklist) {
2642                git_print_header_div('forks');
2643                git_project_list_body(\@forklist, undef, 0, 15,
2644                                      $cgi->a({-href => href(action=>"forks")}, "..."),
2645                                      'noheader');
2646        }
2647
2648        git_footer_html();
2649}
2650
2651sub git_tag {
2652        my $head = git_get_head_hash($project);
2653        git_header_html();
2654        git_print_page_nav('','', $head,undef,$head);
2655        my %tag = parse_tag($hash);
2656        git_print_header_div('commit', esc_html($tag{'name'}), $hash);
2657        print "<div class=\"title_text\">\n" .
2658              "<table cellspacing=\"0\">\n" .
2659              "<tr>\n" .
2660              "<td>object</td>\n" .
2661              "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2662                               $tag{'object'}) . "</td>\n" .
2663              "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2664                                              $tag{'type'}) . "</td>\n" .
2665              "</tr>\n";
2666        if (defined($tag{'author'})) {
2667                my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
2668                print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
2669                print "<tr><td></td><td>" . $ad{'rfc2822'} .
2670                        sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
2671                        "</td></tr>\n";
2672        }
2673        print "</table>\n\n" .
2674              "</div>\n";
2675        print "<div class=\"page_body\">";
2676        my $comment = $tag{'comment'};
2677        foreach my $line (@$comment) {
2678                print esc_html($line) . "<br/>\n";
2679        }
2680        print "</div>\n";
2681        git_footer_html();
2682}
2683
2684sub git_blame2 {
2685        my $fd;
2686        my $ftype;
2687
2688        my ($have_blame) = gitweb_check_feature('blame');
2689        if (!$have_blame) {
2690                die_error('403 Permission denied', "Permission denied");
2691        }
2692        die_error('404 Not Found', "File name not defined") if (!$file_name);
2693        $hash_base ||= git_get_head_hash($project);
2694        die_error(undef, "Couldn't find base commit") unless ($hash_base);
2695        my %co = parse_commit($hash_base)
2696                or die_error(undef, "Reading commit failed");
2697        if (!defined $hash) {
2698                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2699                        or die_error(undef, "Error looking up file");
2700        }
2701        $ftype = git_get_type($hash);
2702        if ($ftype !~ "blob") {
2703                die_error("400 Bad Request", "Object is not a blob");
2704        }
2705        open ($fd, "-|", git_cmd(), "blame", '-p', '--',
2706              $file_name, $hash_base)
2707                or die_error(undef, "Open git-blame failed");
2708        git_header_html();
2709        my $formats_nav =
2710                $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2711                        "blob") .
2712                " | " .
2713                $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2714                        "history") .
2715                " | " .
2716                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2717                        "HEAD");
2718        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2719        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2720        git_print_page_path($file_name, $ftype, $hash_base);
2721        my @rev_color = (qw(light2 dark2));
2722        my $num_colors = scalar(@rev_color);
2723        my $current_color = 0;
2724        my $last_rev;
2725        print <<HTML;
2726<div class="page_body">
2727<table class="blame">
2728<tr><th>Commit</th><th>Line</th><th>Data</th></tr>
2729HTML
2730        my %metainfo = ();
2731        while (1) {
2732                $_ = <$fd>;
2733                last unless defined $_;
2734                my ($full_rev, $orig_lineno, $lineno, $group_size) =
2735                    /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
2736                if (!exists $metainfo{$full_rev}) {
2737                        $metainfo{$full_rev} = {};
2738                }
2739                my $meta = $metainfo{$full_rev};
2740                while (<$fd>) {
2741                        last if (s/^\t//);
2742                        if (/^(\S+) (.*)$/) {
2743                                $meta->{$1} = $2;
2744                        }
2745                }
2746                my $data = $_;
2747                my $rev = substr($full_rev, 0, 8);
2748                my $author = $meta->{'author'};
2749                my %date = parse_date($meta->{'author-time'},
2750                                      $meta->{'author-tz'});
2751                my $date = $date{'iso-tz'};
2752                if ($group_size) {
2753                        $current_color = ++$current_color % $num_colors;
2754                }
2755                print "<tr class=\"$rev_color[$current_color]\">\n";
2756                if ($group_size) {
2757                        print "<td class=\"sha1\"";
2758                        print " title=\"$author, $date\"";
2759                        print " rowspan=\"$group_size\"" if ($group_size > 1);
2760                        print ">";
2761                        print $cgi->a({-href => href(action=>"commit",
2762                                                     hash=>$full_rev,
2763                                                     file_name=>$file_name)},
2764                                      esc_html($rev));
2765                        print "</td>\n";
2766                }
2767                my $blamed = href(action => 'blame',
2768                                  file_name => $meta->{'filename'},
2769                                  hash_base => $full_rev);
2770                print "<td class=\"linenr\">";
2771                print $cgi->a({ -href => "$blamed#l$orig_lineno",
2772                                -id => "l$lineno",
2773                                -class => "linenr" },
2774                              esc_html($lineno));
2775                print "</td>";
2776                print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
2777                print "</tr>\n";
2778        }
2779        print "</table>\n";
2780        print "</div>";
2781        close $fd
2782                or print "Reading blob failed\n";
2783        git_footer_html();
2784}
2785
2786sub git_blame {
2787        my $fd;
2788
2789        my ($have_blame) = gitweb_check_feature('blame');
2790        if (!$have_blame) {
2791                die_error('403 Permission denied', "Permission denied");
2792        }
2793        die_error('404 Not Found', "File name not defined") if (!$file_name);
2794        $hash_base ||= git_get_head_hash($project);
2795        die_error(undef, "Couldn't find base commit") unless ($hash_base);
2796        my %co = parse_commit($hash_base)
2797                or die_error(undef, "Reading commit failed");
2798        if (!defined $hash) {
2799                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2800                        or die_error(undef, "Error lookup file");
2801        }
2802        open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
2803                or die_error(undef, "Open git-annotate failed");
2804        git_header_html();
2805        my $formats_nav =
2806                $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2807                        "blob") .
2808                " | " .
2809                $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2810                        "history") .
2811                " | " .
2812                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2813                        "HEAD");
2814        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2815        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2816        git_print_page_path($file_name, 'blob', $hash_base);
2817        print "<div class=\"page_body\">\n";
2818        print <<HTML;
2819<table class="blame">
2820  <tr>
2821    <th>Commit</th>
2822    <th>Age</th>
2823    <th>Author</th>
2824    <th>Line</th>
2825    <th>Data</th>
2826  </tr>
2827HTML
2828        my @line_class = (qw(light dark));
2829        my $line_class_len = scalar (@line_class);
2830        my $line_class_num = $#line_class;
2831        while (my $line = <$fd>) {
2832                my $long_rev;
2833                my $short_rev;
2834                my $author;
2835                my $time;
2836                my $lineno;
2837                my $data;
2838                my $age;
2839                my $age_str;
2840                my $age_class;
2841
2842                chomp $line;
2843                $line_class_num = ($line_class_num + 1) % $line_class_len;
2844
2845                if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
2846                        $long_rev = $1;
2847                        $author   = $2;
2848                        $time     = $3;
2849                        $lineno   = $4;
2850                        $data     = $5;
2851                } else {
2852                        print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
2853                        next;
2854                }
2855                $short_rev  = substr ($long_rev, 0, 8);
2856                $age        = time () - $time;
2857                $age_str    = age_string ($age);
2858                $age_str    =~ s/ /&nbsp;/g;
2859                $age_class  = age_class($age);
2860                $author     = esc_html ($author);
2861                $author     =~ s/ /&nbsp;/g;
2862
2863                $data = untabify($data);
2864                $data = esc_html ($data);
2865
2866                print <<HTML;
2867  <tr class="$line_class[$line_class_num]">
2868    <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
2869    <td class="$age_class">$age_str</td>
2870    <td>$author</td>
2871    <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
2872    <td class="pre">$data</td>
2873  </tr>
2874HTML
2875        } # while (my $line = <$fd>)
2876        print "</table>\n\n";
2877        close $fd
2878                or print "Reading blob failed.\n";
2879        print "</div>";
2880        git_footer_html();
2881}
2882
2883sub git_tags {
2884        my $head = git_get_head_hash($project);
2885        git_header_html();
2886        git_print_page_nav('','', $head,undef,$head);
2887        git_print_header_div('summary', $project);
2888
2889        my ($taglist) = git_get_refs_list("tags");
2890        if (@$taglist) {
2891                git_tags_body($taglist);
2892        }
2893        git_footer_html();
2894}
2895
2896sub git_heads {
2897        my $head = git_get_head_hash($project);
2898        git_header_html();
2899        git_print_page_nav('','', $head,undef,$head);
2900        git_print_header_div('summary', $project);
2901
2902        my ($headlist) = git_get_refs_list("heads");
2903        if (@$headlist) {
2904                git_heads_body($headlist, $head);
2905        }
2906        git_footer_html();
2907}
2908
2909sub git_blob_plain {
2910        my $expires;
2911
2912        if (!defined $hash) {
2913                if (defined $file_name) {
2914                        my $base = $hash_base || git_get_head_hash($project);
2915                        $hash = git_get_hash_by_path($base, $file_name, "blob")
2916                                or die_error(undef, "Error lookup file");
2917                } else {
2918                        die_error(undef, "No file name defined");
2919                }
2920        } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2921                # blobs defined by non-textual hash id's can be cached
2922                $expires = "+1d";
2923        }
2924
2925        my $type = shift;
2926        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2927                or die_error(undef, "Couldn't cat $file_name, $hash");
2928
2929        $type ||= blob_mimetype($fd, $file_name);
2930
2931        # save as filename, even when no $file_name is given
2932        my $save_as = "$hash";
2933        if (defined $file_name) {
2934                $save_as = $file_name;
2935        } elsif ($type =~ m/^text\//) {
2936                $save_as .= '.txt';
2937        }
2938
2939        print $cgi->header(
2940                -type => "$type",
2941                -expires=>$expires,
2942                -content_disposition => 'inline; filename="' . "$save_as" . '"');
2943        undef $/;
2944        binmode STDOUT, ':raw';
2945        print <$fd>;
2946        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2947        $/ = "\n";
2948        close $fd;
2949}
2950
2951sub git_blob {
2952        my $expires;
2953
2954        if (!defined $hash) {
2955                if (defined $file_name) {
2956                        my $base = $hash_base || git_get_head_hash($project);
2957                        $hash = git_get_hash_by_path($base, $file_name, "blob")
2958                                or die_error(undef, "Error lookup file");
2959                } else {
2960                        die_error(undef, "No file name defined");
2961                }
2962        } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2963                # blobs defined by non-textual hash id's can be cached
2964                $expires = "+1d";
2965        }
2966
2967        my ($have_blame) = gitweb_check_feature('blame');
2968        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2969                or die_error(undef, "Couldn't cat $file_name, $hash");
2970        my $mimetype = blob_mimetype($fd, $file_name);
2971        if ($mimetype !~ m/^text\//) {
2972                close $fd;
2973                return git_blob_plain($mimetype);
2974        }
2975        git_header_html(undef, $expires);
2976        my $formats_nav = '';
2977        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2978                if (defined $file_name) {
2979                        if ($have_blame) {
2980                                $formats_nav .=
2981                                        $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
2982                                                               hash=>$hash, file_name=>$file_name)},
2983                                                "blame") .
2984                                        " | ";
2985                        }
2986                        $formats_nav .=
2987                                $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2988                                                       hash=>$hash, file_name=>$file_name)},
2989                                        "history") .
2990                                " | " .
2991                                $cgi->a({-href => href(action=>"blob_plain",
2992                                                       hash=>$hash, file_name=>$file_name)},
2993                                        "raw") .
2994                                " | " .
2995                                $cgi->a({-href => href(action=>"blob",
2996                                                       hash_base=>"HEAD", file_name=>$file_name)},
2997                                        "HEAD");
2998                } else {
2999                        $formats_nav .=
3000                                $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
3001                }
3002                git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3003                git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3004        } else {
3005                print "<div class=\"page_nav\">\n" .
3006                      "<br/><br/></div>\n" .
3007                      "<div class=\"title\">$hash</div>\n";
3008        }
3009        git_print_page_path($file_name, "blob", $hash_base);
3010        print "<div class=\"page_body\">\n";
3011        my $nr;
3012        while (my $line = <$fd>) {
3013                chomp $line;
3014                $nr++;
3015                $line = untabify($line);
3016                printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
3017                       $nr, $nr, $nr, esc_html($line);
3018        }
3019        close $fd
3020                or print "Reading blob failed.\n";
3021        print "</div>";
3022        git_footer_html();
3023}
3024
3025sub git_tree {
3026        my $have_snapshot = gitweb_have_snapshot();
3027
3028        if (!defined $hash_base) {
3029                $hash_base = "HEAD";
3030        }
3031        if (!defined $hash) {
3032                if (defined $file_name) {
3033                        $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
3034                } else {
3035                        $hash = $hash_base;
3036                }
3037        }
3038        $/ = "\0";
3039        open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
3040                or die_error(undef, "Open git-ls-tree failed");
3041        my @entries = map { chomp; $_ } <$fd>;
3042        close $fd or die_error(undef, "Reading tree failed");
3043        $/ = "\n";
3044
3045        my $refs = git_get_references();
3046        my $ref = format_ref_marker($refs, $hash_base);
3047        git_header_html();
3048        my $basedir = '';
3049        my ($have_blame) = gitweb_check_feature('blame');
3050        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3051                my @views_nav = ();
3052                if (defined $file_name) {
3053                        push @views_nav,
3054                                $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3055                                                       hash=>$hash, file_name=>$file_name)},
3056                                        "history"),
3057                                $cgi->a({-href => href(action=>"tree",
3058                                                       hash_base=>"HEAD", file_name=>$file_name)},
3059                                        "HEAD"),
3060                }
3061                if ($have_snapshot) {
3062                        # FIXME: Should be available when we have no hash base as well.
3063                        push @views_nav,
3064                                $cgi->a({-href => href(action=>"snapshot", hash=>$hash)},
3065                                        "snapshot");
3066                }
3067                git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
3068                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
3069        } else {
3070                undef $hash_base;
3071                print "<div class=\"page_nav\">\n";
3072                print "<br/><br/></div>\n";
3073                print "<div class=\"title\">$hash</div>\n";
3074        }
3075        if (defined $file_name) {
3076                $basedir = $file_name;
3077                if ($basedir ne '' && substr($basedir, -1) ne '/') {
3078                        $basedir .= '/';
3079                }
3080        }
3081        git_print_page_path($file_name, 'tree', $hash_base);
3082        print "<div class=\"page_body\">\n";
3083        print "<table cellspacing=\"0\">\n";
3084        my $alternate = 1;
3085        # '..' (top directory) link if possible
3086        if (defined $hash_base &&
3087            defined $file_name && $file_name =~ m![^/]+$!) {
3088                if ($alternate) {
3089                        print "<tr class=\"dark\">\n";
3090                } else {
3091                        print "<tr class=\"light\">\n";
3092                }
3093                $alternate ^= 1;
3094
3095                my $up = $file_name;
3096                $up =~ s!/?[^/]+$!!;
3097                undef $up unless $up;
3098                # based on git_print_tree_entry
3099                print '<td class="mode">' . mode_str('040000') . "</td>\n";
3100                print '<td class="list">';
3101                print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
3102                                             file_name=>$up)},
3103                              "..");
3104                print "</td>\n";
3105                print "<td class=\"link\"></td>\n";
3106
3107                print "</tr>\n";
3108        }
3109        foreach my $line (@entries) {
3110                my %t = parse_ls_tree_line($line, -z => 1);
3111
3112                if ($alternate) {
3113                        print "<tr class=\"dark\">\n";
3114                } else {
3115                        print "<tr class=\"light\">\n";
3116                }
3117                $alternate ^= 1;
3118
3119                git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
3120
3121                print "</tr>\n";
3122        }
3123        print "</table>\n" .
3124              "</div>";
3125        git_footer_html();
3126}
3127
3128sub git_snapshot {
3129        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
3130        my $have_snapshot = (defined $ctype && defined $suffix);
3131        if (!$have_snapshot) {
3132                die_error('403 Permission denied', "Permission denied");
3133        }
3134
3135        if (!defined $hash) {
3136                $hash = git_get_head_hash($project);
3137        }
3138
3139        my $filename = basename($project) . "-$hash.tar.$suffix";
3140
3141        print $cgi->header(
3142                -type => 'application/x-tar',
3143                -content_encoding => $ctype,
3144                -content_disposition => 'inline; filename="' . "$filename" . '"',
3145                -status => '200 OK');
3146
3147        my $git = git_cmd_str();
3148        my $name = $project;
3149        $name =~ s/\047/\047\\\047\047/g;
3150        open my $fd, "-|",
3151        "$git archive --format=tar --prefix=\'$name\'/ $hash | $command"
3152                or die_error(undef, "Execute git-tar-tree failed.");
3153        binmode STDOUT, ':raw';
3154        print <$fd>;
3155        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
3156        close $fd;
3157
3158}
3159
3160sub git_log {
3161        my $head = git_get_head_hash($project);
3162        if (!defined $hash) {
3163                $hash = $head;
3164        }
3165        if (!defined $page) {
3166                $page = 0;
3167        }
3168        my $refs = git_get_references();
3169
3170        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3171        open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
3172                or die_error(undef, "Open git-rev-list failed");
3173        my @revlist = map { chomp; $_ } <$fd>;
3174        close $fd;
3175
3176        my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
3177
3178        git_header_html();
3179        git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
3180
3181        if (!@revlist) {
3182                my %co = parse_commit($hash);
3183
3184                git_print_header_div('summary', $project);
3185                print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
3186        }
3187        for (my $i = ($page * 100); $i <= $#revlist; $i++) {
3188                my $commit = $revlist[$i];
3189                my $ref = format_ref_marker($refs, $commit);
3190                my %co = parse_commit($commit);
3191                next if !%co;
3192                my %ad = parse_date($co{'author_epoch'});
3193                git_print_header_div('commit',
3194                               "<span class=\"age\">$co{'age_string'}</span>" .
3195                               esc_html($co{'title'}) . $ref,
3196                               $commit);
3197                print "<div class=\"title_text\">\n" .
3198                      "<div class=\"log_link\">\n" .
3199                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
3200                      " | " .
3201                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
3202                      " | " .
3203                      $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
3204                      "<br/>\n" .
3205                      "</div>\n" .
3206                      "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
3207                      "</div>\n";
3208
3209                print "<div class=\"log_body\">\n";
3210                git_print_log($co{'comment'}, -final_empty_line=> 1);
3211                print "</div>\n";
3212        }
3213        git_footer_html();
3214}
3215
3216sub git_commit {
3217        my %co = parse_commit($hash);
3218        if (!%co) {
3219                die_error(undef, "Unknown commit object");
3220        }
3221        my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3222        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
3223
3224        my $parent = $co{'parent'};
3225        if (!defined $parent) {
3226                $parent = "--root";
3227        }
3228        open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $parent, $hash
3229                or die_error(undef, "Open git-diff-tree failed");
3230        my @difftree = map { chomp; $_ } <$fd>;
3231        close $fd or die_error(undef, "Reading git-diff-tree failed");
3232
3233        # filter out commit ID output
3234        @difftree = grep(!/^[0-9a-fA-F]{40}$/, @difftree);
3235
3236        # non-textual hash id's can be cached
3237        my $expires;
3238        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3239                $expires = "+1d";
3240        }
3241        my $refs = git_get_references();
3242        my $ref = format_ref_marker($refs, $co{'id'});
3243
3244        my $have_snapshot = gitweb_have_snapshot();
3245
3246        my @views_nav = ();
3247        if (defined $file_name && defined $co{'parent'}) {
3248                push @views_nav,
3249                        $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)},
3250                                "blame");
3251        }
3252        git_header_html(undef, $expires);
3253        git_print_page_nav('commit', '',
3254                           $hash, $co{'tree'}, $hash,
3255                           join (' | ', @views_nav));
3256
3257        if (defined $co{'parent'}) {
3258                git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
3259        } else {
3260                git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
3261        }
3262        print "<div class=\"title_text\">\n" .
3263              "<table cellspacing=\"0\">\n";
3264        print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
3265              "<tr>" .
3266              "<td></td><td> $ad{'rfc2822'}";
3267        if ($ad{'hour_local'} < 6) {
3268                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3269                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3270        } else {
3271                printf(" (%02d:%02d %s)",
3272                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3273        }
3274        print "</td>" .
3275              "</tr>\n";
3276        print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
3277        print "<tr><td></td><td> $cd{'rfc2822'}" .
3278              sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
3279              "</td></tr>\n";
3280        print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
3281        print "<tr>" .
3282              "<td>tree</td>" .
3283              "<td class=\"sha1\">" .
3284              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
3285                       class => "list"}, $co{'tree'}) .
3286              "</td>" .
3287              "<td class=\"link\">" .
3288              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
3289                      "tree");
3290        if ($have_snapshot) {
3291                print " | " .
3292                      $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
3293        }
3294        print "</td>" .
3295              "</tr>\n";
3296        my $parents = $co{'parents'};
3297        foreach my $par (@$parents) {
3298                print "<tr>" .
3299                      "<td>parent</td>" .
3300                      "<td class=\"sha1\">" .
3301                      $cgi->a({-href => href(action=>"commit", hash=>$par),
3302                               class => "list"}, $par) .
3303                      "</td>" .
3304                      "<td class=\"link\">" .
3305                      $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
3306                      " | " .
3307                      $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
3308                      "</td>" .
3309                      "</tr>\n";
3310        }
3311        print "</table>".
3312              "</div>\n";
3313
3314        print "<div class=\"page_body\">\n";
3315        git_print_log($co{'comment'});
3316        print "</div>\n";
3317
3318        git_difftree_body(\@difftree, $hash, $parent);
3319
3320        git_footer_html();
3321}
3322
3323sub git_blobdiff {
3324        my $format = shift || 'html';
3325
3326        my $fd;
3327        my @difftree;
3328        my %diffinfo;
3329        my $expires;
3330
3331        # preparing $fd and %diffinfo for git_patchset_body
3332        # new style URI
3333        if (defined $hash_base && defined $hash_parent_base) {
3334                if (defined $file_name) {
3335                        # read raw output
3336                        open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base,
3337                                "--", $file_name
3338                                or die_error(undef, "Open git-diff-tree failed");
3339                        @difftree = map { chomp; $_ } <$fd>;
3340                        close $fd
3341                                or die_error(undef, "Reading git-diff-tree failed");
3342                        @difftree
3343                                or die_error('404 Not Found', "Blob diff not found");
3344
3345                } elsif (defined $hash &&
3346                         $hash =~ /[0-9a-fA-F]{40}/) {
3347                        # try to find filename from $hash
3348
3349                        # read filtered raw output
3350                        open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base
3351                                or die_error(undef, "Open git-diff-tree failed");
3352                        @difftree =
3353                                # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
3354                                # $hash == to_id
3355                                grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
3356                                map { chomp; $_ } <$fd>;
3357                        close $fd
3358                                or die_error(undef, "Reading git-diff-tree failed");
3359                        @difftree
3360                                or die_error('404 Not Found', "Blob diff not found");
3361
3362                } else {
3363                        die_error('404 Not Found', "Missing one of the blob diff parameters");
3364                }
3365
3366                if (@difftree > 1) {
3367                        die_error('404 Not Found', "Ambiguous blob diff specification");
3368                }
3369
3370                %diffinfo = parse_difftree_raw_line($difftree[0]);
3371                $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
3372                $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
3373
3374                $hash_parent ||= $diffinfo{'from_id'};
3375                $hash        ||= $diffinfo{'to_id'};
3376
3377                # non-textual hash id's can be cached
3378                if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
3379                    $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
3380                        $expires = '+1d';
3381                }
3382
3383                # open patch output
3384                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3385                        '-p', $hash_parent_base, $hash_base,
3386                        "--", $file_name
3387                        or die_error(undef, "Open git-diff-tree failed");
3388        }
3389
3390        # old/legacy style URI
3391        if (!%diffinfo && # if new style URI failed
3392            defined $hash && defined $hash_parent) {
3393                # fake git-diff-tree raw output
3394                $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
3395                $diffinfo{'from_id'} = $hash_parent;
3396                $diffinfo{'to_id'}   = $hash;
3397                if (defined $file_name) {
3398                        if (defined $file_parent) {
3399                                $diffinfo{'status'} = '2';
3400                                $diffinfo{'from_file'} = $file_parent;
3401                                $diffinfo{'to_file'}   = $file_name;
3402                        } else { # assume not renamed
3403                                $diffinfo{'status'} = '1';
3404                                $diffinfo{'from_file'} = $file_name;
3405                                $diffinfo{'to_file'}   = $file_name;
3406                        }
3407                } else { # no filename given
3408                        $diffinfo{'status'} = '2';
3409                        $diffinfo{'from_file'} = $hash_parent;
3410                        $diffinfo{'to_file'}   = $hash;
3411                }
3412
3413                # non-textual hash id's can be cached
3414                if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
3415                    $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3416                        $expires = '+1d';
3417                }
3418
3419                # open patch output
3420                open $fd, "-|", git_cmd(), "diff", '-p', @diff_opts, $hash_parent, $hash
3421                        or die_error(undef, "Open git-diff failed");
3422        } else  {
3423                die_error('404 Not Found', "Missing one of the blob diff parameters")
3424                        unless %diffinfo;
3425        }
3426
3427        # header
3428        if ($format eq 'html') {
3429                my $formats_nav =
3430                        $cgi->a({-href => href(action=>"blobdiff_plain",
3431                                               hash=>$hash, hash_parent=>$hash_parent,
3432                                               hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
3433                                               file_name=>$file_name, file_parent=>$file_parent)},
3434                                "raw");
3435                git_header_html(undef, $expires);
3436                if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3437                        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3438                        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3439                } else {
3440                        print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
3441                        print "<div class=\"title\">$hash vs $hash_parent</div>\n";
3442                }
3443                if (defined $file_name) {
3444                        git_print_page_path($file_name, "blob", $hash_base);
3445                } else {
3446                        print "<div class=\"page_path\"></div>\n";
3447                }
3448
3449        } elsif ($format eq 'plain') {
3450                print $cgi->header(
3451                        -type => 'text/plain',
3452                        -charset => 'utf-8',
3453                        -expires => $expires,
3454                        -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
3455
3456                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3457
3458        } else {
3459                die_error(undef, "Unknown blobdiff format");
3460        }
3461
3462        # patch
3463        if ($format eq 'html') {
3464                print "<div class=\"page_body\">\n";
3465
3466                git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
3467                close $fd;
3468
3469                print "</div>\n"; # class="page_body"
3470                git_footer_html();
3471
3472        } else {
3473                while (my $line = <$fd>) {
3474                        $line =~ s!a/($hash|$hash_parent)!'a/'.esc_html($diffinfo{'from_file'})!eg;
3475                        $line =~ s!b/($hash|$hash_parent)!'b/'.esc_html($diffinfo{'to_file'})!eg;
3476
3477                        print $line;
3478
3479                        last if $line =~ m!^\+\+\+!;
3480                }
3481                local $/ = undef;
3482                print <$fd>;
3483                close $fd;
3484        }
3485}
3486
3487sub git_blobdiff_plain {
3488        git_blobdiff('plain');
3489}
3490
3491sub git_commitdiff {
3492        my $format = shift || 'html';
3493        my %co = parse_commit($hash);
3494        if (!%co) {
3495                die_error(undef, "Unknown commit object");
3496        }
3497        if (!defined $hash_parent) {
3498                $hash_parent = $co{'parent'} || '--root';
3499        }
3500
3501        # read commitdiff
3502        my $fd;
3503        my @difftree;
3504        if ($format eq 'html') {
3505                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3506                        "--patch-with-raw", "--full-index", $hash_parent, $hash
3507                        or die_error(undef, "Open git-diff-tree failed");
3508
3509                while (chomp(my $line = <$fd>)) {
3510                        # empty line ends raw part of diff-tree output
3511                        last unless $line;
3512                        # filter out commit ID output
3513                        push @difftree, $line
3514                                unless $line =~ m/^[0-9a-fA-F]{40}$/;
3515                }
3516
3517        } elsif ($format eq 'plain') {
3518                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3519                        '-p', $hash_parent, $hash
3520                        or die_error(undef, "Open git-diff-tree failed");
3521
3522        } else {
3523                die_error(undef, "Unknown commitdiff format");
3524        }
3525
3526        # non-textual hash id's can be cached
3527        my $expires;
3528        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3529                $expires = "+1d";
3530        }
3531
3532        # write commit message
3533        if ($format eq 'html') {
3534                my $refs = git_get_references();
3535                my $ref = format_ref_marker($refs, $co{'id'});
3536                my $formats_nav =
3537                        $cgi->a({-href => href(action=>"commitdiff_plain",
3538                                               hash=>$hash, hash_parent=>$hash_parent)},
3539                                "raw");
3540
3541                git_header_html(undef, $expires);
3542                git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
3543                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
3544                git_print_authorship(\%co);
3545                print "<div class=\"page_body\">\n";
3546                if (@{$co{'comment'}} > 1) {
3547                        print "<div class=\"log\">\n";
3548                        git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
3549                        print "</div>\n"; # class="log"
3550                }
3551
3552        } elsif ($format eq 'plain') {
3553                my $refs = git_get_references("tags");
3554                my $tagname = git_get_rev_name_tags($hash);
3555                my $filename = basename($project) . "-$hash.patch";
3556
3557                print $cgi->header(
3558                        -type => 'text/plain',
3559                        -charset => 'utf-8',
3560                        -expires => $expires,
3561                        -content_disposition => 'inline; filename="' . "$filename" . '"');
3562                my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3563                print <<TEXT;
3564From: $co{'author'}
3565Date: $ad{'rfc2822'} ($ad{'tz_local'})
3566Subject: $co{'title'}
3567TEXT
3568                print "X-Git-Tag: $tagname\n" if $tagname;
3569                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3570
3571                foreach my $line (@{$co{'comment'}}) {
3572                        print "$line\n";
3573                }
3574                print "---\n\n";
3575        }
3576
3577        # write patch
3578        if ($format eq 'html') {
3579                git_difftree_body(\@difftree, $hash, $hash_parent);
3580                print "<br/>\n";
3581
3582                git_patchset_body($fd, \@difftree, $hash, $hash_parent);
3583                close $fd;
3584                print "</div>\n"; # class="page_body"
3585                git_footer_html();
3586
3587        } elsif ($format eq 'plain') {
3588                local $/ = undef;
3589                print <$fd>;
3590                close $fd
3591                        or print "Reading git-diff-tree failed\n";
3592        }
3593}
3594
3595sub git_commitdiff_plain {
3596        git_commitdiff('plain');
3597}
3598
3599sub git_history {
3600        if (!defined $hash_base) {
3601                $hash_base = git_get_head_hash($project);
3602        }
3603        if (!defined $page) {
3604                $page = 0;
3605        }
3606        my $ftype;
3607        my %co = parse_commit($hash_base);
3608        if (!%co) {
3609                die_error(undef, "Unknown commit object");
3610        }
3611
3612        my $refs = git_get_references();
3613        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3614
3615        if (!defined $hash && defined $file_name) {
3616                $hash = git_get_hash_by_path($hash_base, $file_name);
3617        }
3618        if (defined $hash) {
3619                $ftype = git_get_type($hash);
3620        }
3621
3622        open my $fd, "-|",
3623                git_cmd(), "rev-list", $limit, "--full-history", $hash_base, "--", $file_name
3624                        or die_error(undef, "Open git-rev-list-failed");
3625        my @revlist = map { chomp; $_ } <$fd>;
3626        close $fd
3627                or die_error(undef, "Reading git-rev-list failed");
3628
3629        my $paging_nav = '';
3630        if ($page > 0) {
3631                $paging_nav .=
3632                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3633                                               file_name=>$file_name)},
3634                                "first");
3635                $paging_nav .= " &sdot; " .
3636                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3637                                               file_name=>$file_name, page=>$page-1),
3638                                 -accesskey => "p", -title => "Alt-p"}, "prev");
3639        } else {
3640                $paging_nav .= "first";
3641                $paging_nav .= " &sdot; prev";
3642        }
3643        if ($#revlist >= (100 * ($page+1)-1)) {
3644                $paging_nav .= " &sdot; " .
3645                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3646                                               file_name=>$file_name, page=>$page+1),
3647                                 -accesskey => "n", -title => "Alt-n"}, "next");
3648        } else {
3649                $paging_nav .= " &sdot; next";
3650        }
3651        my $next_link = '';
3652        if ($#revlist >= (100 * ($page+1)-1)) {
3653                $next_link =
3654                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3655                                               file_name=>$file_name, page=>$page+1),
3656                                 -title => "Alt-n"}, "next");
3657        }
3658
3659        git_header_html();
3660        git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
3661        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3662        git_print_page_path($file_name, $ftype, $hash_base);
3663
3664        git_history_body(\@revlist, ($page * 100), $#revlist,
3665                         $refs, $hash_base, $ftype, $next_link);
3666
3667        git_footer_html();
3668}
3669
3670sub git_search {
3671        if (!defined $searchtext) {
3672                die_error(undef, "Text field empty");
3673        }
3674        if (!defined $hash) {
3675                $hash = git_get_head_hash($project);
3676        }
3677        my %co = parse_commit($hash);
3678        if (!%co) {
3679                die_error(undef, "Unknown commit object");
3680        }
3681
3682        $searchtype ||= 'commit';
3683        if ($searchtype eq 'pickaxe') {
3684                # pickaxe may take all resources of your box and run for several minutes
3685                # with every query - so decide by yourself how public you make this feature
3686                my ($have_pickaxe) = gitweb_check_feature('pickaxe');
3687                if (!$have_pickaxe) {
3688                        die_error('403 Permission denied', "Permission denied");
3689                }
3690        }
3691
3692        git_header_html();
3693        git_print_page_nav('','', $hash,$co{'tree'},$hash);
3694        git_print_header_div('commit', esc_html($co{'title'}), $hash);
3695
3696        print "<table cellspacing=\"0\">\n";
3697        my $alternate = 1;
3698        if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
3699                $/ = "\0";
3700                open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", $hash or next;
3701                while (my $commit_text = <$fd>) {
3702                        if (!grep m/$searchtext/i, $commit_text) {
3703                                next;
3704                        }
3705                        if ($searchtype eq 'author' && !grep m/\nauthor .*$searchtext/i, $commit_text) {
3706                                next;
3707                        }
3708                        if ($searchtype eq 'committer' && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
3709                                next;
3710                        }
3711                        my @commit_lines = split "\n", $commit_text;
3712                        my %co = parse_commit(undef, \@commit_lines);
3713                        if (!%co) {
3714                                next;
3715                        }
3716                        if ($alternate) {
3717                                print "<tr class=\"dark\">\n";
3718                        } else {
3719                                print "<tr class=\"light\">\n";
3720                        }
3721                        $alternate ^= 1;
3722                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3723                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3724                              "<td>" .
3725                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3726                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3727                        my $comment = $co{'comment'};
3728                        foreach my $line (@$comment) {
3729                                if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
3730                                        my $lead = esc_html($1) || "";
3731                                        $lead = chop_str($lead, 30, 10);
3732                                        my $match = esc_html($2) || "";
3733                                        my $trail = esc_html($3) || "";
3734                                        $trail = chop_str($trail, 30, 10);
3735                                        my $text = "$lead<span class=\"match\">$match</span>$trail";
3736                                        print chop_str($text, 80, 5) . "<br/>\n";
3737                                }
3738                        }
3739                        print "</td>\n" .
3740                              "<td class=\"link\">" .
3741                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3742                              " | " .
3743                              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3744                        print "</td>\n" .
3745                              "</tr>\n";
3746                }
3747                close $fd;
3748        }
3749
3750        if ($searchtype eq 'pickaxe') {
3751                $/ = "\n";
3752                my $git_command = git_cmd_str();
3753                open my $fd, "-|", "$git_command rev-list $hash | " .
3754                        "$git_command diff-tree -r --stdin -S\'$searchtext\'";
3755                undef %co;
3756                my @files;
3757                while (my $line = <$fd>) {
3758                        if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
3759                                my %set;
3760                                $set{'file'} = $6;
3761                                $set{'from_id'} = $3;
3762                                $set{'to_id'} = $4;
3763                                $set{'id'} = $set{'to_id'};
3764                                if ($set{'id'} =~ m/0{40}/) {
3765                                        $set{'id'} = $set{'from_id'};
3766                                }
3767                                if ($set{'id'} =~ m/0{40}/) {
3768                                        next;
3769                                }
3770                                push @files, \%set;
3771                        } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
3772                                if (%co) {
3773                                        if ($alternate) {
3774                                                print "<tr class=\"dark\">\n";
3775                                        } else {
3776                                                print "<tr class=\"light\">\n";
3777                                        }
3778                                        $alternate ^= 1;
3779                                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3780                                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3781                                              "<td>" .
3782                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
3783                                                      -class => "list subject"},
3784                                                      esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3785                                        while (my $setref = shift @files) {
3786                                                my %set = %$setref;
3787                                                print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
3788                                                                             hash=>$set{'id'}, file_name=>$set{'file'}),
3789                                                              -class => "list"},
3790                                                              "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
3791                                                      "<br/>\n";
3792                                        }
3793                                        print "</td>\n" .
3794                                              "<td class=\"link\">" .
3795                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3796                                              " | " .
3797                                              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3798                                        print "</td>\n" .
3799                                              "</tr>\n";
3800                                }
3801                                %co = parse_commit($1);
3802                        }
3803                }
3804                close $fd;
3805        }
3806        print "</table>\n";
3807        git_footer_html();
3808}
3809
3810sub git_search_help {
3811        git_header_html();
3812        git_print_page_nav('','', $hash,$hash,$hash);
3813        print <<EOT;
3814<dl>
3815<dt><b>commit</b></dt>
3816<dd>The commit messages and authorship information will be scanned for the given string.</dd>
3817<dt><b>author</b></dt>
3818<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given string.</dd>
3819<dt><b>committer</b></dt>
3820<dd>Name and e-mail of the committer and date of commit will be scanned for the given string.</dd>
3821EOT
3822        my ($have_pickaxe) = gitweb_check_feature('pickaxe');
3823        if ($have_pickaxe) {
3824                print <<EOT;
3825<dt><b>pickaxe</b></dt>
3826<dd>All commits that caused the string to appear or disappear from any file (changes that
3827added, removed or "modified" the string) will be listed. This search can take a while and
3828takes a lot of strain on the server, so please use it wisely.</dd>
3829EOT
3830        }
3831        print "</dl>\n";
3832        git_footer_html();
3833}
3834
3835sub git_shortlog {
3836        my $head = git_get_head_hash($project);
3837        if (!defined $hash) {
3838                $hash = $head;
3839        }
3840        if (!defined $page) {
3841                $page = 0;
3842        }
3843        my $refs = git_get_references();
3844
3845        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3846        open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
3847                or die_error(undef, "Open git-rev-list failed");
3848        my @revlist = map { chomp; $_ } <$fd>;
3849        close $fd;
3850
3851        my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
3852        my $next_link = '';
3853        if ($#revlist >= (100 * ($page+1)-1)) {
3854                $next_link =
3855                        $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
3856                                 -title => "Alt-n"}, "next");
3857        }
3858
3859
3860        git_header_html();
3861        git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
3862        git_print_header_div('summary', $project);
3863
3864        git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
3865
3866        git_footer_html();
3867}
3868
3869## ......................................................................
3870## feeds (RSS, OPML)
3871
3872sub git_rss {
3873        # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
3874        open my $fd, "-|", git_cmd(), "rev-list", "--max-count=150", git_get_head_hash($project)
3875                or die_error(undef, "Open git-rev-list failed");
3876        my @revlist = map { chomp; $_ } <$fd>;
3877        close $fd or die_error(undef, "Reading git-rev-list failed");
3878        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3879        print <<XML;
3880<?xml version="1.0" encoding="utf-8"?>
3881<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
3882<channel>
3883<title>$project $my_uri $my_url</title>
3884<link>${\esc_html("$my_url?p=$project;a=summary")}</link>
3885<description>$project log</description>
3886<language>en</language>
3887XML
3888
3889        for (my $i = 0; $i <= $#revlist; $i++) {
3890                my $commit = $revlist[$i];
3891                my %co = parse_commit($commit);
3892                # we read 150, we always show 30 and the ones more recent than 48 hours
3893                if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
3894                        last;
3895                }
3896                my %cd = parse_date($co{'committer_epoch'});
3897                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3898                        $co{'parent'}, $co{'id'}
3899                        or next;
3900                my @difftree = map { chomp; $_ } <$fd>;
3901                close $fd
3902                        or next;
3903                print "<item>\n" .
3904                      "<title>" .
3905                      sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
3906                      "</title>\n" .
3907                      "<author>" . esc_html($co{'author'}) . "</author>\n" .
3908                      "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
3909                      "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
3910                      "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
3911                      "<description>" . esc_html($co{'title'}) . "</description>\n" .
3912                      "<content:encoded>" .
3913                      "<![CDATA[\n";
3914                my $comment = $co{'comment'};
3915                foreach my $line (@$comment) {
3916                        $line = to_utf8($line);
3917                        print "$line<br/>\n";
3918                }
3919                print "<br/>\n";
3920                foreach my $line (@difftree) {
3921                        if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
3922                                next;
3923                        }
3924                        my $file = esc_html(unquote($7));
3925                        $file = to_utf8($file);
3926                        print "$file<br/>\n";
3927                }
3928                print "]]>\n" .
3929                      "</content:encoded>\n" .
3930                      "</item>\n";
3931        }
3932        print "</channel></rss>";
3933}
3934
3935sub git_opml {
3936        my @list = git_get_projects_list();
3937
3938        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3939        print <<XML;
3940<?xml version="1.0" encoding="utf-8"?>
3941<opml version="1.0">
3942<head>
3943  <title>$site_name OPML Export</title>
3944</head>
3945<body>
3946<outline text="git RSS feeds">
3947XML
3948
3949        foreach my $pr (@list) {
3950                my %proj = %$pr;
3951                my $head = git_get_head_hash($proj{'path'});
3952                if (!defined $head) {
3953                        next;
3954                }
3955                $git_dir = "$projectroot/$proj{'path'}";
3956                my %co = parse_commit($head);
3957                if (!%co) {
3958                        next;
3959                }
3960
3961                my $path = esc_html(chop_str($proj{'path'}, 25, 5));
3962                my $rss  = "$my_url?p=$proj{'path'};a=rss";
3963                my $html = "$my_url?p=$proj{'path'};a=summary";
3964                print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
3965        }
3966        print <<XML;
3967</outline>
3968</body>
3969</opml>
3970XML
3971}