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