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