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