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