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