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