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