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