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