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