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