gitweb / gitweb.perlon commit Merge branch 'maint-1.5.1' into maint (baf5597)
   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
  21BEGIN {
  22        CGI->compile() if $ENV{'MOD_PERL'};
  23}
  24
  25our $cgi = new CGI;
  26our $version = "++GIT_VERSION++";
  27our $my_url = $cgi->url();
  28our $my_uri = $cgi->url(-absolute => 1);
  29
  30# core git executable to use
  31# this can just be "git" if your webserver has a sensible PATH
  32our $GIT = "++GIT_BINDIR++/git";
  33
  34# absolute fs-path which will be prepended to the project path
  35#our $projectroot = "/pub/scm";
  36our $projectroot = "++GITWEB_PROJECTROOT++";
  37
  38# target of the home link on top of all pages
  39our $home_link = $my_uri || "/";
  40
  41# string of the home link on top of all pages
  42our $home_link_str = "++GITWEB_HOME_LINK_STR++";
  43
  44# name of your site or organization to appear in page titles
  45# replace this with something more descriptive for clearer bookmarks
  46our $site_name = "++GITWEB_SITENAME++"
  47                 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
  48
  49# filename of html text to include at top of each page
  50our $site_header = "++GITWEB_SITE_HEADER++";
  51# html text to include at home page
  52our $home_text = "++GITWEB_HOMETEXT++";
  53# filename of html text to include at bottom of each page
  54our $site_footer = "++GITWEB_SITE_FOOTER++";
  55
  56# URI of stylesheets
  57our @stylesheets = ("++GITWEB_CSS++");
  58# URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
  59our $stylesheet = undef;
  60# URI of GIT logo (72x27 size)
  61our $logo = "++GITWEB_LOGO++";
  62# URI of GIT favicon, assumed to be image/png type
  63our $favicon = "++GITWEB_FAVICON++";
  64
  65# URI and label (title) of GIT logo link
  66#our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
  67#our $logo_label = "git documentation";
  68our $logo_url = "http://git.or.cz/";
  69our $logo_label = "git homepage";
  70
  71# source of projects list
  72our $projects_list = "++GITWEB_LIST++";
  73
  74# default order of projects list
  75# valid values are none, project, descr, owner, and age
  76our $default_projects_order = "project";
  77
  78# show repository only if this file exists
  79# (only effective if this variable evaluates to true)
  80our $export_ok = "++GITWEB_EXPORT_OK++";
  81
  82# only allow viewing of repositories also shown on the overview page
  83our $strict_export = "++GITWEB_STRICT_EXPORT++";
  84
  85# list of git base URLs used for URL to where fetch project from,
  86# i.e. full URL is "$git_base_url/$project"
  87our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
  88
  89# default blob_plain mimetype and default charset for text/plain blob
  90our $default_blob_plain_mimetype = 'text/plain';
  91our $default_text_plain_charset  = undef;
  92
  93# file to use for guessing MIME types before trying /etc/mime.types
  94# (relative to the current git repository)
  95our $mimetypes_file = undef;
  96
  97# You define site-wide feature defaults here; override them with
  98# $GITWEB_CONFIG as necessary.
  99our %feature = (
 100        # feature => {
 101        #       'sub' => feature-sub (subroutine),
 102        #       'override' => allow-override (boolean),
 103        #       'default' => [ default options...] (array reference)}
 104        #
 105        # if feature is overridable (it means that allow-override has true value),
 106        # then feature-sub will be called with default options as parameters;
 107        # return value of feature-sub indicates if to enable specified feature
 108        #
 109        # if there is no 'sub' key (no feature-sub), then feature cannot be
 110        # overriden
 111        #
 112        # use gitweb_check_feature(<feature>) to check if <feature> is enabled
 113
 114        # Enable the 'blame' blob view, showing the last commit that modified
 115        # each line in the file. This can be very CPU-intensive.
 116
 117        # To enable system wide have in $GITWEB_CONFIG
 118        # $feature{'blame'}{'default'} = [1];
 119        # To have project specific config enable override in $GITWEB_CONFIG
 120        # $feature{'blame'}{'override'} = 1;
 121        # and in project config gitweb.blame = 0|1;
 122        'blame' => {
 123                'sub' => \&feature_blame,
 124                'override' => 0,
 125                'default' => [0]},
 126
 127        # Enable the 'snapshot' link, providing a compressed tarball of any
 128        # tree. This can potentially generate high traffic if you have large
 129        # project.
 130
 131        # To disable system wide have in $GITWEB_CONFIG
 132        # $feature{'snapshot'}{'default'} = [undef];
 133        # To have project specific config enable override in $GITWEB_CONFIG
 134        # $feature{'snapshot'}{'override'} = 1;
 135        # and in project config gitweb.snapshot = none|gzip|bzip2;
 136        'snapshot' => {
 137                'sub' => \&feature_snapshot,
 138                'override' => 0,
 139                #         => [content-encoding, suffix, program]
 140                'default' => ['x-gzip', 'gz', 'gzip']},
 141
 142        # Enable text search, which will list the commits which match author,
 143        # committer or commit text to a given string.  Enabled by default.
 144        # Project specific override is not supported.
 145        'search' => {
 146                'override' => 0,
 147                'default' => [1]},
 148
 149        # Enable grep search, which will list the files in currently selected
 150        # tree containing the given string. Enabled by default. This can be
 151        # potentially CPU-intensive, of course.
 152
 153        # To enable system wide have in $GITWEB_CONFIG
 154        # $feature{'grep'}{'default'} = [1];
 155        # To have project specific config enable override in $GITWEB_CONFIG
 156        # $feature{'grep'}{'override'} = 1;
 157        # and in project config gitweb.grep = 0|1;
 158        'grep' => {
 159                'override' => 0,
 160                'default' => [1]},
 161
 162        # Enable the pickaxe search, which will list the commits that modified
 163        # a given string in a file. This can be practical and quite faster
 164        # alternative to 'blame', but still potentially CPU-intensive.
 165
 166        # To enable system wide have in $GITWEB_CONFIG
 167        # $feature{'pickaxe'}{'default'} = [1];
 168        # To have project specific config enable override in $GITWEB_CONFIG
 169        # $feature{'pickaxe'}{'override'} = 1;
 170        # and in project config gitweb.pickaxe = 0|1;
 171        'pickaxe' => {
 172                'sub' => \&feature_pickaxe,
 173                'override' => 0,
 174                'default' => [1]},
 175
 176        # Make gitweb use an alternative format of the URLs which can be
 177        # more readable and natural-looking: project name is embedded
 178        # directly in the path and the query string contains other
 179        # auxiliary information. All gitweb installations recognize
 180        # URL in either format; this configures in which formats gitweb
 181        # generates links.
 182
 183        # To enable system wide have in $GITWEB_CONFIG
 184        # $feature{'pathinfo'}{'default'} = [1];
 185        # Project specific override is not supported.
 186
 187        # Note that you will need to change the default location of CSS,
 188        # favicon, logo and possibly other files to an absolute URL. Also,
 189        # if gitweb.cgi serves as your indexfile, you will need to force
 190        # $my_uri to contain the script name in your $GITWEB_CONFIG.
 191        'pathinfo' => {
 192                'override' => 0,
 193                'default' => [0]},
 194
 195        # Make gitweb consider projects in project root subdirectories
 196        # to be forks of existing projects. Given project $projname.git,
 197        # projects matching $projname/*.git will not be shown in the main
 198        # projects list, instead a '+' mark will be added to $projname
 199        # there and a 'forks' view will be enabled for the project, listing
 200        # all the forks. If project list is taken from a file, forks have
 201        # to be listed after the main project.
 202
 203        # To enable system wide have in $GITWEB_CONFIG
 204        # $feature{'forks'}{'default'} = [1];
 205        # Project specific override is not supported.
 206        'forks' => {
 207                'override' => 0,
 208                'default' => [0]},
 209);
 210
 211sub gitweb_check_feature {
 212        my ($name) = @_;
 213        return unless exists $feature{$name};
 214        my ($sub, $override, @defaults) = (
 215                $feature{$name}{'sub'},
 216                $feature{$name}{'override'},
 217                @{$feature{$name}{'default'}});
 218        if (!$override) { return @defaults; }
 219        if (!defined $sub) {
 220                warn "feature $name is not overrideable";
 221                return @defaults;
 222        }
 223        return $sub->(@defaults);
 224}
 225
 226sub feature_blame {
 227        my ($val) = git_get_project_config('blame', '--bool');
 228
 229        if ($val eq 'true') {
 230                return 1;
 231        } elsif ($val eq 'false') {
 232                return 0;
 233        }
 234
 235        return $_[0];
 236}
 237
 238sub feature_snapshot {
 239        my ($ctype, $suffix, $command) = @_;
 240
 241        my ($val) = git_get_project_config('snapshot');
 242
 243        if ($val eq 'gzip') {
 244                return ('x-gzip', 'gz', 'gzip');
 245        } elsif ($val eq 'bzip2') {
 246                return ('x-bzip2', 'bz2', 'bzip2');
 247        } elsif ($val eq 'none') {
 248                return ();
 249        }
 250
 251        return ($ctype, $suffix, $command);
 252}
 253
 254sub gitweb_have_snapshot {
 255        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
 256        my $have_snapshot = (defined $ctype && defined $suffix);
 257
 258        return $have_snapshot;
 259}
 260
 261sub feature_grep {
 262        my ($val) = git_get_project_config('grep', '--bool');
 263
 264        if ($val eq 'true') {
 265                return (1);
 266        } elsif ($val eq 'false') {
 267                return (0);
 268        }
 269
 270        return ($_[0]);
 271}
 272
 273sub feature_pickaxe {
 274        my ($val) = git_get_project_config('pickaxe', '--bool');
 275
 276        if ($val eq 'true') {
 277                return (1);
 278        } elsif ($val eq 'false') {
 279                return (0);
 280        }
 281
 282        return ($_[0]);
 283}
 284
 285# checking HEAD file with -e is fragile if the repository was
 286# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
 287# and then pruned.
 288sub check_head_link {
 289        my ($dir) = @_;
 290        my $headfile = "$dir/HEAD";
 291        return ((-e $headfile) ||
 292                (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
 293}
 294
 295sub check_export_ok {
 296        my ($dir) = @_;
 297        return (check_head_link($dir) &&
 298                (!$export_ok || -e "$dir/$export_ok"));
 299}
 300
 301# rename detection options for git-diff and git-diff-tree
 302# - default is '-M', with the cost proportional to
 303#   (number of removed files) * (number of new files).
 304# - more costly is '-C' (or '-C', '-M'), with the cost proportional to
 305#   (number of changed files + number of removed files) * (number of new files)
 306# - even more costly is '-C', '--find-copies-harder' with cost
 307#   (number of files in the original tree) * (number of new files)
 308# - one might want to include '-B' option, e.g. '-B', '-M'
 309our @diff_opts = ('-M'); # taken from git_commit
 310
 311our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
 312do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
 313
 314# version of the core git binary
 315our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
 316
 317$projects_list ||= $projectroot;
 318
 319# ======================================================================
 320# input validation and dispatch
 321our $action = $cgi->param('a');
 322if (defined $action) {
 323        if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
 324                die_error(undef, "Invalid action parameter");
 325        }
 326}
 327
 328# parameters which are pathnames
 329our $project = $cgi->param('p');
 330if (defined $project) {
 331        if (!validate_pathname($project) ||
 332            !(-d "$projectroot/$project") ||
 333            !check_head_link("$projectroot/$project") ||
 334            ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
 335            ($strict_export && !project_in_list($project))) {
 336                undef $project;
 337                die_error(undef, "No such project");
 338        }
 339}
 340
 341our $file_name = $cgi->param('f');
 342if (defined $file_name) {
 343        if (!validate_pathname($file_name)) {
 344                die_error(undef, "Invalid file parameter");
 345        }
 346}
 347
 348our $file_parent = $cgi->param('fp');
 349if (defined $file_parent) {
 350        if (!validate_pathname($file_parent)) {
 351                die_error(undef, "Invalid file parent parameter");
 352        }
 353}
 354
 355# parameters which are refnames
 356our $hash = $cgi->param('h');
 357if (defined $hash) {
 358        if (!validate_refname($hash)) {
 359                die_error(undef, "Invalid hash parameter");
 360        }
 361}
 362
 363our $hash_parent = $cgi->param('hp');
 364if (defined $hash_parent) {
 365        if (!validate_refname($hash_parent)) {
 366                die_error(undef, "Invalid hash parent parameter");
 367        }
 368}
 369
 370our $hash_base = $cgi->param('hb');
 371if (defined $hash_base) {
 372        if (!validate_refname($hash_base)) {
 373                die_error(undef, "Invalid hash base parameter");
 374        }
 375}
 376
 377our $hash_parent_base = $cgi->param('hpb');
 378if (defined $hash_parent_base) {
 379        if (!validate_refname($hash_parent_base)) {
 380                die_error(undef, "Invalid hash parent base parameter");
 381        }
 382}
 383
 384# other parameters
 385our $page = $cgi->param('pg');
 386if (defined $page) {
 387        if ($page =~ m/[^0-9]/) {
 388                die_error(undef, "Invalid page parameter");
 389        }
 390}
 391
 392our $searchtype = $cgi->param('st');
 393if (defined $searchtype) {
 394        if ($searchtype =~ m/[^a-z]/) {
 395                die_error(undef, "Invalid searchtype parameter");
 396        }
 397}
 398
 399our $searchtext = $cgi->param('s');
 400our $search_regexp;
 401if (defined $searchtext) {
 402        if ($searchtype ne 'grep' and $searchtype ne 'pickaxe' and $searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
 403                die_error(undef, "Invalid search parameter");
 404        }
 405        if (length($searchtext) < 2) {
 406                die_error(undef, "At least two characters are required for search parameter");
 407        }
 408        $search_regexp = quotemeta $searchtext;
 409}
 410
 411# now read PATH_INFO and use it as alternative to parameters
 412sub evaluate_path_info {
 413        return if defined $project;
 414        my $path_info = $ENV{"PATH_INFO"};
 415        return if !$path_info;
 416        $path_info =~ s,^/+,,;
 417        return if !$path_info;
 418        # find which part of PATH_INFO is project
 419        $project = $path_info;
 420        $project =~ s,/+$,,;
 421        while ($project && !check_head_link("$projectroot/$project")) {
 422                $project =~ s,/*[^/]*$,,;
 423        }
 424        # validate project
 425        $project = validate_pathname($project);
 426        if (!$project ||
 427            ($export_ok && !-e "$projectroot/$project/$export_ok") ||
 428            ($strict_export && !project_in_list($project))) {
 429                undef $project;
 430                return;
 431        }
 432        # do not change any parameters if an action is given using the query string
 433        return if $action;
 434        $path_info =~ s,^$project/*,,;
 435        my ($refname, $pathname) = split(/:/, $path_info, 2);
 436        if (defined $pathname) {
 437                # we got "project.git/branch:filename" or "project.git/branch:dir/"
 438                # we could use git_get_type(branch:pathname), but it needs $git_dir
 439                $pathname =~ s,^/+,,;
 440                if (!$pathname || substr($pathname, -1) eq "/") {
 441                        $action  ||= "tree";
 442                        $pathname =~ s,/$,,;
 443                } else {
 444                        $action  ||= "blob_plain";
 445                }
 446                $hash_base ||= validate_refname($refname);
 447                $file_name ||= validate_pathname($pathname);
 448        } elsif (defined $refname) {
 449                # we got "project.git/branch"
 450                $action ||= "shortlog";
 451                $hash   ||= validate_refname($refname);
 452        }
 453}
 454evaluate_path_info();
 455
 456# path to the current git repository
 457our $git_dir;
 458$git_dir = "$projectroot/$project" if $project;
 459
 460# dispatch
 461my %actions = (
 462        "blame" => \&git_blame2,
 463        "blobdiff" => \&git_blobdiff,
 464        "blobdiff_plain" => \&git_blobdiff_plain,
 465        "blob" => \&git_blob,
 466        "blob_plain" => \&git_blob_plain,
 467        "commitdiff" => \&git_commitdiff,
 468        "commitdiff_plain" => \&git_commitdiff_plain,
 469        "commit" => \&git_commit,
 470        "forks" => \&git_forks,
 471        "heads" => \&git_heads,
 472        "history" => \&git_history,
 473        "log" => \&git_log,
 474        "rss" => \&git_rss,
 475        "atom" => \&git_atom,
 476        "search" => \&git_search,
 477        "search_help" => \&git_search_help,
 478        "shortlog" => \&git_shortlog,
 479        "summary" => \&git_summary,
 480        "tag" => \&git_tag,
 481        "tags" => \&git_tags,
 482        "tree" => \&git_tree,
 483        "snapshot" => \&git_snapshot,
 484        "object" => \&git_object,
 485        # those below don't need $project
 486        "opml" => \&git_opml,
 487        "project_list" => \&git_project_list,
 488        "project_index" => \&git_project_index,
 489);
 490
 491if (!defined $action) {
 492        if (defined $hash) {
 493                $action = git_get_type($hash);
 494        } elsif (defined $hash_base && defined $file_name) {
 495                $action = git_get_type("$hash_base:$file_name");
 496        } elsif (defined $project) {
 497                $action = 'summary';
 498        } else {
 499                $action = 'project_list';
 500        }
 501}
 502if (!defined($actions{$action})) {
 503        die_error(undef, "Unknown action");
 504}
 505if ($action !~ m/^(opml|project_list|project_index)$/ &&
 506    !$project) {
 507        die_error(undef, "Project needed");
 508}
 509$actions{$action}->();
 510exit;
 511
 512## ======================================================================
 513## action links
 514
 515sub href(%) {
 516        my %params = @_;
 517        # default is to use -absolute url() i.e. $my_uri
 518        my $href = $params{-full} ? $my_url : $my_uri;
 519
 520        # XXX: Warning: If you touch this, check the search form for updating,
 521        # too.
 522
 523        my @mapping = (
 524                project => "p",
 525                action => "a",
 526                file_name => "f",
 527                file_parent => "fp",
 528                hash => "h",
 529                hash_parent => "hp",
 530                hash_base => "hb",
 531                hash_parent_base => "hpb",
 532                page => "pg",
 533                order => "o",
 534                searchtext => "s",
 535                searchtype => "st",
 536        );
 537        my %mapping = @mapping;
 538
 539        $params{'project'} = $project unless exists $params{'project'};
 540
 541        my ($use_pathinfo) = gitweb_check_feature('pathinfo');
 542        if ($use_pathinfo) {
 543                # use PATH_INFO for project name
 544                $href .= "/$params{'project'}" if defined $params{'project'};
 545                delete $params{'project'};
 546
 547                # Summary just uses the project path URL
 548                if (defined $params{'action'} && $params{'action'} eq 'summary') {
 549                        delete $params{'action'};
 550                }
 551        }
 552
 553        # now encode the parameters explicitly
 554        my @result = ();
 555        for (my $i = 0; $i < @mapping; $i += 2) {
 556                my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
 557                if (defined $params{$name}) {
 558                        push @result, $symbol . "=" . esc_param($params{$name});
 559                }
 560        }
 561        $href .= "?" . join(';', @result) if scalar @result;
 562
 563        return $href;
 564}
 565
 566
 567## ======================================================================
 568## validation, quoting/unquoting and escaping
 569
 570sub validate_pathname {
 571        my $input = shift || return undef;
 572
 573        # no '.' or '..' as elements of path, i.e. no '.' nor '..'
 574        # at the beginning, at the end, and between slashes.
 575        # also this catches doubled slashes
 576        if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
 577                return undef;
 578        }
 579        # no null characters
 580        if ($input =~ m!\0!) {
 581                return undef;
 582        }
 583        return $input;
 584}
 585
 586sub validate_refname {
 587        my $input = shift || return undef;
 588
 589        # textual hashes are O.K.
 590        if ($input =~ m/^[0-9a-fA-F]{40}$/) {
 591                return $input;
 592        }
 593        # it must be correct pathname
 594        $input = validate_pathname($input)
 595                or return undef;
 596        # restrictions on ref name according to git-check-ref-format
 597        if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
 598                return undef;
 599        }
 600        return $input;
 601}
 602
 603# quote unsafe chars, but keep the slash, even when it's not
 604# correct, but quoted slashes look too horrible in bookmarks
 605sub esc_param {
 606        my $str = shift;
 607        $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
 608        $str =~ s/\+/%2B/g;
 609        $str =~ s/ /\+/g;
 610        return $str;
 611}
 612
 613# quote unsafe chars in whole URL, so some charactrs cannot be quoted
 614sub esc_url {
 615        my $str = shift;
 616        $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
 617        $str =~ s/\+/%2B/g;
 618        $str =~ s/ /\+/g;
 619        return $str;
 620}
 621
 622# replace invalid utf8 character with SUBSTITUTION sequence
 623sub esc_html ($;%) {
 624        my $str = shift;
 625        my %opts = @_;
 626
 627        $str = decode_utf8($str);
 628        $str = $cgi->escapeHTML($str);
 629        if ($opts{'-nbsp'}) {
 630                $str =~ s/ /&nbsp;/g;
 631        }
 632        $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
 633        return $str;
 634}
 635
 636# quote control characters and escape filename to HTML
 637sub esc_path {
 638        my $str = shift;
 639        my %opts = @_;
 640
 641        $str = decode_utf8($str);
 642        $str = $cgi->escapeHTML($str);
 643        if ($opts{'-nbsp'}) {
 644                $str =~ s/ /&nbsp;/g;
 645        }
 646        $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
 647        return $str;
 648}
 649
 650# Make control characters "printable", using character escape codes (CEC)
 651sub quot_cec {
 652        my $cntrl = shift;
 653        my %es = ( # character escape codes, aka escape sequences
 654                   "\t" => '\t',   # tab            (HT)
 655                   "\n" => '\n',   # line feed      (LF)
 656                   "\r" => '\r',   # carrige return (CR)
 657                   "\f" => '\f',   # form feed      (FF)
 658                   "\b" => '\b',   # backspace      (BS)
 659                   "\a" => '\a',   # alarm (bell)   (BEL)
 660                   "\e" => '\e',   # escape         (ESC)
 661                   "\013" => '\v', # vertical tab   (VT)
 662                   "\000" => '\0', # nul character  (NUL)
 663                   );
 664        my $chr = ( (exists $es{$cntrl})
 665                    ? $es{$cntrl}
 666                    : sprintf('\%03o', ord($cntrl)) );
 667        return "<span class=\"cntrl\">$chr</span>";
 668}
 669
 670# Alternatively use unicode control pictures codepoints,
 671# Unicode "printable representation" (PR)
 672sub quot_upr {
 673        my $cntrl = shift;
 674        my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
 675        return "<span class=\"cntrl\">$chr</span>";
 676}
 677
 678# git may return quoted and escaped filenames
 679sub unquote {
 680        my $str = shift;
 681
 682        sub unq {
 683                my $seq = shift;
 684                my %es = ( # character escape codes, aka escape sequences
 685                        't' => "\t",   # tab            (HT, TAB)
 686                        'n' => "\n",   # newline        (NL)
 687                        'r' => "\r",   # return         (CR)
 688                        'f' => "\f",   # form feed      (FF)
 689                        'b' => "\b",   # backspace      (BS)
 690                        'a' => "\a",   # alarm (bell)   (BEL)
 691                        'e' => "\e",   # escape         (ESC)
 692                        'v' => "\013", # vertical tab   (VT)
 693                );
 694
 695                if ($seq =~ m/^[0-7]{1,3}$/) {
 696                        # octal char sequence
 697                        return chr(oct($seq));
 698                } elsif (exists $es{$seq}) {
 699                        # C escape sequence, aka character escape code
 700                        return $es{$seq}
 701                }
 702                # quoted ordinary character
 703                return $seq;
 704        }
 705
 706        if ($str =~ m/^"(.*)"$/) {
 707                # needs unquoting
 708                $str = $1;
 709                $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
 710        }
 711        return $str;
 712}
 713
 714# escape tabs (convert tabs to spaces)
 715sub untabify {
 716        my $line = shift;
 717
 718        while ((my $pos = index($line, "\t")) != -1) {
 719                if (my $count = (8 - ($pos % 8))) {
 720                        my $spaces = ' ' x $count;
 721                        $line =~ s/\t/$spaces/;
 722                }
 723        }
 724
 725        return $line;
 726}
 727
 728sub project_in_list {
 729        my $project = shift;
 730        my @list = git_get_projects_list();
 731        return @list && scalar(grep { $_->{'path'} eq $project } @list);
 732}
 733
 734## ----------------------------------------------------------------------
 735## HTML aware string manipulation
 736
 737sub chop_str {
 738        my $str = shift;
 739        my $len = shift;
 740        my $add_len = shift || 10;
 741
 742        # allow only $len chars, but don't cut a word if it would fit in $add_len
 743        # if it doesn't fit, cut it if it's still longer than the dots we would add
 744        $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
 745        my $body = $1;
 746        my $tail = $2;
 747        if (length($tail) > 4) {
 748                $tail = " ...";
 749                $body =~ s/&[^;]*$//; # remove chopped character entities
 750        }
 751        return "$body$tail";
 752}
 753
 754## ----------------------------------------------------------------------
 755## functions returning short strings
 756
 757# CSS class for given age value (in seconds)
 758sub age_class {
 759        my $age = shift;
 760
 761        if (!defined $age) {
 762                return "noage";
 763        } elsif ($age < 60*60*2) {
 764                return "age0";
 765        } elsif ($age < 60*60*24*2) {
 766                return "age1";
 767        } else {
 768                return "age2";
 769        }
 770}
 771
 772# convert age in seconds to "nn units ago" string
 773sub age_string {
 774        my $age = shift;
 775        my $age_str;
 776
 777        if ($age > 60*60*24*365*2) {
 778                $age_str = (int $age/60/60/24/365);
 779                $age_str .= " years ago";
 780        } elsif ($age > 60*60*24*(365/12)*2) {
 781                $age_str = int $age/60/60/24/(365/12);
 782                $age_str .= " months ago";
 783        } elsif ($age > 60*60*24*7*2) {
 784                $age_str = int $age/60/60/24/7;
 785                $age_str .= " weeks ago";
 786        } elsif ($age > 60*60*24*2) {
 787                $age_str = int $age/60/60/24;
 788                $age_str .= " days ago";
 789        } elsif ($age > 60*60*2) {
 790                $age_str = int $age/60/60;
 791                $age_str .= " hours ago";
 792        } elsif ($age > 60*2) {
 793                $age_str = int $age/60;
 794                $age_str .= " min ago";
 795        } elsif ($age > 2) {
 796                $age_str = int $age;
 797                $age_str .= " sec ago";
 798        } else {
 799                $age_str .= " right now";
 800        }
 801        return $age_str;
 802}
 803
 804# convert file mode in octal to symbolic file mode string
 805sub mode_str {
 806        my $mode = oct shift;
 807
 808        if (S_ISDIR($mode & S_IFMT)) {
 809                return 'drwxr-xr-x';
 810        } elsif (S_ISLNK($mode)) {
 811                return 'lrwxrwxrwx';
 812        } elsif (S_ISREG($mode)) {
 813                # git cares only about the executable bit
 814                if ($mode & S_IXUSR) {
 815                        return '-rwxr-xr-x';
 816                } else {
 817                        return '-rw-r--r--';
 818                };
 819        } else {
 820                return '----------';
 821        }
 822}
 823
 824# convert file mode in octal to file type string
 825sub file_type {
 826        my $mode = shift;
 827
 828        if ($mode !~ m/^[0-7]+$/) {
 829                return $mode;
 830        } else {
 831                $mode = oct $mode;
 832        }
 833
 834        if (S_ISDIR($mode & S_IFMT)) {
 835                return "directory";
 836        } elsif (S_ISLNK($mode)) {
 837                return "symlink";
 838        } elsif (S_ISREG($mode)) {
 839                return "file";
 840        } else {
 841                return "unknown";
 842        }
 843}
 844
 845# convert file mode in octal to file type description string
 846sub file_type_long {
 847        my $mode = shift;
 848
 849        if ($mode !~ m/^[0-7]+$/) {
 850                return $mode;
 851        } else {
 852                $mode = oct $mode;
 853        }
 854
 855        if (S_ISDIR($mode & S_IFMT)) {
 856                return "directory";
 857        } elsif (S_ISLNK($mode)) {
 858                return "symlink";
 859        } elsif (S_ISREG($mode)) {
 860                if ($mode & S_IXUSR) {
 861                        return "executable";
 862                } else {
 863                        return "file";
 864                };
 865        } else {
 866                return "unknown";
 867        }
 868}
 869
 870
 871## ----------------------------------------------------------------------
 872## functions returning short HTML fragments, or transforming HTML fragments
 873## which don't belong to other sections
 874
 875# format line of commit message.
 876sub format_log_line_html {
 877        my $line = shift;
 878
 879        $line = esc_html($line, -nbsp=>1);
 880        if ($line =~ m/([0-9a-fA-F]{8,40})/) {
 881                my $hash_text = $1;
 882                my $link =
 883                        $cgi->a({-href => href(action=>"object", hash=>$hash_text),
 884                                -class => "text"}, $hash_text);
 885                $line =~ s/$hash_text/$link/;
 886        }
 887        return $line;
 888}
 889
 890# format marker of refs pointing to given object
 891sub format_ref_marker {
 892        my ($refs, $id) = @_;
 893        my $markers = '';
 894
 895        if (defined $refs->{$id}) {
 896                foreach my $ref (@{$refs->{$id}}) {
 897                        my ($type, $name) = qw();
 898                        # e.g. tags/v2.6.11 or heads/next
 899                        if ($ref =~ m!^(.*?)s?/(.*)$!) {
 900                                $type = $1;
 901                                $name = $2;
 902                        } else {
 903                                $type = "ref";
 904                                $name = $ref;
 905                        }
 906
 907                        $markers .= " <span class=\"$type\" title=\"$ref\">" .
 908                                    esc_html($name) . "</span>";
 909                }
 910        }
 911
 912        if ($markers) {
 913                return ' <span class="refs">'. $markers . '</span>';
 914        } else {
 915                return "";
 916        }
 917}
 918
 919# format, perhaps shortened and with markers, title line
 920sub format_subject_html {
 921        my ($long, $short, $href, $extra) = @_;
 922        $extra = '' unless defined($extra);
 923
 924        if (length($short) < length($long)) {
 925                return $cgi->a({-href => $href, -class => "list subject",
 926                                -title => decode_utf8($long)},
 927                       esc_html($short) . $extra);
 928        } else {
 929                return $cgi->a({-href => $href, -class => "list subject"},
 930                       esc_html($long)  . $extra);
 931        }
 932}
 933
 934# format patch (diff) line (rather not to be used for diff headers)
 935sub format_diff_line {
 936        my $line = shift;
 937        my ($from, $to) = @_;
 938        my $diff_class = "";
 939
 940        chomp $line;
 941
 942        if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
 943                # combined diff
 944                my $prefix = substr($line, 0, scalar @{$from->{'href'}});
 945                if ($line =~ m/^\@{3}/) {
 946                        $diff_class = " chunk_header";
 947                } elsif ($line =~ m/^\\/) {
 948                        $diff_class = " incomplete";
 949                } elsif ($prefix =~ tr/+/+/) {
 950                        $diff_class = " add";
 951                } elsif ($prefix =~ tr/-/-/) {
 952                        $diff_class = " rem";
 953                }
 954        } else {
 955                # assume ordinary diff
 956                my $char = substr($line, 0, 1);
 957                if ($char eq '+') {
 958                        $diff_class = " add";
 959                } elsif ($char eq '-') {
 960                        $diff_class = " rem";
 961                } elsif ($char eq '@') {
 962                        $diff_class = " chunk_header";
 963                } elsif ($char eq "\\") {
 964                        $diff_class = " incomplete";
 965                }
 966        }
 967        $line = untabify($line);
 968        if ($from && $to && $line =~ m/^\@{2} /) {
 969                my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
 970                        $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
 971
 972                $from_lines = 0 unless defined $from_lines;
 973                $to_lines   = 0 unless defined $to_lines;
 974
 975                if ($from->{'href'}) {
 976                        $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
 977                                             -class=>"list"}, $from_text);
 978                }
 979                if ($to->{'href'}) {
 980                        $to_text   = $cgi->a({-href=>"$to->{'href'}#l$to_start",
 981                                             -class=>"list"}, $to_text);
 982                }
 983                $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
 984                        "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
 985                return "<div class=\"diff$diff_class\">$line</div>\n";
 986        } elsif ($from && $to && $line =~ m/^\@{3}/) {
 987                my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
 988                my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
 989
 990                @from_text = split(' ', $ranges);
 991                for (my $i = 0; $i < @from_text; ++$i) {
 992                        ($from_start[$i], $from_nlines[$i]) =
 993                                (split(',', substr($from_text[$i], 1)), 0);
 994                }
 995
 996                $to_text   = pop @from_text;
 997                $to_start  = pop @from_start;
 998                $to_nlines = pop @from_nlines;
 999
1000                $line = "<span class=\"chunk_info\">$prefix ";
1001                for (my $i = 0; $i < @from_text; ++$i) {
1002                        if ($from->{'href'}[$i]) {
1003                                $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1004                                                  -class=>"list"}, $from_text[$i]);
1005                        } else {
1006                                $line .= $from_text[$i];
1007                        }
1008                        $line .= " ";
1009                }
1010                if ($to->{'href'}) {
1011                        $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1012                                          -class=>"list"}, $to_text);
1013                } else {
1014                        $line .= $to_text;
1015                }
1016                $line .= " $prefix</span>" .
1017                         "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1018                return "<div class=\"diff$diff_class\">$line</div>\n";
1019        }
1020        return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1021}
1022
1023## ----------------------------------------------------------------------
1024## git utility subroutines, invoking git commands
1025
1026# returns path to the core git executable and the --git-dir parameter as list
1027sub git_cmd {
1028        return $GIT, '--git-dir='.$git_dir;
1029}
1030
1031# returns path to the core git executable and the --git-dir parameter as string
1032sub git_cmd_str {
1033        return join(' ', git_cmd());
1034}
1035
1036# get HEAD ref of given project as hash
1037sub git_get_head_hash {
1038        my $project = shift;
1039        my $o_git_dir = $git_dir;
1040        my $retval = undef;
1041        $git_dir = "$projectroot/$project";
1042        if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
1043                my $head = <$fd>;
1044                close $fd;
1045                if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
1046                        $retval = $1;
1047                }
1048        }
1049        if (defined $o_git_dir) {
1050                $git_dir = $o_git_dir;
1051        }
1052        return $retval;
1053}
1054
1055# get type of given object
1056sub git_get_type {
1057        my $hash = shift;
1058
1059        open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
1060        my $type = <$fd>;
1061        close $fd or return;
1062        chomp $type;
1063        return $type;
1064}
1065
1066sub git_get_project_config {
1067        my ($key, $type) = @_;
1068
1069        return unless ($key);
1070        $key =~ s/^gitweb\.//;
1071        return if ($key =~ m/\W/);
1072
1073        my @x = (git_cmd(), 'config');
1074        if (defined $type) { push @x, $type; }
1075        push @x, "--get";
1076        push @x, "gitweb.$key";
1077        my $val = qx(@x);
1078        chomp $val;
1079        return ($val);
1080}
1081
1082# get hash of given path at given ref
1083sub git_get_hash_by_path {
1084        my $base = shift;
1085        my $path = shift || return undef;
1086        my $type = shift;
1087
1088        $path =~ s,/+$,,;
1089
1090        open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
1091                or die_error(undef, "Open git-ls-tree failed");
1092        my $line = <$fd>;
1093        close $fd or return undef;
1094
1095        if (!defined $line) {
1096                # there is no tree or hash given by $path at $base
1097                return undef;
1098        }
1099
1100        #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1101        $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
1102        if (defined $type && $type ne $2) {
1103                # type doesn't match
1104                return undef;
1105        }
1106        return $3;
1107}
1108
1109# get path of entry with given hash at given tree-ish (ref)
1110# used to get 'from' filename for combined diff (merge commit) for renames
1111sub git_get_path_by_hash {
1112        my $base = shift || return;
1113        my $hash = shift || return;
1114
1115        local $/ = "\0";
1116
1117        open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
1118                or return undef;
1119        while (my $line = <$fd>) {
1120                chomp $line;
1121
1122                #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423  gitweb'
1123                #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f  gitweb/README'
1124                if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
1125                        close $fd;
1126                        return $1;
1127                }
1128        }
1129        close $fd;
1130        return undef;
1131}
1132
1133## ......................................................................
1134## git utility functions, directly accessing git repository
1135
1136sub git_get_project_description {
1137        my $path = shift;
1138
1139        open my $fd, "$projectroot/$path/description" or return undef;
1140        my $descr = <$fd>;
1141        close $fd;
1142        if (defined $descr) {
1143                chomp $descr;
1144        }
1145        return $descr;
1146}
1147
1148sub git_get_project_url_list {
1149        my $path = shift;
1150
1151        open my $fd, "$projectroot/$path/cloneurl" or return;
1152        my @git_project_url_list = map { chomp; $_ } <$fd>;
1153        close $fd;
1154
1155        return wantarray ? @git_project_url_list : \@git_project_url_list;
1156}
1157
1158sub git_get_projects_list {
1159        my ($filter) = @_;
1160        my @list;
1161
1162        $filter ||= '';
1163        $filter =~ s/\.git$//;
1164
1165        my ($check_forks) = gitweb_check_feature('forks');
1166
1167        if (-d $projects_list) {
1168                # search in directory
1169                my $dir = $projects_list . ($filter ? "/$filter" : '');
1170                # remove the trailing "/"
1171                $dir =~ s!/+$!!;
1172                my $pfxlen = length("$dir");
1173
1174                File::Find::find({
1175                        follow_fast => 1, # follow symbolic links
1176                        dangling_symlinks => 0, # ignore dangling symlinks, silently
1177                        wanted => sub {
1178                                # skip project-list toplevel, if we get it.
1179                                return if (m!^[/.]$!);
1180                                # only directories can be git repositories
1181                                return unless (-d $_);
1182
1183                                my $subdir = substr($File::Find::name, $pfxlen + 1);
1184                                # we check related file in $projectroot
1185                                if ($check_forks and $subdir =~ m#/.#) {
1186                                        $File::Find::prune = 1;
1187                                } elsif (check_export_ok("$projectroot/$filter/$subdir")) {
1188                                        push @list, { path => ($filter ? "$filter/" : '') . $subdir };
1189                                        $File::Find::prune = 1;
1190                                }
1191                        },
1192                }, "$dir");
1193
1194        } elsif (-f $projects_list) {
1195                # read from file(url-encoded):
1196                # 'git%2Fgit.git Linus+Torvalds'
1197                # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1198                # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1199                my %paths;
1200                open my ($fd), $projects_list or return;
1201        PROJECT:
1202                while (my $line = <$fd>) {
1203                        chomp $line;
1204                        my ($path, $owner) = split ' ', $line;
1205                        $path = unescape($path);
1206                        $owner = unescape($owner);
1207                        if (!defined $path) {
1208                                next;
1209                        }
1210                        if ($filter ne '') {
1211                                # looking for forks;
1212                                my $pfx = substr($path, 0, length($filter));
1213                                if ($pfx ne $filter) {
1214                                        next PROJECT;
1215                                }
1216                                my $sfx = substr($path, length($filter));
1217                                if ($sfx !~ /^\/.*\.git$/) {
1218                                        next PROJECT;
1219                                }
1220                        } elsif ($check_forks) {
1221                        PATH:
1222                                foreach my $filter (keys %paths) {
1223                                        # looking for forks;
1224                                        my $pfx = substr($path, 0, length($filter));
1225                                        if ($pfx ne $filter) {
1226                                                next PATH;
1227                                        }
1228                                        my $sfx = substr($path, length($filter));
1229                                        if ($sfx !~ /^\/.*\.git$/) {
1230                                                next PATH;
1231                                        }
1232                                        # is a fork, don't include it in
1233                                        # the list
1234                                        next PROJECT;
1235                                }
1236                        }
1237                        if (check_export_ok("$projectroot/$path")) {
1238                                my $pr = {
1239                                        path => $path,
1240                                        owner => decode_utf8($owner),
1241                                };
1242                                push @list, $pr;
1243                                (my $forks_path = $path) =~ s/\.git$//;
1244                                $paths{$forks_path}++;
1245                        }
1246                }
1247                close $fd;
1248        }
1249        return @list;
1250}
1251
1252sub git_get_project_owner {
1253        my $project = shift;
1254        my $owner;
1255
1256        return undef unless $project;
1257
1258        # read from file (url-encoded):
1259        # 'git%2Fgit.git Linus+Torvalds'
1260        # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1261        # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1262        if (-f $projects_list) {
1263                open (my $fd , $projects_list);
1264                while (my $line = <$fd>) {
1265                        chomp $line;
1266                        my ($pr, $ow) = split ' ', $line;
1267                        $pr = unescape($pr);
1268                        $ow = unescape($ow);
1269                        if ($pr eq $project) {
1270                                $owner = decode_utf8($ow);
1271                                last;
1272                        }
1273                }
1274                close $fd;
1275        }
1276        if (!defined $owner) {
1277                $owner = get_file_owner("$projectroot/$project");
1278        }
1279
1280        return $owner;
1281}
1282
1283sub git_get_last_activity {
1284        my ($path) = @_;
1285        my $fd;
1286
1287        $git_dir = "$projectroot/$path";
1288        open($fd, "-|", git_cmd(), 'for-each-ref',
1289             '--format=%(committer)',
1290             '--sort=-committerdate',
1291             '--count=1',
1292             'refs/heads') or return;
1293        my $most_recent = <$fd>;
1294        close $fd or return;
1295        if (defined $most_recent &&
1296            $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
1297                my $timestamp = $1;
1298                my $age = time - $timestamp;
1299                return ($age, age_string($age));
1300        }
1301}
1302
1303sub git_get_references {
1304        my $type = shift || "";
1305        my %refs;
1306        # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
1307        # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
1308        open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
1309                ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
1310                or return;
1311
1312        while (my $line = <$fd>) {
1313                chomp $line;
1314                if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type/?[^^]+)!) {
1315                        if (defined $refs{$1}) {
1316                                push @{$refs{$1}}, $2;
1317                        } else {
1318                                $refs{$1} = [ $2 ];
1319                        }
1320                }
1321        }
1322        close $fd or return;
1323        return \%refs;
1324}
1325
1326sub git_get_rev_name_tags {
1327        my $hash = shift || return undef;
1328
1329        open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
1330                or return;
1331        my $name_rev = <$fd>;
1332        close $fd;
1333
1334        if ($name_rev =~ m|^$hash tags/(.*)$|) {
1335                return $1;
1336        } else {
1337                # catches also '$hash undefined' output
1338                return undef;
1339        }
1340}
1341
1342## ----------------------------------------------------------------------
1343## parse to hash functions
1344
1345sub parse_date {
1346        my $epoch = shift;
1347        my $tz = shift || "-0000";
1348
1349        my %date;
1350        my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
1351        my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
1352        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
1353        $date{'hour'} = $hour;
1354        $date{'minute'} = $min;
1355        $date{'mday'} = $mday;
1356        $date{'day'} = $days[$wday];
1357        $date{'month'} = $months[$mon];
1358        $date{'rfc2822'}   = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
1359                             $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
1360        $date{'mday-time'} = sprintf "%d %s %02d:%02d",
1361                             $mday, $months[$mon], $hour ,$min;
1362        $date{'iso-8601'}  = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
1363                             1900+$year, $mon, $mday, $hour ,$min, $sec;
1364
1365        $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
1366        my $local = $epoch + ((int $1 + ($2/60)) * 3600);
1367        ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
1368        $date{'hour_local'} = $hour;
1369        $date{'minute_local'} = $min;
1370        $date{'tz_local'} = $tz;
1371        $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
1372                                  1900+$year, $mon+1, $mday,
1373                                  $hour, $min, $sec, $tz);
1374        return %date;
1375}
1376
1377sub parse_tag {
1378        my $tag_id = shift;
1379        my %tag;
1380        my @comment;
1381
1382        open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
1383        $tag{'id'} = $tag_id;
1384        while (my $line = <$fd>) {
1385                chomp $line;
1386                if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
1387                        $tag{'object'} = $1;
1388                } elsif ($line =~ m/^type (.+)$/) {
1389                        $tag{'type'} = $1;
1390                } elsif ($line =~ m/^tag (.+)$/) {
1391                        $tag{'name'} = $1;
1392                } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
1393                        $tag{'author'} = $1;
1394                        $tag{'epoch'} = $2;
1395                        $tag{'tz'} = $3;
1396                } elsif ($line =~ m/--BEGIN/) {
1397                        push @comment, $line;
1398                        last;
1399                } elsif ($line eq "") {
1400                        last;
1401                }
1402        }
1403        push @comment, <$fd>;
1404        $tag{'comment'} = \@comment;
1405        close $fd or return;
1406        if (!defined $tag{'name'}) {
1407                return
1408        };
1409        return %tag
1410}
1411
1412sub parse_commit_text {
1413        my ($commit_text, $withparents) = @_;
1414        my @commit_lines = split '\n', $commit_text;
1415        my %co;
1416
1417        pop @commit_lines; # Remove '\0'
1418
1419        if (! @commit_lines) {
1420                return;
1421        }
1422
1423        my $header = shift @commit_lines;
1424        if ($header !~ m/^[0-9a-fA-F]{40}/) {
1425                return;
1426        }
1427        ($co{'id'}, my @parents) = split ' ', $header;
1428        while (my $line = shift @commit_lines) {
1429                last if $line eq "\n";
1430                if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1431                        $co{'tree'} = $1;
1432                } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
1433                        push @parents, $1;
1434                } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1435                        $co{'author'} = $1;
1436                        $co{'author_epoch'} = $2;
1437                        $co{'author_tz'} = $3;
1438                        if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
1439                                $co{'author_name'}  = $1;
1440                                $co{'author_email'} = $2;
1441                        } else {
1442                                $co{'author_name'} = $co{'author'};
1443                        }
1444                } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1445                        $co{'committer'} = $1;
1446                        $co{'committer_epoch'} = $2;
1447                        $co{'committer_tz'} = $3;
1448                        $co{'committer_name'} = $co{'committer'};
1449                        if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
1450                                $co{'committer_name'}  = $1;
1451                                $co{'committer_email'} = $2;
1452                        } else {
1453                                $co{'committer_name'} = $co{'committer'};
1454                        }
1455                }
1456        }
1457        if (!defined $co{'tree'}) {
1458                return;
1459        };
1460        $co{'parents'} = \@parents;
1461        $co{'parent'} = $parents[0];
1462
1463        foreach my $title (@commit_lines) {
1464                $title =~ s/^    //;
1465                if ($title ne "") {
1466                        $co{'title'} = chop_str($title, 80, 5);
1467                        # remove leading stuff of merges to make the interesting part visible
1468                        if (length($title) > 50) {
1469                                $title =~ s/^Automatic //;
1470                                $title =~ s/^merge (of|with) /Merge ... /i;
1471                                if (length($title) > 50) {
1472                                        $title =~ s/(http|rsync):\/\///;
1473                                }
1474                                if (length($title) > 50) {
1475                                        $title =~ s/(master|www|rsync)\.//;
1476                                }
1477                                if (length($title) > 50) {
1478                                        $title =~ s/kernel.org:?//;
1479                                }
1480                                if (length($title) > 50) {
1481                                        $title =~ s/\/pub\/scm//;
1482                                }
1483                        }
1484                        $co{'title_short'} = chop_str($title, 50, 5);
1485                        last;
1486                }
1487        }
1488        if ($co{'title'} eq "") {
1489                $co{'title'} = $co{'title_short'} = '(no commit message)';
1490        }
1491        # remove added spaces
1492        foreach my $line (@commit_lines) {
1493                $line =~ s/^    //;
1494        }
1495        $co{'comment'} = \@commit_lines;
1496
1497        my $age = time - $co{'committer_epoch'};
1498        $co{'age'} = $age;
1499        $co{'age_string'} = age_string($age);
1500        my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1501        if ($age > 60*60*24*7*2) {
1502                $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1503                $co{'age_string_age'} = $co{'age_string'};
1504        } else {
1505                $co{'age_string_date'} = $co{'age_string'};
1506                $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1507        }
1508        return %co;
1509}
1510
1511sub parse_commit {
1512        my ($commit_id) = @_;
1513        my %co;
1514
1515        local $/ = "\0";
1516
1517        open my $fd, "-|", git_cmd(), "rev-list",
1518                "--parents",
1519                "--header",
1520                "--max-count=1",
1521                $commit_id,
1522                "--",
1523                or die_error(undef, "Open git-rev-list failed");
1524        %co = parse_commit_text(<$fd>, 1);
1525        close $fd;
1526
1527        return %co;
1528}
1529
1530sub parse_commits {
1531        my ($commit_id, $maxcount, $skip, $arg, $filename) = @_;
1532        my @cos;
1533
1534        $maxcount ||= 1;
1535        $skip ||= 0;
1536
1537        local $/ = "\0";
1538
1539        open my $fd, "-|", git_cmd(), "rev-list",
1540                "--header",
1541                ($arg ? ($arg) : ()),
1542                ("--max-count=" . $maxcount),
1543                ("--skip=" . $skip),
1544                $commit_id,
1545                "--",
1546                ($filename ? ($filename) : ())
1547                or die_error(undef, "Open git-rev-list failed");
1548        while (my $line = <$fd>) {
1549                my %co = parse_commit_text($line);
1550                push @cos, \%co;
1551        }
1552        close $fd;
1553
1554        return wantarray ? @cos : \@cos;
1555}
1556
1557# parse ref from ref_file, given by ref_id, with given type
1558sub parse_ref {
1559        my $ref_file = shift;
1560        my $ref_id = shift;
1561        my $type = shift || git_get_type($ref_id);
1562        my %ref_item;
1563
1564        $ref_item{'type'} = $type;
1565        $ref_item{'id'} = $ref_id;
1566        $ref_item{'epoch'} = 0;
1567        $ref_item{'age'} = "unknown";
1568        if ($type eq "tag") {
1569                my %tag = parse_tag($ref_id);
1570                $ref_item{'comment'} = $tag{'comment'};
1571                if ($tag{'type'} eq "commit") {
1572                        my %co = parse_commit($tag{'object'});
1573                        $ref_item{'epoch'} = $co{'committer_epoch'};
1574                        $ref_item{'age'} = $co{'age_string'};
1575                } elsif (defined($tag{'epoch'})) {
1576                        my $age = time - $tag{'epoch'};
1577                        $ref_item{'epoch'} = $tag{'epoch'};
1578                        $ref_item{'age'} = age_string($age);
1579                }
1580                $ref_item{'reftype'} = $tag{'type'};
1581                $ref_item{'name'} = $tag{'name'};
1582                $ref_item{'refid'} = $tag{'object'};
1583        } elsif ($type eq "commit"){
1584                my %co = parse_commit($ref_id);
1585                $ref_item{'reftype'} = "commit";
1586                $ref_item{'name'} = $ref_file;
1587                $ref_item{'title'} = $co{'title'};
1588                $ref_item{'refid'} = $ref_id;
1589                $ref_item{'epoch'} = $co{'committer_epoch'};
1590                $ref_item{'age'} = $co{'age_string'};
1591        } else {
1592                $ref_item{'reftype'} = $type;
1593                $ref_item{'name'} = $ref_file;
1594                $ref_item{'refid'} = $ref_id;
1595        }
1596
1597        return %ref_item;
1598}
1599
1600# parse line of git-diff-tree "raw" output
1601sub parse_difftree_raw_line {
1602        my $line = shift;
1603        my %res;
1604
1605        # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1606        # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1607        if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1608                $res{'from_mode'} = $1;
1609                $res{'to_mode'} = $2;
1610                $res{'from_id'} = $3;
1611                $res{'to_id'} = $4;
1612                $res{'status'} = $5;
1613                $res{'similarity'} = $6;
1614                if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1615                        ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1616                } else {
1617                        $res{'file'} = unquote($7);
1618                }
1619        }
1620        # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
1621        # combined diff (for merge commit)
1622        elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
1623                $res{'nparents'}  = length($1);
1624                $res{'from_mode'} = [ split(' ', $2) ];
1625                $res{'to_mode'} = pop @{$res{'from_mode'}};
1626                $res{'from_id'} = [ split(' ', $3) ];
1627                $res{'to_id'} = pop @{$res{'from_id'}};
1628                $res{'status'} = [ split('', $4) ];
1629                $res{'to_file'} = unquote($5);
1630        }
1631        # 'c512b523472485aef4fff9e57b229d9d243c967f'
1632        elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1633                $res{'commit'} = $1;
1634        }
1635
1636        return wantarray ? %res : \%res;
1637}
1638
1639# parse line of git-ls-tree output
1640sub parse_ls_tree_line ($;%) {
1641        my $line = shift;
1642        my %opts = @_;
1643        my %res;
1644
1645        #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1646        $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
1647
1648        $res{'mode'} = $1;
1649        $res{'type'} = $2;
1650        $res{'hash'} = $3;
1651        if ($opts{'-z'}) {
1652                $res{'name'} = $4;
1653        } else {
1654                $res{'name'} = unquote($4);
1655        }
1656
1657        return wantarray ? %res : \%res;
1658}
1659
1660## ......................................................................
1661## parse to array of hashes functions
1662
1663sub git_get_heads_list {
1664        my $limit = shift;
1665        my @headslist;
1666
1667        open my $fd, '-|', git_cmd(), 'for-each-ref',
1668                ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
1669                '--format=%(objectname) %(refname) %(subject)%00%(committer)',
1670                'refs/heads'
1671                or return;
1672        while (my $line = <$fd>) {
1673                my %ref_item;
1674
1675                chomp $line;
1676                my ($refinfo, $committerinfo) = split(/\0/, $line);
1677                my ($hash, $name, $title) = split(' ', $refinfo, 3);
1678                my ($committer, $epoch, $tz) =
1679                        ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
1680                $name =~ s!^refs/heads/!!;
1681
1682                $ref_item{'name'}  = $name;
1683                $ref_item{'id'}    = $hash;
1684                $ref_item{'title'} = $title || '(no commit message)';
1685                $ref_item{'epoch'} = $epoch;
1686                if ($epoch) {
1687                        $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
1688                } else {
1689                        $ref_item{'age'} = "unknown";
1690                }
1691
1692                push @headslist, \%ref_item;
1693        }
1694        close $fd;
1695
1696        return wantarray ? @headslist : \@headslist;
1697}
1698
1699sub git_get_tags_list {
1700        my $limit = shift;
1701        my @tagslist;
1702
1703        open my $fd, '-|', git_cmd(), 'for-each-ref',
1704                ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
1705                '--format=%(objectname) %(objecttype) %(refname) '.
1706                '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
1707                'refs/tags'
1708                or return;
1709        while (my $line = <$fd>) {
1710                my %ref_item;
1711
1712                chomp $line;
1713                my ($refinfo, $creatorinfo) = split(/\0/, $line);
1714                my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
1715                my ($creator, $epoch, $tz) =
1716                        ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
1717                $name =~ s!^refs/tags/!!;
1718
1719                $ref_item{'type'} = $type;
1720                $ref_item{'id'} = $id;
1721                $ref_item{'name'} = $name;
1722                if ($type eq "tag") {
1723                        $ref_item{'subject'} = $title;
1724                        $ref_item{'reftype'} = $reftype;
1725                        $ref_item{'refid'}   = $refid;
1726                } else {
1727                        $ref_item{'reftype'} = $type;
1728                        $ref_item{'refid'}   = $id;
1729                }
1730
1731                if ($type eq "tag" || $type eq "commit") {
1732                        $ref_item{'epoch'} = $epoch;
1733                        if ($epoch) {
1734                                $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
1735                        } else {
1736                                $ref_item{'age'} = "unknown";
1737                        }
1738                }
1739
1740                push @tagslist, \%ref_item;
1741        }
1742        close $fd;
1743
1744        return wantarray ? @tagslist : \@tagslist;
1745}
1746
1747## ----------------------------------------------------------------------
1748## filesystem-related functions
1749
1750sub get_file_owner {
1751        my $path = shift;
1752
1753        my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1754        my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1755        if (!defined $gcos) {
1756                return undef;
1757        }
1758        my $owner = $gcos;
1759        $owner =~ s/[,;].*$//;
1760        return decode_utf8($owner);
1761}
1762
1763## ......................................................................
1764## mimetype related functions
1765
1766sub mimetype_guess_file {
1767        my $filename = shift;
1768        my $mimemap = shift;
1769        -r $mimemap or return undef;
1770
1771        my %mimemap;
1772        open(MIME, $mimemap) or return undef;
1773        while (<MIME>) {
1774                next if m/^#/; # skip comments
1775                my ($mime, $exts) = split(/\t+/);
1776                if (defined $exts) {
1777                        my @exts = split(/\s+/, $exts);
1778                        foreach my $ext (@exts) {
1779                                $mimemap{$ext} = $mime;
1780                        }
1781                }
1782        }
1783        close(MIME);
1784
1785        $filename =~ /\.([^.]*)$/;
1786        return $mimemap{$1};
1787}
1788
1789sub mimetype_guess {
1790        my $filename = shift;
1791        my $mime;
1792        $filename =~ /\./ or return undef;
1793
1794        if ($mimetypes_file) {
1795                my $file = $mimetypes_file;
1796                if ($file !~ m!^/!) { # if it is relative path
1797                        # it is relative to project
1798                        $file = "$projectroot/$project/$file";
1799                }
1800                $mime = mimetype_guess_file($filename, $file);
1801        }
1802        $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1803        return $mime;
1804}
1805
1806sub blob_mimetype {
1807        my $fd = shift;
1808        my $filename = shift;
1809
1810        if ($filename) {
1811                my $mime = mimetype_guess($filename);
1812                $mime and return $mime;
1813        }
1814
1815        # just in case
1816        return $default_blob_plain_mimetype unless $fd;
1817
1818        if (-T $fd) {
1819                return 'text/plain' .
1820                       ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1821        } elsif (! $filename) {
1822                return 'application/octet-stream';
1823        } elsif ($filename =~ m/\.png$/i) {
1824                return 'image/png';
1825        } elsif ($filename =~ m/\.gif$/i) {
1826                return 'image/gif';
1827        } elsif ($filename =~ m/\.jpe?g$/i) {
1828                return 'image/jpeg';
1829        } else {
1830                return 'application/octet-stream';
1831        }
1832}
1833
1834## ======================================================================
1835## functions printing HTML: header, footer, error page
1836
1837sub git_header_html {
1838        my $status = shift || "200 OK";
1839        my $expires = shift;
1840
1841        my $title = "$site_name";
1842        if (defined $project) {
1843                $title .= " - " . decode_utf8($project);
1844                if (defined $action) {
1845                        $title .= "/$action";
1846                        if (defined $file_name) {
1847                                $title .= " - " . esc_path($file_name);
1848                                if ($action eq "tree" && $file_name !~ m|/$|) {
1849                                        $title .= "/";
1850                                }
1851                        }
1852                }
1853        }
1854        my $content_type;
1855        # require explicit support from the UA if we are to send the page as
1856        # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1857        # we have to do this because MSIE sometimes globs '*/*', pretending to
1858        # support xhtml+xml but choking when it gets what it asked for.
1859        if (defined $cgi->http('HTTP_ACCEPT') &&
1860            $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1861            $cgi->Accept('application/xhtml+xml') != 0) {
1862                $content_type = 'application/xhtml+xml';
1863        } else {
1864                $content_type = 'text/html';
1865        }
1866        print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1867                           -status=> $status, -expires => $expires);
1868        my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
1869        print <<EOF;
1870<?xml version="1.0" encoding="utf-8"?>
1871<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1872<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1873<!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1874<!-- git core binaries version $git_version -->
1875<head>
1876<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1877<meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
1878<meta name="robots" content="index, nofollow"/>
1879<title>$title</title>
1880EOF
1881# print out each stylesheet that exist
1882        if (defined $stylesheet) {
1883#provides backwards capability for those people who define style sheet in a config file
1884                print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
1885        } else {
1886                foreach my $stylesheet (@stylesheets) {
1887                        next unless $stylesheet;
1888                        print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
1889                }
1890        }
1891        if (defined $project) {
1892                printf('<link rel="alternate" title="%s log RSS feed" '.
1893                       'href="%s" type="application/rss+xml" />'."\n",
1894                       esc_param($project), href(action=>"rss"));
1895                printf('<link rel="alternate" title="%s log Atom feed" '.
1896                       'href="%s" type="application/atom+xml" />'."\n",
1897                       esc_param($project), href(action=>"atom"));
1898        } else {
1899                printf('<link rel="alternate" title="%s projects list" '.
1900                       'href="%s" type="text/plain; charset=utf-8"/>'."\n",
1901                       $site_name, href(project=>undef, action=>"project_index"));
1902                printf('<link rel="alternate" title="%s projects feeds" '.
1903                       'href="%s" type="text/x-opml"/>'."\n",
1904                       $site_name, href(project=>undef, action=>"opml"));
1905        }
1906        if (defined $favicon) {
1907                print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
1908        }
1909
1910        print "</head>\n" .
1911              "<body>\n";
1912
1913        if (-f $site_header) {
1914                open (my $fd, $site_header);
1915                print <$fd>;
1916                close $fd;
1917        }
1918
1919        print "<div class=\"page_header\">\n" .
1920              $cgi->a({-href => esc_url($logo_url),
1921                       -title => $logo_label},
1922                      qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
1923        print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
1924        if (defined $project) {
1925                print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1926                if (defined $action) {
1927                        print " / $action";
1928                }
1929                print "\n";
1930        }
1931        print "</div>\n";
1932
1933        my ($have_search) = gitweb_check_feature('search');
1934        if ((defined $project) && ($have_search)) {
1935                if (!defined $searchtext) {
1936                        $searchtext = "";
1937                }
1938                my $search_hash;
1939                if (defined $hash_base) {
1940                        $search_hash = $hash_base;
1941                } elsif (defined $hash) {
1942                        $search_hash = $hash;
1943                } else {
1944                        $search_hash = "HEAD";
1945                }
1946                $cgi->param("a", "search");
1947                $cgi->param("h", $search_hash);
1948                $cgi->param("p", $project);
1949                print $cgi->startform(-method => "get", -action => $my_uri) .
1950                      "<div class=\"search\">\n" .
1951                      $cgi->hidden(-name => "p") . "\n" .
1952                      $cgi->hidden(-name => "a") . "\n" .
1953                      $cgi->hidden(-name => "h") . "\n" .
1954                      $cgi->popup_menu(-name => 'st', -default => 'commit',
1955                                       -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
1956                      $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
1957                      " search:\n",
1958                      $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1959                      "</div>" .
1960                      $cgi->end_form() . "\n";
1961        }
1962}
1963
1964sub git_footer_html {
1965        print "<div class=\"page_footer\">\n";
1966        if (defined $project) {
1967                my $descr = git_get_project_description($project);
1968                if (defined $descr) {
1969                        print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1970                }
1971                print $cgi->a({-href => href(action=>"rss"),
1972                              -class => "rss_logo"}, "RSS") . " ";
1973                print $cgi->a({-href => href(action=>"atom"),
1974                              -class => "rss_logo"}, "Atom") . "\n";
1975        } else {
1976                print $cgi->a({-href => href(project=>undef, action=>"opml"),
1977                              -class => "rss_logo"}, "OPML") . " ";
1978                print $cgi->a({-href => href(project=>undef, action=>"project_index"),
1979                              -class => "rss_logo"}, "TXT") . "\n";
1980        }
1981        print "</div>\n" ;
1982
1983        if (-f $site_footer) {
1984                open (my $fd, $site_footer);
1985                print <$fd>;
1986                close $fd;
1987        }
1988
1989        print "</body>\n" .
1990              "</html>";
1991}
1992
1993sub die_error {
1994        my $status = shift || "403 Forbidden";
1995        my $error = shift || "Malformed query, file missing or permission denied";
1996
1997        git_header_html($status);
1998        print <<EOF;
1999<div class="page_body">
2000<br /><br />
2001$status - $error
2002<br />
2003</div>
2004EOF
2005        git_footer_html();
2006        exit;
2007}
2008
2009## ----------------------------------------------------------------------
2010## functions printing or outputting HTML: navigation
2011
2012sub git_print_page_nav {
2013        my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
2014        $extra = '' if !defined $extra; # pager or formats
2015
2016        my @navs = qw(summary shortlog log commit commitdiff tree);
2017        if ($suppress) {
2018                @navs = grep { $_ ne $suppress } @navs;
2019        }
2020
2021        my %arg = map { $_ => {action=>$_} } @navs;
2022        if (defined $head) {
2023                for (qw(commit commitdiff)) {
2024                        $arg{$_}{'hash'} = $head;
2025                }
2026                if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
2027                        for (qw(shortlog log)) {
2028                                $arg{$_}{'hash'} = $head;
2029                        }
2030                }
2031        }
2032        $arg{'tree'}{'hash'} = $treehead if defined $treehead;
2033        $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
2034
2035        print "<div class=\"page_nav\">\n" .
2036                (join " | ",
2037                 map { $_ eq $current ?
2038                       $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
2039                 } @navs);
2040        print "<br/>\n$extra<br/>\n" .
2041              "</div>\n";
2042}
2043
2044sub format_paging_nav {
2045        my ($action, $hash, $head, $page, $nrevs) = @_;
2046        my $paging_nav;
2047
2048
2049        if ($hash ne $head || $page) {
2050                $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
2051        } else {
2052                $paging_nav .= "HEAD";
2053        }
2054
2055        if ($page > 0) {
2056                $paging_nav .= " &sdot; " .
2057                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
2058                                 -accesskey => "p", -title => "Alt-p"}, "prev");
2059        } else {
2060                $paging_nav .= " &sdot; prev";
2061        }
2062
2063        if ($nrevs >= (100 * ($page+1)-1)) {
2064                $paging_nav .= " &sdot; " .
2065                        $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
2066                                 -accesskey => "n", -title => "Alt-n"}, "next");
2067        } else {
2068                $paging_nav .= " &sdot; next";
2069        }
2070
2071        return $paging_nav;
2072}
2073
2074## ......................................................................
2075## functions printing or outputting HTML: div
2076
2077sub git_print_header_div {
2078        my ($action, $title, $hash, $hash_base) = @_;
2079        my %args = ();
2080
2081        $args{'action'} = $action;
2082        $args{'hash'} = $hash if $hash;
2083        $args{'hash_base'} = $hash_base if $hash_base;
2084
2085        print "<div class=\"header\">\n" .
2086              $cgi->a({-href => href(%args), -class => "title"},
2087              $title ? $title : $action) .
2088              "\n</div>\n";
2089}
2090
2091#sub git_print_authorship (\%) {
2092sub git_print_authorship {
2093        my $co = shift;
2094
2095        my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
2096        print "<div class=\"author_date\">" .
2097              esc_html($co->{'author_name'}) .
2098              " [$ad{'rfc2822'}";
2099        if ($ad{'hour_local'} < 6) {
2100                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2101                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2102        } else {
2103                printf(" (%02d:%02d %s)",
2104                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2105        }
2106        print "]</div>\n";
2107}
2108
2109sub git_print_page_path {
2110        my $name = shift;
2111        my $type = shift;
2112        my $hb = shift;
2113
2114
2115        print "<div class=\"page_path\">";
2116        print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
2117                      -title => 'tree root'}, decode_utf8("[$project]"));
2118        print " / ";
2119        if (defined $name) {
2120                my @dirname = split '/', $name;
2121                my $basename = pop @dirname;
2122                my $fullname = '';
2123
2124                foreach my $dir (@dirname) {
2125                        $fullname .= ($fullname ? '/' : '') . $dir;
2126                        print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
2127                                                     hash_base=>$hb),
2128                                      -title => $fullname}, esc_path($dir));
2129                        print " / ";
2130                }
2131                if (defined $type && $type eq 'blob') {
2132                        print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
2133                                                     hash_base=>$hb),
2134                                      -title => $name}, esc_path($basename));
2135                } elsif (defined $type && $type eq 'tree') {
2136                        print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
2137                                                     hash_base=>$hb),
2138                                      -title => $name}, esc_path($basename));
2139                        print " / ";
2140                } else {
2141                        print esc_path($basename);
2142                }
2143        }
2144        print "<br/></div>\n";
2145}
2146
2147# sub git_print_log (\@;%) {
2148sub git_print_log ($;%) {
2149        my $log = shift;
2150        my %opts = @_;
2151
2152        if ($opts{'-remove_title'}) {
2153                # remove title, i.e. first line of log
2154                shift @$log;
2155        }
2156        # remove leading empty lines
2157        while (defined $log->[0] && $log->[0] eq "") {
2158                shift @$log;
2159        }
2160
2161        # print log
2162        my $signoff = 0;
2163        my $empty = 0;
2164        foreach my $line (@$log) {
2165                if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
2166                        $signoff = 1;
2167                        $empty = 0;
2168                        if (! $opts{'-remove_signoff'}) {
2169                                print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
2170                                next;
2171                        } else {
2172                                # remove signoff lines
2173                                next;
2174                        }
2175                } else {
2176                        $signoff = 0;
2177                }
2178
2179                # print only one empty line
2180                # do not print empty line after signoff
2181                if ($line eq "") {
2182                        next if ($empty || $signoff);
2183                        $empty = 1;
2184                } else {
2185                        $empty = 0;
2186                }
2187
2188                print format_log_line_html($line) . "<br/>\n";
2189        }
2190
2191        if ($opts{'-final_empty_line'}) {
2192                # end with single empty line
2193                print "<br/>\n" unless $empty;
2194        }
2195}
2196
2197# return link target (what link points to)
2198sub git_get_link_target {
2199        my $hash = shift;
2200        my $link_target;
2201
2202        # read link
2203        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2204                or return;
2205        {
2206                local $/;
2207                $link_target = <$fd>;
2208        }
2209        close $fd
2210                or return;
2211
2212        return $link_target;
2213}
2214
2215# given link target, and the directory (basedir) the link is in,
2216# return target of link relative to top directory (top tree);
2217# return undef if it is not possible (including absolute links).
2218sub normalize_link_target {
2219        my ($link_target, $basedir, $hash_base) = @_;
2220
2221        # we can normalize symlink target only if $hash_base is provided
2222        return unless $hash_base;
2223
2224        # absolute symlinks (beginning with '/') cannot be normalized
2225        return if (substr($link_target, 0, 1) eq '/');
2226
2227        # normalize link target to path from top (root) tree (dir)
2228        my $path;
2229        if ($basedir) {
2230                $path = $basedir . '/' . $link_target;
2231        } else {
2232                # we are in top (root) tree (dir)
2233                $path = $link_target;
2234        }
2235
2236        # remove //, /./, and /../
2237        my @path_parts;
2238        foreach my $part (split('/', $path)) {
2239                # discard '.' and ''
2240                next if (!$part || $part eq '.');
2241                # handle '..'
2242                if ($part eq '..') {
2243                        if (@path_parts) {
2244                                pop @path_parts;
2245                        } else {
2246                                # link leads outside repository (outside top dir)
2247                                return;
2248                        }
2249                } else {
2250                        push @path_parts, $part;
2251                }
2252        }
2253        $path = join('/', @path_parts);
2254
2255        return $path;
2256}
2257
2258# print tree entry (row of git_tree), but without encompassing <tr> element
2259sub git_print_tree_entry {
2260        my ($t, $basedir, $hash_base, $have_blame) = @_;
2261
2262        my %base_key = ();
2263        $base_key{'hash_base'} = $hash_base if defined $hash_base;
2264
2265        # The format of a table row is: mode list link.  Where mode is
2266        # the mode of the entry, list is the name of the entry, an href,
2267        # and link is the action links of the entry.
2268
2269        print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
2270        if ($t->{'type'} eq "blob") {
2271                print "<td class=\"list\">" .
2272                        $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2273                                               file_name=>"$basedir$t->{'name'}", %base_key),
2274                                -class => "list"}, esc_path($t->{'name'}));
2275                if (S_ISLNK(oct $t->{'mode'})) {
2276                        my $link_target = git_get_link_target($t->{'hash'});
2277                        if ($link_target) {
2278                                my $norm_target = normalize_link_target($link_target, $basedir, $hash_base);
2279                                if (defined $norm_target) {
2280                                        print " -> " .
2281                                              $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
2282                                                                     file_name=>$norm_target),
2283                                                       -title => $norm_target}, esc_path($link_target));
2284                                } else {
2285                                        print " -> " . esc_path($link_target);
2286                                }
2287                        }
2288                }
2289                print "</td>\n";
2290                print "<td class=\"link\">";
2291                print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2292                                             file_name=>"$basedir$t->{'name'}", %base_key)},
2293                              "blob");
2294                if ($have_blame) {
2295                        print " | " .
2296                              $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
2297                                                     file_name=>"$basedir$t->{'name'}", %base_key)},
2298                                      "blame");
2299                }
2300                if (defined $hash_base) {
2301                        print " | " .
2302                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2303                                                     hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
2304                                      "history");
2305                }
2306                print " | " .
2307                        $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
2308                                               file_name=>"$basedir$t->{'name'}")},
2309                                "raw");
2310                print "</td>\n";
2311
2312        } elsif ($t->{'type'} eq "tree") {
2313                print "<td class=\"list\">";
2314                print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2315                                             file_name=>"$basedir$t->{'name'}", %base_key)},
2316                              esc_path($t->{'name'}));
2317                print "</td>\n";
2318                print "<td class=\"link\">";
2319                print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2320                                             file_name=>"$basedir$t->{'name'}", %base_key)},
2321                              "tree");
2322                if (defined $hash_base) {
2323                        print " | " .
2324                              $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2325                                                     file_name=>"$basedir$t->{'name'}")},
2326                                      "history");
2327                }
2328                print "</td>\n";
2329        }
2330}
2331
2332## ......................................................................
2333## functions printing large fragments of HTML
2334
2335sub fill_from_file_info {
2336        my ($diff, @parents) = @_;
2337
2338        $diff->{'from_file'} = [ ];
2339        $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
2340        for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
2341                if ($diff->{'status'}[$i] eq 'R' ||
2342                    $diff->{'status'}[$i] eq 'C') {
2343                        $diff->{'from_file'}[$i] =
2344                                git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
2345                }
2346        }
2347
2348        return $diff;
2349}
2350
2351# parameters can be strings, or references to arrays of strings
2352sub from_ids_eq {
2353        my ($a, $b) = @_;
2354
2355        if (ref($a) eq "ARRAY" && ref($b) eq "ARRAY" && @$a == @$b) {
2356                for (my $i = 0; $i < @$a; ++$i) {
2357                        return 0 unless ($a->[$i] eq $b->[$i]);
2358                }
2359                return 1;
2360        } elsif (!ref($a) && !ref($b)) {
2361                return $a eq $b;
2362        } else {
2363                return 0;
2364        }
2365}
2366
2367
2368sub git_difftree_body {
2369        my ($difftree, $hash, @parents) = @_;
2370        my ($parent) = $parents[0];
2371        my ($have_blame) = gitweb_check_feature('blame');
2372        print "<div class=\"list_head\">\n";
2373        if ($#{$difftree} > 10) {
2374                print(($#{$difftree} + 1) . " files changed:\n");
2375        }
2376        print "</div>\n";
2377
2378        print "<table class=\"" .
2379              (@parents > 1 ? "combined " : "") .
2380              "diff_tree\">\n";
2381        my $alternate = 1;
2382        my $patchno = 0;
2383        foreach my $line (@{$difftree}) {
2384                my $diff;
2385                if (ref($line) eq "HASH") {
2386                        # pre-parsed (or generated by hand)
2387                        $diff = $line;
2388                } else {
2389                        $diff = parse_difftree_raw_line($line);
2390                }
2391
2392                if ($alternate) {
2393                        print "<tr class=\"dark\">\n";
2394                } else {
2395                        print "<tr class=\"light\">\n";
2396                }
2397                $alternate ^= 1;
2398
2399                if (exists $diff->{'nparents'}) { # combined diff
2400
2401                        fill_from_file_info($diff, @parents)
2402                                unless exists $diff->{'from_file'};
2403
2404                        if ($diff->{'to_id'} ne ('0' x 40)) {
2405                                # file exists in the result (child) commit
2406                                print "<td>" .
2407                                      $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2408                                                             file_name=>$diff->{'to_file'},
2409                                                             hash_base=>$hash),
2410                                              -class => "list"}, esc_path($diff->{'to_file'})) .
2411                                      "</td>\n";
2412                        } else {
2413                                print "<td>" .
2414                                      esc_path($diff->{'to_file'}) .
2415                                      "</td>\n";
2416                        }
2417
2418                        if ($action eq 'commitdiff') {
2419                                # link to patch
2420                                $patchno++;
2421                                print "<td class=\"link\">" .
2422                                      $cgi->a({-href => "#patch$patchno"}, "patch") .
2423                                      " | " .
2424                                      "</td>\n";
2425                        }
2426
2427                        my $has_history = 0;
2428                        my $not_deleted = 0;
2429                        for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
2430                                my $hash_parent = $parents[$i];
2431                                my $from_hash = $diff->{'from_id'}[$i];
2432                                my $from_path = $diff->{'from_file'}[$i];
2433                                my $status = $diff->{'status'}[$i];
2434
2435                                $has_history ||= ($status ne 'A');
2436                                $not_deleted ||= ($status ne 'D');
2437
2438                                if ($status eq 'A') {
2439                                        print "<td  class=\"link\" align=\"right\"> | </td>\n";
2440                                } elsif ($status eq 'D') {
2441                                        print "<td class=\"link\">" .
2442                                              $cgi->a({-href => href(action=>"blob",
2443                                                                     hash_base=>$hash,
2444                                                                     hash=>$from_hash,
2445                                                                     file_name=>$from_path)},
2446                                                      "blob" . ($i+1)) .
2447                                              " | </td>\n";
2448                                } else {
2449                                        if ($diff->{'to_id'} eq $from_hash) {
2450                                                print "<td class=\"link nochange\">";
2451                                        } else {
2452                                                print "<td class=\"link\">";
2453                                        }
2454                                        print $cgi->a({-href => href(action=>"blobdiff",
2455                                                                     hash=>$diff->{'to_id'},
2456                                                                     hash_parent=>$from_hash,
2457                                                                     hash_base=>$hash,
2458                                                                     hash_parent_base=>$hash_parent,
2459                                                                     file_name=>$diff->{'to_file'},
2460                                                                     file_parent=>$from_path)},
2461                                                      "diff" . ($i+1)) .
2462                                              " | </td>\n";
2463                                }
2464                        }
2465
2466                        print "<td class=\"link\">";
2467                        if ($not_deleted) {
2468                                print $cgi->a({-href => href(action=>"blob",
2469                                                             hash=>$diff->{'to_id'},
2470                                                             file_name=>$diff->{'to_file'},
2471                                                             hash_base=>$hash)},
2472                                              "blob");
2473                                print " | " if ($has_history);
2474                        }
2475                        if ($has_history) {
2476                                print $cgi->a({-href => href(action=>"history",
2477                                                             file_name=>$diff->{'to_file'},
2478                                                             hash_base=>$hash)},
2479                                              "history");
2480                        }
2481                        print "</td>\n";
2482
2483                        print "</tr>\n";
2484                        next; # instead of 'else' clause, to avoid extra indent
2485                }
2486                # else ordinary diff
2487
2488                my ($to_mode_oct, $to_mode_str, $to_file_type);
2489                my ($from_mode_oct, $from_mode_str, $from_file_type);
2490                if ($diff->{'to_mode'} ne ('0' x 6)) {
2491                        $to_mode_oct = oct $diff->{'to_mode'};
2492                        if (S_ISREG($to_mode_oct)) { # only for regular file
2493                                $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
2494                        }
2495                        $to_file_type = file_type($diff->{'to_mode'});
2496                }
2497                if ($diff->{'from_mode'} ne ('0' x 6)) {
2498                        $from_mode_oct = oct $diff->{'from_mode'};
2499                        if (S_ISREG($to_mode_oct)) { # only for regular file
2500                                $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
2501                        }
2502                        $from_file_type = file_type($diff->{'from_mode'});
2503                }
2504
2505                if ($diff->{'status'} eq "A") { # created
2506                        my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
2507                        $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
2508                        $mode_chng   .= "]</span>";
2509                        print "<td>";
2510                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2511                                                     hash_base=>$hash, file_name=>$diff->{'file'}),
2512                                      -class => "list"}, esc_path($diff->{'file'}));
2513                        print "</td>\n";
2514                        print "<td>$mode_chng</td>\n";
2515                        print "<td class=\"link\">";
2516                        if ($action eq 'commitdiff') {
2517                                # link to patch
2518                                $patchno++;
2519                                print $cgi->a({-href => "#patch$patchno"}, "patch");
2520                                print " | ";
2521                        }
2522                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2523                                                     hash_base=>$hash, file_name=>$diff->{'file'})},
2524                                      "blob");
2525                        print "</td>\n";
2526
2527                } elsif ($diff->{'status'} eq "D") { # deleted
2528                        my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
2529                        print "<td>";
2530                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
2531                                                     hash_base=>$parent, file_name=>$diff->{'file'}),
2532                                       -class => "list"}, esc_path($diff->{'file'}));
2533                        print "</td>\n";
2534                        print "<td>$mode_chng</td>\n";
2535                        print "<td class=\"link\">";
2536                        if ($action eq 'commitdiff') {
2537                                # link to patch
2538                                $patchno++;
2539                                print $cgi->a({-href => "#patch$patchno"}, "patch");
2540                                print " | ";
2541                        }
2542                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
2543                                                     hash_base=>$parent, file_name=>$diff->{'file'})},
2544                                      "blob") . " | ";
2545                        if ($have_blame) {
2546                                print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
2547                                                             file_name=>$diff->{'file'})},
2548                                              "blame") . " | ";
2549                        }
2550                        print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
2551                                                     file_name=>$diff->{'file'})},
2552                                      "history");
2553                        print "</td>\n";
2554
2555                } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
2556                        my $mode_chnge = "";
2557                        if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
2558                                $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
2559                                if ($from_file_type ne $to_file_type) {
2560                                        $mode_chnge .= " from $from_file_type to $to_file_type";
2561                                }
2562                                if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
2563                                        if ($from_mode_str && $to_mode_str) {
2564                                                $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
2565                                        } elsif ($to_mode_str) {
2566                                                $mode_chnge .= " mode: $to_mode_str";
2567                                        }
2568                                }
2569                                $mode_chnge .= "]</span>\n";
2570                        }
2571                        print "<td>";
2572                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2573                                                     hash_base=>$hash, file_name=>$diff->{'file'}),
2574                                      -class => "list"}, esc_path($diff->{'file'}));
2575                        print "</td>\n";
2576                        print "<td>$mode_chnge</td>\n";
2577                        print "<td class=\"link\">";
2578                        if ($action eq 'commitdiff') {
2579                                # link to patch
2580                                $patchno++;
2581                                print $cgi->a({-href => "#patch$patchno"}, "patch") .
2582                                      " | ";
2583                        } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
2584                                # "commit" view and modified file (not onlu mode changed)
2585                                print $cgi->a({-href => href(action=>"blobdiff",
2586                                                             hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
2587                                                             hash_base=>$hash, hash_parent_base=>$parent,
2588                                                             file_name=>$diff->{'file'})},
2589                                              "diff") .
2590                                      " | ";
2591                        }
2592                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2593                                                     hash_base=>$hash, file_name=>$diff->{'file'})},
2594                                       "blob") . " | ";
2595                        if ($have_blame) {
2596                                print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
2597                                                             file_name=>$diff->{'file'})},
2598                                              "blame") . " | ";
2599                        }
2600                        print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
2601                                                     file_name=>$diff->{'file'})},
2602                                      "history");
2603                        print "</td>\n";
2604
2605                } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
2606                        my %status_name = ('R' => 'moved', 'C' => 'copied');
2607                        my $nstatus = $status_name{$diff->{'status'}};
2608                        my $mode_chng = "";
2609                        if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
2610                                # mode also for directories, so we cannot use $to_mode_str
2611                                $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
2612                        }
2613                        print "<td>" .
2614                              $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2615                                                     hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
2616                                      -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
2617                              "<td><span class=\"file_status $nstatus\">[$nstatus from " .
2618                              $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
2619                                                     hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
2620                                      -class => "list"}, esc_path($diff->{'from_file'})) .
2621                              " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
2622                              "<td class=\"link\">";
2623                        if ($action eq 'commitdiff') {
2624                                # link to patch
2625                                $patchno++;
2626                                print $cgi->a({-href => "#patch$patchno"}, "patch") .
2627                                      " | ";
2628                        } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
2629                                # "commit" view and modified file (not only pure rename or copy)
2630                                print $cgi->a({-href => href(action=>"blobdiff",
2631                                                             hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
2632                                                             hash_base=>$hash, hash_parent_base=>$parent,
2633                                                             file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
2634                                              "diff") .
2635                                      " | ";
2636                        }
2637                        print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2638                                                     hash_base=>$parent, file_name=>$diff->{'to_file'})},
2639                                      "blob") . " | ";
2640                        if ($have_blame) {
2641                                print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
2642                                                             file_name=>$diff->{'to_file'})},
2643                                              "blame") . " | ";
2644                        }
2645                        print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
2646                                                    file_name=>$diff->{'to_file'})},
2647                                      "history");
2648                        print "</td>\n";
2649
2650                } # we should not encounter Unmerged (U) or Unknown (X) status
2651                print "</tr>\n";
2652        }
2653        print "</table>\n";
2654}
2655
2656sub git_patchset_body {
2657        my ($fd, $difftree, $hash, @hash_parents) = @_;
2658        my ($hash_parent) = $hash_parents[0];
2659
2660        my $patch_idx = 0;
2661        my $patch_number = 0;
2662        my $patch_line;
2663        my $diffinfo;
2664        my (%from, %to);
2665
2666        print "<div class=\"patchset\">\n";
2667
2668        # skip to first patch
2669        while ($patch_line = <$fd>) {
2670                chomp $patch_line;
2671
2672                last if ($patch_line =~ m/^diff /);
2673        }
2674
2675 PATCH:
2676        while ($patch_line) {
2677                my @diff_header;
2678                my ($from_id, $to_id);
2679
2680                # git diff header
2681                #assert($patch_line =~ m/^diff /) if DEBUG;
2682                #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
2683                $patch_number++;
2684                push @diff_header, $patch_line;
2685
2686                # extended diff header
2687        EXTENDED_HEADER:
2688                while ($patch_line = <$fd>) {
2689                        chomp $patch_line;
2690
2691                        last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
2692
2693                        if ($patch_line =~ m/^index ([0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
2694                                $from_id = $1;
2695                                $to_id   = $2;
2696                        } elsif ($patch_line =~ m/^index ((?:[0-9a-fA-F]{40},)+[0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
2697                                $from_id = [ split(',', $1) ];
2698                                $to_id   = $2;
2699                        }
2700
2701                        push @diff_header, $patch_line;
2702                }
2703                my $last_patch_line = $patch_line;
2704
2705                # check if current patch belong to current raw line
2706                # and parse raw git-diff line if needed
2707                if (defined $diffinfo &&
2708                    defined $from_id && defined $to_id &&
2709                    from_ids_eq($diffinfo->{'from_id'}, $from_id) &&
2710                    $diffinfo->{'to_id'} eq $to_id) {
2711                        # this is continuation of a split patch
2712                        print "<div class=\"patch cont\">\n";
2713                } else {
2714                        # advance raw git-diff output if needed
2715                        $patch_idx++ if defined $diffinfo;
2716
2717                        # read and prepare patch information
2718                        if (ref($difftree->[$patch_idx]) eq "HASH") {
2719                                # pre-parsed (or generated by hand)
2720                                $diffinfo = $difftree->[$patch_idx];
2721                        } else {
2722                                $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
2723                        }
2724                        if ($diffinfo->{'nparents'}) {
2725                                # combined diff
2726                                $from{'file'} = [];
2727                                $from{'href'} = [];
2728                                fill_from_file_info($diffinfo, @hash_parents)
2729                                        unless exists $diffinfo->{'from_file'};
2730                                for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2731                                        $from{'file'}[$i] = $diffinfo->{'from_file'}[$i] || $diffinfo->{'to_file'};
2732                                        if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2733                                                $from{'href'}[$i] = href(action=>"blob",
2734                                                                         hash_base=>$hash_parents[$i],
2735                                                                         hash=>$diffinfo->{'from_id'}[$i],
2736                                                                         file_name=>$from{'file'}[$i]);
2737                                        } else {
2738                                                $from{'href'}[$i] = undef;
2739                                        }
2740                                }
2741                        } else {
2742                                $from{'file'} = $diffinfo->{'from_file'} || $diffinfo->{'file'};
2743                                if ($diffinfo->{'status'} ne "A") { # not new (added) file
2744                                        $from{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2745                                                             hash=>$diffinfo->{'from_id'},
2746                                                             file_name=>$from{'file'});
2747                                } else {
2748                                        delete $from{'href'};
2749                                }
2750                        }
2751
2752                        $to{'file'} = $diffinfo->{'to_file'} || $diffinfo->{'file'};
2753                        if ($diffinfo->{'to_id'} ne ('0' x 40)) { # file exists in result
2754                                $to{'href'} = href(action=>"blob", hash_base=>$hash,
2755                                                   hash=>$diffinfo->{'to_id'},
2756                                                   file_name=>$to{'file'});
2757                        } else {
2758                                delete $to{'href'};
2759                        }
2760                        # this is first patch for raw difftree line with $patch_idx index
2761                        # we index @$difftree array from 0, but number patches from 1
2762                        print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
2763                }
2764
2765                # print "git diff" header
2766                $patch_line = shift @diff_header;
2767                if ($diffinfo->{'nparents'}) {
2768
2769                        # combined diff
2770                        $patch_line =~ s!^(diff (.*?) )"?.*$!$1!;
2771                        if ($to{'href'}) {
2772                                $patch_line .= $cgi->a({-href => $to{'href'}, -class => "path"},
2773                                                       esc_path($to{'file'}));
2774                        } else { # file was deleted
2775                                $patch_line .= esc_path($to{'file'});
2776                        }
2777
2778                } else {
2779
2780                        $patch_line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2781                        if ($from{'href'}) {
2782                                $patch_line .= $cgi->a({-href => $from{'href'}, -class => "path"},
2783                                                       'a/' . esc_path($from{'file'}));
2784                        } else { # file was added
2785                                $patch_line .= 'a/' . esc_path($from{'file'});
2786                        }
2787                        $patch_line .= ' ';
2788                        if ($to{'href'}) {
2789                                $patch_line .= $cgi->a({-href => $to{'href'}, -class => "path"},
2790                                                       'b/' . esc_path($to{'file'}));
2791                        } else { # file was deleted
2792                                $patch_line .= 'b/' . esc_path($to{'file'});
2793                        }
2794
2795                }
2796                print "<div class=\"diff header\">$patch_line</div>\n";
2797
2798                # print extended diff header
2799                print "<div class=\"diff extended_header\">\n" if (@diff_header > 0);
2800        EXTENDED_HEADER:
2801                foreach $patch_line (@diff_header) {
2802                        # match <path>
2803                        if ($patch_line =~ s!^((copy|rename) from ).*$!$1! && $from{'href'}) {
2804                                $patch_line .= $cgi->a({-href=>$from{'href'}, -class=>"path"},
2805                                                       esc_path($from{'file'}));
2806                        }
2807                        if ($patch_line =~ s!^((copy|rename) to ).*$!$1! && $to{'href'}) {
2808                                $patch_line .= $cgi->a({-href=>$to{'href'}, -class=>"path"},
2809                                                       esc_path($to{'file'}));
2810                        }
2811                        # match single <mode>
2812                        if ($patch_line =~ m/\s(\d{6})$/) {
2813                                $patch_line .= '<span class="info"> (' .
2814                                               file_type_long($1) .
2815                                               ')</span>';
2816                        }
2817                        # match <hash>
2818                        if ($patch_line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2819                                # can match only for combined diff
2820                                $patch_line = 'index ';
2821                                for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2822                                        if ($from{'href'}[$i]) {
2823                                                $patch_line .= $cgi->a({-href=>$from{'href'}[$i],
2824                                                                        -class=>"hash"},
2825                                                                       substr($diffinfo->{'from_id'}[$i],0,7));
2826                                        } else {
2827                                                $patch_line .= '0' x 7;
2828                                        }
2829                                        # separator
2830                                        $patch_line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2831                                }
2832                                $patch_line .= '..';
2833                                if ($to{'href'}) {
2834                                        $patch_line .= $cgi->a({-href=>$to{'href'}, -class=>"hash"},
2835                                                               substr($diffinfo->{'to_id'},0,7));
2836                                } else {
2837                                        $patch_line .= '0' x 7;
2838                                }
2839
2840                        } elsif ($patch_line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2841                                # can match only for ordinary diff
2842                                my ($from_link, $to_link);
2843                                if ($from{'href'}) {
2844                                        $from_link = $cgi->a({-href=>$from{'href'}, -class=>"hash"},
2845                                                             substr($diffinfo->{'from_id'},0,7));
2846                                } else {
2847                                        $from_link = '0' x 7;
2848                                }
2849                                if ($to{'href'}) {
2850                                        $to_link = $cgi->a({-href=>$to{'href'}, -class=>"hash"},
2851                                                           substr($diffinfo->{'to_id'},0,7));
2852                                } else {
2853                                        $to_link = '0' x 7;
2854                                }
2855                                #affirm {
2856                                #       my ($from_hash, $to_hash) =
2857                                #               ($patch_line =~ m/^index ([0-9a-fA-F]{40})..([0-9a-fA-F]{40})/);
2858                                #       my ($from_id, $to_id) =
2859                                #               ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2860                                #       ($from_hash eq $from_id) && ($to_hash eq $to_id);
2861                                #} if DEBUG;
2862                                my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2863                                $patch_line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2864                        }
2865                        print $patch_line . "<br/>\n";
2866                }
2867                print "</div>\n"  if (@diff_header > 0); # class="diff extended_header"
2868
2869                # from-file/to-file diff header
2870                $patch_line = $last_patch_line;
2871                if (! $patch_line) {
2872                        print "</div>\n"; # class="patch"
2873                        last PATCH;
2874                }
2875                next PATCH if ($patch_line =~ m/^diff /);
2876                #assert($patch_line =~ m/^---/) if DEBUG;
2877                if (!$diffinfo->{'nparents'} && # not from-file line for combined diff
2878                    $from{'href'} && $patch_line =~ m!^--- "?a/!) {
2879                        $patch_line = '--- a/' .
2880                                      $cgi->a({-href=>$from{'href'}, -class=>"path"},
2881                                              esc_path($from{'file'}));
2882                }
2883                print "<div class=\"diff from_file\">$patch_line</div>\n";
2884
2885                $patch_line = <$fd>;
2886                chomp $patch_line;
2887
2888                #assert($patch_line =~ m/^+++/) if DEBUG;
2889                if ($to{'href'} && $patch_line =~ m!^\+\+\+ "?b/!) {
2890                        $patch_line = '+++ b/' .
2891                                      $cgi->a({-href=>$to{'href'}, -class=>"path"},
2892                                              esc_path($to{'file'}));
2893                }
2894                print "<div class=\"diff to_file\">$patch_line</div>\n";
2895
2896                # the patch itself
2897        LINE:
2898                while ($patch_line = <$fd>) {
2899                        chomp $patch_line;
2900
2901                        next PATCH if ($patch_line =~ m/^diff /);
2902
2903                        print format_diff_line($patch_line, \%from, \%to);
2904                }
2905
2906        } continue {
2907                print "</div>\n"; # class="patch"
2908        }
2909
2910        if ($patch_number == 0) {
2911                if (@hash_parents > 1) {
2912                        print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
2913                } else {
2914                        print "<div class=\"diff nodifferences\">No differences found</div>\n";
2915                }
2916        }
2917
2918        print "</div>\n"; # class="patchset"
2919}
2920
2921# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2922
2923sub git_project_list_body {
2924        my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
2925
2926        my ($check_forks) = gitweb_check_feature('forks');
2927
2928        my @projects;
2929        foreach my $pr (@$projlist) {
2930                my (@aa) = git_get_last_activity($pr->{'path'});
2931                unless (@aa) {
2932                        next;
2933                }
2934                ($pr->{'age'}, $pr->{'age_string'}) = @aa;
2935                if (!defined $pr->{'descr'}) {
2936                        my $descr = git_get_project_description($pr->{'path'}) || "";
2937                        $pr->{'descr_long'} = decode_utf8($descr);
2938                        $pr->{'descr'} = chop_str($descr, 25, 5);
2939                }
2940                if (!defined $pr->{'owner'}) {
2941                        $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2942                }
2943                if ($check_forks) {
2944                        my $pname = $pr->{'path'};
2945                        if (($pname =~ s/\.git$//) &&
2946                            ($pname !~ /\/$/) &&
2947                            (-d "$projectroot/$pname")) {
2948                                $pr->{'forks'} = "-d $projectroot/$pname";
2949                        }
2950                        else {
2951                                $pr->{'forks'} = 0;
2952                        }
2953                }
2954                push @projects, $pr;
2955        }
2956
2957        $order ||= $default_projects_order;
2958        $from = 0 unless defined $from;
2959        $to = $#projects if (!defined $to || $#projects < $to);
2960
2961        print "<table class=\"project_list\">\n";
2962        unless ($no_header) {
2963                print "<tr>\n";
2964                if ($check_forks) {
2965                        print "<th></th>\n";
2966                }
2967                if ($order eq "project") {
2968                        @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2969                        print "<th>Project</th>\n";
2970                } else {
2971                        print "<th>" .
2972                              $cgi->a({-href => href(project=>undef, order=>'project'),
2973                                       -class => "header"}, "Project") .
2974                              "</th>\n";
2975                }
2976                if ($order eq "descr") {
2977                        @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2978                        print "<th>Description</th>\n";
2979                } else {
2980                        print "<th>" .
2981                              $cgi->a({-href => href(project=>undef, order=>'descr'),
2982                                       -class => "header"}, "Description") .
2983                              "</th>\n";
2984                }
2985                if ($order eq "owner") {
2986                        @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2987                        print "<th>Owner</th>\n";
2988                } else {
2989                        print "<th>" .
2990                              $cgi->a({-href => href(project=>undef, order=>'owner'),
2991                                       -class => "header"}, "Owner") .
2992                              "</th>\n";
2993                }
2994                if ($order eq "age") {
2995                        @projects = sort {$a->{'age'} <=> $b->{'age'}} @projects;
2996                        print "<th>Last Change</th>\n";
2997                } else {
2998                        print "<th>" .
2999                              $cgi->a({-href => href(project=>undef, order=>'age'),
3000                                       -class => "header"}, "Last Change") .
3001                              "</th>\n";
3002                }
3003                print "<th></th>\n" .
3004                      "</tr>\n";
3005        }
3006        my $alternate = 1;
3007        for (my $i = $from; $i <= $to; $i++) {
3008                my $pr = $projects[$i];
3009                if ($alternate) {
3010                        print "<tr class=\"dark\">\n";
3011                } else {
3012                        print "<tr class=\"light\">\n";
3013                }
3014                $alternate ^= 1;
3015                if ($check_forks) {
3016                        print "<td>";
3017                        if ($pr->{'forks'}) {
3018                                print "<!-- $pr->{'forks'} -->\n";
3019                                print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
3020                        }
3021                        print "</td>\n";
3022                }
3023                print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3024                                        -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
3025                      "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3026                                        -class => "list", -title => $pr->{'descr_long'}},
3027                                        esc_html($pr->{'descr'})) . "</td>\n" .
3028                      "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
3029                print "<td class=\"". age_class($pr->{'age'}) . "\">" .
3030                      (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
3031                      "<td class=\"link\">" .
3032                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
3033                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
3034                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
3035                      $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
3036                      ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
3037                      "</td>\n" .
3038                      "</tr>\n";
3039        }
3040        if (defined $extra) {
3041                print "<tr>\n";
3042                if ($check_forks) {
3043                        print "<td></td>\n";
3044                }
3045                print "<td colspan=\"5\">$extra</td>\n" .
3046                      "</tr>\n";
3047        }
3048        print "</table>\n";
3049}
3050
3051sub git_shortlog_body {
3052        # uses global variable $project
3053        my ($commitlist, $from, $to, $refs, $extra) = @_;
3054
3055        my $have_snapshot = gitweb_have_snapshot();
3056
3057        $from = 0 unless defined $from;
3058        $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3059
3060        print "<table class=\"shortlog\" cellspacing=\"0\">\n";
3061        my $alternate = 1;
3062        for (my $i = $from; $i <= $to; $i++) {
3063                my %co = %{$commitlist->[$i]};
3064                my $commit = $co{'id'};
3065                my $ref = format_ref_marker($refs, $commit);
3066                if ($alternate) {
3067                        print "<tr class=\"dark\">\n";
3068                } else {
3069                        print "<tr class=\"light\">\n";
3070                }
3071                $alternate ^= 1;
3072                # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
3073                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3074                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
3075                      "<td>";
3076                print format_subject_html($co{'title'}, $co{'title_short'},
3077                                          href(action=>"commit", hash=>$commit), $ref);
3078                print "</td>\n" .
3079                      "<td class=\"link\">" .
3080                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
3081                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
3082                      $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
3083                if ($have_snapshot) {
3084                        print " | " . $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
3085                }
3086                print "</td>\n" .
3087                      "</tr>\n";
3088        }
3089        if (defined $extra) {
3090                print "<tr>\n" .
3091                      "<td colspan=\"4\">$extra</td>\n" .
3092                      "</tr>\n";
3093        }
3094        print "</table>\n";
3095}
3096
3097sub git_history_body {
3098        # Warning: assumes constant type (blob or tree) during history
3099        my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
3100
3101        $from = 0 unless defined $from;
3102        $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
3103
3104        print "<table class=\"history\" cellspacing=\"0\">\n";
3105        my $alternate = 1;
3106        for (my $i = $from; $i <= $to; $i++) {
3107                my %co = %{$commitlist->[$i]};
3108                if (!%co) {
3109                        next;
3110                }
3111                my $commit = $co{'id'};
3112
3113                my $ref = format_ref_marker($refs, $commit);
3114
3115                if ($alternate) {
3116                        print "<tr class=\"dark\">\n";
3117                } else {
3118                        print "<tr class=\"light\">\n";
3119                }
3120                $alternate ^= 1;
3121                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3122                      # shortlog uses      chop_str($co{'author_name'}, 10)
3123                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
3124                      "<td>";
3125                # originally git_history used chop_str($co{'title'}, 50)
3126                print format_subject_html($co{'title'}, $co{'title_short'},
3127                                          href(action=>"commit", hash=>$commit), $ref);
3128                print "</td>\n" .
3129                      "<td class=\"link\">" .
3130                      $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
3131                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
3132
3133                if ($ftype eq 'blob') {
3134                        my $blob_current = git_get_hash_by_path($hash_base, $file_name);
3135                        my $blob_parent  = git_get_hash_by_path($commit, $file_name);
3136                        if (defined $blob_current && defined $blob_parent &&
3137                                        $blob_current ne $blob_parent) {
3138                                print " | " .
3139                                        $cgi->a({-href => href(action=>"blobdiff",
3140                                                               hash=>$blob_current, hash_parent=>$blob_parent,
3141                                                               hash_base=>$hash_base, hash_parent_base=>$commit,
3142                                                               file_name=>$file_name)},
3143                                                "diff to current");
3144                        }
3145                }
3146                print "</td>\n" .
3147                      "</tr>\n";
3148        }
3149        if (defined $extra) {
3150                print "<tr>\n" .
3151                      "<td colspan=\"4\">$extra</td>\n" .
3152                      "</tr>\n";
3153        }
3154        print "</table>\n";
3155}
3156
3157sub git_tags_body {
3158        # uses global variable $project
3159        my ($taglist, $from, $to, $extra) = @_;
3160        $from = 0 unless defined $from;
3161        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
3162
3163        print "<table class=\"tags\" cellspacing=\"0\">\n";
3164        my $alternate = 1;
3165        for (my $i = $from; $i <= $to; $i++) {
3166                my $entry = $taglist->[$i];
3167                my %tag = %$entry;
3168                my $comment = $tag{'subject'};
3169                my $comment_short;
3170                if (defined $comment) {
3171                        $comment_short = chop_str($comment, 30, 5);
3172                }
3173                if ($alternate) {
3174                        print "<tr class=\"dark\">\n";
3175                } else {
3176                        print "<tr class=\"light\">\n";
3177                }
3178                $alternate ^= 1;
3179                if (defined $tag{'age'}) {
3180                        print "<td><i>$tag{'age'}</i></td>\n";
3181                } else {
3182                        print "<td></td>\n";
3183                }
3184                print "<td>" .
3185                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
3186                               -class => "list name"}, esc_html($tag{'name'})) .
3187                      "</td>\n" .
3188                      "<td>";
3189                if (defined $comment) {
3190                        print format_subject_html($comment, $comment_short,
3191                                                  href(action=>"tag", hash=>$tag{'id'}));
3192                }
3193                print "</td>\n" .
3194                      "<td class=\"selflink\">";
3195                if ($tag{'type'} eq "tag") {
3196                        print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
3197                } else {
3198                        print "&nbsp;";
3199                }
3200                print "</td>\n" .
3201                      "<td class=\"link\">" . " | " .
3202                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
3203                if ($tag{'reftype'} eq "commit") {
3204                        print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
3205                              " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log");
3206                } elsif ($tag{'reftype'} eq "blob") {
3207                        print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
3208                }
3209                print "</td>\n" .
3210                      "</tr>";
3211        }
3212        if (defined $extra) {
3213                print "<tr>\n" .
3214                      "<td colspan=\"5\">$extra</td>\n" .
3215                      "</tr>\n";
3216        }
3217        print "</table>\n";
3218}
3219
3220sub git_heads_body {
3221        # uses global variable $project
3222        my ($headlist, $head, $from, $to, $extra) = @_;
3223        $from = 0 unless defined $from;
3224        $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
3225
3226        print "<table class=\"heads\" cellspacing=\"0\">\n";
3227        my $alternate = 1;
3228        for (my $i = $from; $i <= $to; $i++) {
3229                my $entry = $headlist->[$i];
3230                my %ref = %$entry;
3231                my $curr = $ref{'id'} eq $head;
3232                if ($alternate) {
3233                        print "<tr class=\"dark\">\n";
3234                } else {
3235                        print "<tr class=\"light\">\n";
3236                }
3237                $alternate ^= 1;
3238                print "<td><i>$ref{'age'}</i></td>\n" .
3239                      ($curr ? "<td class=\"current_head\">" : "<td>") .
3240                      $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'}),
3241                               -class => "list name"},esc_html($ref{'name'})) .
3242                      "</td>\n" .
3243                      "<td class=\"link\">" .
3244                      $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'})}, "shortlog") . " | " .
3245                      $cgi->a({-href => href(action=>"log", hash=>$ref{'name'})}, "log") . " | " .
3246                      $cgi->a({-href => href(action=>"tree", hash=>$ref{'name'}, hash_base=>$ref{'name'})}, "tree") .
3247                      "</td>\n" .
3248                      "</tr>";
3249        }
3250        if (defined $extra) {
3251                print "<tr>\n" .
3252                      "<td colspan=\"3\">$extra</td>\n" .
3253                      "</tr>\n";
3254        }
3255        print "</table>\n";
3256}
3257
3258sub git_search_grep_body {
3259        my ($commitlist, $from, $to, $extra) = @_;
3260        $from = 0 unless defined $from;
3261        $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3262
3263        print "<table class=\"grep\" cellspacing=\"0\">\n";
3264        my $alternate = 1;
3265        for (my $i = $from; $i <= $to; $i++) {
3266                my %co = %{$commitlist->[$i]};
3267                if (!%co) {
3268                        next;
3269                }
3270                my $commit = $co{'id'};
3271                if ($alternate) {
3272                        print "<tr class=\"dark\">\n";
3273                } else {
3274                        print "<tr class=\"light\">\n";
3275                }
3276                $alternate ^= 1;
3277                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3278                      "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3279                      "<td>" .
3280                      $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3281                               esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3282                my $comment = $co{'comment'};
3283                foreach my $line (@$comment) {
3284                        if ($line =~ m/^(.*)($search_regexp)(.*)$/i) {
3285                                my $lead = esc_html($1) || "";
3286                                $lead = chop_str($lead, 30, 10);
3287                                my $match = esc_html($2) || "";
3288                                my $trail = esc_html($3) || "";
3289                                $trail = chop_str($trail, 30, 10);
3290                                my $text = "$lead<span class=\"match\">$match</span>$trail";
3291                                print chop_str($text, 80, 5) . "<br/>\n";
3292                        }
3293                }
3294                print "</td>\n" .
3295                      "<td class=\"link\">" .
3296                      $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3297                      " | " .
3298                      $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3299                print "</td>\n" .
3300                      "</tr>\n";
3301        }
3302        if (defined $extra) {
3303                print "<tr>\n" .
3304                      "<td colspan=\"3\">$extra</td>\n" .
3305                      "</tr>\n";
3306        }
3307        print "</table>\n";
3308}
3309
3310## ======================================================================
3311## ======================================================================
3312## actions
3313
3314sub git_project_list {
3315        my $order = $cgi->param('o');
3316        if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3317                die_error(undef, "Unknown order parameter");
3318        }
3319
3320        my @list = git_get_projects_list();
3321        if (!@list) {
3322                die_error(undef, "No projects found");
3323        }
3324
3325        git_header_html();
3326        if (-f $home_text) {
3327                print "<div class=\"index_include\">\n";
3328                open (my $fd, $home_text);
3329                print <$fd>;
3330                close $fd;
3331                print "</div>\n";
3332        }
3333        git_project_list_body(\@list, $order);
3334        git_footer_html();
3335}
3336
3337sub git_forks {
3338        my $order = $cgi->param('o');
3339        if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3340                die_error(undef, "Unknown order parameter");
3341        }
3342
3343        my @list = git_get_projects_list($project);
3344        if (!@list) {
3345                die_error(undef, "No forks found");
3346        }
3347
3348        git_header_html();
3349        git_print_page_nav('','');
3350        git_print_header_div('summary', "$project forks");
3351        git_project_list_body(\@list, $order);
3352        git_footer_html();
3353}
3354
3355sub git_project_index {
3356        my @projects = git_get_projects_list($project);
3357
3358        print $cgi->header(
3359                -type => 'text/plain',
3360                -charset => 'utf-8',
3361                -content_disposition => 'inline; filename="index.aux"');
3362
3363        foreach my $pr (@projects) {
3364                if (!exists $pr->{'owner'}) {
3365                        $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}");
3366                }
3367
3368                my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
3369                # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
3370                $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3371                $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3372                $path  =~ s/ /\+/g;
3373                $owner =~ s/ /\+/g;
3374
3375                print "$path $owner\n";
3376        }
3377}
3378
3379sub git_summary {
3380        my $descr = git_get_project_description($project) || "none";
3381        my %co = parse_commit("HEAD");
3382        my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
3383        my $head = $co{'id'};
3384
3385        my $owner = git_get_project_owner($project);
3386
3387        my $refs = git_get_references();
3388        # These get_*_list functions return one more to allow us to see if
3389        # there are more ...
3390        my @taglist  = git_get_tags_list(16);
3391        my @headlist = git_get_heads_list(16);
3392        my @forklist;
3393        my ($check_forks) = gitweb_check_feature('forks');
3394
3395        if ($check_forks) {
3396                @forklist = git_get_projects_list($project);
3397        }
3398
3399        git_header_html();
3400        git_print_page_nav('summary','', $head);
3401
3402        print "<div class=\"title\">&nbsp;</div>\n";
3403        print "<table cellspacing=\"0\">\n" .
3404              "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
3405              "<tr><td>owner</td><td>$owner</td></tr>\n";
3406        if (defined $cd{'rfc2822'}) {
3407                print "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
3408        }
3409
3410        # use per project git URL list in $projectroot/$project/cloneurl
3411        # or make project git URL from git base URL and project name
3412        my $url_tag = "URL";
3413        my @url_list = git_get_project_url_list($project);
3414        @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
3415        foreach my $git_url (@url_list) {
3416                next unless $git_url;
3417                print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
3418                $url_tag = "";
3419        }
3420        print "</table>\n";
3421
3422        if (-s "$projectroot/$project/README.html") {
3423                if (open my $fd, "$projectroot/$project/README.html") {
3424                        print "<div class=\"title\">readme</div>\n";
3425                        print $_ while (<$fd>);
3426                        close $fd;
3427                }
3428        }
3429
3430        # we need to request one more than 16 (0..15) to check if
3431        # those 16 are all
3432        my @commitlist = $head ? parse_commits($head, 17) : ();
3433        if (@commitlist) {
3434                git_print_header_div('shortlog');
3435                git_shortlog_body(\@commitlist, 0, 15, $refs,
3436                                  $#commitlist <=  15 ? undef :
3437                                  $cgi->a({-href => href(action=>"shortlog")}, "..."));
3438        }
3439
3440        if (@taglist) {
3441                git_print_header_div('tags');
3442                git_tags_body(\@taglist, 0, 15,
3443                              $#taglist <=  15 ? undef :
3444                              $cgi->a({-href => href(action=>"tags")}, "..."));
3445        }
3446
3447        if (@headlist) {
3448                git_print_header_div('heads');
3449                git_heads_body(\@headlist, $head, 0, 15,
3450                               $#headlist <= 15 ? undef :
3451                               $cgi->a({-href => href(action=>"heads")}, "..."));
3452        }
3453
3454        if (@forklist) {
3455                git_print_header_div('forks');
3456                git_project_list_body(\@forklist, undef, 0, 15,
3457                                      $#forklist <= 15 ? undef :
3458                                      $cgi->a({-href => href(action=>"forks")}, "..."),
3459                                      'noheader');
3460        }
3461
3462        git_footer_html();
3463}
3464
3465sub git_tag {
3466        my $head = git_get_head_hash($project);
3467        git_header_html();
3468        git_print_page_nav('','', $head,undef,$head);
3469        my %tag = parse_tag($hash);
3470
3471        if (! %tag) {
3472                die_error(undef, "Unknown tag object");
3473        }
3474
3475        git_print_header_div('commit', esc_html($tag{'name'}), $hash);
3476        print "<div class=\"title_text\">\n" .
3477              "<table cellspacing=\"0\">\n" .
3478              "<tr>\n" .
3479              "<td>object</td>\n" .
3480              "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3481                               $tag{'object'}) . "</td>\n" .
3482              "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3483                                              $tag{'type'}) . "</td>\n" .
3484              "</tr>\n";
3485        if (defined($tag{'author'})) {
3486                my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
3487                print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
3488                print "<tr><td></td><td>" . $ad{'rfc2822'} .
3489                        sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
3490                        "</td></tr>\n";
3491        }
3492        print "</table>\n\n" .
3493              "</div>\n";
3494        print "<div class=\"page_body\">";
3495        my $comment = $tag{'comment'};
3496        foreach my $line (@$comment) {
3497                chomp $line;
3498                print esc_html($line, -nbsp=>1) . "<br/>\n";
3499        }
3500        print "</div>\n";
3501        git_footer_html();
3502}
3503
3504sub git_blame2 {
3505        my $fd;
3506        my $ftype;
3507
3508        my ($have_blame) = gitweb_check_feature('blame');
3509        if (!$have_blame) {
3510                die_error('403 Permission denied', "Permission denied");
3511        }
3512        die_error('404 Not Found', "File name not defined") if (!$file_name);
3513        $hash_base ||= git_get_head_hash($project);
3514        die_error(undef, "Couldn't find base commit") unless ($hash_base);
3515        my %co = parse_commit($hash_base)
3516                or die_error(undef, "Reading commit failed");
3517        if (!defined $hash) {
3518                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3519                        or die_error(undef, "Error looking up file");
3520        }
3521        $ftype = git_get_type($hash);
3522        if ($ftype !~ "blob") {
3523                die_error('400 Bad Request', "Object is not a blob");
3524        }
3525        open ($fd, "-|", git_cmd(), "blame", '-p', '--',
3526              $file_name, $hash_base)
3527                or die_error(undef, "Open git-blame failed");
3528        git_header_html();
3529        my $formats_nav =
3530                $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3531                        "blob") .
3532                " | " .
3533                $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3534                        "history") .
3535                " | " .
3536                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3537                        "HEAD");
3538        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3539        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3540        git_print_page_path($file_name, $ftype, $hash_base);
3541        my @rev_color = (qw(light2 dark2));
3542        my $num_colors = scalar(@rev_color);
3543        my $current_color = 0;
3544        my $last_rev;
3545        print <<HTML;
3546<div class="page_body">
3547<table class="blame">
3548<tr><th>Commit</th><th>Line</th><th>Data</th></tr>
3549HTML
3550        my %metainfo = ();
3551        while (1) {
3552                $_ = <$fd>;
3553                last unless defined $_;
3554                my ($full_rev, $orig_lineno, $lineno, $group_size) =
3555                    /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
3556                if (!exists $metainfo{$full_rev}) {
3557                        $metainfo{$full_rev} = {};
3558                }
3559                my $meta = $metainfo{$full_rev};
3560                while (<$fd>) {
3561                        last if (s/^\t//);
3562                        if (/^(\S+) (.*)$/) {
3563                                $meta->{$1} = $2;
3564                        }
3565                }
3566                my $data = $_;
3567                chomp $data;
3568                my $rev = substr($full_rev, 0, 8);
3569                my $author = $meta->{'author'};
3570                my %date = parse_date($meta->{'author-time'},
3571                                      $meta->{'author-tz'});
3572                my $date = $date{'iso-tz'};
3573                if ($group_size) {
3574                        $current_color = ++$current_color % $num_colors;
3575                }
3576                print "<tr class=\"$rev_color[$current_color]\">\n";
3577                if ($group_size) {
3578                        print "<td class=\"sha1\"";
3579                        print " title=\"". esc_html($author) . ", $date\"";
3580                        print " rowspan=\"$group_size\"" if ($group_size > 1);
3581                        print ">";
3582                        print $cgi->a({-href => href(action=>"commit",
3583                                                     hash=>$full_rev,
3584                                                     file_name=>$file_name)},
3585                                      esc_html($rev));
3586                        print "</td>\n";
3587                }
3588                open (my $dd, "-|", git_cmd(), "rev-parse", "$full_rev^")
3589                        or die_error(undef, "Open git-rev-parse failed");
3590                my $parent_commit = <$dd>;
3591                close $dd;
3592                chomp($parent_commit);
3593                my $blamed = href(action => 'blame',
3594                                  file_name => $meta->{'filename'},
3595                                  hash_base => $parent_commit);
3596                print "<td class=\"linenr\">";
3597                print $cgi->a({ -href => "$blamed#l$orig_lineno",
3598                                -id => "l$lineno",
3599                                -class => "linenr" },
3600                              esc_html($lineno));
3601                print "</td>";
3602                print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
3603                print "</tr>\n";
3604        }
3605        print "</table>\n";
3606        print "</div>";
3607        close $fd
3608                or print "Reading blob failed\n";
3609        git_footer_html();
3610}
3611
3612sub git_blame {
3613        my $fd;
3614
3615        my ($have_blame) = gitweb_check_feature('blame');
3616        if (!$have_blame) {
3617                die_error('403 Permission denied', "Permission denied");
3618        }
3619        die_error('404 Not Found', "File name not defined") if (!$file_name);
3620        $hash_base ||= git_get_head_hash($project);
3621        die_error(undef, "Couldn't find base commit") unless ($hash_base);
3622        my %co = parse_commit($hash_base)
3623                or die_error(undef, "Reading commit failed");
3624        if (!defined $hash) {
3625                $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3626                        or die_error(undef, "Error lookup file");
3627        }
3628        open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
3629                or die_error(undef, "Open git-annotate failed");
3630        git_header_html();
3631        my $formats_nav =
3632                $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3633                        "blob") .
3634                " | " .
3635                $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3636                        "history") .
3637                " | " .
3638                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3639                        "HEAD");
3640        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3641        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3642        git_print_page_path($file_name, 'blob', $hash_base);
3643        print "<div class=\"page_body\">\n";
3644        print <<HTML;
3645<table class="blame">
3646  <tr>
3647    <th>Commit</th>
3648    <th>Age</th>
3649    <th>Author</th>
3650    <th>Line</th>
3651    <th>Data</th>
3652  </tr>
3653HTML
3654        my @line_class = (qw(light dark));
3655        my $line_class_len = scalar (@line_class);
3656        my $line_class_num = $#line_class;
3657        while (my $line = <$fd>) {
3658                my $long_rev;
3659                my $short_rev;
3660                my $author;
3661                my $time;
3662                my $lineno;
3663                my $data;
3664                my $age;
3665                my $age_str;
3666                my $age_class;
3667
3668                chomp $line;
3669                $line_class_num = ($line_class_num + 1) % $line_class_len;
3670
3671                if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
3672                        $long_rev = $1;
3673                        $author   = $2;
3674                        $time     = $3;
3675                        $lineno   = $4;
3676                        $data     = $5;
3677                } else {
3678                        print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
3679                        next;
3680                }
3681                $short_rev  = substr ($long_rev, 0, 8);
3682                $age        = time () - $time;
3683                $age_str    = age_string ($age);
3684                $age_str    =~ s/ /&nbsp;/g;
3685                $age_class  = age_class($age);
3686                $author     = esc_html ($author);
3687                $author     =~ s/ /&nbsp;/g;
3688
3689                $data = untabify($data);
3690                $data = esc_html ($data);
3691
3692                print <<HTML;
3693  <tr class="$line_class[$line_class_num]">
3694    <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
3695    <td class="$age_class">$age_str</td>
3696    <td>$author</td>
3697    <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
3698    <td class="pre">$data</td>
3699  </tr>
3700HTML
3701        } # while (my $line = <$fd>)
3702        print "</table>\n\n";
3703        close $fd
3704                or print "Reading blob failed.\n";
3705        print "</div>";
3706        git_footer_html();
3707}
3708
3709sub git_tags {
3710        my $head = git_get_head_hash($project);
3711        git_header_html();
3712        git_print_page_nav('','', $head,undef,$head);
3713        git_print_header_div('summary', $project);
3714
3715        my @tagslist = git_get_tags_list();
3716        if (@tagslist) {
3717                git_tags_body(\@tagslist);
3718        }
3719        git_footer_html();
3720}
3721
3722sub git_heads {
3723        my $head = git_get_head_hash($project);
3724        git_header_html();
3725        git_print_page_nav('','', $head,undef,$head);
3726        git_print_header_div('summary', $project);
3727
3728        my @headslist = git_get_heads_list();
3729        if (@headslist) {
3730                git_heads_body(\@headslist, $head);
3731        }
3732        git_footer_html();
3733}
3734
3735sub git_blob_plain {
3736        my $expires;
3737
3738        if (!defined $hash) {
3739                if (defined $file_name) {
3740                        my $base = $hash_base || git_get_head_hash($project);
3741                        $hash = git_get_hash_by_path($base, $file_name, "blob")
3742                                or die_error(undef, "Error lookup file");
3743                } else {
3744                        die_error(undef, "No file name defined");
3745                }
3746        } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3747                # blobs defined by non-textual hash id's can be cached
3748                $expires = "+1d";
3749        }
3750
3751        my $type = shift;
3752        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3753                or die_error(undef, "Couldn't cat $file_name, $hash");
3754
3755        $type ||= blob_mimetype($fd, $file_name);
3756
3757        # save as filename, even when no $file_name is given
3758        my $save_as = "$hash";
3759        if (defined $file_name) {
3760                $save_as = $file_name;
3761        } elsif ($type =~ m/^text\//) {
3762                $save_as .= '.txt';
3763        }
3764
3765        print $cgi->header(
3766                -type => "$type",
3767                -expires=>$expires,
3768                -content_disposition => 'inline; filename="' . "$save_as" . '"');
3769        undef $/;
3770        binmode STDOUT, ':raw';
3771        print <$fd>;
3772        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
3773        $/ = "\n";
3774        close $fd;
3775}
3776
3777sub git_blob {
3778        my $expires;
3779
3780        if (!defined $hash) {
3781                if (defined $file_name) {
3782                        my $base = $hash_base || git_get_head_hash($project);
3783                        $hash = git_get_hash_by_path($base, $file_name, "blob")
3784                                or die_error(undef, "Error lookup file");
3785                } else {
3786                        die_error(undef, "No file name defined");
3787                }
3788        } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3789                # blobs defined by non-textual hash id's can be cached
3790                $expires = "+1d";
3791        }
3792
3793        my ($have_blame) = gitweb_check_feature('blame');
3794        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3795                or die_error(undef, "Couldn't cat $file_name, $hash");
3796        my $mimetype = blob_mimetype($fd, $file_name);
3797        if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)!) {
3798                close $fd;
3799                return git_blob_plain($mimetype);
3800        }
3801        # we can have blame only for text/* mimetype
3802        $have_blame &&= ($mimetype =~ m!^text/!);
3803
3804        git_header_html(undef, $expires);
3805        my $formats_nav = '';
3806        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3807                if (defined $file_name) {
3808                        if ($have_blame) {
3809                                $formats_nav .=
3810                                        $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
3811                                                               hash=>$hash, file_name=>$file_name)},
3812                                                "blame") .
3813                                        " | ";
3814                        }
3815                        $formats_nav .=
3816                                $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3817                                                       hash=>$hash, file_name=>$file_name)},
3818                                        "history") .
3819                                " | " .
3820                                $cgi->a({-href => href(action=>"blob_plain",
3821                                                       hash=>$hash, file_name=>$file_name)},
3822                                        "raw") .
3823                                " | " .
3824                                $cgi->a({-href => href(action=>"blob",
3825                                                       hash_base=>"HEAD", file_name=>$file_name)},
3826                                        "HEAD");
3827                } else {
3828                        $formats_nav .=
3829                                $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
3830                }
3831                git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3832                git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3833        } else {
3834                print "<div class=\"page_nav\">\n" .
3835                      "<br/><br/></div>\n" .
3836                      "<div class=\"title\">$hash</div>\n";
3837        }
3838        git_print_page_path($file_name, "blob", $hash_base);
3839        print "<div class=\"page_body\">\n";
3840        if ($mimetype =~ m!^text/!) {
3841                my $nr;
3842                while (my $line = <$fd>) {
3843                        chomp $line;
3844                        $nr++;
3845                        $line = untabify($line);
3846                        printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
3847                               $nr, $nr, $nr, esc_html($line, -nbsp=>1);
3848                }
3849        } elsif ($mimetype =~ m!^image/!) {
3850                print qq!<img type="$mimetype"!;
3851                if ($file_name) {
3852                        print qq! alt="$file_name" title="$file_name"!;
3853                }
3854                print qq! src="! .
3855                      href(action=>"blob_plain", hash=>$hash,
3856                           hash_base=>$hash_base, file_name=>$file_name) .
3857                      qq!" />\n!;
3858        }
3859        close $fd
3860                or print "Reading blob failed.\n";
3861        print "</div>";
3862        git_footer_html();
3863}
3864
3865sub git_tree {
3866        my $have_snapshot = gitweb_have_snapshot();
3867
3868        if (!defined $hash_base) {
3869                $hash_base = "HEAD";
3870        }
3871        if (!defined $hash) {
3872                if (defined $file_name) {
3873                        $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
3874                } else {
3875                        $hash = $hash_base;
3876                }
3877        }
3878        $/ = "\0";
3879        open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
3880                or die_error(undef, "Open git-ls-tree failed");
3881        my @entries = map { chomp; $_ } <$fd>;
3882        close $fd or die_error(undef, "Reading tree failed");
3883        $/ = "\n";
3884
3885        my $refs = git_get_references();
3886        my $ref = format_ref_marker($refs, $hash_base);
3887        git_header_html();
3888        my $basedir = '';
3889        my ($have_blame) = gitweb_check_feature('blame');
3890        if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3891                my @views_nav = ();
3892                if (defined $file_name) {
3893                        push @views_nav,
3894                                $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3895                                                       hash=>$hash, file_name=>$file_name)},
3896                                        "history"),
3897                                $cgi->a({-href => href(action=>"tree",
3898                                                       hash_base=>"HEAD", file_name=>$file_name)},
3899                                        "HEAD"),
3900                }
3901                if ($have_snapshot) {
3902                        # FIXME: Should be available when we have no hash base as well.
3903                        push @views_nav,
3904                                $cgi->a({-href => href(action=>"snapshot", hash=>$hash)},
3905                                        "snapshot");
3906                }
3907                git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
3908                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
3909        } else {
3910                undef $hash_base;
3911                print "<div class=\"page_nav\">\n";
3912                print "<br/><br/></div>\n";
3913                print "<div class=\"title\">$hash</div>\n";
3914        }
3915        if (defined $file_name) {
3916                $basedir = $file_name;
3917                if ($basedir ne '' && substr($basedir, -1) ne '/') {
3918                        $basedir .= '/';
3919                }
3920        }
3921        git_print_page_path($file_name, 'tree', $hash_base);
3922        print "<div class=\"page_body\">\n";
3923        print "<table cellspacing=\"0\">\n";
3924        my $alternate = 1;
3925        # '..' (top directory) link if possible
3926        if (defined $hash_base &&
3927            defined $file_name && $file_name =~ m![^/]+$!) {
3928                if ($alternate) {
3929                        print "<tr class=\"dark\">\n";
3930                } else {
3931                        print "<tr class=\"light\">\n";
3932                }
3933                $alternate ^= 1;
3934
3935                my $up = $file_name;
3936                $up =~ s!/?[^/]+$!!;
3937                undef $up unless $up;
3938                # based on git_print_tree_entry
3939                print '<td class="mode">' . mode_str('040000') . "</td>\n";
3940                print '<td class="list">';
3941                print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
3942                                             file_name=>$up)},
3943                              "..");
3944                print "</td>\n";
3945                print "<td class=\"link\"></td>\n";
3946
3947                print "</tr>\n";
3948        }
3949        foreach my $line (@entries) {
3950                my %t = parse_ls_tree_line($line, -z => 1);
3951
3952                if ($alternate) {
3953                        print "<tr class=\"dark\">\n";
3954                } else {
3955                        print "<tr class=\"light\">\n";
3956                }
3957                $alternate ^= 1;
3958
3959                git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
3960
3961                print "</tr>\n";
3962        }
3963        print "</table>\n" .
3964              "</div>";
3965        git_footer_html();
3966}
3967
3968sub git_snapshot {
3969        my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
3970        my $have_snapshot = (defined $ctype && defined $suffix);
3971        if (!$have_snapshot) {
3972                die_error('403 Permission denied', "Permission denied");
3973        }
3974
3975        if (!defined $hash) {
3976                $hash = git_get_head_hash($project);
3977        }
3978
3979        my $filename = decode_utf8(basename($project)) . "-$hash.tar.$suffix";
3980
3981        print $cgi->header(
3982                -type => "application/$ctype",
3983                -content_disposition => 'inline; filename="' . "$filename" . '"',
3984                -status => '200 OK');
3985
3986        my $git = git_cmd_str();
3987        my $name = $project;
3988        $name =~ s/\047/\047\\\047\047/g;
3989        open my $fd, "-|",
3990                "$git archive --format=tar --prefix=\'$name\'/ $hash | $command"
3991                or die_error(undef, "Execute git-tar-tree failed");
3992        binmode STDOUT, ':raw';
3993        print <$fd>;
3994        binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
3995        close $fd;
3996
3997}
3998
3999sub git_log {
4000        my $head = git_get_head_hash($project);
4001        if (!defined $hash) {
4002                $hash = $head;
4003        }
4004        if (!defined $page) {
4005                $page = 0;
4006        }
4007        my $refs = git_get_references();
4008
4009        my @commitlist = parse_commits($hash, 101, (100 * $page));
4010
4011        my $paging_nav = format_paging_nav('log', $hash, $head, $page, (100 * ($page+1)));
4012
4013        git_header_html();
4014        git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
4015
4016        if (!@commitlist) {
4017                my %co = parse_commit($hash);
4018
4019                git_print_header_div('summary', $project);
4020                print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
4021        }
4022        my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
4023        for (my $i = 0; $i <= $to; $i++) {
4024                my %co = %{$commitlist[$i]};
4025                next if !%co;
4026                my $commit = $co{'id'};
4027                my $ref = format_ref_marker($refs, $commit);
4028                my %ad = parse_date($co{'author_epoch'});
4029                git_print_header_div('commit',
4030                               "<span class=\"age\">$co{'age_string'}</span>" .
4031                               esc_html($co{'title'}) . $ref,
4032                               $commit);
4033                print "<div class=\"title_text\">\n" .
4034                      "<div class=\"log_link\">\n" .
4035                      $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4036                      " | " .
4037                      $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4038                      " | " .
4039                      $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4040                      "<br/>\n" .
4041                      "</div>\n" .
4042                      "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
4043                      "</div>\n";
4044
4045                print "<div class=\"log_body\">\n";
4046                git_print_log($co{'comment'}, -final_empty_line=> 1);
4047                print "</div>\n";
4048        }
4049        if ($#commitlist >= 100) {
4050                print "<div class=\"page_nav\">\n";
4051                print $cgi->a({-href => href(action=>"log", hash=>$hash, page=>$page+1),
4052                               -accesskey => "n", -title => "Alt-n"}, "next");
4053                print "</div>\n";
4054        }
4055        git_footer_html();
4056}
4057
4058sub git_commit {
4059        $hash ||= $hash_base || "HEAD";
4060        my %co = parse_commit($hash);
4061        if (!%co) {
4062                die_error(undef, "Unknown commit object");
4063        }
4064        my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4065        my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
4066
4067        my $parent  = $co{'parent'};
4068        my $parents = $co{'parents'}; # listref
4069
4070        # we need to prepare $formats_nav before any parameter munging
4071        my $formats_nav;
4072        if (!defined $parent) {
4073                # --root commitdiff
4074                $formats_nav .= '(initial)';
4075        } elsif (@$parents == 1) {
4076                # single parent commit
4077                $formats_nav .=
4078                        '(parent: ' .
4079                        $cgi->a({-href => href(action=>"commit",
4080                                               hash=>$parent)},
4081                                esc_html(substr($parent, 0, 7))) .
4082                        ')';
4083        } else {
4084                # merge commit
4085                $formats_nav .=
4086                        '(merge: ' .
4087                        join(' ', map {
4088                                $cgi->a({-href => href(action=>"commit",
4089                                                       hash=>$_)},
4090                                        esc_html(substr($_, 0, 7)));
4091                        } @$parents ) .
4092                        ')';
4093        }
4094
4095        if (!defined $parent) {
4096                $parent = "--root";
4097        }
4098        my @difftree;
4099        open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
4100                @diff_opts,
4101                (@$parents <= 1 ? $parent : '-c'),
4102                $hash, "--"
4103                or die_error(undef, "Open git-diff-tree failed");
4104        @difftree = map { chomp; $_ } <$fd>;
4105        close $fd or die_error(undef, "Reading git-diff-tree failed");
4106
4107        # non-textual hash id's can be cached
4108        my $expires;
4109        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4110                $expires = "+1d";
4111        }
4112        my $refs = git_get_references();
4113        my $ref = format_ref_marker($refs, $co{'id'});
4114
4115        my $have_snapshot = gitweb_have_snapshot();
4116
4117        git_header_html(undef, $expires);
4118        git_print_page_nav('commit', '',
4119                           $hash, $co{'tree'}, $hash,
4120                           $formats_nav);
4121
4122        if (defined $co{'parent'}) {
4123                git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
4124        } else {
4125                git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
4126        }
4127        print "<div class=\"title_text\">\n" .
4128              "<table cellspacing=\"0\">\n";
4129        print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
4130              "<tr>" .
4131              "<td></td><td> $ad{'rfc2822'}";
4132        if ($ad{'hour_local'} < 6) {
4133                printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
4134                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4135        } else {
4136                printf(" (%02d:%02d %s)",
4137                       $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4138        }
4139        print "</td>" .
4140              "</tr>\n";
4141        print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
4142        print "<tr><td></td><td> $cd{'rfc2822'}" .
4143              sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
4144              "</td></tr>\n";
4145        print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
4146        print "<tr>" .
4147              "<td>tree</td>" .
4148              "<td class=\"sha1\">" .
4149              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
4150                       class => "list"}, $co{'tree'}) .
4151              "</td>" .
4152              "<td class=\"link\">" .
4153              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
4154                      "tree");
4155        if ($have_snapshot) {
4156                print " | " .
4157                      $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
4158        }
4159        print "</td>" .
4160              "</tr>\n";
4161
4162        foreach my $par (@$parents) {
4163                print "<tr>" .
4164                      "<td>parent</td>" .
4165                      "<td class=\"sha1\">" .
4166                      $cgi->a({-href => href(action=>"commit", hash=>$par),
4167                               class => "list"}, $par) .
4168                      "</td>" .
4169                      "<td class=\"link\">" .
4170                      $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
4171                      " | " .
4172                      $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
4173                      "</td>" .
4174                      "</tr>\n";
4175        }
4176        print "</table>".
4177              "</div>\n";
4178
4179        print "<div class=\"page_body\">\n";
4180        git_print_log($co{'comment'});
4181        print "</div>\n";
4182
4183        git_difftree_body(\@difftree, $hash, @$parents);
4184
4185        git_footer_html();
4186}
4187
4188sub git_object {
4189        # object is defined by:
4190        # - hash or hash_base alone
4191        # - hash_base and file_name
4192        my $type;
4193
4194        # - hash or hash_base alone
4195        if ($hash || ($hash_base && !defined $file_name)) {
4196                my $object_id = $hash || $hash_base;
4197
4198                my $git_command = git_cmd_str();
4199                open my $fd, "-|", "$git_command cat-file -t $object_id 2>/dev/null"
4200                        or die_error('404 Not Found', "Object does not exist");
4201                $type = <$fd>;
4202                chomp $type;
4203                close $fd
4204                        or die_error('404 Not Found', "Object does not exist");
4205
4206        # - hash_base and file_name
4207        } elsif ($hash_base && defined $file_name) {
4208                $file_name =~ s,/+$,,;
4209
4210                system(git_cmd(), "cat-file", '-e', $hash_base) == 0
4211                        or die_error('404 Not Found', "Base object does not exist");
4212
4213                # here errors should not hapen
4214                open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
4215                        or die_error(undef, "Open git-ls-tree failed");
4216                my $line = <$fd>;
4217                close $fd;
4218
4219                #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
4220                unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
4221                        die_error('404 Not Found', "File or directory for given base does not exist");
4222                }
4223                $type = $2;
4224                $hash = $3;
4225        } else {
4226                die_error('404 Not Found', "Not enough information to find object");
4227        }
4228
4229        print $cgi->redirect(-uri => href(action=>$type, -full=>1,
4230                                          hash=>$hash, hash_base=>$hash_base,
4231                                          file_name=>$file_name),
4232                             -status => '302 Found');
4233}
4234
4235sub git_blobdiff {
4236        my $format = shift || 'html';
4237
4238        my $fd;
4239        my @difftree;
4240        my %diffinfo;
4241        my $expires;
4242
4243        # preparing $fd and %diffinfo for git_patchset_body
4244        # new style URI
4245        if (defined $hash_base && defined $hash_parent_base) {
4246                if (defined $file_name) {
4247                        # read raw output
4248                        open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4249                                $hash_parent_base, $hash_base,
4250                                "--", (defined $file_parent ? $file_parent : ()), $file_name
4251                                or die_error(undef, "Open git-diff-tree failed");
4252                        @difftree = map { chomp; $_ } <$fd>;
4253                        close $fd
4254                                or die_error(undef, "Reading git-diff-tree failed");
4255                        @difftree
4256                                or die_error('404 Not Found', "Blob diff not found");
4257
4258                } elsif (defined $hash &&
4259                         $hash =~ /[0-9a-fA-F]{40}/) {
4260                        # try to find filename from $hash
4261
4262                        # read filtered raw output
4263                        open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4264                                $hash_parent_base, $hash_base, "--"
4265                                or die_error(undef, "Open git-diff-tree failed");
4266                        @difftree =
4267                                # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
4268                                # $hash == to_id
4269                                grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
4270                                map { chomp; $_ } <$fd>;
4271                        close $fd
4272                                or die_error(undef, "Reading git-diff-tree failed");
4273                        @difftree
4274                                or die_error('404 Not Found', "Blob diff not found");
4275
4276                } else {
4277                        die_error('404 Not Found', "Missing one of the blob diff parameters");
4278                }
4279
4280                if (@difftree > 1) {
4281                        die_error('404 Not Found', "Ambiguous blob diff specification");
4282                }
4283
4284                %diffinfo = parse_difftree_raw_line($difftree[0]);
4285                $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
4286                $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
4287
4288                $hash_parent ||= $diffinfo{'from_id'};
4289                $hash        ||= $diffinfo{'to_id'};
4290
4291                # non-textual hash id's can be cached
4292                if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
4293                    $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
4294                        $expires = '+1d';
4295                }
4296
4297                # open patch output
4298                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4299                        '-p', ($format eq 'html' ? "--full-index" : ()),
4300                        $hash_parent_base, $hash_base,
4301                        "--", (defined $file_parent ? $file_parent : ()), $file_name
4302                        or die_error(undef, "Open git-diff-tree failed");
4303        }
4304
4305        # old/legacy style URI
4306        if (!%diffinfo && # if new style URI failed
4307            defined $hash && defined $hash_parent) {
4308                # fake git-diff-tree raw output
4309                $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
4310                $diffinfo{'from_id'} = $hash_parent;
4311                $diffinfo{'to_id'}   = $hash;
4312                if (defined $file_name) {
4313                        if (defined $file_parent) {
4314                                $diffinfo{'status'} = '2';
4315                                $diffinfo{'from_file'} = $file_parent;
4316                                $diffinfo{'to_file'}   = $file_name;
4317                        } else { # assume not renamed
4318                                $diffinfo{'status'} = '1';
4319                                $diffinfo{'from_file'} = $file_name;
4320                                $diffinfo{'to_file'}   = $file_name;
4321                        }
4322                } else { # no filename given
4323                        $diffinfo{'status'} = '2';
4324                        $diffinfo{'from_file'} = $hash_parent;
4325                        $diffinfo{'to_file'}   = $hash;
4326                }
4327
4328                # non-textual hash id's can be cached
4329                if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
4330                    $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4331                        $expires = '+1d';
4332                }
4333
4334                # open patch output
4335                open $fd, "-|", git_cmd(), "diff", @diff_opts,
4336                        '-p', ($format eq 'html' ? "--full-index" : ()),
4337                        $hash_parent, $hash, "--"
4338                        or die_error(undef, "Open git-diff failed");
4339        } else  {
4340                die_error('404 Not Found', "Missing one of the blob diff parameters")
4341                        unless %diffinfo;
4342        }
4343
4344        # header
4345        if ($format eq 'html') {
4346                my $formats_nav =
4347                        $cgi->a({-href => href(action=>"blobdiff_plain",
4348                                               hash=>$hash, hash_parent=>$hash_parent,
4349                                               hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
4350                                               file_name=>$file_name, file_parent=>$file_parent)},
4351                                "raw");
4352                git_header_html(undef, $expires);
4353                if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4354                        git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4355                        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4356                } else {
4357                        print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
4358                        print "<div class=\"title\">$hash vs $hash_parent</div>\n";
4359                }
4360                if (defined $file_name) {
4361                        git_print_page_path($file_name, "blob", $hash_base);
4362                } else {
4363                        print "<div class=\"page_path\"></div>\n";
4364                }
4365
4366        } elsif ($format eq 'plain') {
4367                print $cgi->header(
4368                        -type => 'text/plain',
4369                        -charset => 'utf-8',
4370                        -expires => $expires,
4371                        -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
4372
4373                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4374
4375        } else {
4376                die_error(undef, "Unknown blobdiff format");
4377        }
4378
4379        # patch
4380        if ($format eq 'html') {
4381                print "<div class=\"page_body\">\n";
4382
4383                git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
4384                close $fd;
4385
4386                print "</div>\n"; # class="page_body"
4387                git_footer_html();
4388
4389        } else {
4390                while (my $line = <$fd>) {
4391                        $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
4392                        $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
4393
4394                        print $line;
4395
4396                        last if $line =~ m!^\+\+\+!;
4397                }
4398                local $/ = undef;
4399                print <$fd>;
4400                close $fd;
4401        }
4402}
4403
4404sub git_blobdiff_plain {
4405        git_blobdiff('plain');
4406}
4407
4408sub git_commitdiff {
4409        my $format = shift || 'html';
4410        $hash ||= $hash_base || "HEAD";
4411        my %co = parse_commit($hash);
4412        if (!%co) {
4413                die_error(undef, "Unknown commit object");
4414        }
4415
4416        # we need to prepare $formats_nav before any parameter munging
4417        my $formats_nav;
4418        if ($format eq 'html') {
4419                $formats_nav =
4420                        $cgi->a({-href => href(action=>"commitdiff_plain",
4421                                               hash=>$hash, hash_parent=>$hash_parent)},
4422                                "raw");
4423
4424                if (defined $hash_parent) {
4425                        # commitdiff with two commits given
4426                        my $hash_parent_short = $hash_parent;
4427                        if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4428                                $hash_parent_short = substr($hash_parent, 0, 7);
4429                        }
4430                        $formats_nav .=
4431                                ' (from: ' .
4432                                $cgi->a({-href => href(action=>"commitdiff",
4433                                                       hash=>$hash_parent)},
4434                                        esc_html($hash_parent_short)) .
4435                                ')';
4436                } elsif (!$co{'parent'}) {
4437                        # --root commitdiff
4438                        $formats_nav .= ' (initial)';
4439                } elsif (scalar @{$co{'parents'}} == 1) {
4440                        # single parent commit
4441                        $formats_nav .=
4442                                ' (parent: ' .
4443                                $cgi->a({-href => href(action=>"commitdiff",
4444                                                       hash=>$co{'parent'})},
4445                                        esc_html(substr($co{'parent'}, 0, 7))) .
4446                                ')';
4447                } else {
4448                        # merge commit
4449                        $formats_nav .=
4450                                ' (merge: ' .
4451                                join(' ', map {
4452                                        $cgi->a({-href => href(action=>"commitdiff",
4453                                                               hash=>$_)},
4454                                                esc_html(substr($_, 0, 7)));
4455                                } @{$co{'parents'}} ) .
4456                                ')';
4457                }
4458        }
4459
4460        my $hash_parent_param = $hash_parent;
4461        if (!defined $hash_parent) {
4462                $hash_parent_param =
4463                        @{$co{'parents'}} > 1 ? '-c' : $co{'parent'} || '--root';
4464        }
4465
4466        # read commitdiff
4467        my $fd;
4468        my @difftree;
4469        if ($format eq 'html') {
4470                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4471                        "--no-commit-id", "--patch-with-raw", "--full-index",
4472                        $hash_parent_param, $hash, "--"
4473                        or die_error(undef, "Open git-diff-tree failed");
4474
4475                while (my $line = <$fd>) {
4476                        chomp $line;
4477                        # empty line ends raw part of diff-tree output
4478                        last unless $line;
4479                        push @difftree, scalar parse_difftree_raw_line($line);
4480                }
4481
4482        } elsif ($format eq 'plain') {
4483                open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4484                        '-p', $hash_parent_param, $hash, "--"
4485                        or die_error(undef, "Open git-diff-tree failed");
4486
4487        } else {
4488                die_error(undef, "Unknown commitdiff format");
4489        }
4490
4491        # non-textual hash id's can be cached
4492        my $expires;
4493        if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4494                $expires = "+1d";
4495        }
4496
4497        # write commit message
4498        if ($format eq 'html') {
4499                my $refs = git_get_references();
4500                my $ref = format_ref_marker($refs, $co{'id'});
4501
4502                git_header_html(undef, $expires);
4503                git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
4504                git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
4505                git_print_authorship(\%co);
4506                print "<div class=\"page_body\">\n";
4507                if (@{$co{'comment'}} > 1) {
4508                        print "<div class=\"log\">\n";
4509                        git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
4510                        print "</div>\n"; # class="log"
4511                }
4512
4513        } elsif ($format eq 'plain') {
4514                my $refs = git_get_references("tags");
4515                my $tagname = git_get_rev_name_tags($hash);
4516                my $filename = basename($project) . "-$hash.patch";
4517
4518                print $cgi->header(
4519                        -type => 'text/plain',
4520                        -charset => 'utf-8',
4521                        -expires => $expires,
4522                        -content_disposition => 'inline; filename="' . "$filename" . '"');
4523                my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4524                print <<TEXT;
4525From: $co{'author'}
4526Date: $ad{'rfc2822'} ($ad{'tz_local'})
4527Subject: $co{'title'}
4528TEXT
4529                print "X-Git-Tag: $tagname\n" if $tagname;
4530                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4531
4532                foreach my $line (@{$co{'comment'}}) {
4533                        print "$line\n";
4534                }
4535                print "---\n\n";
4536        }
4537
4538        # write patch
4539        if ($format eq 'html') {
4540                git_difftree_body(\@difftree, $hash, $hash_parent || @{$co{'parents'}});
4541                print "<br/>\n";
4542
4543                git_patchset_body($fd, \@difftree, $hash, $hash_parent || @{$co{'parents'}});
4544                close $fd;
4545                print "</div>\n"; # class="page_body"
4546                git_footer_html();
4547
4548        } elsif ($format eq 'plain') {
4549                local $/ = undef;
4550                print <$fd>;
4551                close $fd
4552                        or print "Reading git-diff-tree failed\n";
4553        }
4554}
4555
4556sub git_commitdiff_plain {
4557        git_commitdiff('plain');
4558}
4559
4560sub git_history {
4561        if (!defined $hash_base) {
4562                $hash_base = git_get_head_hash($project);
4563        }
4564        if (!defined $page) {
4565                $page = 0;
4566        }
4567        my $ftype;
4568        my %co = parse_commit($hash_base);
4569        if (!%co) {
4570                die_error(undef, "Unknown commit object");
4571        }
4572
4573        my $refs = git_get_references();
4574        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
4575
4576        if (!defined $hash && defined $file_name) {
4577                $hash = git_get_hash_by_path($hash_base, $file_name);
4578        }
4579        if (defined $hash) {
4580                $ftype = git_get_type($hash);
4581        }
4582
4583        my @commitlist = parse_commits($hash_base, 101, (100 * $page), "--full-history", $file_name);
4584
4585        my $paging_nav = '';
4586        if ($page > 0) {
4587                $paging_nav .=
4588                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4589                                               file_name=>$file_name)},
4590                                "first");
4591                $paging_nav .= " &sdot; " .
4592                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4593                                               file_name=>$file_name, page=>$page-1),
4594                                 -accesskey => "p", -title => "Alt-p"}, "prev");
4595        } else {
4596                $paging_nav .= "first";
4597                $paging_nav .= " &sdot; prev";
4598        }
4599        if ($#commitlist >= 100) {
4600                $paging_nav .= " &sdot; " .
4601                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4602                                               file_name=>$file_name, page=>$page+1),
4603                                 -accesskey => "n", -title => "Alt-n"}, "next");
4604        } else {
4605                $paging_nav .= " &sdot; next";
4606        }
4607        my $next_link = '';
4608        if ($#commitlist >= 100) {
4609                $next_link =
4610                        $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4611                                               file_name=>$file_name, page=>$page+1),
4612                                 -accesskey => "n", -title => "Alt-n"}, "next");
4613        }
4614
4615        git_header_html();
4616        git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
4617        git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4618        git_print_page_path($file_name, $ftype, $hash_base);
4619
4620        git_history_body(\@commitlist, 0, 99,
4621                         $refs, $hash_base, $ftype, $next_link);
4622
4623        git_footer_html();
4624}
4625
4626sub git_search {
4627        my ($have_search) = gitweb_check_feature('search');
4628        if (!$have_search) {
4629                die_error('403 Permission denied', "Permission denied");
4630        }
4631        if (!defined $searchtext) {
4632                die_error(undef, "Text field empty");
4633        }
4634        if (!defined $hash) {
4635                $hash = git_get_head_hash($project);
4636        }
4637        my %co = parse_commit($hash);
4638        if (!%co) {
4639                die_error(undef, "Unknown commit object");
4640        }
4641        if (!defined $page) {
4642                $page = 0;
4643        }
4644
4645        $searchtype ||= 'commit';
4646        if ($searchtype eq 'pickaxe') {
4647                # pickaxe may take all resources of your box and run for several minutes
4648                # with every query - so decide by yourself how public you make this feature
4649                my ($have_pickaxe) = gitweb_check_feature('pickaxe');
4650                if (!$have_pickaxe) {
4651                        die_error('403 Permission denied', "Permission denied");
4652                }
4653        }
4654        if ($searchtype eq 'grep') {
4655                my ($have_grep) = gitweb_check_feature('grep');
4656                if (!$have_grep) {
4657                        die_error('403 Permission denied', "Permission denied");
4658                }
4659        }
4660
4661        git_header_html();
4662
4663        if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
4664                my $greptype;
4665                if ($searchtype eq 'commit') {
4666                        $greptype = "--grep=";
4667                } elsif ($searchtype eq 'author') {
4668                        $greptype = "--author=";
4669                } elsif ($searchtype eq 'committer') {
4670                        $greptype = "--committer=";
4671                }
4672                $greptype .= $search_regexp;
4673                my @commitlist = parse_commits($hash, 101, (100 * $page), $greptype);
4674
4675                my $paging_nav = '';
4676                if ($page > 0) {
4677                        $paging_nav .=
4678                                $cgi->a({-href => href(action=>"search", hash=>$hash,
4679                                                       searchtext=>$searchtext, searchtype=>$searchtype)},
4680                                        "first");
4681                        $paging_nav .= " &sdot; " .
4682                                $cgi->a({-href => href(action=>"search", hash=>$hash,
4683                                                       searchtext=>$searchtext, searchtype=>$searchtype,
4684                                                       page=>$page-1),
4685                                         -accesskey => "p", -title => "Alt-p"}, "prev");
4686                } else {
4687                        $paging_nav .= "first";
4688                        $paging_nav .= " &sdot; prev";
4689                }
4690                if ($#commitlist >= 100) {
4691                        $paging_nav .= " &sdot; " .
4692                                $cgi->a({-href => href(action=>"search", hash=>$hash,
4693                                                       searchtext=>$searchtext, searchtype=>$searchtype,
4694                                                       page=>$page+1),
4695                                         -accesskey => "n", -title => "Alt-n"}, "next");
4696                } else {
4697                        $paging_nav .= " &sdot; next";
4698                }
4699                my $next_link = '';
4700                if ($#commitlist >= 100) {
4701                        $next_link =
4702                                $cgi->a({-href => href(action=>"search", hash=>$hash,
4703                                                       searchtext=>$searchtext, searchtype=>$searchtype,
4704                                                       page=>$page+1),
4705                                         -accesskey => "n", -title => "Alt-n"}, "next");
4706                }
4707
4708                git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
4709                git_print_header_div('commit', esc_html($co{'title'}), $hash);
4710                git_search_grep_body(\@commitlist, 0, 99, $next_link);
4711        }
4712
4713        if ($searchtype eq 'pickaxe') {
4714                git_print_page_nav('','', $hash,$co{'tree'},$hash);
4715                git_print_header_div('commit', esc_html($co{'title'}), $hash);
4716
4717                print "<table cellspacing=\"0\">\n";
4718                my $alternate = 1;
4719                $/ = "\n";
4720                my $git_command = git_cmd_str();
4721                my $searchqtext = $searchtext;
4722                $searchqtext =~ s/'/'\\''/;
4723                open my $fd, "-|", "$git_command rev-list $hash | " .
4724                        "$git_command diff-tree -r --stdin -S\'$searchqtext\'";
4725                undef %co;
4726                my @files;
4727                while (my $line = <$fd>) {
4728                        if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
4729                                my %set;
4730                                $set{'file'} = $6;
4731                                $set{'from_id'} = $3;
4732                                $set{'to_id'} = $4;
4733                                $set{'id'} = $set{'to_id'};
4734                                if ($set{'id'} =~ m/0{40}/) {
4735                                        $set{'id'} = $set{'from_id'};
4736                                }
4737                                if ($set{'id'} =~ m/0{40}/) {
4738                                        next;
4739                                }
4740                                push @files, \%set;
4741                        } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
4742                                if (%co) {
4743                                        if ($alternate) {
4744                                                print "<tr class=\"dark\">\n";
4745                                        } else {
4746                                                print "<tr class=\"light\">\n";
4747                                        }
4748                                        $alternate ^= 1;
4749                                        print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4750                                              "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
4751                                              "<td>" .
4752                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4753                                                      -class => "list subject"},
4754                                                      esc_html(chop_str($co{'title'}, 50)) . "<br/>");
4755                                        while (my $setref = shift @files) {
4756                                                my %set = %$setref;
4757                                                print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
4758                                                                             hash=>$set{'id'}, file_name=>$set{'file'}),
4759                                                              -class => "list"},
4760                                                              "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
4761                                                      "<br/>\n";
4762                                        }
4763                                        print "</td>\n" .
4764                                              "<td class=\"link\">" .
4765                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4766                                              " | " .
4767                                              $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4768                                        print "</td>\n" .
4769                                              "</tr>\n";
4770                                }
4771                                %co = parse_commit($1);
4772                        }
4773                }
4774                close $fd;
4775
4776                print "</table>\n";
4777        }
4778
4779        if ($searchtype eq 'grep') {
4780                git_print_page_nav('','', $hash,$co{'tree'},$hash);
4781                git_print_header_div('commit', esc_html($co{'title'}), $hash);
4782
4783                print "<table cellspacing=\"0\">\n";
4784                my $alternate = 1;
4785                my $matches = 0;
4786                $/ = "\n";
4787                open my $fd, "-|", git_cmd(), 'grep', '-n', '-i', '-E', $searchtext, $co{'tree'};
4788                my $lastfile = '';
4789                while (my $line = <$fd>) {
4790                        chomp $line;
4791                        my ($file, $lno, $ltext, $binary);
4792                        last if ($matches++ > 1000);
4793                        if ($line =~ /^Binary file (.+) matches$/) {
4794                                $file = $1;
4795                                $binary = 1;
4796                        } else {
4797                                (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
4798                        }
4799                        if ($file ne $lastfile) {
4800                                $lastfile and print "</td></tr>\n";
4801                                if ($alternate++) {
4802                                        print "<tr class=\"dark\">\n";
4803                                } else {
4804                                        print "<tr class=\"light\">\n";
4805                                }
4806                                print "<td class=\"list\">".
4807                                        $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
4808                                                               file_name=>"$file"),
4809                                                -class => "list"}, esc_path($file));
4810                                print "</td><td>\n";
4811                                $lastfile = $file;
4812                        }
4813                        if ($binary) {
4814                                print "<div class=\"binary\">Binary file</div>\n";
4815                        } else {
4816                                $ltext = untabify($ltext);
4817                                if ($ltext =~ m/^(.*)($searchtext)(.*)$/i) {
4818                                        $ltext = esc_html($1, -nbsp=>1);
4819                                        $ltext .= '<span class="match">';
4820                                        $ltext .= esc_html($2, -nbsp=>1);
4821                                        $ltext .= '</span>';
4822                                        $ltext .= esc_html($3, -nbsp=>1);
4823                                } else {
4824                                        $ltext = esc_html($ltext, -nbsp=>1);
4825                                }
4826                                print "<div class=\"pre\">" .
4827                                        $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
4828                                                               file_name=>"$file").'#l'.$lno,
4829                                                -class => "linenr"}, sprintf('%4i', $lno))
4830                                        . ' ' .  $ltext . "</div>\n";
4831                        }
4832                }
4833                if ($lastfile) {
4834                        print "</td></tr>\n";
4835                        if ($matches > 1000) {
4836                                print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
4837                        }
4838                } else {
4839                        print "<div class=\"diff nodifferences\">No matches found</div>\n";
4840                }
4841                close $fd;
4842
4843                print "</table>\n";
4844        }
4845        git_footer_html();
4846}
4847
4848sub git_search_help {
4849        git_header_html();
4850        git_print_page_nav('','', $hash,$hash,$hash);
4851        print <<EOT;
4852<dl>
4853<dt><b>commit</b></dt>
4854<dd>The commit messages and authorship information will be scanned for the given string.</dd>
4855EOT
4856        my ($have_grep) = gitweb_check_feature('grep');
4857        if ($have_grep) {
4858                print <<EOT;
4859<dt><b>grep</b></dt>
4860<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
4861    a different one) are searched for the given
4862<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a>
4863(POSIX extended) and the matches are listed. On large
4864trees, this search can take a while and put some strain on the server, so please use it with
4865some consideration.</dd>
4866EOT
4867        }
4868        print <<EOT;
4869<dt><b>author</b></dt>
4870<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given string.</dd>
4871<dt><b>committer</b></dt>
4872<dd>Name and e-mail of the committer and date of commit will be scanned for the given string.</dd>
4873EOT
4874        my ($have_pickaxe) = gitweb_check_feature('pickaxe');
4875        if ($have_pickaxe) {
4876                print <<EOT;
4877<dt><b>pickaxe</b></dt>
4878<dd>All commits that caused the string to appear or disappear from any file (changes that
4879added, removed or "modified" the string) will be listed. This search can take a while and
4880takes a lot of strain on the server, so please use it wisely.</dd>
4881EOT
4882        }
4883        print "</dl>\n";
4884        git_footer_html();
4885}
4886
4887sub git_shortlog {
4888        my $head = git_get_head_hash($project);
4889        if (!defined $hash) {
4890                $hash = $head;
4891        }
4892        if (!defined $page) {
4893                $page = 0;
4894        }
4895        my $refs = git_get_references();
4896
4897        my @commitlist = parse_commits($hash, 101, (100 * $page));
4898
4899        my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, (100 * ($page+1)));
4900        my $next_link = '';
4901        if ($#commitlist >= 100) {
4902                $next_link =
4903                        $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
4904                                 -accesskey => "n", -title => "Alt-n"}, "next");
4905        }
4906
4907        git_header_html();
4908        git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
4909        git_print_header_div('summary', $project);
4910
4911        git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
4912
4913        git_footer_html();
4914}
4915
4916## ......................................................................
4917## feeds (RSS, Atom; OPML)
4918
4919sub git_feed {
4920        my $format = shift || 'atom';
4921        my ($have_blame) = gitweb_check_feature('blame');
4922
4923        # Atom: http://www.atomenabled.org/developers/syndication/
4924        # RSS:  http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
4925        if ($format ne 'rss' && $format ne 'atom') {
4926                die_error(undef, "Unknown web feed format");
4927        }
4928
4929        # log/feed of current (HEAD) branch, log of given branch, history of file/directory
4930        my $head = $hash || 'HEAD';
4931        my @commitlist = parse_commits($head, 150);
4932
4933        my %latest_commit;
4934        my %latest_date;
4935        my $content_type = "application/$format+xml";
4936        if (defined $cgi->http('HTTP_ACCEPT') &&
4937                 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
4938                # browser (feed reader) prefers text/xml
4939                $content_type = 'text/xml';
4940        }
4941        if (defined($commitlist[0])) {
4942                %latest_commit = %{$commitlist[0]};
4943                %latest_date   = parse_date($latest_commit{'author_epoch'});
4944                print $cgi->header(
4945                        -type => $content_type,
4946                        -charset => 'utf-8',
4947                        -last_modified => $latest_date{'rfc2822'});
4948        } else {
4949                print $cgi->header(
4950                        -type => $content_type,
4951                        -charset => 'utf-8');
4952        }
4953
4954        # Optimization: skip generating the body if client asks only
4955        # for Last-Modified date.
4956        return if ($cgi->request_method() eq 'HEAD');
4957
4958        # header variables
4959        my $title = "$site_name - $project/$action";
4960        my $feed_type = 'log';
4961        if (defined $hash) {
4962                $title .= " - '$hash'";
4963                $feed_type = 'branch log';
4964                if (defined $file_name) {
4965                        $title .= " :: $file_name";
4966                        $feed_type = 'history';
4967                }
4968        } elsif (defined $file_name) {
4969                $title .= " - $file_name";
4970                $feed_type = 'history';
4971        }
4972        $title .= " $feed_type";
4973        my $descr = git_get_project_description($project);
4974        if (defined $descr) {
4975                $descr = esc_html($descr);
4976        } else {
4977                $descr = "$project " .
4978                         ($format eq 'rss' ? 'RSS' : 'Atom') .
4979                         " feed";
4980        }
4981        my $owner = git_get_project_owner($project);
4982        $owner = esc_html($owner);
4983
4984        #header
4985        my $alt_url;
4986        if (defined $file_name) {
4987                $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
4988        } elsif (defined $hash) {
4989                $alt_url = href(-full=>1, action=>"log", hash=>$hash);
4990        } else {
4991                $alt_url = href(-full=>1, action=>"summary");
4992        }
4993        print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
4994        if ($format eq 'rss') {
4995                print <<XML;
4996<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
4997<channel>
4998XML
4999                print "<title>$title</title>\n" .
5000                      "<link>$alt_url</link>\n" .
5001                      "<description>$descr</description>\n" .
5002                      "<language>en</language>\n";
5003        } elsif ($format eq 'atom') {
5004                print <<XML;
5005<feed xmlns="http://www.w3.org/2005/Atom">
5006XML
5007                print "<title>$title</title>\n" .
5008                      "<subtitle>$descr</subtitle>\n" .
5009                      '<link rel="alternate" type="text/html" href="' .
5010                      $alt_url . '" />' . "\n" .
5011                      '<link rel="self" type="' . $content_type . '" href="' .
5012                      $cgi->self_url() . '" />' . "\n" .
5013                      "<id>" . href(-full=>1) . "</id>\n" .
5014                      # use project owner for feed author
5015                      "<author><name>$owner</name></author>\n";
5016                if (defined $favicon) {
5017                        print "<icon>" . esc_url($favicon) . "</icon>\n";
5018                }
5019                if (defined $logo_url) {
5020                        # not twice as wide as tall: 72 x 27 pixels
5021                        print "<logo>" . esc_url($logo) . "</logo>\n";
5022                }
5023                if (! %latest_date) {
5024                        # dummy date to keep the feed valid until commits trickle in:
5025                        print "<updated>1970-01-01T00:00:00Z</updated>\n";
5026                } else {
5027                        print "<updated>$latest_date{'iso-8601'}</updated>\n";
5028                }
5029        }
5030
5031        # contents
5032        for (my $i = 0; $i <= $#commitlist; $i++) {
5033                my %co = %{$commitlist[$i]};
5034                my $commit = $co{'id'};
5035                # we read 150, we always show 30 and the ones more recent than 48 hours
5036                if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
5037                        last;
5038                }
5039                my %cd = parse_date($co{'author_epoch'});
5040
5041                # get list of changed files
5042                open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5043                        $co{'parent'} || "--root",
5044                        $co{'id'}, "--", (defined $file_name ? $file_name : ())
5045                        or next;
5046                my @difftree = map { chomp; $_ } <$fd>;
5047                close $fd
5048                        or next;
5049
5050                # print element (entry, item)
5051                my $co_url = href(-full=>1, action=>"commit", hash=>$commit);
5052                if ($format eq 'rss') {
5053                        print "<item>\n" .
5054                              "<title>" . esc_html($co{'title'}) . "</title>\n" .
5055                              "<author>" . esc_html($co{'author'}) . "</author>\n" .
5056                              "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
5057                              "<guid isPermaLink=\"true\">$co_url</guid>\n" .
5058                              "<link>$co_url</link>\n" .
5059                              "<description>" . esc_html($co{'title'}) . "</description>\n" .
5060                              "<content:encoded>" .
5061                              "<![CDATA[\n";
5062                } elsif ($format eq 'atom') {
5063                        print "<entry>\n" .
5064                              "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
5065                              "<updated>$cd{'iso-8601'}</updated>\n" .
5066                              "<author>\n" .
5067                              "  <name>" . esc_html($co{'author_name'}) . "</name>\n";
5068                        if ($co{'author_email'}) {
5069                                print "  <email>" . esc_html($co{'author_email'}) . "</email>\n";
5070                        }
5071                        print "</author>\n" .
5072                              # use committer for contributor
5073                              "<contributor>\n" .
5074                              "  <name>" . esc_html($co{'committer_name'}) . "</name>\n";
5075                        if ($co{'committer_email'}) {
5076                                print "  <email>" . esc_html($co{'committer_email'}) . "</email>\n";
5077                        }
5078                        print "</contributor>\n" .
5079                              "<published>$cd{'iso-8601'}</published>\n" .
5080                              "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
5081                              "<id>$co_url</id>\n" .
5082                              "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
5083                              "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
5084                }
5085                my $comment = $co{'comment'};
5086                print "<pre>\n";
5087                foreach my $line (@$comment) {
5088                        $line = esc_html($line);
5089                        print "$line\n";
5090                }
5091                print "</pre><ul>\n";
5092                foreach my $difftree_line (@difftree) {
5093                        my %difftree = parse_difftree_raw_line($difftree_line);
5094                        next if !$difftree{'from_id'};
5095
5096                        my $file = $difftree{'file'} || $difftree{'to_file'};
5097
5098                        print "<li>" .
5099                              "[" .
5100                              $cgi->a({-href => href(-full=>1, action=>"blobdiff",
5101                                                     hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
5102                                                     hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
5103                                                     file_name=>$file, file_parent=>$difftree{'from_file'}),
5104                                      -title => "diff"}, 'D');
5105                        if ($have_blame) {
5106                                print $cgi->a({-href => href(-full=>1, action=>"blame",
5107                                                             file_name=>$file, hash_base=>$commit),
5108                                              -title => "blame"}, 'B');
5109                        }
5110                        # if this is not a feed of a file history
5111                        if (!defined $file_name || $file_name ne $file) {
5112                                print $cgi->a({-href => href(-full=>1, action=>"history",
5113                                                             file_name=>$file, hash=>$commit),
5114                                              -title => "history"}, 'H');
5115                        }
5116                        $file = esc_path($file);
5117                        print "] ".
5118                              "$file</li>\n";
5119                }
5120                if ($format eq 'rss') {
5121                        print "</ul>]]>\n" .
5122                              "</content:encoded>\n" .
5123                              "</item>\n";
5124                } elsif ($format eq 'atom') {
5125                        print "</ul>\n</div>\n" .
5126                              "</content>\n" .
5127                              "</entry>\n";
5128                }
5129        }
5130
5131        # end of feed
5132        if ($format eq 'rss') {
5133                print "</channel>\n</rss>\n";
5134        }       elsif ($format eq 'atom') {
5135                print "</feed>\n";
5136        }
5137}
5138
5139sub git_rss {
5140        git_feed('rss');
5141}
5142
5143sub git_atom {
5144        git_feed('atom');
5145}
5146
5147sub git_opml {
5148        my @list = git_get_projects_list();
5149
5150        print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
5151        print <<XML;
5152<?xml version="1.0" encoding="utf-8"?>
5153<opml version="1.0">
5154<head>
5155  <title>$site_name OPML Export</title>
5156</head>
5157<body>
5158<outline text="git RSS feeds">
5159XML
5160
5161        foreach my $pr (@list) {
5162                my %proj = %$pr;
5163                my $head = git_get_head_hash($proj{'path'});
5164                if (!defined $head) {
5165                        next;
5166                }
5167                $git_dir = "$projectroot/$proj{'path'}";
5168                my %co = parse_commit($head);
5169                if (!%co) {
5170                        next;
5171                }
5172
5173                my $path = esc_html(chop_str($proj{'path'}, 25, 5));
5174                my $rss  = "$my_url?p=$proj{'path'};a=rss";
5175                my $html = "$my_url?p=$proj{'path'};a=summary";
5176                print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
5177        }
5178        print <<XML;
5179</outline>
5180</body>
5181</opml>
5182XML
5183}