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