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