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