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